Wednesday, September 30, 2009

SharePoint Web Part Development Tutorial


It is hard to find out simple way to create SharePoint web parts with visual designing. After looking at custom features, in this article I'm going to show you how to create custom SharePoint web part using Web User Control in Visual Studio.

Creating the Web Part

First Create New Project called "ProjectView" and select ASP.NET Web Application (Figure 1 & 2). Don’t use shortcuts.


Then Add new Web User Control called "ProjectViewControl" to your project (Figure 3 & 4).


Then Add reference to the “Microsoft.SharePoint.dll”. It can be found in your sharepoint server’s ISAPI folder (Figure 5 & 6).


You should copy this file along with “Microsoft.SharePoint.Search.dll” and “Microsoft.SharePoint.Search.xml” from the same directory to a directory on your local computer if you are developing your project on a machine not having SharePoint or MOSS.

Then go to your SharePoint site’s folder (You can find it in SharePoint server) and create a folder called “usercontroles” if does not exist (Figure 7).

Find your site’s “Web.config” file within the same folder and open it (Figure 7).

Then add new Class called “WebControl.cs” which inherits from “WebPart” Class to your project (Figure 8) and paste this code there.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace ProjectView
{
    public class WebControl : WebPart
    {
        protected string UserControlPath = @"~/usercontrols/";
        protected string UserControlName = @"ProjectViewControl.ascx";

        private ProjectViewControl mycontrol;
        private string exceptions = "";

        protected override void CreateChildControls()
        {
            try
            {
                mycontrol = (ProjectViewControl)this.Page.LoadControl(UserControlPath + UserControlName);
                Controls.Add(mycontrol);
            }
            catch (Exception CreateChildControls_Exception)
            {
                exceptions += "CreateChildControls_Exception: " + CreateChildControls_Exception.Message;
            }
            finally
            {
                base.CreateChildControls();
            }
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            try
            {
                base.RenderContents(writer);
            }
            catch (Exception RenderContents_Exception)
            {
                exceptions += "RenderContents_Exception: " + RenderContents_Exception.Message;
            }
            finally
            {
                if (exceptions.Length > 0)
                {
                    writer.WriteLine(exceptions);
                }
            }
        }
    }
}

There don’t forget to add following two lines to the top, now your “WebControl.cs” Class should like above.

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

Then drag and drop a text box and two buttons to ProjectViewControl.ascx. Double click those buttons to add custom code (Figure 9 & 10).


Signing your web part project

To deploy this Web Part and Web User Control to GAC and the Microsoft Office SharePoint Server, we should assign a Strong Name key and sign the control.

To do this, right click the “ProjectView” node in Solution Explorer and select Properties. Then select the Signing tab from the choices on the left. Check the "Sign the assembly" box and select from the "Choose a strong name key file" drop down list (Figure 11).

There give a key file name and click ok. Now you can build your project and ready to deploy.

Deploying the Web Part and Web User Control

Here is deploying steps;

1. Copy the "ProjectViewControl.ascx" file to the created usercontroles folder (Figure 7).

2. Drag and drop the compiled DLL (You can find it in your project folder's bin folder) into the Global Assembly Cache. The Global Assembly Cache is a special folder located at %WINDIR%\assembly where %WINDIR% is the full path to your Windows folder (e.g. C:\Windows or C:\Winnt).

3. Get the publicKeyToken property of our assembly. You can find it by right click on the file and select properties in "assembly" folder (Figure 12).

4. Update the "Web.config file"

4.1 Insert these three lines between <SafeControls> and </SafeControls> tags.

<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="WebControl" Safe="True" />
<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="ProjectViewControl" Safe="True" />
<SafeControl Assembly="ProjectView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a73871474819663" Namespace="ProjectView" TypeName="*" Safe="True" />

4.2 Insert this line between <assemblies> and </assemblies> tags.

<add assembly="ProjectView, Version=1.0.0.0, Culture=neutral,PublicKeyToken=9a73871474819663" />

5. Insert new XML file called "myprojectview.webpart" (Figure 13) and paste this code.

<?xml version="1.0" encoding="utf-8" ?>
<webParts>
    <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
        <metaData>
            <type name="ProjectView.WebControl, ProjectView, Version=1.0.0.0,Culture=neutral,PublicKeyToken=9a73871474819663" />
            <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
        </metaData>
        <data>
            <properties>
                <property name="Title" type="string">My first custom Web Part</property>
                <property name="Description" type="string">
                    webpart created by using web user controles
                </property>
                <property name="ChromeType">TitleOnly</property>
                <property name="ChromeState">Normal</property>
                <property name="ItemLimit" type="int">15</property>
                <property name="ItemStyle" type="string">Default</property>
            </properties>
        </data>
    </webPart>
</webParts>

6. Upload the "myprojectview.webpart" file to Share Point's Web Part gallery. (You should have permission to see the Site Action tab and upload) (Figure 14, 15, 17, 18 & 19)





Use your Web Part

To use your Web Part in a page, follow these steps;

1. Edit a SharePoint page (Figure 19, 20 & 21)

2. Select a zone into which you want to place your Web Part

3. Add the Web Part to the zone

4. Exit from the Edit mode



Remember that you cannot copy DLL from MyDocument folder. So first copy the DLL to some location in SharePoint Server and then drag and drop it into assembly folder.

If you are interested you can try SharePoint charting (Chart inside web part) to see how you can add nice chart inside to this web part. Also try custom features.

57 comments:

  1. My PC does not have the ISAPI folder to get the sharepoint dll... Do i need to have sharepoint installed in order to get this dll?

    Can i go and copy the dll from sharepoint and paste it in my local folder?

    thanks

    ReplyDelete
  2. Hi,
    Your local PC dose not contain that dll file and also you need windows server OS installed to install SharePoint.

    If you can log in to server computer directly or remotely, develop your web part within the server is the best way.

    If you haven't access to the server you have to contact your system administrator and get a copy of that file, then place it in your local hard drive and set the reference as figure 05.

    Anyway you need to access the server when you are deploying your web part.

    Thanks !

    ReplyDelete
  3. Thanks for the info. Very helpful

    ReplyDelete
  4. Hi
    Thanks for the info, but do you know any idea for maintain the view state for all the control, so I can use a simple submit Form?

    ReplyDelete
  5. Hi,
    According to my experience this is the simple way to use custom controls in sharepoint web part.

    ReplyDelete
  6. hey....muchas gracias por este tutorial me ha sacado de problemas..........gracias XD

    ReplyDelete
  7. Hi al.renovato,

    Gracias a Google Translator Entiendo lo que usted ha dicho, muchas gracias por sus comentarios!

    ReplyDelete
  8. Hi, You said to update the web.config file. I assume this is the one in this location:

    "C:\Inetpub\wwwroot\wss\VirtualDirectories\80"

    But do you need to update the web.config file in your VS2008 project folder at all?

    Thanks, Ashok

    ReplyDelete
  9. Hi,

    I am assuming you update the web.config file in the following folder:

    "C:\Inetpub\wwwroot\wss\VirtualDirectories\80"

    Do you need to do anything to the web.config file within your project folder?

    Thanks, Ashok

    ReplyDelete
  10. Hi Ashok,

    Here I'm talking about your site's web.config file. If your site is "http://mysite:5050/",
    Then you can find it in
    "C:\Inetpub\wwwroot\wss\VirtualDirectories\5050"
    Please check figure 7.
    Thanks !

    ReplyDelete
  11. Good idea! Thanks, its work!

    Best regards,
    Katavary.

    ReplyDelete
  12. Hi! Thank you . To all participant, please have a look at our updated contest post.
    Web development

    ReplyDelete
  13. This is fantastic!!! I walked through the whole process and it's working perfecting. Here is my question... When I modify the *control.ascx.cs file, what is the best way to have the webpart updated on the SP server? I have done a rebuild and recopied the DLL over to the GAC (the token stayed the same) and then when I try to add the webpart again (when I edit the page) it is still the old version.

    What is the easiest way to update the webpart when all I need to do is change one line inside the *control.ascx.cs file?

    ReplyDelete
  14. hi theBlaine,
    thanks for the comment, if you are editing the *control.ascx.cs file you have to reset the IIS server after rebuild and recopied the DLL over to the GAC. Use iisreset command in SP server's run window.
    thanks,
    Saranga Rathnayake

    ReplyDelete
  15. Though my webpart is working.... I now receive this error in the event log on a very regular basis. I have built the DLL on a separate machine as the SP server.

    Event Type: Error
    Event Source: Windows SharePoint Services 3
    Event Category: General
    Event ID: 6762
    Date: 1/26/2010
    Time: 8:23:40 AM
    User: N/A
    Computer: SERVER
    Description:
    Error initializing Safe control - Assembly:SQLSERVER_Test, Version=1.0.0.14, Culture=neutral,

    PublicKeyToken=eb4131ea0115cef0 TypeName: SQLSERVER_Test.ProjectViewControl Error: Could not load type

    'SQLSERVER_Test.ProjectViewControl' from assembly 'SQLSERVER_Test, Version=1.0.0.14, Culture=neutral,

    PublicKeyToken=eb4131ea0115cef0'.

    ReplyDelete
  16. I am running SharePoint v3 on that server. That article refers to v2 and says that v3 is not affected by this issue.

    I will keep looking and if I find anything I will post it here.

    ReplyDelete
  17. @ theBlaine,
    Hi,
    please post the solution if you find one.
    thanks indeed.
    Saranga Rathnayake

    ReplyDelete
  18. Saranga,

    Thanks for your article. very interesting indeed. I have a question though: how do we move from one user control to another.

    Suppose you have usercontrol1 inside that webpage, and inside usercontrol1 you have a hyperlink to something that uses usercontrol2.

    Please advise of the best solution for this.

    Thanks
    jika

    ReplyDelete
  19. @ Anonymous,
    This cannot be done using above method, you have to have one usercontrol file for one web part.
    best solution is designing the web part within one usercontrol with different panels.
    thanks !

    ReplyDelete
  20. @ Nitin S Tiwari,
    Thanks for your valuable comment !

    ReplyDelete
  21. nice and clean work!!! Thanks for the article

    ReplyDelete
  22. hello,
    thanks for the post,
    however, I have a problem,
    the button doesn't work, even I debug, the code inside the Page_Onload is executed, but it didn't execute the code inside the button,
    Thanks

    ReplyDelete
  23. @ Anonymous,
    Can you see the webpart after you upload it? Please do IIS reset if you redeploy the DLL and make sure you update the Web.config file correctly.
    thanks !

    ReplyDelete
  24. Hi,

    Can you debug your code with this method, by choosing "Tools -> Attach to process" is Visual Studio, with sinchronized assemblies?

    ReplyDelete
  25. @ Anonymous,
    I don't think, but just try.
    You can debug the events using "Console Application" or "Windows Form Application" and then put them inside the web part.
    thanks !

    ReplyDelete
  26. So if, after loading and viewing the web part successfully in the Sharepoint Environment, I want to make an adjustment to it in VisualStudio then update the web part on SP what all needs to happen to redeploy an updated web part?

    ReplyDelete
  27. this is goos stuff thanks alot
    but i have a question
    supposing i want to add a connection to sql server
    basically in my website (projectview) i can edit my web.cong to add a connection string
    but how can i use that web.config or actually make my webuserconrol read the connection from that web.config
    please advise
    regards

    ReplyDelete
  28. @ Anonymous,
    Yes, if you make changes you have to rebuilt and re-deploy the DLL. There keep in mind to reset the ISS using "iisreset" command.
    thanks !

    ReplyDelete
  29. @ Roni,
    Why don't you use ProjectViewControl.cs file itself to create the connection. Did you try that?

    ReplyDelete
  30. i did do it btw and yes it worked
    i just add in the sharepoint web.config file my app settings and it willl read from it..it worked
    what i am trying to do now is add a reference to the microsoft enterprise library data file
    microsoft.practices.enterpriselibrary.data.dll
    anyway i need to know something
    i am new to sharepoint dev but not for asp.net
    what i found so far is that i can create an asp.net usercontrol and add it as a webpart to sharepoint or i can create an asp.net webpart and add it as a webpart to sharepoint or i can customise my pages using the microsoft office sharepoint designer to connect to a datasource and to set lets say all the insert,update,delete,select functions in my pages
    (anyhow if some1 could recommend other stuff or correct me if i am wrong please do so)
    so what is the best thing?
    the best method to do so
    thanks

    ReplyDelete
  31. Must the WebControl be written in C#? Can I use VB? I tried duplicating this in VB but the control is not loading and it gives me this error

    A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.

    The control also doesn't show up in the "Web Part Gallery: New Web Parts "

    Regards,
    Charlie

    ReplyDelete
  32. Can Web Parts be written in VB.NET? I duplicated all the steps but in VB and WSS3 would not load the control. Is there a trick to get VB to work?

    Thanks for the awesome tutorial,
    Charlie

    ReplyDelete
  33. Hi Charlie,
    I'm sorry I didn't test this in VB.NET, but it should work.
    Accounting to your error message I can assume the error is with the web.config file.
    Please double check whether you update the web.config file correctly as mentioned in the tutorial. There check wherher you are giving correct "namespace" and "class-name" according to your code.
    Thanks !

    ReplyDelete
  34. im getting cannot import this webpart error ? any ideas ?

    ReplyDelete
  35. sorry :p that was my bad forgot to change the assembly in the XML file :D...great post ! thanks

    ReplyDelete
  36. how can i make a WSP file by using this method

    ReplyDelete
  37. can i use the WSPBuilder to make a WSP file and will it work

    ReplyDelete
  38. @ tK,
    It's OK, thanks for your comment.

    ReplyDelete
  39. @ Anonymous,
    You don't need to use this method to create WSP file, you can create custom sharepoint features by following my post Creating SharePoint Features

    ReplyDelete
  40. hi sarange...what i want to achieve is that im using the sharepoint installer for packing up my webpart in order to forward it to my clients...the sharepoint installer needs a WSP file in order to pack all the web part files ...i want to ask how can i make a WSP of this method when im done building my webpart...or if u can advice me on some other packing tools for this method on how i can automate the web part installation to my clients ? thanks a lot ....

    ReplyDelete
  41. @ tk,
    I'm sorry I don't know whether it is possible, if you find some way please post it here.
    thanks !

    ReplyDelete
  42. Is it necessary to sign the web part before it can be used, or can I add it to the safe controls without the "publicKey" property?

    ReplyDelete
  43. @ Daniel Harris,
    Yes, you have to sign otherwise you will not be able to put the DLL in Global Assembly Cache.
    Please ask if you have problems with signing.
    Thanks !

    ReplyDelete
  44. Why are you advocating manual changes to the web.config and 12 hive? All this could be achieved by adding the web part to a feature and wrapping it up in a WSP file.

    ReplyDelete
  45. @ tripwire,
    Thank you for your comment.
    Yes, I have discussed how to create SharePoint feature here.
    Here I have discussed how we can create web part with visual design, If you know better way please post a link here.
    Thank You !

    ReplyDelete
  46. Cool!!!
    Simple way but very helpful!
    Thanx buddy!

    ReplyDelete
  47. எனக்கு நிறைய உதவியது மிக தெளிவாக இந்த கட்டுரை, மிகவும் நன்றி. மன்னிக்கவும் நான் Google இல் சிங்களம் உள்ள மொழிபெயர்ப்பு கிடையாது.

    Thanks

    ReplyDelete
  48. @ JRF,
    நீங்கள் அதை நீங்கள் உதவுகிறது நான் சந்தோஷமாக இருக்கிறேன், வரவேற்பு இருக்கிறீர்கள்.

    ReplyDelete
  49. I can't drag and drop ProjectView.dll into GAC.
    Plz help me. I also tried to log on by administrator but it didn't work.

    ReplyDelete
  50. Hi,The type of Web Design Cochin program can cut your time in half and keep your cost for each web page down to a minimum.thanks.........

    ReplyDelete
  51. hi, couldnot find out ISAPI folder from the directory C:\Program Files\Common Files\microsoft shared\Web Server Extensions\ 14 in Developement machine.
    then how can paste the dll Microsoft.SharePoint.Search.dll” and “Microsoft.SharePoint.Search.xml.... need solution cause of ISAPI ?

    ReplyDelete
  52. hi, couldnot find out ISAPI folder from the directory C:\Program Files\Common Files\microsoft shared\Web Server Extensions\ 14 in Developement machine.
    then how can paste the dll Microsoft.SharePoint.Search.dll” and “Microsoft.SharePoint.Search.xml.... need solution cause of ISAPI ?

    ReplyDelete
  53. could not find out the ISAPI folder from C:\Program Files\Common Files\microsoft shared\Web Server Extensions\14 in developement machine.
    then how can i paste the “Microsoft.SharePoint.Search.dll” and “Microsoft.SharePoint.Search.xml” ...

    Need Solutin for the ISAPI Cause?

    ReplyDelete
  54. Could not drop the ProjectView.DLL into C:\windows\Assembly...
    i have tried to drag and drop it into assembly but it seems not dropped in to Asssembly.. it seems no changes in Assembly folder.


    ReplyDelete
  55. Could not drop the Projectview.dll into GAC. i have tried to drag it and drop into GAC, but it seems no changes in GAC..

    almost i finished the webpart , but one thing left ( drag and drop ProjectView.dll into GAC.)
    to use the web part in sharepont..

    Am looking forward your solution for this issue..

    Thanks In Advance

    ReplyDelete