Building Your First Web Part Page


The steps in this section walk you through the process of creating your first Web Part Page. At first it can seem very overwhelming as there are a lot of new controls to use and a lot of new terminology. After you have completed the Web Part Page, you are strongly encouraged to play with it, modify it, and experiment with it before continuing on to the next section so that you can familiarize yourself with the behavior and functionality of Web Parts within ASP.NET 2.0. Rather than have you examine the completed solution, this section is designed to walk you through all of the individual steps required in creating a Web Part Page so that you can gain a thorough understanding of the process and can reuse that process in your own applications. Use the following walk-through to create your first web part page:

1.

Create a new ASP.NET web application called FirstWebPartPage. When you have the application created, modify the Web.config so that it points to the personalization provider created in the preceding section. Your new Web.config should look a lot like the one shown in Listing 26.1.

2.

You will want to divide your page up into zones. A zone is a container for Web Parts and is often used to divide content areas of differing sizes and purposes. Common scenarios involve top zones, side bars, central content zones, footers, and occasionally right-justified side bars. In this case, open default.aspx and create a three-column table in between the default <div> tags. Make sure that your View menu (when looking at the designer view) has both Non-Visual Controls and Details checked so that you can see everything that's going on in both source view and design view.

3.

Open your Toolbox and expand the Web Parts group. Drag the WebPartManager component from the Toolbox onto your web page (this works in either design or HTML view) directly above the three-column table created in step 2. Rename the component to wpManager. The WebPartManager provides the plumbing necessary to convert a standard page of static controls into a dynamic Web Part Page.

4.

Drag a WebPartZone from the Toolbox into the leftmost table cell in the first row of the table you created earlier. Call this control zoneSideBar. Set the HeaderText property to "Side Bar".

5.

Drag another WebPartZone control from the Toolbox into the middle column of the table. Call that control zoneMain. Set the HeaderText property to "Main Zone".

6.

At this point you should have a WebPartManager followed by a three-column table. The left column should contain the zoneSideBar control and the middle column should contain the zoneMain control. From the design view, drag a treeView control and drop it in the box framed by the side bar zone. Feel free to add random nodes and format it as you see fit. The important thing to note is that when you switch to source view, you will see that the TReeView is now contained within a ZoneTemplate element inside the zoneSideBar control. At runtime, the treeView control will automatically become the child control of a GenericWebPart, giving it access to all of the functionality provided by the Web Parts engine.

7.

You might notice that in the design view, the treeView control is inside another frame labeled "Untitled" with the Web Part menu down-arrow icon. This is because the TReeView is actually inside an unlabeled GenericWebPart. To fix this, you can add title="Tree" to the TReeView's declaration. You'll get a warning message about it in the source view, but you can ignore it because when you switch back to the design view, "Untitled" will have been replaced with "TRee".

8.

Now drag three different labels into the zoneMain zone control. Don't worry about separating them with <br/> tagsthe fact that they are contained within a WebPartZone will automatically make them appear within their own frames. Call them lblOne, lblTwo, and lblThree respectively. You can add whatever text you like to them. Set the Title property on them using the source view. If you feel like it, you can right-click zoneSideBar and zoneMain, choose Auto Format, and select something more colorful than the default zone colors. Figure 26.2 shows a screenshot of the author's designer at this stage of the walkthrough.

Figure 26.2. Visual Studio 2005 Designer, building a Web Part Page.


9.

When you run your application now, you should see four different Web Parts on the page. Each of them has a drop-down menu that appears when you click the down-arrow icon that contains a "Minimize" link and a "Close" link. If this isn't the case, go back over the preceding steps to make sure you didn't miss anything before continuing.

Web Part Page Caveats

As you play with the Web Part Page, you might end up clicking the Close link. If you do this, and you don't have some facility on the page to switch the Web Part Zones into Edit mode, you will never see that Web Part again. The personalization provider will have recorded the closed state of that Web Part, and the only way to get it back is to switch the zones into Edit mode so that you can edit the properties of the closed Web Part to make it visible again. A lot of developers familiar with SharePoint often take it for granted that such an ability to switch to edit mode exists by default. As you'll see in this walkthrough, you will need a user control that allows your page to switch into and out of edit mode. The good news is that this control can be used on as many pages in as many applications as you like.

10.

At this point, you now have a functioning Web Part Page that is displaying multiple Web Parts in multiple Web Part Zones. The problem now is that you don't have any way of switching the page into edit mode to allow the user to change the layout of the parts and their properties. To enable the user to switch between edit and browse modes, you'll need to create a user control to facilitate that change. To get started, right-click the web application and choose Add New Item and choose Web User Control. Call the control PageStateSwitcher.ascx.

11.

MSDN's walkthrough of creating a Web Part Page contains the complete source code for a user control that enables page state switching. However, at the time of this writing, that walkthrough appears to be for Beta 2 and won't work properly. Because this task is virtually essential for every single Web Part Page you create, the author is providing the source code for his version of that control, which works with the retail version of Visual Studio 2005. First, set the PageStateSwitcher.ascx code to the following:

[View full width]

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PageStateSwitcher.ascx.cs" Inherits="PageStateSwitcher" %> <asp:Panel runat="server" BackColor="PaleGoldenrod" BorderWidth="1" BorderColor="black" Width="250"> <asp:Label runat="server" Text="Display Mode" Font-Bold="true" Width="100"/>&nbsp; <asp:DropDownList runat="server" AutoPostBack="true" OnSelectedIndexChanged="dlDisplayModes_SelectedIndexChanged"/><br /> <asp:LinkButton runat="server" Text="Reset User Data to Default" OnClick="lnkbReset_Click" /><br /> <asp:Panel runat="server" Font-Size="9pt" BackColor="lightgray" Width="250" GroupingText=" Scope Change " Visible="false"> <asp:RadioButton runat="server" Text="User" AutoPostBack="True" GroupName="ScopeChange" OnCheckedChanged="rdoUser_CheckedChanged" /> <asp:RadioButton runat="server" Text="Shared" AutoPostBack="True" GroupName="ScopeChange" OnCheckedChanged="rdoShared_CheckedChanged" /> </asp:Panel> </asp:Panel>


12.

Now open the PageStateSwitcher.ascx.cs file and enter the following source code:

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class PageStateSwitcher : System.Web.UI.UserControl { private WebPartManager mgr; protected void Page_Load(object sender, EventArgs e) { } protected override void OnInit(EventArgs e) {     base.OnInit(e);     mgr = WebPartManager.GetCurrentWebPartManager(Page);     foreach (WebPartDisplayMode mode in mgr.SupportedDisplayModes)     {         // if the mode is available, add it to the dropdown         if (mode.IsEnabled(mgr))         {             string modeName = mode.Name;             dlDisplayModes.Items.Add(new ListItem(                 modeName, modeName));         }     }     if (mgr.Personalization.CanEnterSharedScope)     {         pnlScopeChange.Visible = true;         if (mgr.Personalization.Scope == PersonalizationScope.User)             rdoUser.Checked = true;         else             rdoShared.Checked = true;     } } protected void dlDisplayModes_SelectedIndexChanged(object sender, EventArgs e) {     string selectedMode = dlDisplayModes.SelectedValue;     WebPartDisplayMode newMode = mgr.SupportedDisplayModes[selectedMode];     if (newMode != null)         mgr.DisplayMode = newMode; } protected override void OnPreRender(EventArgs e) {     ListItemCollection lic = dlDisplayModes.Items;     int curMode = lic.IndexOf(lic.FindByText(mgr.DisplayMode.Name));     dlDisplayModes.SelectedIndex = curMode; } protected void rdoUser_CheckedChanged(object sender, EventArgs e) {     if (mgr.Personalization.Scope == PersonalizationScope.Shared)         mgr.Personalization.ToggleScope(); } protected void rdoShared_CheckedChanged(object sender, EventArgs e) {     if ((mgr.Personalization.Scope == PersonalizationScope.User) &&         (mgr.Personalization.CanEnterSharedScope))     {         mgr.Personalization.ToggleScope();     } } protected void lnkbReset_Click(object sender, EventArgs e) {     mgr.Personalization.ResetPersonalizationState(); } } 


13.

Now go back to default.aspx in whatever view you want and drag PageStateSwitcher.ascx from the Solution Explorer onto the design surface below the three-column table, just before the last </div> tag.

14.

Run default.aspx and play around with the page for a while. Notice that when you switch the page into Design mode, borders appear around each zone as well as the zone's name. To watch the real magic happen, left-click and hold on a Web Part's title bar (while in Design mode) and drag it into some other location. You can move Web Parts between zones as well as change their display order. To prove that personalization is remembering your changes, make some visible changes to the page, close the page, and then reopen it. It will reappear in the same state in which you left it.

Entering Shared Scope

By default, users cannot enter shared scope. This means that when you run the application at this point in the walkthrough, the scope-changing panel will never appear. To allow your users to enter shared scope, you can add the following lines to the <personalization> section of your <webParts> element in Web.config:

<authorization>   <allow users="*" verbs="enterSharedScope"/> </authorization> 


If you want finer-grained control over who can enter shared scope, you can make use of a role provider and only allow users who belong to specific roles to enter shared scope. This is definitely recommended for production scenarios because you do not want every user of your web application to be able to make global changes to the layout of a page.

15.

Now that you have a Web Part Page that has multiple Web Part Zones and multiple Web Parts and has a control that allows users to switch into Design mode, you need some additional tools to allow users to make changes to Web Part properties. These tools fit nicely into an EditorZone. To create an EditorZone, drag one from the Toolbox into the third column of the table that hasn't been used yet. Rename this control to zoneEditor.

16.

Drag an AppearanceEditorPart and a LayoutEditorPart into the EditorZone control. You'll see that both of those parts will also be wrapped in a ZoneTemplate control. Note that if you drag these controls while in source view, you will have to create the ZoneTemplate element manually.

17.

If you haven't already been impressed by the Web Parts engine so far, you will definitely be at this step. Run the application again and you will see that there is a new display mode: Edit. Select that mode and all of the Web Parts on the page again switch into what looks like design mode. However, if you select one of their drop-down menus, you'll see a new Edit option. Click that and all of the editors contained within the EditorZone will appear, as shown in Figure 26.3.



Figure 26.3. A Web Part Page with editing enabled.


18.

So far you've seen how to declaratively add Web Parts to a Web Part Page by placing them directly in the aspx within a WebPartZone. With a little bit of work, you can also allow users to interactively select which Web Parts they want on their page by picking them from a catalog. To add catalog support to your page, start by dragging a CatalogZone control onto your page directly below the EditorZone you just created.

19.

You can add a couple of different kinds of catalog parts, but the one you'll add in this walkthrough is the DeclarativeCatalogPart, which allows you to declare the list of parts contained in the catalog directly within the page. Drag the DeclarativeCatalogPart from the Toolbox in design view into the CatalogZone just created. VS will create the ZoneTemplate for you.

20.

You can either drag controls onto the surface of the DeclarativeCatalogPart, or you can go into source view and create a WebPartsTemplate child element and declare the controls within that element. For this walkthrough, place a Calendar, a TextBox, and a Label with some random text into the WebPartsTemplate. Also remember that you can add any control here: a user control, a standard ASP.NET server control, or a control you have created that inherits directly from WebPart.

21.

After you've added a couple of controls to the catalog's WebPartsTemplate, add a Title property to each of them so that the catalog has some way of displaying a description of the Web Part to the user. The code for your DeclarativeCatalogPart will look similar to this:

<asp:DeclarativeCatalogPart  runat="server">     <WebPartsTemplate>         <asp:Calendar  runat="server" Title="Misc Calendar" />         <asp:TextBox  runat="Server" Title="Test Text Box" />         <asp:Label  runat="server" Title="Sample Label" />     </WebPartsTemplate> </asp:DeclarativeCatalogPart> 


22.

When you run the application now, you will find that yet another display mode has been added to the drop-down list: Catalog. Select this display mode and the CatalogZone will appear. It will then display a list of checkboxes next to the titles of the controls you added in step 20. You can see how the catalog will allow you to add Web Parts by selecting them and choosing the zone in which you want them to appear. Figure 26.4 shows a sample page after the user has added the Calendar control to the Side Bar zone.

Figure 26.4. Using the catalog zone to add Web Parts at runtime.


23.

Again, to be sure that personalization storage is working properly, if you close the page after making changes by using the Catalog and then reopen the page, it will remember all of those changes so long as you are still authenticated as the same user (this walkthrough is using Windows authentication).



Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net