Click here to Skip to main content
Click here to Skip to main content
Go to top

SharePoint - .Asp.net user control as a Webpart

, 11 Nov 2009
Rate this:
Please Sign up or sign in to vote.
SharePoint - .Asp.net user control as a Webpart

Introduction

In my first article of SharePoint webpart

(Developing and Deploying Custom Web Parts for SharePoint Portal 2007) CustomWebpartSharepoint.aspx

I have discuss how to make the custom web part, in that case you have to make the class library project and do all work at code behind, even you have to write the code to render the controls. This really a very cumbersome and time taking task. But not need to worry at all, SharePoint has introduce one new way to make the webparts, which is very easy, in that you just need to make user control in asp.net and deploy that usercontrol in SharePoint, so my this article will show you all steps of development and deployment of usercontrol.

B. Developing

1. To get started with creating Usercontrol in Microsoft Visual Studio 2005, Open the IDE and create a new C# project, Select Asp.net web application as Project Type. Name It as UserControl_WebPart.

2. Add the usercontrol (ascx) and web page (aspx) in the project and provide the name for usercontrol – ‘UsercontrolWebPart’, now do what you want to do with, I have just putted the Login control in my example. After that test your usercontrol by running it with the web page.

3. Add the reference of Mirosoft.sharepoint.DLL to the project.

4. Add new class into the project named – UCwebpart.cs, which basically deploy the Usercontrol into the SharePoint.

5. Following is the description of the code.

a. A a. add following these two Namespaces.

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

b. Inherit the class from the WebPart class.

public class UCwebpart : WebPart  

c. Provide the following two variables, which provide the address of the usercontrol.

    private UsercontrolWebPart usercontrol;
    private string error = "";
    private string Pathofusercontrol = @"/";

d. Add the method ‘CreateChildControls’, which load the usercontrol in the sharepoint.

protected override void CreateChildControls()
        {
            try
            {
               string tooldir = this.Page.Request.MapPath(Pathofusercontrol);
               string[] textArray1 = null;
                try
                {
                     textArray1 = Directory.GetFiles(tooldir);
                }
               catch (Exception exception1)
                {
                    error += string.Format(exception1.ToString());
                    return;
                }
                usercontrol = (UsercontrolWebPart)this.Page.LoadControl(Pathofusercontrol + @"UsercontrolWebPart.ascx");
                Controls.Add(usercontrol);
            }
            catch (Exception CreateChildControls_Exception)
            {
                error += "CreateChildControls_Exception 2: " + CreateChildControls_Exception.Message + " - Path is" + Pathofusercontrol.ToString() + "--End";

            }//end catch
            base.CreateChildControls();
        }

e. Add the methid ‘RenderContents‘, which render the contents of the usercontrol.

protected override void RenderContents(HtmlTextWriter writer)
         {
            try
            {
                base.RenderContents(writer);
             }
             catch (Exception RenderContents_Exception)
             {
                error += RenderContents_Exception.Message;
              }
            finally
             {
                if (error.Length > 0)
                 {
                   writer.WriteLine(error);
                 }
             }
        }

6. Give your assembly a strong name. Just go into the Project Properties and then go to the "Signing" tab (see Figure 1) to do this. Alternatively, you can use the sn.exe command line tool to generate strong names for you.

 

 

7. Add new one xml file to the project and provide the following contents to it.

<?xml version="1.0" encoding="utf-8" ?>





<pre><webParts> 
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3"> 
	<metaData> 
		<type name="UserControl_WebPart.UCwebpart, UserControl_WebPart, Version=1.0.0.0,Culture=neutral, 
		PublicKeyToken=#################" /> 
		<importErrorMessage>Cannot import this Web Part.</importErrorMessage> 
	</metaData> 
	<data> 
		<properties> 
			<property name="Title" type="string">Web Part</property> 
			<property name="Description" type="string"> 
			</property> 
			<property name="ChromeType">TitleOnly</property> 
			<property name="ChromeState"><city w:st="on" /><place w:st="on" />Normal</place /></city /></property> 
			<property name="ItemLimit" type="int">15</property> 
			<property name="ItemStyle" type="string">Default</property> 
		</properties> 
	</data> 
</webPart> 
</webParts> 

NOTE: change the value public key token, which you will find when deploy the dll into the GAC folder. 

The final contents are here of the project.

C. Deployment

1. Deploy the assembly to the Assembly Folder (GAC) (requires the assembly to be strong named). Drag and Drop the assembly (dll) file, Named UserControl_WebPart.dll from source folder to the Gac Folder (C:\WINDOWS\ASSEMBLY).

2.The Assembly (dll), UserControl_WebPart.dll will be copied in to GAC folder.

3. Now take the public key token for the UserControl_WebPart.dll assembly (dll), select the file first and then click mouse right button, and select the properties.

4. The properties will open and then select the public key token, copy it, and paste the key into any text file.

5. Drag Drop the UsercontrolWebPart.ascx User Control.

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

6. Open the web.config file of the SharePoint application from the following path.

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

7. Add the following attribute, in the last of <sharepoint><safecontrols> element.

<SafeControl Assembly="UserControl_WebPart, Version=1.0.0.0, Culture=neutral, 


<p style="TEXT-ALIGN: justify">PublicKeyToken=93b5b0fffa462560" Namespace="UserControl_WebPart" TypeName="*" 




</p>

<p style="TEXT-ALIGN: justify">Safe="True"/> 



</p>

8. Now replace the public key token, copied from GAC, with the existing key highlighted in yellow color.

<SafeControl Assembly="UserControl_WebPart, Version=1.0.0.0, Culture=neutral, 


<p style="TEXT-ALIGN: justify">PublicKeyToken=93b5b0fffa462560" Namespace="UserControl_WebPart" TypeName="*" 




</p>

<p style="TEXT-ALIGN: justify">Safe="True"/> 




</p>

9. Run the SharePoint application and open the Home Page and go to SiteAction->SiteSetings, then click the on the Modify all site Settings link.

10.Click on the Web Parts link under the Galleries section.

11. After opening the web part gallery click on new button, highlighted in the following figure.

12. Click on the upload button.

13. A new screen window will appear, where you have to provide the XML file, which you have created in the project before, and yes please change the value of attribute PublicKeyToken in the xml file.

14. After clicking on ok button of the previous screen, again new window will appears, where you can provide the value of webpart.

15. After clicking on ok button, you will go back to the webpart gallery, where you can check that your web part name appears with small new icon.

16. Click on SiteNavigation->EditPage.

17. Now click on “Add Web Part” link, as shown in the following figure.

 

18. Then a new window will appear from where you can add your web part.

 

19. Mark the check box of your web part and click on add button, after you will go back to you page, where you will find your web part.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gaurav-Mehta
Technical Lead
India India
Gaurav Mehta is from Delhi, India. He has to his credit, a Bachelor’s Degree in commerce and a Master's in Computer and Software Applications. He started his career with C and C++ and then moved on to Microsoft Technologies. He has been in this industry for more than 6.5 years. Gaurav is primarily involved in requirement analysis; designing and developing web and win apps.
 

http://www.GauravMehta.com

http://www.GauravMehtasBlog.com
 



Comments and Discussions

 
Questioni have a problem in running PinmemberAbahi22-Dec-12 2:39 
GeneralMy vote of 5 Pinmemberpksaraswat16-Sep-12 18:40 
QuestionObject reference not set to an instance of an object error [modified] Pinmemberpooneh_ce21-Dec-11 21:22 
QuestionStep 5 in the Deployment is lacking PinmemberMember 35090802-Nov-11 0:36 
QuestionFor the noobs: How to reference Microsoft.SharePoint [modified] PinmemberMember 35090801-Nov-11 20:52 
GeneralMy vote of 4 Pinmemberoma26115-Jul-10 20:46 
GeneralError in Loadcontrol PinmemberMartin Brand7-Mar-10 6:02 
GeneralRe: Error in Loadcontrol PinmemberMlsoun2-Jun-10 21:27 
GeneralRe: Error in Loadcontrol Pinmemberazamqadri16-Nov-10 16:52 
GeneralGood Article PinmemberSakshi Smriti8-Jan-10 0:07 
GeneralSmartParts - way to go Pinmembershridha_agarwal12-Nov-09 19:59 
GeneralVery helpful PinmemberShailendra Arusiya11-Nov-09 23:58 
GeneralExellent PinmemberPoonam S11-Nov-09 23:49 
GeneralWSPBuilder Template PinmemberKenrik11-Nov-09 20:33 
GeneralRe: WSPBuilder Template Pinmembershridha_agarwal12-Nov-09 19:55 
GeneralNice one. PinmemberRaghu Karupakala11-Nov-09 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 11 Nov 2009
Article Copyright 2009 by Gaurav-Mehta
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid