WebParts in ASP.NET 2.0

No.of Views997
Bookmarked0 times
Downloads 
Votes0
By  Paru   On  16 Feb 2010 02:02:41
Tag : ASP.NET , Web Parts
WebParts in ASP.NET 2.0
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Web Parts are objects in the Portal Framework which the end user can open, close or move from one zone of the page to another. Web Parts are included in ASP.NET server control framework and are used like any other ASP.NET server controls. You can also build your own custom Web Parts.
A web part is different from a frame in so far as it is not filled with content by accessing an URL. It is a server side control that is served to the browser as plain HTML and is populated with content grabbed from external sites using HTML scarping or web services.

Building pages with Web Parts:

Listed are the components employed by the web parts framework for performing specific functions.

1. The WebPartManager manages all the web parts on a page and is invisible at runtime.

2. The WebPart is the content container that the user sees. This is an abstract class and the developer has to create his own webpart through inheritance or through other user controls.

3. The WebPartZone controls and provides an overall layout for the webpart controls it contains. A page can have one or more zones.

4. The CatalogPart is the base class for catalog WebPart controls that present a list of available web parts to users. The classes that are derived are ImportCatalogPart, DeclarativeCatalogPart and PageCatalogPart.

5. CatalogZone is a container for CatalogPart controls.

6. The ConnectionsZone is a container for the connections defined between pairs of webparts found on a page.

7. The ImportPart provides the base class for editing controls that allow modifications to webparts. It has its own interface and allows users set properties.

8. EditorZone is a container for the EditorPart control. 

Web Part Display Modes

There are four display modes

Browser mode

The View mode is the mode that is normally displayed to the end users. In this mode a web part can be maximized, minimized or closed. It can also be removed from the page but does not get deleted. It gets stored in the catalog for future retrieval.

Catalog mode

The Catalog mode is used to store web parts that are to be added or are removed from a page. The developer will have to define a zone called the CatalogZone and add a ZoneTemplate. A PageCatalogPart control template will have to be added to the zone to enable users to add and remove web parts from the zone. If new or user defined controls have to be added to a Zone, one or more TemplateCatalogParts will have to be implemented. Each instance of this control type represents a control group. Controls pertaining to that group can be added to the control by using the template.

Edit mode

The Edit Zone is displayed the instant the WebPartManager kicks into action. The zone contains a ZoneTemplate to store the content. The AppearanceEditorPart users can define the appearance of the web part. The LayouteditorPart provides settings for status of the Web Part—minimized, maximized or closed. The BehaviourEditorPart is used to update the behavior of a Web Part. The PropertyGridEditorPart control offers flexibility and can handle custom properties of a Web Part control. The developer needs to set the changeable property to true so that these controls can modified through the Web using this attribute.

Design mode.

The Design mode enables the developer, place his controls in specific locations and design the look and feel of the page visually. Often the web parts are placed within zones. The zones are placed within table cells and take over the display of content to be shown. Each zone has a ZoneTemplate assigned to it. These templates can be edited within VS.NET. A number of server controls can be added including user controls as contents to the Zone. These controls can now be treated as web parts and the user can switch them off and on at will. If more than one control is added to a zone the ContentWebPart control is recommended for use. This contains one ContentTemplate, which can be edited visually in the IDE.

Connect Mode

In the sample I have not included Connect mode.
This mode allows webparts to communicate with each other. We can make static connections once (in our code) or we can allow users to create connecttions at runtime according to their needs. The Connection mode doesn’t mean mean that the webpart is connecting to a database rather means it is connected to other webparts. For example if a webpart contains a grid, used to display some records and we want to filter it on the users input, then we could use a textbox in another webpart, which would send the filter criteria text by using the connect mode.

 

Please try this out:
In our example we will place two WebParts on a page. One will be for the user input and the other for showing it. In your web project create two user controls - one will be named Provider and other Consumer. Place these two controls in webparts. Add a new class in the App_Code directory and name it ITextProvider. Paste the following code in it.

public interface ITextToPass
{
string GetText();
}


We are going to use this interface in both Provider and Consumer user controls to pass text between these two entities. Place a textbox in the Provider user control and paste the following code in the code behind. 

public partial class ProviderWebPart :

System.Web.UI.UserControl, ITextToPass
{
[ConnectionProvider("TextToPass", "TextProvider")]
public ITextToPass GetTextTransferInterface()
{
return ((ITextToPass)(this));
}

public string GetText()
{
return TextBox1.Text;
}
}

As you can see we are implementing the ITextToPass interface which we have just created. By using this interface we return text entered in the TextBox to pass it to the Consumer user control. We also used the ConnectionProvider attribute which exposes a webpart connection point. For more details about that you can read the following article.
Next place a Label in the Consumer webpart and paste the following code in its .cs file.

[ConnectionConsumer("Text", "TextConsumer")]
public void GetTextTransferInterface(ITextToPass provider)
{
Label1.Text = provider.GetText();
}

 The Consumer Connection point doesn’t return any value. It utilizes the value from the provider by using the ITextToPass interface. Now on selecting the connection mode from the WebpartManager, we can see the connect option in the webpart’s menu.

Image Loading

For the sake of simplicity I have changed the text of the button. When we click connect from the menu we will see following screen.

Image Loading

Click on the Create a connection to a Consumer and you will see the following screen. Select the webpart as a consumer from the dropdownlist.

Image Loading

Once you are connected you will see the following screen, which allows you to enter the text to pass to the Consumer - enter string A String. 

Image Loading

Once you have pressed the Pass Text To Other Webpart button you will see in the following screen that the Consumer webpart shows the passed text in a Label control. 

Image Loading

This way we can pass values from one webpart to another. As I mentioned earlier we can set static connections in our code, so users will not be able to set the Provider and Consumer by themselves. 

Saving the Page State

Before we run the project, one question that arises in my mind is: where is this page settings going to be saved for every user? Any page setting modified by the users will remain as it is; these settings are saved in a database. In our scenario we are going to use the built in login and sign up controls. Lets get started:
First of all you should set the authentication mode to Forms in your Web.Config file. Then add a new webform to your project called Login.aspx. Drag and drop a login control in it, and set the DestinationPageUrl property of it to default.aspx. Add another webform to your project called Signup.aspx - drag and drop the CreateUserWizard control on this page, so that users can easily register. Also make sure that the Sql Express service is running. We are going to use the default asp.net database called ASPNETDB.mdf which is automatically created in applications app_data folder. This database already has the appropriate schema to save the page state for every user. The screenshot below shows how you should see your database in the Visual Studio explorer.

Image Loading

The table aspnet_PersonalizationPerUser is used to saves the page settings for every user. It is saved in serialized format, in the PageSettings field. Luckily we do not need to touch that table at all, because asp.net 2.0 provides us with the necessary Personalization API. 

Setting Up the Database

To create the database to store our page settings, run the utility named as aspnet_regsql.exe. It is located in the \Windows\Framework\v2.0.50727 folder. This utility helps us create the tables and stored procedures required to create the database. Following is the screenshot of the wizard provided by this utility: 

Image Loading

The last thing that is left is to change and add some settings in the web.config. Below is how your web.config should look like. It basically enables the Membership and profiles features, which we need for our purpose. Please note that I have also used the <Clear/> tag in the membership and providers tag to remove the settings from the machine.config. Other than that I also added a connection string to my database called Database1.

<connectionStrings>
<clear/>
<add name="LocalSqlServer"
connectionString="data source=127.0.0.1;database=Database1;
user id=sa ;password=sa"/>
</connectionStrings>
<system.web>
<compilation debug="true"/>
<authentication mode="Forms" />
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
applicationName="/CustomConnections" />
</providers>
</membership>

<profile enabled="true" defaultProvider="TableProfileProvider">
<providers>
<clear/>
<add name="TableProfileProvider"
type="Microsoft.Samples.SqlTableProfileProvider"
connectionStringName="LocalSqlServer"
table="asdspnet_Profile"
applicationName="/CustomConnections"/>
</providers>
</profile>
</system.web>

Advantages of using WebParts

A significant advantage that accrues to the developer is the functionality available for page development. The Visual Studio.NET drag and drop creation and configuration of web parts in the visual designer, is a great boon. It improves speed of development.

Any existing ASP.NET control can be used as a Web Part control. Customized WebParts can also be created by deriving them form the WebPart class. If the visual designer is packaged with the control, any user can just drag and drop the control and configure it at design time without writing a single line of additional code.

Web Application development is made rapid as you can use web parts to create fully integrated, personalizable web applications.

The standalone application could be packaged with a complete set of WebPart controls that the user can configure and personalize.

Happy Coding.

Sample Project Source

Download source files -1000 kb

 
Sign Up to vote for this article
 
About Author
 
Paru
Occupation-Not Provided
Company-Not Provided
Member Type-Fresh
Location-Not Provided
Joined date-31 Jul 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top