Understanding ASP.NET Web Parts
(
Jul 26 2007 - 10:51:19 AM by
Timothy Khouri) - [
print article]
ASP.NET 2.0 was a major improvement upon web development everywhere. One very powerful aspect of ASP.NET 2.0 is the ability to make your web application personalizable using the Web Part framework. With the launch of MOSS (Microsoft Office SharePoint Server 2007) many companies and developers have rekindled focus on utilizing this amazing tool. This article will start with the basics of understanding web parts and personalization. Attached at the end of the article is a full source code solution.
We'll start by discussing what it means to make a web page "personalizable", then we'll mention a few common aspects of personalization that have been implemented by different internet entities (such as Google). The "meat" of the article will discuss how you can quickly get web parts working in an ASP.NET 2.0 web site and a brief description of each of the WebPartZone types.
By the end of this article you should know:
- What it means to make a web page personalizable.
- How to quickly setup the Personalization framework in ASP.NET 2.0.
- How to make your own custom web parts.
Other major concepts such as distributing your business logic throughout seemingly disconnected controls, Model View Control ideologies, atomic design and integration with Microsoft SharePoint 2007 will not be discussed in this article. Those topics will be explored in future articles, but for now the basics will be covered.
What is Personalization?
Personalization is a semi-generic term that basically means allowing users to customize the way they use and look at your web pages. For instance, if you have a Google account (such as Gmail or Adsense) you can change the Google home-page to have a different background, custom web parts (to display the weather or your email's inbox) and other useful tools. These customizations are specific to your account only, so when you log out or if someone else goes to Google, they will not see the changes that you have made.
The concept is easy to understand, but it takes a lot of work to create this kind of functionality from scratch. This is where ASP.NET 2.0 comes in with the Personalization framework. You get out-of-the-box functionality including drag-and-drop layout design, creating and editing custom properties, connecting parts together in a provider-to-consumer relationship and a lot more.
It is important to know that personalization doesn't need to be specific to each user. You can have a web page, or part of a web page that is personalizable in a "Shared" environment. This would allow a site moderator to change the layout or properties of a site and have the changes affect all users.
Setting Up Web Parts in ASP.NET 2.0
If you are familiar with the Membership API or the Profile API in ASP.NET 2.0, then you're already 50% familiar with the Personalization API. Just like the other APIs (Membership, Profiles and Roles), you'll need to make some simple configuration entries in your web.config file to tell your application that you want to use web parts, and where you want to store / retrieve the serialized data.
The three items that you need are:
- A connection string.
- The "webParts" element configured.
- A database that is configured using aspnet_regsql.exe.
I won't go into detail about how to configure your database, but if you are not familiar with doing this already then you can read this article which explains it quickly: Membership Using ASP.NET AJAX.
We'll assume that we have the following connection string in our web.config file:
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=.\SQLEXPRESS; AttachDbFileName=|DataDirectory|MyDB.mdf; Integrated Security=True; User Instance=True" />
</connectionStrings>
The following is a sample <webParts> configuration section. This goes in the <system.web> section of your web.config file. I am using Windows authentication for this example and I'm intentionally allowing all users to have the ability to edit the site for this demo. Here is my sample configuration:
<webParts enableExport="true">
<personalization defaultProvider="MyWebPartProvider">
<providers>
<add name="MyWebPartProvider"
connectionStringName="MyConnection"
type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider" />
</providers>
<authorization>
<allow users="*" verbs="enterSharedScope" />
<allow users="*" verbs="modifyState" />
</authorization>
</personalization>
</webParts>
Creating and Implementing Custom Web Parts
Now that we have configured our web site to use the Personalization API we are ready to build our simple Web Parts Demo Site. We will create a one-page site that will consist of two "web part zones." A web part zone is a panel (or section of your page) that you want to be customizable. Our page is going to be divided up into two sections; a left panel and a right panel. This will help to demonstrate how easy it is to drag-and-drop your web parts from one zone to another.
Other than the basic "WebPartZone" which displays the web parts that you configured, there are three types of zones that you will need to be familiar with. Those are the:
- CatalogZone - Allowing you to add web parts to a WebPartZone.
- EditZone - Allowing you to edit web part properties of parts that are in a WebPartZone.
- ConnectionsZone - Allowing you to "connect" two web parts together in a provider-to-consumer relationship.
Each zone knows how to treat web parts that are inside of them. For instance, if you put your own custom web part inside of a CatalogZone, then when your page is in "Catalog" mode, you will see a list of all web parts inside the CatalogZone available to be added to one of your WebPartZones.
We'll talk about switching your pages "mode" in a bit, but for now lets look at an example of a CatalogZone.
<asp:CatalogZone ID="PartsCatalog" runat="server">
<ZoneTemplate>
<asp:DeclarativeCatalogPart ID="DeclarativeCatalog" runat="server">
<WebPartsTemplate>
<MyWebParts:MyLiteralTextWebPart ID="PartOne" runat="server" Title="The Literal Thingy" />
</WebPartsTemplate>
</asp:DeclarativeCatalogPart>
</ZoneTemplate>
</asp:CatalogZone>
This is what the CatalogZone will look like:
Note that you can change the "Title" of the web part to say whatever friendly label you want in the CatalogZone. Also, you may have noticed that I am using a simple drop-down box in the top right corner to switch the "DisplayMode" from the default mode (which is "Browse") to the "Catalog" mode. This tells ASP.NET that you want to display the catalog zone.
Now let's see an example of using the PropertyGridEditorPart to change the "DisplayText" property that we created on our custom web part (which you'll see in the code sample attached at the end of the article).
Here the code for is our custom web part:
public class MyLiteralTextWebPart : WebPart
{
private string _displayText;
[Personalizable(true), WebBrowsable(true)]
public string DisplayText
{
get { return this._displayText; }
set { this._displayText = value; }
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.Write(this.DisplayText);
}
}
Here is the ASP.NET code for our "EditorZone":
<asp:EditorZone ID="EditZone" runat="server">
<ZoneTemplate>
<asp:PropertyGridEditorPart ID="PropertyEditor" runat="server" />
</ZoneTemplate>
</asp:EditorZone>
And here is what all of this looks like when you're editing your custom web part:
Changing the DisplayMode to "Design" is one of the simplest of modes, only allowing users to organize (drag-and-drop) the web parts or close them (so that they no longer display).
The last zone is very powerful in some areas, but also very limited. The ConnectionsZone allows you to tie two web parts together in a provider-to-consumer relationship where one of you web parts will "provide" some sort of data and the other will "consume" it during the "PreRender" event.
We'll create two more web parts: one that will act as the provider which will supply a simple DateTime format string; the other will consume that value and display the current date formatted the way the provider specified.
Here is part of the code (which will be in the full source code attached at the end of the article). These are two methods in the sample provider and sample consumer web parts:
[ConnectionProvider("Get Format String")]
public string GetFormatString()
{
return this._formatTextBox.Text;
}
[ConnectionConsumer("Display Formatted DateTime")]
public void DisplayFormattedDateTime(string suppliedFormatString)
{
string formattedDateTime = DateTime.Now.ToString(suppliedFormatString);
this.Controls.Add(new LiteralControl(formattedDateTime));
}
Here is what it looks like when you are connecting two controls:
In Conclusion
Web parts and the idea of creating personalizable web sites are becoming more popular as the internet evolves. Try converting one of your web applications to have customizable sections. Also, you don't need to create a custom control (inheriting from WebPart), you can put UserControls or other ASP.NET controls into a WebPartZone and ASP.NET will wrap it in a GenericWebPart for you.
Here is the source code for the above application, try it out for yourself: SingingEels_WebParts.zip.