Search This Blog

Monday, January 19, 2015

Developing Web Part using Web User Control.

1-Overview

In this article we will see how to create web user control (.ascx file) and wrap it inside SharePoint web part. This will significantly save time in developing web part and it helps to resolve child-control-level errors within web part.
Versions supported:
Windows SharePoint services
Windows SharePoint Portal Server
MOSS 2007/SP2010
Steps:
Now, we first go with developing web user control (brief) then we’ll move on creating web part.
A. Creating web user control

1) create new web application
2. Add new item > User control
3. Add controls you want in user control on web part.
We have added following code on button click event.
lblMsg.Text = "<b>Details:<b> " + "<br />" +
            "Name: " + txtName.Text + "<br />" +
            "Address:" + txtAddress.Text + "<br />" +
            "City: " + txtCity.Text;  

4. Add user control on aspx page and test it.
5. Output may look like.
 Why UserControl in Web part?
  • Good thing is web part using Usercontrol is easy to create and error on web part will be more specific and displays within web part (Using response.write () method).
  • Moreover you need to change only the GUID and Path of the Usercontrol (.ascx files) if you want to deploy any user control in web part.
  • Compile and Deploy time overhead reduced. Yeah, that’s true. If you want to modify anything in web part just modify aspx page and code in .CS file from layout folder (where we deploy usercontrol files) and u all set. No need to put dll in GAC, bin no IISRESET nothing.   
Now, let’s see how we can plug this user control inside web part of SharePoint.

B. Create Web Part Project
1. Open visual studio 2005
2. Create new project of type ‘Web Part’.
3. Load User Control in Web Part Project.
  • Declare variables
Control_myControl;                                                                  String err;     

Declare variable err of type String
In Render method write the statement
_myControl.RenderControl(writer);


Write method definition for CreateChildControls
protected override void CreateChildControls()

Write body for CreateChildControls
this.Controls.Clear ();
myControl = this.Page.LoadControl("\\_layouts\\WebUserControl.ascx");
this.Controls.Add (_myControl);

4. Deploy Web Part
Note: In latter articles we’ll see how to create and deploy web part and related stuff.
  • Copy WebUserControl.ascx and WebUserControl.ascx.cs files in following directory :
 C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS
  • Copy UserControl.dll from   > Desktop\UserControl\UserControl\obj\Debug
And put it inside BIN directory of your SharePoint site. Drag and drop dll to GAC (Run > c:\windows\assembly)
  • Add <Safecontrol> entry to web.config
<SafeControl Assembly="UserControl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" Namespace="UserControl" TypeName="*" Safe="True" />

  • Go to Sitesettings > Modify all Settings > gallery > web part > New and populate new control to gallery.

  • Reset IIS ( Run > cmd > iisreset)
  • New web part is ready to use on any page.

Sample code:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace UserControl
{
    [Guid("A1B4DDEA-0CC1-40c8-91B1-339D161E7F45")] // your GUID here.

// Goto tools > create GUID

   public class UserControl : System.Web.UI.WebControls.WebParts.WebPart
    {
        //Variables
       
  Control _myControl;
        String err;

        public UserControl()
        {
            this.ExportMode = WebPartExportMode.All;

// Specifies whether all, some, or none of a WebPart control's properties can be exported.
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                _myControl.RenderControl(writer);
            }
            catch (Exception e)
            {
                writer.Write(e.Message + " : " + err);
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                this.Controls.Clear();
                _myControl = this.Page.LoadControl("\\_layouts\\WebUserControl.ascx");
                this.Controls.Add(_myControl);
            }
            catch (Exception e)
            {
                err = e.Message;
            }
        }
    }
}


2-   

Add a Custom User Control to a SharePoint 2010 Master Page

Creating a Custom User Control has some advantages:
  • They can be placed where you want them – not like Web Parts.
  • They can easily be shown / hidden depending on the current Page using Code.
One Problem that you might be facing: How to use the SharePoint Object Model within a User Control? This can be solved using the following code snippet:
            using (SPSite site = new SPSite(Request.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // Your Code Here!
                }
            }
1. Create an Empty Visual Studio 2010 Project

2. Add a User Control to the Project

3. Deploy the Project to SharePoint 2010
4. Add the User Control to the Master Page
First you have to Register the User Control:

<%@ Register TagPrefix=”myControl” TagName=”CurrentPageControl” Src=”~/_controltemplates/MasterPageControl/CurrentPageControl.ascx” %>
Then you can add the Control to the Page:
<myControl:CurrentPageControl ID=”myControl” runat=”server” />

No comments:

Post a Comment