Monday, September 13, 2010

User Control vs. Custom Control in ASP.NET

ASP.NET provides two models of creating web controls  – user controls and custom controls.

In this article, we will discuss about following points.

1. What is User Control?
2. What is Custom Control?
3. What is the difference between User Control and Custom Control?
4. How to select appropriate Web Control out of two?

Go through the following explanation of all points.

1. What is User Control?
 
User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. These are custom, reusable controls, and they use the same techniques that are employed by HTML and Web server controls. They offer an easy way to partition and reuse common user interfaces across ASP.NET Web applications. They use the same Web Forms programming model on which a Web Forms page works.

How to create a user control

The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the <html>, <body>, and <form> elements since a Web Forms page hosts the user control. To create a user control, follow these steps:

• Open a text or HTML editor, and create a server-side code block exposing all the properties, methods, and events.
<script language="C#" runat="server">
public void button1_Click(object sender, EventArgs e)
{
          label1.Text = "Hello World!!!";
}
</script>
• Create a user interface for the user control.
<asp:Label id="label1" runat="server"/>
<br><br>
<asp:button id="button1" text="Hit" OnClick="button1_Click" runat="server" />

How to use a user control in a Web Forms page

• Create a new Web Forms page (.aspx) in Microsoft Visual Studio .NET 2002, Microsoft Visual Studio .NET 2003, Microsoft Visual Studio 2005, or any text editor.

• Declare the @ Register directive. For example, use the following code.
<%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>
Note Assume that the user control and the Web Forms page are in the same location.

• To use the user control in the Web Forms page, use the following code after the @ Register directive.
<html>
<body>
<form runat="server">
<UC:TestControl id="Test1" runat="server"/>
</form>
</body>
</html>

How to create an instance of a user control programmatically in the code behind file of a Web Forms page

The previous example has instantiated a user control declaratively in a Web Forms page using the @ Register directive. However, you can instantiate a user control dynamically and add it to the page. Here are the steps for doing that:

1. Create a new Web Forms page in Visual Studio.

2. Navigate to the code behind file generated for this Web Forms page.

3. In the Page_Load event of the Page class, write the following code.

// Load the control by calling LoadControl on the page class.
Control c1 = LoadControl("test.ascx");

// add the loaded control in the page controls collection.
Page.Controls.Add(c1);
Note You can add a user control dynamically at certain events of the page life cycle.

How a user control is processed

When a page with a user control is requested, the following occurs:

• The page parser parses the .ascx file specified in the Src attribute in the @ Register directive and generates a class that derives from the System.Web.UI.UserControl class.

• The parser then dynamically compiles the class into an assembly.

• If you are using Visual Studio, then at design time only, Visual Studio creates a code behind file for the user control, and the file is precompiled by the designer itself.

• Finally, the class for the user control, which is generated through the process of dynamic code generation and compilation, includes the code for the code behind file (.ascx.cs) as well as the code written inside the .ascx file.

2. What is Custom Control?

Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does.

How to choose the base class for your custom control

To write a custom control, you should directly or indirectly derive the new class from the System.Web.UI.Control class or from the System.Web.UI.WebControls.WebControl class:

• You should derive from System.Web.UI.Control if you want the control to render nonvisual elements. For example, <meta> and <head> are examples of non-visual rendering.

• You should derive from System.Web.UI.WebControls.WebControl if you want the control to render HTML that generates a visual interface on the client computer.

If you want to change the functionality of existing controls, such as a button or label, you can directly derive the new class with these existing classes and can change their default behavior.

In brief, the Control class provides the basic functionality by which you can place it in the control tree for a Page class. The WebControl class adds the functionality to the base Control class for displaying visual content on the client computer. For example, you can use the WebControl class to control the look and styles through properties like font, color, and height.

How to create Custom Control

• Create Class Library project in Visual Studio.

• Add new class to your project called SimpleLabel, and derive SimpleLabel from the ‘System.Web.UI.Control’ class. It will create ‘SimpleLabel.ascx’ and ‘SimpleLabel.ascx.cs’ files.
public class SimpleLabel : Control {}

• Add some functionality to the class.
protected override void Render(HtmlTextWriter writer)
{
          writer.Write("Hello World from custom control");
}

• Compile the class library project. It will generate the DLL output.

• Open an existing or create a new ASP.NET Web application project.

• Add a Web Forms page where the custom control can be used.

• Add a reference to the class library in the references section of the ASP.NET project.

• Register the custom control on the Web Forms page.
<%@ Register TagPrefix="CC " Namespace=" CustomServerControlsLib " Assembly="CustomServerControlsLib " %>

• To instantiate or use the custom control on the Web Forms page, add the following line of code in the <form> tags.
<form id="Form1" method="post" runat="server">
<CC: SimpleLabel id="ctlSimpleControl" runat="server">
</CC: SimpleLabel >
</form>

• Run the Web Forms page, and you will see the output from the custom control.

3. What is the difference between User Control and Custom Control?
 
FactorsUser ControlCustom Control
CreationCreation is similar to the way Web Forms pages are created; well-suited for rapid application development (RAD)Writing involves lots of code because there is no designer support
ContentA much better choice when you need static content within a fixed layout, for example, when you make headers and footersMore suited for when an application requires dynamic content to be displayed; can be reused across an application, for example, for a data bound table control with dynamic rows
DesignWriting doesn't require much application designing because they are authored at design time and mostly contain static dataWriting from scratch requires a good understanding of the control's life cycle and the order in which events execute, which is normally taken care of in user controls
DeploymentDesigned for single-application scenarios

Deployed in the source form (.ascx) along with the source code of the application

If the same control needs to be used in more than one application, it introduces redundancy and maintenance problems
Designed so that it can be used by more than one application

Deployed either in the application's Bin directory or in the global assembly cache

Distributed easily and without problems associated with redundancy and maintenance
Locationwe have to use it within the application and it rests in the application directorywe can keep it in the Toolbox and use it whenever we want
 
4. How to select appropriate Web Control out of two?

The single most important factor is how the control will be used – will the control be application specific or generic and redistributable? If the control is application specific and contains a lot of static layout, such as a site header and footer, a user control would make sense. If the control is generic, redistributable, and contains dynamic layout, such as the server controls that ship with the .NET SDK, then a custom control would be more suitable.

Read more on my other blogs also:
Web Controls
Infix to Postfix Conversion
SharePoint 2010 Overview

Web Controls in ASP.NET

When we drag a control from the Web Controls section of the toolbox onto a form, VS.NET automatically gives the tag a runat=”server” attribute and an ID. The IDE also automatically adds a protected field to our code behind class for us to interact with the control programmatically. In the following example we have dragged a TextBox control onto the web form, and adjusted the appearance using the Properties window of the web form designer.


<asp:TextBox id="TextBox1" runat="server" Font-Names="Courier New"/>

We can also interact with this control from code behind.

protected System.Web.UI.WebControls.TextBox TextBox1;
private void Page_Load(object sender, System.EventArgs e)
{
          TextBox1.Text = "Foo Berry Tea";
          TextBox1.BackColor = Color.LightGray;
          TextBox1.ForeColor = Color.Red;
}

Notice the web control version of a textbox operates at a slightly higher level of abstraction when compared to the HTML control. For example, the TextBox control has properties to set the colors (BackColor, ForeColor). We don’t need to know how to use inline styles – the code for the control will take care of rendering the correct HTML to achieve the desired appearance in the client’s web browser.

The web controls section of the toolbox also offers some controls you won’t find in pure HTML. These controls, like the RegularExpressionValidator, produce a combination of HTML and JavaScript on the client to offer more functionality than you can get from available HTML controls.

The web control approach is object oriented, easier to use server-side, and more robust than using HTML controls. Since everything in software development has a trade-off, you might be wondering what the downside to using a web control is (some may say the trade-off is performance, but in reality the overhead of using a web control is almost negligible). There really is no downside to using web controls over HTML controls – we should always favor using the web control.

The next question then might be: why did Microsoft give us two sets of controls if web controls are always superior? One answer might be that HTML controls offer a path for porting HTML and ASP applications to .NET. Just give an HTML tag a runat and ID attribute and one can start using the control from code-behind. Another answer is that we can still find scenarios where HTML controls are useful in brand new .NET applications.

Tuesday, September 7, 2010

SharePoint Object Model

SharePoint Object Model is the way of accessing, creating, deleting the SharePoint lists, document libraries, features, meetings, subsites, etc through the visual studio code. It uses SharePoint hierarchy from SPSite to SPField for the same.


There are several namespaces (around 50) that house the SharePoint object model. Out of these 50 namespaces we are using only 16 namespaces, rest of the namespaces are reserved for Microsoft internal use.
SharePoint Object Model is used for operations on following fields:
  • Document Library
  • Lists
  • Features
  • Meetings
  • Sites
  • Solutions
  • User Profiles
  • Business Data Catalog

Refer the following diagram to get an idea about SharePoint Object Model overview.
Above diagram shows how the SharePoint List is accessed using SPSite, SPWeb objects.
Let’s see how the SharePoint Object Model is used for every SharePoint entity.

1) Document Library:

NameSpace: Microsoft.Sharepoint

Classes: SPDocumentLibrary, SPPictureLibrary

Document libraries are a special type of list designed to store documents. To access a document library through object model we need to use Microsoft.Sharepoint namespace. To use this namespace in ASP.net we need to add a reference of Microsoft.Sharepoint.dll. This dll we can find from the below mentioned path:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

Lets take each and every class in this namespace:
          In C# code: SPDocumentLibrary obj = (DocumentLibrary)oList.
         oList is an object for list. The above code will cast the list object into Document Library.
  • SPPictureLibrary Class: This class represents a picture library in Windows SharePoint Services. Both classes are used in the same manner.
         In C# code: SPPictureLibrary oPictureLibrary = (SPPictureLibrary)list;

         The only difference is: As the name indicates SPDocumentLibrary is used for Document Library and   SPPictureLibrary is used for Picture Library.
         Code Example:


2) Lists:

NameSpace: Microsoft.Sharepoint

Classes: SPList, SPListItem, SPLIstItemCollection

SPList object represent a List, SPListItem represent a List Item in the List and SPListItemCollection object represent a full item collection in the SPLIST.
  • SPList: Represents a list on a Microsoft SharePoint Foundation Web site.
  • SPListItem: Represents an item or row in a SharePoint list.
  • SPListItemCollection: Represents a collection of SPListItem objects
Code Example:


3) Features:

NameSpace: Microsoft.Sharepoint

 
Classes: SPFeatureDefinition, SPFeatureScope, SPElementDefinition, SPFeature, SPFeatureProperty

 
For using the features through SharePoint object model we need Microsoft.Sharepoint dll and you can get the dll from the above mentioned path.
  • SPFeatureDefinition Class: Contains the base definition of an SPFeature, including its name, identifier, scope, and version
  • SPFeatureScope Class: Specifies the scope to which the feature applies.
  • SPElementDefinition Class: Serves as the base class for implementing element types within Windows SharePoint Services
  • SPFeature Class: Represents the state of a feature at its corresponding scope
  • SPFeatureProperty Class: Represents a single Feature property.
Code Example:

 

4) Meetings:
NameSpace: Microsoft.Sharepoint.Meetings

Classes: SPMeetings, MtgUtility
For using meetings through object model we need to add Microsoft.Sharepoint dll as mentioned above. The classes under this category are explained as below:
SPMeeting Class: - Provides methods and properties that can be used to work with a Meeting Workspace. Suppose if you want to create a meeting workspace through object model then we need to use this class. There are different kind of meeting template that can be handled like Basic meeting, Decision Meeting, Multiple meeting etc.
MtgUtility: - Initialize a new instance of the MtgUtility class. To access the MtgUtility service and its methods, set a Web reference to http://Server_Name/[sites/][Site_Name/]_vti_bin/xxx.asmx.
Code Example:


5) Sites:


NameSpace: Microsoft.Sharepoint, Microsoft.Sharepoint.Administration (only for SPSiteCollection)

Classes: SPSite, SPSiteCollection, SPWeb

Sites objects are used to access the SharePoint site, the classes under this category of SharePoint Object model are explained as below:

SPSite: Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.

SPWeb: Represents a Windows SharePoint Services Web site

SPSiteCollection: Represents a collection of SPSite objects or site collections that are associated with a particular Web application, including a top-level Web site and all its sub-sites. Each SPSite object, or site collection, is represented within a SPSiteCollection objects that consists of the collection of all site collections in the Web application.

Code Example:

 
6) Solutions:


NameSpace: Microsoft.Sharepoint.Administration

Classes: SPSolution, SPFeatureReceiver, SPSolutionCollector

It provides administrative types and members for managing a Windows SharePoint Services deployment. There are so many classes, delegates, interface under this namespace.

SPSolution: Represents a solution on a farm.

SPFeatureReceiver:
Base abstract class that can be overridden to trap the activation, deactivation, installation, or uninstallation of a Feature.
Use the SPFeatureReceiver class to trap events that are raised after the Feature installation, uninstallation, activation, or deactivation action has been performed.
It is not possible to cancel an installation or uninstallation through Feature events.

SPSolutionCollector: Represents a collection of SPSolution objects.

7) User Profiles:

NameSpace: Microsoft.Office.Server.UserProfiles

Classes: UserProfile, UserProfileManager

UserProfile: Represents a user profile for a person in the user profile database

UserProfileManager: A collection of UserProfile objects used to access user profile data. To access a specific user profile, call the UserProfileManager class to create a UserProfile object and retrieve the corresponding data from the user profile database.

Code Example:


8) Business Data Catalog:


NameSpace: Microsoft.Office.Server.ApplicationRegistry.Administration

Classes: EntityCollection, ApplicationRegistry

EntityCollection: Represents a collection of Entity objects. Provides methods to create and enumerate entities.

ApplicationRegistry: Provides access to all of the line-of-business (LOB) systems and LOB system instances registered in the Business Data Catalog. This is the top-level object in the Business Data Catalog's object model. It is the entry point for you to create, read, update and delete all the metadata objects including LobSystem, Entity and Method. The ApplicationRegistry object has its own ACL and a user should at least have the Edit right on it to create a new LobSystem.


Memory issues with the Object Model:

• Management of these objects should be done with care. They use unmanaged resources, especially SPSite and SPWeb, so Dispose must be called at the finally block or else your application will leak memory.

• Another important memory issue involves the SharePoint indexing. Playing around with the code you probably noticed that everything is grouped into collections, such as the Sites collection and the Lists collection and can be accessed through indexing (i.e. Sites[i]). Well, under the hood SharePoint creates a new instance for each index and each of them needs to be disposed separately. This means that very easily, by a simple if (Sites[i] != null) you're leaking an object.MS came out with a tool called ‘SPDisposeCheck to help manage the SP objects.

You can visit my others blogs also related to SharePoint:
 
Checkpoints for creating Custom Event Handlers
Strong Named Assembly in SharePoint
SharePoint 2010 Overview