• Beth Massi - Sharing the goodness

    Creating a SharePoint Visual Web Part using Visual Studio 2010

    • 21 Comments

    Last year we built a business application for order management for Northwind Traders on the Office and SharePoint platform using Visual Studio 2008 and Office & SharePoint 2007. Lately I’ve been writing articles that show how to upgrade it to Office & SharePoint 2010 using Visual Studio 2010. If you missed them:

    I also released the migrated sample application here: http://code.msdn.microsoft.com/OBANorthwind

    If you look at the VS2010 solution in that sample you’ll see a few extra projects in there that add more functionality to our application. One of those new pieces is a Visual Web Part that shows low inventory from the Northwind database. Northwind’s operations department not only wants to see Order status in SharePoint (which we built into our workflow) but also wants to be able to quickly eyeball any low inventory. Visual Studio 2010 includes many new project and item templates for SharePoint 2010, one being a Visual Web part. If you’re familiar with ASP.NET development then you can easily start building a SharePoint web part using Visual Studio 2010. Let’s see how we can do that.

    Creating a Visual Web Part Project in Visual Studio

    First thing you need to do is open Visual Studio as an Administrator. You need to do this when you are programming against SharePoint because the debugger & tools need Administrator access to SharePoint. Visual Studio will warn you if you forget.

    Next create a new project and select SharePoint 2010 -> Visual Web Part. (Make sure you select Visual Web Part and not Web Part). Name the project LowInventoryWebPart. The SharePoint Customization Wizard opens. Select your SharePoint site, in my case I’ve created a team site called Northwind.

    Notice that “Deploy as a farm solution” is the only option. This means that when you design a visual web part it is available to all site collections on the farm as opposed to a sandboxed solution which is only available at the site collection level. The key difference between these two is what processes they run in, farm being the IIS worker process, which dictates which access levels they have. For more information on the differences see Differences Between Sandboxed and Farm Solutions in the MSDN library.

    image

    Click Finish and the the ASP.NET designer opens and displays a web user control that we can design. But first we need to add a service reference to our data service. If you recall we are exposing our line-of-business data (in this case the Northwind SQL database) over WCF-REST using a data service. As long as we can access this service from our SharePoint instance once we deploy, then we’re good to go.

    To add a Service Reference to the data service, select Project -> Add Service Reference. If your data service is in the same solution as in the case of this one, just click Discover to browse the types that the data service exposes. Set the Namespace to NorthwindService and click OK.

    Designing the Visual Web Part and Loading Data

    I don’t have any super-fancy design skillz here so we’re just going to create a data-bound GridView and then write a LINQ query to get the low inventory items to display. The key takeaway is that this would be the same code to write if we were writing any ASP.NET webpage, you can even use the Ajax controls in the toolbox. In the next section below we’ll take advantage of the SharePoint server model in order to interact with SharePoint lists, but to pull data from our LOB database it’s standard data access stuff.

    So from the Data tab in the toolbox, I’m going to drag a GridView onto the form. I’m also going to drop a Label at the bottom of the form to display any errors or messages. I can style these controls how I like and these styles will be displayed the same way in the Web Part in SharePoint.

    image

    Right-click on the designer to open the code-behind. In the Page_Load event handler we’ll write the code to load the low inventory from our data service:

    Imports System
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports LowInventoryWebPart.NorthwindService
    
    Partial Public Class LowInventoryWebPartUserControl
        Inherits UserControl
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
            'Webpart Code to display Low Inventory:
            Try
                Dim ctx As New NorthwindEntities(New Uri("http://myserver/Northwind.svc/"))
    
                Dim result = From p In ctx.Products _
                             Where p.UnitsInStock <= p.ReorderLevel _
                             Order By p.UnitsInStock
    
    
                Me.GridView1.AutoGenerateColumns = True
                Me.GridView1.DataSource = result.ToList()
                Me.GridView1.DataBind()
    
            Catch ex As Exception
                Me.Label1.Text = ex.ToString
            End Try
        End Sub
    
    End Class

    Debugging the Web Part

    Let’s test this so far. Set the LowInventoryWebPart project as the startup project of your solution (if it isn’t already) and set a breakpoint on the LINQ query. Hit F5 and Visual Studio will recycle the IIS worker process, package & deploy & activate the feature, and attach the debugger automatically for you. This is shown in the Output window and it’s fun to watch so you may want to pin that window open. :-)

    ------ Deploy started: Project: LowInventoryWebPart, Configuration: Debug Any CPU ------
    
    Active Deployment Configuration: Default
    Run Pre-Deployment Command:
      Skipping deployment step because a pre-deployment command is not specified.
    Recycle IIS Application Pool:
      Skipping application pool recycle because no matching package on the server was found.
    Retract Solution:
      Skipping package retraction because no matching package on the server was found.
    Add Solution:
      Adding solution 'LowInventoryWebPart.wsp'...
      Deploying solution 'LowInventoryWebPart.wsp'...
    Activate Features:
      Activating feature 'Feature1' ...
    Run Post-Deployment Command:
      Skipping deployment step because a post-deployment command is not specified.
    ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
    ========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========

    The nice thing is that Visual Studio handles all the deployment as well as all the cleanup. When you close the debugger the feature is deactivated and the package is retracted and deleted. Notice that you can also specify pre and post deployment commands, plus a whole lot more. The Feature and Package designers are very flexible. (For more information watch this Channel 9 Interview: SharePoint Feature and Package Designers in Visual Studio 2010 and read Packaging and Deploying SharePoint Solutions in the MSDN library.)

    In order to debug this sucker we first have to add it to a page on our site. When the debugger starts up, it opens a page to the site we specified in the SharePoint Customization Wizard in the beginning. So select Site Actions in the upper left, then Edit Page. Select the Insert tab on the Ribbon and click Web Part. Select the Custom category and you should see your web part. Select it and click Add on the bottom right of the section.

    image

    At this point you should hit your breakpoint. Hit F11 and the query will return the low inventory so you can see the data as you design the page. The Page_Load will get called a couple times when designing the web part so keep that in mind.

    Next drop down the LowInventoryWebPart menu at the top right of the web part and select Edit Web Part to open the properties. Set the Title to “Low Inventory” and click OK. On the Page tab on the Ribbon select Save to save and close the page editor. Now we’ve got a nice looking web part for browsing low inventory. Sweet!

    image

    Close the browser window and this will close your debugging session, recycle the IIS app pool, deactivate the feature and retract the solution automatically for you. These steps are also displayed in the Output window.

    Interacting with SharePoint using the Server Object Model

    Well that was pretty easy to incorporate our LOB data into SharePoint with a simple web part and a data service but what if the user sees a critically low item and wants to add an item to the Task list? It would be nice if they could do it right here. The way we interact with SharePoint in a Visual Web Part is via the SharePoint Server Object Model. There are also SharePoint client object models as well; one for Silverlight clients and one for other .NET Framework clients. But because we are on the server when we are running a web part, we have access here to the server object model.

    So let’s add a TextBox and a Button to our web part that allow the user to enter tasks directly onto the Task list. Go back to design mode on the Web Part, hit enter under the GridView and and type “Create Task:” under it. From the Standard tab on the toolbox, drag a Textbox onto the form then drag a Button and set its Text property to “Add”.

    Double-click on the button and we can write this code in the Button1 click event handler to add a Task:

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
        'Webpart code to Add to task list 
        Try
            Dim mySite As SPWeb = SPContext.Current.Web
            Dim listItems As SPListItemCollection = mySite.Lists("Tasks").Items
    
            Dim item As SPListItem = listItems.Add()
    
            item("Title") = Me.TextBox1.Text
            item("Assigned To") = mySite.AllUsers(Me.Context.User.Identity.Name)
    
            item.Update()
            Me.TextBox1.Text = ""
            Me.Label1.Text = "Your task has been added to the task list"
    
        Catch ex As Exception
            Me.Label1.Text = ex.ToString
        End Try
    End Sub

    The way we access the current SharePoint site by using the SPContext object and getting the Current.Web. Just like you have an HttpContext in ASP.NET development you have a SPContext in SharePoint development. So let’s test this one out. Put a breakpoint on the Button1_Click handler and hit F5 to deploy and debug. The second time around you don’t need to add the web part to the site page again but it will be refreshed with our new controls and code.

    Now create a task by entering a description and click the Add button. The breakpoint will hit and you can debug the code and explore some of the server object model.

    image

    When you’re done, navigate to the task list to see that your task has been added.

    image

    This project is included in the Northwind OBA solution for VS2010 located here http://code.msdn.microsoft.com/OBANorthwind  so have a look. If you’re an ASP.NET developer just getting started with SharePoint development there’s still a lot to learn, but fortunately Visual Studio 2010 can help make an unfamiliar platform easier to approach with the right tools in hand.

    Download Visual Studio 2010 Beta and read the walkthroughs here: http://msdn.com/vstudio

    Enjoy!

  • Beth Massi - Sharing the goodness

    New Blog from the WPF & Silverlight Designer Team Just Launched!

    • 5 Comments

    The WPF and Silverlight Designer team (a.k.a Cider team) launched a blog last week and they already have a TON of content!
    http://blogs.msdn.com/wpfsldesigner/

    Wow I need to catch up!  I’m told during the months of January and February they will be adding a good bit of WPF & Silverlight content that will focus on the Designer toolset and walkthroughs using the Designer as well as some posts for control authors.

    You can leave feedback for the Cider Team on the blog or you can send comments and questions using Twitter and include #wpfdesigner or #sldesigner in your tweets.

    My favorite tag on the blog so far is How To. ;-)

    Enjoy! (I know I will)

  • Beth Massi - Sharing the goodness

    Northwind Office Business Application Updated for Visual Studio, Office & SharePoint 2010

    • 0 Comments

    Last year we built a business application for order management for Northwind Traders on the Office and SharePoint platform using Visual Studio 2008 and Office & SharePoint 2007. Recently I started releasing articles that show how to upgrade the VS2008 version to VS2010:

    Today I updated the sample with some more goodies including some SharePoint 2010 web parts that I’ll write about soon. But I wanted to let you know sooner rather than later that you can play with all of the code today. This is also the same code I demonstrated last week at our East Bay.NET User’s group meeting.

    Here ya go: http://code.msdn.microsoft.com/OBANorthwind

    This sample was built using Visual Studio 2010 Beta 2, Office 2010 Beta & SharePoint 2010 Beta and it demonstrates:

    1. A way to easily expose line-of-business (LOB) data using WCF Data Services (formerly known as ADO.NET Data Services)
    2. An Outlook 2010 Add-in that displays LOB data in a WPF control that I built in 5 minutes using the new drag-drop data binding and designer features
    3. How to store and retrieve structured data from Word 2010 documents
    4. An Excel 2010 document customization that edits LOB data through the data service and provides data visualization
    5. A SharePoint 2010 Document Library Workflow that adds Order info to the database by reading word documents and updates and reports order statuses based on changes in the database using the data service
    6. A SharePoint 2010 Visual Web Part that reports low inventory in the database using the data service and allows users to add tasks
    7. A SharePoint 2010 Silverlight Web Part that demonstrates how to deploy Silverlight web parts to SharePoint 2010 and use the SharePoint Silverlight client library to add tasks

    Enjoy!

  • Beth Massi - Sharing the goodness

    Migrating a 2007 Workflow to Visual Studio & SharePoint 2010

    • 7 Comments

    Lately I’ve been converting an Office business application we built last year with Visual Studio 2008 to Visual Studio and Office 2010. Last couple posts we tackled converting the Outlook client piece. In this post I want to focus on the server side and show how we can convert the SharePoint 2007 workflow we built with Visual Studio 2008 to a SharePoint 2010 workflow in Visual Studio 2010.

    In Visual Studio 2008 under the Office –> 2007 node in the New Project dialog we could choose from a variety of Office client templates. There was included a SharePoint Sequential Workflow and SharePoint State Machine Workflow. These were the only SharePoint templates available to us. As you’ve probably heard already, Visual Studio 2010 provides much more support for SharePoint and includes many more project and item templates, now included in its own SharePoint –> 2010 node:

    image

    You can still build Sequential and State Machine workflows for SharePoint 2007 in Visual Studio 2010 but you’ll be able to do a lot more against SharePoint 2010. Let’s see how we can convert the Sequential Workflow we built against SharePoint 2007 to SharePoint 2010 using Visual Studio 2010.

    Convert the Solution to Visual Studio 2010

    The first step is to open the VS2008 solution in VS2010. This will through the (probably familiar) Visual Studio conversion wizard. This doesn’t change the code itself, it just upgrades the solution and project files. Now if you are doing this on a machine that doesn’t have SharePoint 2007 installed, but instead has SharePoint 2010, then you won’t be able to run this workflow. Makes sense. You need to have the version of SharePoint you’re developing against on the dev box. Luckily, with SharePoint 2010 you can have it installed on a client OS like Win 7.

    Create the Order Document Library on SharePoint 2010

    Since we want to migrate this example to SharePoint 2010, I have to have that installed that on my development machine (which also means we can’t run the 2007 workflow). We also need to set up SharePoint with the same document library we had before or our migrated code won’t run either.

    If you recall this workflow processes purchase orders that are added to the Orders document library so we’ll also need to set that up with the same columns we had before. Even though the UI looks a bit different, the process is the same as I described in the previous article on SharePoint 2007. Once you get the Order document library set up with the additional columns we need, it should look similar to this:

    image

    Add a New SharePoint 2010 Sequential Workflow

    Since we can’t run the SharePoint 2007 workflow, the easiest thing to do is add a new SharePoint 2010 Workflow project to your solution and then move the workflow code over. With your solution open, select File –> Add –> New Project, expand the SharePoint 2010 node and then select the SharePoint 2010 Sequential Workflow.

    imageThe SharePoint Customization wizard opens. I’ll name this project NorthwindWorkflow2010 and then I need to select my SharePoint 2010 site, set the display name and select List Workflow. (Notice in SharePoint 2010 we can also create a Site Workflow as well).

    Click Next and then select the same lists to associate the workflow with that you were using before in the 2007 Workflow. In the case of this example the only thing to select is the Orders document library in the first dropdown.

    Click Next and then select how the workflow should start up. In our case leave the defaults. We want this workflow to start up when an item is added to the list.

    Once you hit Finish the project is generated and appears in the Solution Explorer.

    Add Service and Assembly References, then Copy your Code

    image Next you’ll need to re-add any assembly references you were using before to get your workflow code running. In this example we need to add a reference to the DocumentFormat.OpenXml. I also need to add a service reference to the data service we were using to access our LOB data, in this case NorthwindDataService. In fact, I have this already in the Solution so I can just right-click on the NorthwindWorkflow2010 project, select Add Service Reference, and then in the dialog just click the Discover button to find the data service. Name it NorthwindServiceReference and click OK.

    Now comes the fun part. We can just copy all the code files into the new project. First though I need to rename the Workflow1 “sub-folder” to ProcesOrder in the 2010 project. Yes you should notice that the file structure is different in the 2010 project. For instance, you’ll see Package and Features “folders” under the project. This is because there are new tools for packaging features (like Lily showed us on Channel 9) among a ton of other tools. We refer to these “folders” as SharePoint Project Items (SPI).

    image Once you rename the Workflow SPI to ProcessOrder then you can delete the actual workflow Workflow1. Then drag the ProcessOrder workflow from the old project into this new one, just make sure you add it to the ProccessOrder SPI. Also drag all the other code files into your new project.

    Next open up the Elements.xml file and make sure you see the correct name of your workflow in there. Make sure the CodeBesideClass attribute is correct:

    CodeBesideClass="NorthwindWorkflow2010.ProcessOrder"

    If this isn’t correct then your workflow will deploy correctly, but it will fail to start so be sure to double-check this.

    The only other thing we need to do now is fix up one Imports statement in our code-behind for the workflow because the name of our project changed. In our example, the OrderManager.vb is referencing our service so that needs to be fixed up:

    Imports NorthwindWorkflow2010.NorthwindServiceReference

    Finally remove the old workflow project (NorthwindWorkflow) from the solution by right-clicking on the project name and selecting remove.

    Run it!

    Now you should be able to run the new workflow in SharePoint 2010. Set the NorthwindWorkflow2010 as your startup project, make sure you start the NorthwindDataService and then hit F5 to deploy and debug. When we add a new purchase order to the Orders doc library the workflow will run and process our order by putting the order data into the database using the data service just like before, but now we’re developing against SharePoint 2010 and we can take advantage of the new tools in Visual Studio 2010.

    If you’d like to play with this workflow (plus all the other pieces of the Northwind Traders application) you can download the entire solution upgraded to Visual Studio, Office and SharePoint 2010 here.

    Next time I’ll show how we can create a simple Visual Web Part that displays inventory information from the Northwind database and allows us to assign tasks using the SharePoint server object model.

    Enjoy!

  • Beth Massi - Sharing the goodness

    Visual Studio 2010 “Tip of the Day” Returns!

    • 1 Comments

    If you used to rely on Sara Ford and her amazing Visual Studio tips you’ll be happy to know that there’s a new tipster in town taking over for her for Visual Studio 2010. Zain Naboulsi, a Developer Evangelist, has started the Tip of the Day series back up again!

    Check it out: http://blogs.msdn.com/zainnab/archive/tags/vs2010/Tips+and+Tricks/default.aspx

    Enjoy!

  • Beth Massi - Sharing the goodness

    Speaking at East Bay.NET Tomorrow Night on VSTO & SharePoint 2010

    • 2 Comments

    Wow, welcome back from the holidays! I hope yours were as fun and relaxing as mine were. It's always a wonderful time of year to stay with friends and family and concentrate on what's really important in life.

    Well it's time to get back at it and I am refreshed and ready to go! I'm working on a fun-filled presentation for EastBay.NET on building business applications on the Office and SharePoint 2010 platform using Visual Studio 2010. Here's the official talk description:

    Building Business Productivity Solutions with Visual Studio 2010 
    The Visual Studio and Office teams have made significant investments in improving the developer experience for building and deploying Office and SharePoint applications. In this demo-heavy session, we will walk through an end-to-end business application built on Office and SharePoint 2010 and discuss architecture options to consider when building these systems. You'll learn how to use Visual Studio and it’s enhanced set of RAD tools that allows users to consume external line-of-business data within the familiar Office UIs.

    When: Wednesday, 1/13/2010 at 6:45 PM
    Where: University of Phoenix Learning Center in Livermore, 2481 Constitution Drive, Room 105

    Register for this meeting here.

    I'm also playing with some Silverlight right now to see if I can squeeze in how to deploy Silverlight web parts to SharePoint 2010. The deployment is made so easy with Visual Studio 2010. (Check out Mike's Channel 9 interview on how to do it: Implementing a Silverlight SharePoint WebPart with Visual Studio 2010)

    And as an added bonus I talked Ward Bell from IdeaBlade (Silverlight MVP) into coming out and presenting FUNdamentals, a 30 minute intro session we do before our main talks here at EastBay.NET. He's going to show you the basics of WCF Data Services (a.k.a ADO.NET Data Services, a.k.a Astoria). I'll be using this technology to expose our LOB data to Office and SharePoint but I won't have time to show you more than a brief overview on how to set it up. So if you've never used the technology then come early and learn from Ward how it works.

    It should be a very fun filled evening from two awesome speakers (if I do say so myself ;-)) so I hope to see you there.

    Enjoy!

Page 1 of 1 (6 items)