Click here to Skip to main content
15,861,366 members
Articles / Web Development / ASP.NET

SharePoint - .Asp.net user control as a Webpart

Rate me:
Please Sign up or sign in to vote.
4.85/5 (12 votes)
11 Nov 2009CPOL4 min read 71.5K   714   24   16
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.

Image 1

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.

Image 2

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

Image 3

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

Image 4

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.

Image 5

 

Image 6

 

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.

Image 7

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).

Image 8

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

Image 9

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.

Image 10

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

Image 11

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.

Image 12

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

Image 13

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

Image 14

12. Click on the upload button.

Image 15

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.

Image 16

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

Image 17

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.

Image 18

16. Click on SiteNavigation->EditPage.

Image 19

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

Image 20

 

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

Image 21

 

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.

 Image 22

License

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


Written By
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 Pin
Abahi22-Dec-12 2:39
Abahi22-Dec-12 2:39 
GeneralMy vote of 5 Pin
pksaraswat16-Sep-12 18:40
pksaraswat16-Sep-12 18:40 
QuestionObject reference not set to an instance of an object error Pin
pooneh_ce21-Dec-11 21:22
pooneh_ce21-Dec-11 21:22 
QuestionStep 5 in the Deployment is lacking Pin
navyjax22-Nov-11 0:36
navyjax22-Nov-11 0:36 
QuestionFor the noobs: How to reference Microsoft.SharePoint Pin
navyjax21-Nov-11 20:52
navyjax21-Nov-11 20:52 
GeneralMy vote of 4 Pin
Manoj Ahlawat5-Jul-10 20:46
Manoj Ahlawat5-Jul-10 20:46 
GeneralError in Loadcontrol Pin
Martin Brand7-Mar-10 6:02
Martin Brand7-Mar-10 6:02 
GeneralRe: Error in Loadcontrol Pin
Mlsoun2-Jun-10 21:27
Mlsoun2-Jun-10 21:27 
GeneralRe: Error in Loadcontrol Pin
azamqadri16-Nov-10 16:52
azamqadri16-Nov-10 16:52 
GeneralGood Article Pin
Sakshi Smriti8-Jan-10 0:07
Sakshi Smriti8-Jan-10 0:07 
GeneralSmartParts - way to go Pin
shridha_agarwal12-Nov-09 19:59
shridha_agarwal12-Nov-09 19:59 
GeneralVery helpful Pin
Shailendra Arusiya11-Nov-09 23:58
Shailendra Arusiya11-Nov-09 23:58 
GeneralExellent Pin
Poonam S11-Nov-09 23:49
Poonam S11-Nov-09 23:49 
GeneralWSPBuilder Template Pin
Kenrik11-Nov-09 20:33
Kenrik11-Nov-09 20:33 
GeneralRe: WSPBuilder Template Pin
shridha_agarwal12-Nov-09 19:55
shridha_agarwal12-Nov-09 19:55 
GeneralNice one. Pin
RK KL11-Nov-09 4:17
RK KL11-Nov-09 4:17 

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

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