Wednesday, October 15, 2008

web parts in asp.net 2.0

http://dotnetslackers.com/articles/aspnet/UsingWebPartsInASPNet20.aspx


Using WebParts in ASP.Net 2.0

Published: 28 Feb 2007
By: Abdul Sami

This article describes various aspects of using webparts in asp.net 2.0.
Introduction

It would not be wrong to say that Webparts are going to be the future of web based management systems. WebParts give us the option of dragging and dropping of objects on a page as well as, changing titles and border style properties of objects at runtime. Before the introduction of WebParts it was used to be a hectic task because we had to write a lot of JavaScript and had to save the state of objects in a database.

There are two basic things in WebParts:

* WebPart manager
* WebPart zones

WebPartManager

The WebPartManager is the manager for all webparts. If you use webparts in your web projects you are required to use the WebPartManager. Usually you just drag and drop this into your webform and are ready to go.
WebPart Zones

There are four kinds of zones in webpart zones:

* WebPart Zone
* Editor Zone
* Catalog Zone
* Connection Zone

WebPart Zone

The webpart Zone is the basic unit for webparts. By placing different contents in a webpart zone we can allow a user to drag and drop contents on a page.

To use different zones add a dropdownlist to your webform and add the following items to it.

* Browse
* Display
* Edit
* Catalog
* Connect

Paste the following code in the SelectedIndexChanged event of the dropdownlist (this assumes the dropdownlist’s id is cmbOptions and the webpart Manager’s id is WebPartManager1).

if (cmbOptions.SelectedValue == "Design")
{
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
else if (cmbOptions.SelectedValue == "Browse")
{
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
}
else if (cmbOptions.SelectedValue == "Catalog")
{
WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}
else if (cmbOptions.SelectedValue == "Edit")
{
WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
}
else if (cmbOptions.SelectedValue == "Connect")
{
WebPartManager1.DisplayMode = WebPartManager.ConnectDisplayMode;
}

Browse mode

The Browse mode is the default mode of webparts. In Browse mode we can not drag and drop the webparts but we can see two options, minimize and close. Minimizing a webpart will still display it in minimized state. If you choose close then it can only be restored while being in catalog mode which we will discuss later in this article. Here’s a sample webpart being displayed in Browse mode.
Design mode

In design mode we can drag drop objects between webparts. There are two webparts named as Links and Search. The following screenshot shows the Links webpart being dragged over the Search one.

Edit Mode

The edit mode is used to edit webparts at runtime. Editing a webpart is further divided into four types: Appearance, Behavior, Property and Layout. We will first see how to use the Appearance and LayoutEditorPart.
AppearanceEditorPart and LayoutEditorPart

First, place an editor zone into the web form. Then place an AppearanceEditorPart and LayoutEditorPart inside the editor zone. Run the application and select the edit mode from the dropdownlist. Click edit from the menu available for webparts.

You will see following output.

We can change the title of the webpart here. We can also see some basic options in the edit mode. Chrome type is the border and title style. The Chrome state gives you the option of minimizing it or not.
PropertyGridEditorPart

By using the property editor we can change the properties of the objects in our webparts. In our example we are going to change the CSSClass property of the object. To use this we will follow the same method as explained in the AppearanceEditorPart and LayoutEditorPart section.

Place an editor zone into the web form. Then place a PropertyGridEditorPart inside the editor zone. To use the editor zone add a new user control into your project. Place a textbox in the user control and place this user control inside the webpart of the web form. In the code behind of user control paste the following code.

string _cssClass = "FrmTxtBox";
[WebBrowsable(), Personalizable(true)]
public string CssClass
{
get { return _cssClass; }
set { TextBox1.CssClass= value; }
}

protected void Page_Load(Object sender, EventArgs e)
{
TextBox1.CssClass = CssClass;
}

The above code changes the CssClass of the TextBox. This property will now be available in the webparts edit mode and we will be able to change this at run-time as well. Besides setting the CssClass we have also used two additional attributes in the class declaration:

* WebBrowsable - It allows a webpart to display a user defined property in edit mode.
* Personalizable - It allows a property to be editable.

Now run this page. If we choose the edit mode from the webpart menu, we will see the following edit button in options menu of the webpart. The screenshot below illustrates this.

On selection of the edit link from the webpart menu we will have the CssClass property in edit mode. The screenshot below displays what it would look like:

As we can see this TextBox is using FrmTxtBox as the default class. It is defined in a stylesheet with attributes of border color in black. We can now apply a different class which I have named as CustomClass1, which has no border. After changing the CssClass name, press the OK button and you will see the textbox with the new border style.

This way we change the properties of objects used inside the webparts.
Catalog mode

The Catalog mode gives us the option to add/remove webparts at runtime. For example if we have few modules like weather, news, shopping, horoscope etc. and want to give the user an option to show or hide these modules at runtime, we can accomplish this task using the catalog mode.
CatalogZone

The CatalogZone is divided into three subtypes: PageCatalogPart, DeclarativeCatalogPart and ImportCatalogPart. On the webform add a CatalogZone and add the previous mentioned three types into it. We can show webparts with the help of the Pagecatalog which are closed by using the close option of the webpart, as seen in following screenshot.

The PagecatalogPart displays the number of webparts which are closed by using this option. The DeclarativeCatalogPart displays the number of elements which are added in design mode to the catalog zone. Click on the smart tag option of the DeclarativeCatalogPart zone and select edit template, then add controls into the catalog zone.

ImportCatalog

The ImportCatalog displays the number of elements which have been selected for import. We can import files with the extension .WebPart. To export a file as a .WebPart type add the following line to your web.config.



Then we can follow one of these two methods:

* Set the ExportMode property of the control to All. If your control is derived from webpart, you can do this in markup as shown in the following example.



* Or writing the following code during PageLoad.

GenericWebPart gwp = WebUserControl2_1.Parent;
gwp.ExportMode = WebPartExportMode.All;

Now we can add any of these webparts to our webform, by selecting the control and the zone where we want to add it. The screenshot below illustrates this:
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.

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.

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.

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.

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.

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.

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.

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:

This wizard creates the following tables in database which we select during this wizard:

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



connectionString="data source=127.0.0.1;database=Database1;
user id=sa ;password=sa"/>







type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
applicationName="/CustomConnections" />






type="Microsoft.Samples.SqlTableProfileProvider"
connectionStringName="LocalSqlServer"
table="asdspnet_Profile"
applicationName="/CustomConnections"/>




Summary

Webparts provide us an easy way to customize our website at runtime. Apart from Sharepoint portal server, webparts are introduced in asp.net 2.0. I have tried to cover all the common aspects of webparts in this article, like using different types of webparts and using a custom database.
About Abdul Sami
Sorry, no bio is available

View complete profile
Top Articles in this category

JavaScript with ASP.NET 2.0 Pages - Part 1
ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and method of working with JavaScript code. This article explores the enhancements and the various ways of injecting JavaScript programmatically into ASP.NET 2.0 pages.

ASP.NET ComboBox
The ASP.NET ComboBox is an attempt to try and enhance some of the features of the Normal ASP.NET DropDownList.

Upload multiple files using the HtmlInputFile control
In this article, Haissam Abdul Malak will explain how to upload multiple files using several file upload controls. This article will demonstrates how to create a webform with three HtmlInputFile controls which will allow the user to upload three files at a time.

JavaScript with ASP.NET 2.0 Pages - Part 2
ASP.NET provides a number of ways of working with client-side script. This article explores the usage and drawbacks of ASP.NET script callbacks, and briefly presents a bird's view of ASP.NET AJAX.

An Architectural View of the ASP.NET MVC Framework
Dino Esposito introduces the ASP.NET MVC framework.

No comments: