Sharing the goodness…
Beth Massi is a Senior Program Manager on the Visual Studio team at Microsoft and a community champion for .NET developers. Learn more about Beth.
More videos »
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.
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.
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.
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.
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:
Partial Public Class LowInventoryWebPartUserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
'Webpart Code to display Low Inventory:
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()
Catch ex As Exception
Me.Label1.Text = ex.ToString
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.
Skipping package retraction because no matching package on the server was found.
Adding solution 'LowInventoryWebPart.wsp'...
Deploying solution 'LowInventoryWebPart.wsp'...
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.
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!
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.
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
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)
Me.TextBox1.Text = ""
Me.Label1.Text = "Your task has been added to the task list"
Catch ex As Exception
Me.Label1.Text = ex.ToString
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.
When you’re done, navigate to the task list to see that your task has been added.
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
It would be nice to be able to develop web parts for WSS off of the server. Will MS create a developer SDK that developers can install on their developer PC's (not a server) so they can develop and deploy web parts to a SharePoint server?
I'm not aware of such SDK. But you can now install SharePoint 2010 on a Windows 7 (or Vista) machine for development with Visual Studio 2010 and then after dev and testing you can take the .wsp Visual Studio creates and deploy it to your server.
I see what you want but right now VS and SharePoint need to be on the same box for development. However that box doesn't have to be a server OS anymore, it can be a client OS with 2010. If you want to install the SharePoint 2010 beta on Windows 7, take a look at this post: http://blogs.msdn.com/bethmassi/archive/2009/12/02/setting-up-windows-7-for-office-sharepoint-2010-beta-development.aspx
@Beth, what version of Vista will WSS 2010 run on? I'm running Vista with IIS 7 and SP2, also what version of Win 7 will WSS 2010 run on? Though I don't have it, I'm looking to possibly upgrade to it soon.
You'll need 64-bit Windows 7 Professional or higher or 64-bit Vista SP1 or higher (not home edition).
Hi Mike, you might want to take a look at the SharePoint SDK available here:
It targets SharePoint 2010 Beta and can be used from Visual Studio 2010.
I am looking for sample of visual webparts for
- connecting webparts
Can you create webparts and deploy to a SharePoint 2007 server using Visual Studio 2010?
i am creating real estate web portal.i want to create wizard style web form using share point web portal.can any body help me how sharepoint web portal help me creating wizards in my portal
I want to access annoucement items to datalist. how can I access to visaul webpart
Is that possible to migrate the webpart created in vs 2008 to vs 2010
Sundarram, if you used VSeWSS to create your web part in VS2008, then you should take a look at a conversion tool that has been created that will help you migrate these projects into the new VS2010 structure. You can find that tool here: code.msdn.microsoft.com/VSeWSSImport
If you did not use VSeWSS, you will need to create a new, empty VS2010 project targeting SP2010 and then add a web part (or visual web part) to the project. After that you can copy/paste your markup/code.
Hope this helps,
Senior Program Manager - Visual Studio
I converted the webpart for VS 2010 using the VSeWss tool. The project is building with out any error and it also deployed sucessfully but when i try to add the webpart to the sharepoint website it throw the following error mesage
"The directory is not a subdirectory of the root directory. (Exception from HRESULT: 0x80070090)"
What could be causing this problem. Please advice
@Mike - like she said you can install SharePoint 2010 on your Win7/Vista Workstation by modifying the setup config file to ignore. here a link to it
really easy to do!
hi all.can anyone tell me how to upload pictures to picture gallery of sharepoint from asp page.
Thanks for the post. Do you know if its possible to create a custom Ribbon with a visual web part. It seems like it should be but the only examples I've found have been with the non-visual type.