Create and deploy user control in sharepoint using feature

Introduction

In this article I will describe that How to create and deploy user control in sharepoint using feature.

Create User Control Brief: 

We will create a very simple ASP.NET user control (.ascx) which will just display “Hello World”. To load this control in sharepoint we will create a generic webpart which can load any user control in sharepoint.

Deploy User Control Brief:

In this article I will not explain that how to deploy solution using feature. For this you can refer my previous article which explain about “Create and deploy webpart using feature”.

Here I will explain that where we should keep user control in solution structure as well as how it should be available to sharepoint when we activate feature.

Technical Details

User Control .ascx file code:-

1
2
3
4
5
6
7
8
9
<%@ control language="C#" autoeventwireup="true" inherits="Home.Project.UI.UserControls.HelloWorld, Home.Project.Solution" %>
<table>
<tbody>
<tr>
<td>Hello World.   
<asp:Label ID="lblTest" Text="" runat="server" /></td>
</tr>
</tbody>
</table>

Below point is important to write line number 1 in above code:-
namespace = “Home.Project.UI.UserControls.HelloWorld”
dll name = “Home.Project.Solution”

User Control .ascx.cs file code:-

1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.Web;
 
namespace Home.Project.UI.UserControls
{
    public partial class HelloWorld : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

Generic WebPart to load user control:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 
using System;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
 
namespace MyProjects.UI.WebParts
{
    public class GenericUserControlPicker : System.Web.UI.WebControls.WebParts.WebPart
    {
        #region Variables
 
        const string ConfigMessage = "Please provide user control path";
        const string ErrorMessage = "There is some error. Please contact Administrator.";
        private UserControl userControl;
        private string userControlPath = string.Empty;
 
        [WebBrowsable(), Personalizable(),
        WebDisplayName("User control path"),
        WebDescription("Relative path to the user control 
                       (Ex:~/_controltemplates/usercontrols/HelloWorld.ascx)")]
        public string UserControlPath
        {
            get
            {
                return userControlPath;
            }
            set
            {
                userControlPath = value;
            }
        }
 
        #endregion
 
        #region CreateChildControls
 
        ///<summary> 
        /// Create all your controls here for rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
 
            {
                base.CreateChildControls();
                this.Controls.Clear();
                if (String.IsNullOrEmpty(UserControlPath))
                {
                    HandleException(ConfigMessage);
                }
                else
                {
                    userControl = (UserControl)LoadControl(UserControlPath);
                    this.Controls.Add(userControl);
                }
            }
            catch
            {
                HandleException(ErrorMessage);
            }
        }
        #endregion
 
        #region Load user control
        ///User control path
        public object LoadControl(string controlPath)
        {
            this.Page.Title = this.Title;
            return  this.Page.LoadControl(controlPath);
        }
        #endregion
 
        #region Handle Exception
        ///<summary>
        /// add error message in web part
       /// </summary>
        public void HandleException(string Message)
        {
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(Message));
        }
        #endregion
 
    }
}

Solution Structure:-

This project should be WSP builder project, so that it will automatically add entry in webconfig like safe control entry etc…
The important point is; you should place user control under 12 or 14 hive  “/Templates/ControlTemplates/”. In this example i have created my custom folder under controltemplates. So the actual path of user control will be (considering sharepoint 2010):
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\UserControls\HelloWorld.ascx

To place your user control in above path using wsp deployment you have to keep only .ascx (not .ascx.cs) file in below structure.

solution_usercontrol

Steps to make work user control:-

1. Deploy WSP and activate feature on site…
2. Then add “GenericUserControlPicker” webpart.
3. Edit Page and modify web part property.
4. Add user control path in miscellaneous category : “~/_controltemplates/usercontrols/HelloWorld.ascx”
5. Apply and click ok.
6. Page will display Hello world.

Note: How to create webpart using feature, what is GenericUserControlPicker.webpart file, what is feature and elements.xml file? For all these questions please refer my other article “Create and deploy webpart using feature

Hope it helps.
Thanks!
Avinash

calendarApril 11, 2012 · cardInfoyen · comments2 Comments
tagTags: , , , , , , , , ,  · Posted in: MOSS, SharePoint, WebPart

2 Responses

  1. Stephen Davidson - July 8, 2012

    Hey There, great articl…although i’m getting this error when i deploy to SP?

    Error 1 Error occurred in deployment step ‘Add Solution’: Error: Cannot add the specified assembly to the global assembly cache: GenericUserControlPicker.dll.
    0 0 VisualWebPartProject5

    Any ideas?

  2. Infoyen - July 9, 2012

    Cannot Add the Specified Assembly to the GAC
    or
    Cannot add the specified assembly to the global assembly cache

    This error is not because of my solution which is provided by this post.

    However here my suggestion for this issue:-

    1. Delete the respective dll from GAC. If it says it can not removed sinces its used.
    then you have to find which process is using this dll.
    There are several tools to find. However i use “ProcessExplorer”.

    Once you are able to delete dll from gac, deploy again. error should be resolved.

    2. Please refer below articles about this issue. It might help you.

    http://social.technet.microsoft.com/Forums/en-US/sharepointadmin/thread/01846928-50a8-4061-8fbf-283dc7a2c582/
    http://social.msdn.microsoft.com/Forums/lv-LV/sharepointdevelopment/thread/9c6f4817-b61e-4e53-b049-f66824b16d57
    http://www.mstechblogs.com/paul/error-of-the-day-cannot-add-the-specified-assembly-to-the-gac

    Thanks

Leave a Reply

Spam Protection: , required

myworldmaps infoyen