Using Webparts in ASP.NET 2.0

Introduction to Web Parts in ASP.Net 2.0

Introduction

It would not be wrong to say that web parts are going to be the future of web-based management systems. Web parts give you the option of dragging and dropping objects on a page, plus changing titles, border styles, and properties of objects at runtime. Before the introduction of web parts, it used to be a hectic task because you had to write a lot of JavaScript and to save the state of contents in a database.

There are two basic things in web parts:

  • Web part manager
  • Web part zones

Web Part Manager

Web part manager is a manager for web parts behind the scene. You normally doesn't do a lot of things with web part manager either in code or in design mode.

Web Part Zones

There are four kind of zones in web parts:

  • Web Part Zone
  • Editor Zone
  • Catalog Zone
  • Connection Zone

Web Part Zone

It's a basic unit of web parts. By placing different contents in a web part zone, you can allow a user to drag and drop contents on a page.

To use different zonesm place a drop-down list and add following items in it.

  1. Browse
  2. Display
  3. Edit
  4. Catalog
  5. Connect

Write the following code on the onChangeIndex event of this drop-down list.

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;
}

1: Browse mode

Browse mode is the default mode of web parts. In browse mode, you cannot drag and drop the web parts but you can see two options, minimize and close. Minimizing a web part will still show it, but in a minimized state.

If you select close, it can be restored only in catalog mode. You will see later in this article how to use that.

2. Design mode

In design mode, you can drag drop objects between web parts as you can see in the following screenshot. There are two web parts named "links" and "Search."

3. Edit mode

In edit mode, you can edit web parts at runtime as well. Editing a web part is further divided into four types: Appearance, Behavior, Property, and Layout. You will see first how to use the Appearance and LayoutEditor parts.

AppearanceEditorPart & LayoutEditorPart

  1. Place editor zone on the page.
  2. Place AppearanceEditorPart and LayoutEditorPart in theeditor zone.
  3. Run the application and select edit mode from the option box.
  4. Click edit from the menu available for web parts.

You will see following output.

You can change the title of web parts here. You can see some basic options in edit mode. The chrome type is about the border and title style. The chrome state gives you the option of minimizing it or not.

PropertyGridEditorPart

By using the property editor, you can change properties of objects in your web parts. In the example, you are going to change the CSSClass property of the object. To use this, you will follow the same method of editor parts.

  1. Place the editor zone on the page.
  2. Place a PropertyGridEditorPart inside the editor zone.
  3. To use the editor zone, add a new user control in the project.
  4. Place a textbox on it.
  5. Place this user control in a web part of a web form.
  6. In the code behind of the user control, write the following code:
  7. 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;
    }
    

As you can see in the code above, you have changed a textbox's CSS class by using a property. You will change this property value in a web parts edit mode.

WebBrowsable() Attribute

It allows a web part to display property in a web browser in edit mode.

Personalizable() Attribute

It allows a property to be editable.

Now, run this page. Suppose you choose edit mode from the options combo. You will see the following edit button in the options menu of the web part.

When you select the edit link from the webpart menu, you will have the CssClass property in edit mode.

As you can see, this textbox has FrmTxtBox named class applied to it by default. It is defined in a stylesheet with attributes of the border color in black.

To apply a different class named CustomClass1, I have created this class in the stylesheet. This class has no border color defined in it.

After changing the CssClass name, press the OK button. You will see a textbox with the default border style.

So, in this way, you change the properties of objects using web parts.

4: Catalog mode

Catalog mode gives you the option to add/remove web parts at runtime. Say, for example, you have a few modules such as weather, news, shopping, horoscope, and so forth and want to give users an option to show or hide these modules at runtime. You can accomplish this task by using catalog mode.

Catalog zone is further divided into three types: Page, Declarative, and Import.

Add a Catalog zone on the page. Then, add PageCatalogPart, DeclarativeCatalogPart, and ImportCatalogPart in the catalog zone. YouWe can show web parts with the help of the Page catalog that is closed by usingthe "close" option of the web part. You can see this in the following screenshot.

Page catalog displays the number of web parts that are closed by using this option.

Declarative catalog displays the number of elements that are added in design mode in catalog zone. Click on the smart tag option of the declarative catalog zone and select edit template. Add controls in the catalog zone.

Import Catalog displays the number of elements that are selected to import. You can import files that have the ".WebPart" extension. To export a file as a .WebPart type file, add the following line to web.config.

<webParts enableExport="true"></webParts>

Then, you can follow one of these two methods:

  1. 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.
  2. <aspSample:CustomWebPart id="Sample" runat="server"
                             ExportMode="All" />
    
  3. Or, you can write the following code on page load.
  4. Dim gwp As GenericWebPart
    gwp = WebUserControl2_1.Parent
    gwp.ExportMode = WebPartExportMode.All
    

Now, you can add any of these web parts to the page by selecting control and the zone where you want to add it.

Using Webparts in ASP.NET 2.0

Connect mode

This mode allows web parts to communicate with each other. You can make static connections once (in your code), or you can allow users to connect at runtime according to their needs. Connection mode doesn't mean that you connect to the database but that you connect web parts together.

Say, for example, you have a web part with a grid, displaying some records, and you want to filter it on user input. You can put in a textbox for user input in the other web part and send text by using connect mode.

In the example, you will place two web parts on a page. One will be for user input and the other for showing it.

  1. Create two user controls. Name one provider and the other consumer.
  2. Place these two controls in web parts.
  3. Add a new class in the App_Code directory and name it ITextProvider.
  4. Write the following text in it.

    public interface ITextToPass
    {
       string GetText();
    }
    

    You will use this interface in both provider and consumer user controls to pass text between these two entities.

  5. Place a textbox in Provider user control and write down following text in code behind.
  6. 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, you are implementing an interface that you have just created. By using this interface, you return text entered in the textbox to pass to the consumer user control.

Using the ConnectionProvider attribute means exposing a web part that exposes a connection point. For detail, you can read the following article.

Place a label in the consumer web part and add write the following code in its .cs file.

public partial class ConsumerWebpart : System.Web.UI.UserControl
{
   [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 the selecting connection mode of WebpartManager, you can see the connect option in the web part's menu.

[Webparts12.jpg]

For the sake of simplicity, I have changed the text of the button. When you click connect, you will see the following screens.

[Webparts13.jpg]

[Webparts14.jpg]

Click on Create a connection to a Consumer and you will see the following screen. Select the web part as a consumer from the combo.

[Webparts14.jpg]

[Webparts15.jpg]

You will see the following screen to enter text to pass to the consumer. Pass string "A String" for the consumer.

[Webparts16.jpg]

You can see in the following screen that the consumer web part shows text in a label that we have passed to it.

[Webparts17.jpg]

So, in this way, you can pass values from one web part to another. As I mentioned earlier, you can set static connections in your code so that users will not be able to set the provider and consumer by themselves.

Saving Page State in a Database

Before you run the project, one question that arises is about where this page setting will be saved for each user.

Any page setting modified by users will remain as it is; these settings are saved in database. In your scenario, you are going to use a built-in login and sign up control.

  1. Modify authentication mode to Forms in the Web.Config file.
  2. Add a new file to project "Login.aspx".
  3. Place a login control in it, and set DestinationPageUrl to default.aspx.
  4. Add another file to project, named "Signup.aspx".
  5. Add a signup control on this page, for signup.
  6. Also, make sure that Sql Express services is started.

On signup, by using these controls a database named "ASPNETDB.mdf" is automatically created in the applications app_data folder. This database has appropriate tables and stored procedures to save page state according to each user.

[Webparts18.jpg]

This is the default setting; a page's setting is saved in this database according to each user logged in. This setting is mentioned in the machine.config file; to customize that, you need to override these settings in your application's web.config file.

The table named aspnet_users saves a user's basic information. The aspnet_PersonalizationPerUser table saves page settings according to userid. The page setting is saved in serialized format, in the PageSettings field.

Customizing the Database

By default, web parts use the ASPNETDB.mdf file, Now, the question is how to adapt the application's database for web parts.

Setting Up the Database

To customize a database for webparts, run the utility named aspnet_regsql.exe. It is present in the \Windows\Framework\v2.0.50727 subdirectory. This utility helps yu create tables and stored procedures required to customize the database. Following is the screenshot of the wizard provided by this utility:

[Webparts19.jpg]

This wizard creates the following tables in the database that you select during this wizard:

[Webparts20.jpg]

One more thing that you need to do is to customize your web.config file. Following is the setting for the web.config file:

[Webparts21.jpg]

As I mentioned earlier, settings for the database are mentioned in the machine.config file. To customize that, you need to override these settings in your application's web.config file. Initially, you define connectionstring.

LocalSqlServer is the name of connectionstring in the machine.config file as well; to override this, you will mention the same connectionstring name. ApplicationName is any name that can mention for identification of your application. For my application, I have set the application name to CustomConnections. It can be any.

So, in this way, you can customize the database for a database other than ASPNETDB.



About the Author

Abdul Sami

vefmmd

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Hundreds of millions of users have adopted public cloud storage solutions to satisfy their Private Online File Sharing and Collaboration (OFS) needs. With new headlines on cloud privacy issues appearing almost daily, the need to explore private alternatives has never been stronger. Join ESG Senior Analyst Terri McClure and Connected Data in this on-demand webinar to take a look at the business drivers behind OFS adoption, how organizations can benefit from on-premise deployments, and emerging private OFS …

Most Popular Programming Stories

More for Developers

RSS Feeds