Friday, October 7, 2011

Web Parts in ASP.NET

This article discuss about the Web Parts, new feature introduced in ASP.NET 2.0. You can see many websites that are modular in nature today. Many websites often organize their content into modules that allows for personalization.
Information is broken down into manageable parts which end users can rearrange or move around the parts to suit their preferences. User has also the flexibility to save his preferences for future browser sessions. This way, end user can be empowered to personalize site dynamically.
Before ASP.NET 2.0, developer had to build his own custom personalization framework to implement personalization feature in the application.
In ASP.NET 2.0 you can build web portal that offer personalization and modularization of information using new Portal framework. This new framework provides effective way to build a modular web site that dynamically reapplies settings on a per-user basis. 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.
Don't confuse ASP.NET 2.0 Web Parts with Microsoft SharePoint services even though they use same Portal Framework. These two technologies are not the same.

Advantages of Web Parts

  • Web Parts allows for personalization of page content. They allows users to move or hide the Web Parts and add new Web Parts changing the page layout.
  • Web Parts allows user to export or import Web Parts settings for use in other pages. Web Parts retain the properties, appearance and the data across the pages when imported or exported.
  • Web Parts can be assigned role-based access. So you can determine which Web Parts can share by all or which should be hidden for certain roles. This helps us to provide customized content based on security.
  • Web Parts can talk to each other. You can utilize the data in one Web Part in another Web Part for different purposes.

Web Parts Modes

The modular and customizable sites that you can build with the new Portal Framework enable you to put the web page that is in view into several modes for the end user. Modes are very powerful in that they enable user to edit Web Parts, delete the Web Parts or customize Web Parts.
  • a) Normal mode: End user cannot edit or move sections of page.
  • b) Edit Mode: End user can edit Web Parts on the page including Web Parts title, color or even setting custom properties.
  • c) Design Mode: End user can rearrange the order of the pageĆ¢€™s Web Parts in a WebPartZone.
  • d) Catalog Mode: End user enjoys the choice to add new Web Parts or add deleted Web Parts in any WebPartZone on the page.

Web Parts components

You can study Web Parts under three different categories. Each category adds it own value in Portal Framework (Web Parts).
  • Personalization
  • UI Structural components
  • WebParts UI controls

Personalization

Personalization is the core behavior of WebParts. You can modify or personalize the layout, appearance and behavior of WebParts controls. Personalized settings are persisted for future browser sessions.

UI Structural components

UI structural components create infrastructure for the WebParts to work on a page. They provide core services needed by any Web Part including coordinating and tracking all individual WebParts controls. They also control the different modes in which a page can be (Normal, Edit, Design, and Catalog). It also manages WebParts zones. For example: WebPartManager control is one such UI Structural component which should be required on each page that holds WebParts.

WebParts UI controls

Web Parts control set is extensive and flexible which can be used to build Web Parts or you can create your own custom Web Parts by inheriting from the System.Web.UI.WebControls.WebParts.Webpart class. You can also reuse existing ASP.NET server controls as Web Parts controls by encapsulating it in a genericwebpart class.
Portal Framework defines everything in terms of zones. Zones are container of Web Parts controls. They act as layout managers on Web Parts page. Zones are managed by Portal Framework manager.

WebPartManager

WebPartManager control is server control that completely manages the state of the zones and content placed in the zones on a per-user basis. This control doesn't have any visual interface, can add and delete items within zones of the page. You can have only one WebPartManager for each page that works with Portal Framework. You can run WebPartManager in one of several display modes. It facilities communication between different elements contained in the zones. For example: you can pass a specific name/value pairs from one item to another item within the same zone, or between items in different zones.
You can drag and drop the WebPartManager control from the toolbox to the design surface. Since it doesn't have a UI interface, it appears as a gray box. You can find all Web Parts server controls in WebParts section of toolbox as shown below.

WebParts in Toolbox
After you place the WebPartManager control on the page, the next step is to create zones from which you can utilize the Portal Framework. Web zones define specific rows or columns as individual content areas managed by WebPartManager.
There is a sample Web Parts project, used in this tutorial. To start the sample, you need to unzip files and create some virtual directory. Set ASP.NET version to 2.0 for directory if needed. Disable anonymous access and activate Integrated Windows Authentication, like in image bellow.

Set authentication methods
You can open web site through an Visual Studio 2005, like showed bellow:

Design view in Visual Studio 2005
You can observe that above page includes <asp:WebPartManager> control that manages the items contained in the three zones on this page. You can declare each web zone in one of two ways. You can use the <asp:WebPartZone> element directly in the code, or you can create the zones within the table by dragging and dropping WebPartZone controls onto the design surface. You can look at WebPartZone clearly in above design. WebPartZone control defines an area of items that can be moved, minimized or maximized based on user preferences. You can place anything in zones including HTML elements, web server controls, user controls and custom controls. You can see declaration of WebPartZone controls in above HTML code. Any thing placed into WebPartZone can be treated as Web Part. Useful attributes of WebPartZone include LayoutOrientation attribute which controls the display of items either horizontally or vertically. You can observe in our above example, first WebPartZone has horizontal layout.

ZoneTemplate Element

In order to include items within the WebPartZone control, we must include a <zoneTemplate> element. This will bind all the items present within a particular zone.
When using visual studio 2005, by default, IDE creates a Microsoft SQL Server Express Edition file called ASPNETDB.MDF and stores it in the App_Data folder. Portal Framework uses this database to store all the customization points. So, we are using Microsoft SQL Server Express Edition for this example
Start the web application and you should see output like this:

Output listing
In the output listed above, you can observe that when we click down arrow present next to name of Web Part, we will have options to minimize or close Web Part.

Changing mode of page

You can use either WebPartManager class directly or through the use of WebPartManager server control, you can change the mode of page. Changing the mode allows the user to make changes to pages they are working with. All the changes (mode changes) are recorded to ASPNETDB.MDF database associated with app_data directory created exclusively for Web Parts.
Using WebPartManager object, you can add new Web Parts to the page. It also enables end user to drag and drop elements around the page. You can also change order in which items appear in a zone.
Let's see with an example how to add dynamically to add Web Parts to a page using capabilities of Portal Framework. The ASP.NET 2.0 Portal Framework enables an end user to add Web Parts, but you must also provide the end user with a list of items he can add. To do this, simply add a Catalog zone <asp:CatalogZone> control to page. It is designed to allow for categorization of the items that can be placed on the page. (I have added professional auto formatting style, so you see some code related to that in below listing)
<asp:CatalogZone ID="CatalogZone1" runat="server" BackColor="#F7F6F3" BorderColor="#CCCCCC"
                    BorderWidth="1px" Font-Names="Verdana" Padding="6">
                    <PartLinkStyle Font-Size="0.8em" />
                    <PartTitleStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.8em" ForeColor="White" />
                    <EditUIStyle Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" />
                    <PartStyle BorderColor="#F7F6F3" BorderWidth="5px" />
                    <HeaderVerbStyle Font-Bold="False" Font-Size="0.8em" Font-Underline="False" ForeColor="#333333" />
                    <PartChromeStyle BorderColor="#E2DED6" BorderStyle="Solid" BorderWidth="1px" />
                    <EmptyZoneTextStyle Font-Size="0.8em" ForeColor="#333333" />
                    <SelectedPartLinkStyle Font-Size="0.8em" />
                    <VerbStyle Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" />
                    <LabelStyle Font-Size="0.8em" ForeColor="#333333" />
                    <FooterStyle BackColor="#E2DED6" HorizontalAlign="Right" />
                    <HeaderStyle BackColor="#E2DED6" Font-Bold="True" Font-Size="0.8em" ForeColor="#333333" />
                    <InstructionTextStyle Font-Size="0.8em" ForeColor="#333333" />
                </asp:CatalogZone>
Once a Catalog Zone section is present on the page, the page is enabled for the Catalog mode. After the Catalog Zone is in place, next step is to create <ZoneTemplate> section within the Catalog Zone because this is also a templated control.
Add PageCatalogPart control inside <ZoneTemplate> section within the Catalog Zone. When the mode is changed to Catalog Mode, you can see the catalog control in output. Here in our example, just click the Catalog button to change mode to Catalog and you can see the catalog control.
Now click the display button. You can see the below output listing. Now click small down ward arrow besides Chicago or ASP.NET Tutorials Item.
Now select close option from the dropdown list. You can see it in below output.

Selecting Close option from dropdown
You can observe from below listing that Chicago Web Part is removed from the screen.

Webpartzone2 is disappeared which include chicago picture
Now click Catalog button. At this point, you can see the deleted Web Parts in the catalog zone. The PageCatalogPart control contains a title and checkbox list of items that can be selected. The pageCatalogPart control also includes a dropdown list of all available Web Part Zones on the page. From here, you can place the selected Web Parts into one of the Web Part Zones available from the list. After you chose the Web Parts and the appropriate zone in which you want to place item, click the add button and Web Part appear in the specified location. In below listing I chose to add Deleted Chicago Web Part into WebPartzone1. Now you can see the Chicago Web Part in WebPartZone1.

Output after clicking Catalog button and adding Chicago webpartzone2 back to scree

Moving Web Parts

We can also move WebParts from one zone to another zone. This is possible through Design mode. From our example we can see that we have three zones. You can observe from above listing that WebPartZone2 is empty. Let's move calendar control to WebPartZone2. To move calendar control just hover mouse over title of Calendar control and you can see crosshair mouse symbol. Click the left mouse button and hold the Web Part and drag it to WebPartZone2. While dragging, the calendar control becomes transparent and drops the calendar control in WebPartZone2 where the blue line appears. Below listing gives you an idea. I am dragging calendar control from WebPartzone1 to WebPartZone2.

Moving Calendar control from Webpartzone1 to Webpartzone2

Editing the Web Parts

Another Web Part mode that allows end-user to edit the Web Parts is Edit mode. This mode enables users to modify the settings related to behavior, appearance and layout for a particular Web Part on the page. To make this happen, we have to add EditorZone to the page similar to CatalogZone.
<asp:EditorZone ID="EditorZone1" runat="server">
                    <ZoneTemplate>
                        <asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
                        <asp:BehaviorEditorPart ID="BehaviorEditorPart1" runat="server" />
                        <asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" />
                         </ZoneTemplate>
                    </asp:EditorZone>
The three controls <BehaviorEditorPart>, <LayoutEditorPart>, <AppearanceEditorPart> allows to modify/edit the appearance, Layout and Behavioral aspects of WebPart respectively.
Run the code. Click the Edit button. You can observe that when you click the down arrow next to title of any WebPart, you have also Edit option in the dropdown list. You can see it in the below listing.

Editing the Calendar control properties
When the user clicks the Edit link from dropdown list you can see Appearance Editor/Layout Editor appear in the EditorZone. You can see it from below listing

Output after clicking Edit button
From the listing, we might see that Appearance section allows users to change title and how the title of Web Part appears. Layout section enables user to change the order in which Web Parts appears in a zone or move Web Parts from one zone to another. Behavior section enables site editors to change dynamics of how end user can modify Web Parts.
To display Behavior section, you have to make modifications to Web.Config
<system.web>
    <webParts>
      <personalization>
        <authorization>
          <allow users ="*" verbs ="enterSharedScope"/>
        </authorization>
      </personalization>
    </webParts>
At the same time, you will have to add this code to Page_Load event.
protected void Page_Load(object sender, EventArgs e)
    {
        if (WebPartManager1.Personalization.Scope == PersonalizationScope.User)
        {
            if (WebPartManager1.Personalization.CanEnterSharedScope)
             {
                        WebPartManager1.Personalization.ToggleScope();
              }
    }

}

Output Listing with Behavior section

Connecting Web Parts

You can connect Web Parts using <asp:ConnectionsZone> control. This control allows making property connections between the Web Parts on the same page.
This article completed focused on developing customizable portal application using declarative approaches provided by Portal Framework. This article also introduced to WebPartManager, WebPartZone, and the Web Part controls. Various display modes and their impacts on their page are also discussed. You may find that Portal Framework more invaluable in creating completely modular and customizable web pages.