DevExpertise

Practical tips and tricks for all things .NET, SharePoint, Silverlight, InfoPath, and general application development.

ASP.NET Tip/Trick: Use a Base Page Class for All Application Pages

Posted by DevExpert on 25th March 2009

All coders worth their salt know that duplicating code isn’t a best practice, and you should consolidate and leverage object inheritance where necessary.  When done correctly, this promotes better maintainability and a better overall application.

I’ve been doing a lot of straight ASP.NET application programming lately, and no matter how many ASP.NET applications I write, I always use a certain number of common methods in my pages’ code-behind.  For example, I get and set view state values, I retrieve values from the cache, or verify query strings have been included.  Because I’m doing these same types of things in most of my pages, it makes sense to include a lot of the leg work in a base class that each of my pages can inherit.  This blog post will provide you the default base class I always start with, and will explain and demonstrate a few of the methods.

At a high level, my base class is divided into the following four regions:

image

Query String Methods
Let’s take a look at the Query String Methods first.  Many pages will have support for query strings, and most of the time these query string values will need to be validated.  Consider a scenario where you are accessing data from a database, and you navigate to a page with a URL of http://webapp/page.aspx?id=10.  You pull out the ID query string value and pass that in as a parameter and retrieve the appropriate results.  But what if you modify the query string value and access a page with a URL of http://webapp/page.aspx?id=abc?  Are you checking to make sure the value is numeric? Are you even checking to make sure an ID query string has been specified?  Well, you should!  A lot of this logic can be wrapped in a base class, and through the use of inheritance and overridden methods, the specific logic can be written. 

I have three methods declared in my base class:

  • RequiredQueryStrings: Returns a list of all required query string keys.
  • CheckQueryStrings: Ensures all required query strings have been specified.
  • CheckQueryStringValues: Ensures the specified query string values are actually valid.

These methods are declared as follows:

/// <summary>
/// When overriden, returns a list of all required query string keys
/// </summary>
/// <returns></returns>
protected virtual List<string> RequiredQueryStrings() {
    return null;
}

/// <summary>
/// When overriden, checks the actual values of query strings
/// </summary>
/// <returns></returns>
protected virtual bool CheckQueryStringValues() {
    return true;
}

/// <summary>
/// Verifies the required query string are actually present
/// </summary>
/// <returns></returns>
protected bool CheckQueryStrings() {
    List<string> values = RequiredQueryStrings();

    if (values == null || values.Count == 0) {
        return true;
    }
    else {
        foreach (string value in values) {
            if (Request.QueryString[value] == null) {
                return false;
            }
        }
    }

    return true;
}


In addition to these methods, my base page’s Init method checks these methods and depending on the results, allows the rest of the code to run or redirects you to an error page:

protected override void OnInit(EventArgs e) {
    base.OnInit(e);

    if (!CheckQueryStrings()) {
        // all required query strings have not been specified
        RedirectToPage("Error.aspx");
    }

    if (!CheckQueryStringValues()) {
        // one or more query string values are invalid
        RedirectToPage("Error.aspx");
    }
}


To use this, I simply inherit my application pages from my PageBase class, and override the appropriate methods:

public partial class ViewWidget : PageBase {

    protected override List<string> RequiredQueryStrings() {
        List<string> values = new List<string>();
        values.Add("widgetID");

        return values;
    }

    protected override bool CheckQueryStringValues() {
        int widgetID = 0;
        int.TryParse(Request.QueryString["widgetID"].ToString(), out widgetID);

        return (widgetID > 0);
    }

    protected void Page_Load(object sender, EventArgs e) { }
}


Notice all I’m doing is overriding the base class methods, and specifying the things that are required.  It’s up to the base class to do the actual error handling, which in my case involves navigating to an error page.  The important thing to note is that the error handling logic is declared in ONE place.  Each individual page is only responsible for identifying the values that should be checked.

Now, when I access my ViewWidget.aspx page with a valid URL, such as http://webapp/ViewWidget.aspx?widgetID=10, I get the following page:

image


If I access it with an invalid URL, such as http://webapp/ViewWidget.aspx?widgetID=xyz, I get redirected to the error page:

image

 

Redirection Methods

Chances are your web application contains more than just one page, and you will have to navigate to other pages.  Once in awhile ASP.NET will throw a ThreadAbortException when redirecting to another page, which doesn’t matter, and we don’t really need to do anything when that occurs.  My redirection methods consist of two methods:

  • RedirectToPage: Redirects to a page and ignores the exception that is sometimes thrown.
  • RedirectToPageWithQueryStrings: Redirects to a page and includes all current query string keys and values.  Since this method ultimately calls RedirectToPage, any exception is also ignored.

These methods are declared as follows:

/// <summary>
/// Redirects the application to the specified page, and ignores the
/// erroneous error that is sometimes thrown
/// </summary>
/// <param name="url"></param>
protected void RedirectToPage(string url){
    try{
        Response.Redirect(url);
    }
    catch{
        // catch the ThreadAbortException that is occasionally thrown by ASP.NET
    }
}
/// <summary>
/// Redirects to another page and carries over all current
/// query string keys and values
/// </summary>
/// <param name="url"></param>
protected void RedirectToPageWithQueryStrings(string url) {
    string queryStringList = string.Empty;

    if (!string.IsNullOrEmpty(url)) {
        if (Request.QueryString.Count > 0){

            // rebuild the query string list
            for(int i = 0; i < Request.QueryString.Count;i++){
                queryStringList += string.Format("{0}={1}&",
                    Request.QueryString.GetKey(i), Request.QueryString.Get(i));
            }

            // remove the erroneous ampersand
            queryStringList = queryStringList.TrimEnd(new char[] { '&' });

            // append the '?' to the beginning
            if (!string.IsNullOrEmpty(queryStringList)) {
                url = "?" + queryStringList;
            }
        }

        RedirectToPage(url);
    }
}

 

View State Methods

I utilize view state occasionally, and have included a couple methods to help manage this:

  • GetViewStateValue: Retrieves a value from view state, and if it doesn’t exist returns the specified default value.
  • SetViewStateValue: Sets a view state value.
  • ClearViewStateValue: Clears a view state value.

These methods are declared as follows:

/// <summary>
/// Retrieves a value from ViewState
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
protected object GetViewStateValue(string key, object defaultValue) {
    return ((ViewState[key] == null) ? defaultValue : ViewState[key]);
}

/// <summary>
/// Sets a value in ViewState
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
protected void SetViewStateValue(string key, object val) {
    ViewState[key] = val;
}

/// <summary>
/// Clears a value from ViewState
/// </summary>
/// <param name="key"></param>
protected void ClearViewStateValue(string key) {
    ViewState[key] = null;
}

 

Cache Methods

I also leverage the application cache, and have included a few methods to help manage this as well:

  • GetCachedItem: Retrieves a value from the application cache, and if it doesn’t exist returns null.
  • SetCachedItem: Adds an item to the application cache.
  • ClearCachedItem: Removes an item from the application cache.

These methods are declared as follows:

/// <summary>
/// Returns an item from the application cache
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
protected object GetCachedItem(string key) {
    object returnValue = null;

    try {
        returnValue = Cache.Get(key);
    }
    catch { }

    return returnValue;
}

/// <summary>
/// Adds in item to the application cache
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="minutes"></param>
protected void SetCachedItem(string key, object value, int minutes) {
    try {
        Cache.Insert(key, value, null,
            DateTime.Now.AddMinutes(minutes), TimeSpan.Zero);
    }
    catch { }
}

/// <summary>
/// Clears an item from the application cache
/// </summary>
/// <param name="key"></param>
protected void ClearCachedItem(string key) {
    try {
        Cache.Remove(key);
    }
    catch { }
}

 


These are just a few of the methods that are good candidates for placement in a base class.  You could just as easily as methods to manage session variables, or some other type of common functionality in your application.  The point is to identify places where you can simplify and reuse code.  This will make it much easier to develop, maintain, and enhance in the future.

I’ve included my base page in the ZIP file below.  As always, my code is provide as-is and without warranty!

Download: PageBase.zip

Tags: ,
Posted in .NET, ASP.NET | 21 Comments »

Integrating a Custom ASP.NET Application into SharePoint (Part 2)

Posted by DevExpert on 25th February 2009

In my last post, I began describing how to integrate a custom ASP.NET application into SharePoint.  SharePoint is a fantastic platform for building applications, and being able to create your own pages and application structure is a huge win when you need to add missing functionality, or to integrate a non-SharePoint application into SharePoint.

My previous post covered the basics – where to place your custom artifacts, how to inherit the master page and navigation, and how the custom application runs in the context specified in the URL.  This post will briefly cover securing your application pages and will also cover some useful design and UI techniques to give your application a truly integrated look and feel.

If you took at a look at the code I provided, you may have noticed that my custom base class that sets the master page is inheriting from LayoutsPageBase.  This is a page in the object model that is specifically meant to be inherited, and provides us the means to check the users’ rights.  Since Natnael Gebremariam of Bamboo Solutions already did a fantastic job of explaining this and some of the nuances in his post here, I will skip that and just provide a high-level overview.  Basically there are 3 properties that can be overridden to customize the required permissions for your page:

  • AllowAnonymousAccess: A boolean value indicating if the page is accessible by anonymous users.
  • RequireSiteAdministrator: A boolean value indicating if the page is only accessible by site collection administrators.
  • RightsRequired: A list of SPBasePermissions that specify the granular permissions that are necessary to access the page.

For the purposes of this blog series I kept it simple, and I’m denying anonymous access, not requiring users to be site collection administrators, but requiring the user to have at least ManageLists and ManageWeb permissions:

protected override bool AllowAnonymousAccess {
    get {
        return false;
    }
}

protected override bool RequireSiteAdministrator {
    get {
        // only allow site collection administrators access?
        return false;
    }
}

protected override SPBasePermissions RightsRequired {
    get {
        SPBasePermissions permissions = base.RightsRequired
            | SPBasePermissions.ManageLists
            | SPBasePermissions.ManageWeb;

        return permissions;
    }
}

What I don’t particularly like is only being able to specify the permissions that are available through SharePoint, and not being able to specify my own. What if I wanted to check against Active Directory, or the users’ presence in a group, or validate against a line-of-business application?  It’s not built-in, but Natnael describes a pretty good approach that will allow you to accomplish this.

Alright, now that I have the security in place, I can begin building the application.  I’m going to pretend this application is a front-end to a line-of-business database that manages my Widget inventory.  The focus of the rest of this post is going to be on utilizing some out-of-the-box SharePoint web controls.  Don’t pay too much attention to the implementation of these, as this will serve as an overview of some of the server and user controls that you can leverage.  In future posts I’ll elaborate a little on some of these and provide the nitty-gritty details, but for the sake of brevity I’ll just be covering the basics here.

First, we need to register the controls that we are going to use at the top of the ASPX pages.  This is not a comprehensive list, but should give you the idea:

<%@ Register TagPrefix="wssuc" TagName="InputFormSection" Src="/_controltemplates/InputFormSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="InputFormControl" Src="/_controltemplates/InputFormControl.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ButtonSection" Src="/_controltemplates/ButtonSection.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBar" Src="/_controltemplates/ToolBar.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="ToolBarButton" Src="/_controltemplates/ToolBarButton.ascx" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


Toolbar/SPToolBarButton

Many applications have a need for a toolbar, and even SharePoint is littered with them.  You’re able to build one of your own by using the Toolbar.ascx user control (inside the CONTROLTEMPLATES folder), and the SPToolBarButton controls (found within the Microsoft.SharePoint.WebControls namespace):

<wssuc:Toolbar id="tb" runat="server">
    <Template_Buttons>
        <SharePoint:SPToolBarButton
            ID="btnAdd" runat="server" Text="Add Widget"
            ImageUrl="Images/add.gif" NavigateUrl="AddWidget.aspx" />
        <SharePoint:SPToolBarButton
            ID="btnRefresh" runat="server" Text="Refresh List"
            ImageUrl="Images/refresh1.ico" OnClick="btnRefresh_Click" />
    </Template_Buttons>
    <Template_RightButtons>
        <SharePoint:SPToolBarButton
            ID="btnHelp" runat="server" Text="Help"
            ImageUrl="Images/help.gif" NavigateUrl="Help.aspx"  />
    </Template_RightButtons>
</wssuc:Toolbar>


The above markup will render:

image 

SPGridView

The next control worth mentioning is the all-powerful SPGridView control.  This control is inherited from the ASP.NET GridView control which is already a great control, but the SPGridView provides a ton more functionality.  In supports grouping, it automatically inherits the styles of SharePoint, and you are able to add drop-down menus to your items, like users are already used to in lists and libraries.  The markup syntax is pretty straightforward:

<SharePoint:SPGridView
    ID="grid" runat="server" AutoGenerateColumns="false" AllowSorting="true"
    AllowGrouping="true" GroupField="Category" AllowGroupCollapse="true">

    <Columns>
        <asp:BoundField HeaderText="ID" DataField="ID" SortExpression="ID" />
         <asp:BoundField
            HeaderText="Name" DataField="Name"
            SortExpression="Name" />
        <asp:BoundField
            HeaderText="Price" DataField="Price"
            SortExpression="Price" />
        <asp:BoundField
            HeaderText="Quantity on Hand" DataField="QuantityOnHand"
            SortExpression="QuantityOnHand" />
        <asp:BoundField
            HeaderText="Date Added" DataField="DateAdded"
            SortExpression="DateAdded" />
    </Columns>
</SharePoint:SPGridView>


The above markup will render

image

Let’s take this a step further and add the familiar drop-down list to the Name column.  There are a ton of examples on how to do this in code-behind, most notably Powlo’s posts here and here, but here’s a little preview on how to do this in the markup.  First, we need to create our MenuTemplate, which defines the items in the drop-down list:

<SharePoint:MenuTemplate ID="menuTemplate" runat="server">
    <SharePoint:MenuItemTemplate ID="menuEdit" runat="server"
        Text="Edit Widget" ImageUrl="Images/gear.gif"
        ClientOnClickScript="javascript:editSomething('%ID%');" />
    <SharePoint:MenuItemTemplate ID="menuDelete" runat="server"
        Text="Delete Widget" ImageUrl="Images/delete.gif"
        ClientOnClickScript="javascript:deleteSomething('%ID%');" />
</SharePoint:MenuTemplate>


Next, replace the BoundField with an SPMenuField, and specify the menu this is bound to by assigning the MenuTemplateID property to the ID of the menu template we just created.  The TokenNameAndValueFields property assigns a token to a field in the data source.  In this example, I’m declaring two tokens, one for ID and another for Name, which can then be used elsewhere.  The NavigateUrlFields specifies the fields that can be used in the URL set in the NavigateUrlFormat property, and in the same order (it works like the String.Format() method):

<SharePoint:SPMenuField
    HeaderText="Name" TextFields="Name" MenuTemplateId="menuTemplate"
    TokenNameAndValueFields="ID=ID,NAME=Name" NavigateUrlFields="ID"
    NavigateUrlFormat="EditWidget.aspx?id={0}" /> 


The above markup will render:

image 


Form Fields

For creating form fields, there are a ton of ways to skin this cat, but I typically choose one of the following two approaches.  Typically your data-entry forms should either look like the forms used for new list items, or the forms for new lists, sites, or pages.  The simplest and arguably cleanest approach is to just use the ASP.NET controls you’re used to, such as a TextBox, DropDownList, etc., and place them in a table that have the SharePoint styles applied to them.  The end result will look something like this:

image

The markup is pretty simple; the important part is is the style classes applied to the elements, specifically ms-formlabel, ms-formbody, and ms-input.  For the sake of brevity, here is a portion of the markup for the above form:

<tr>
  <td class="ms-formlabel">
      Date Added:
  </td>
  <td class="ms-formbody">
      <asp:TextBox id="txtDateAdded" runat="server" CssClass="ms-input" width="200px" />
  </td>
</tr>
<tr>
  <td class="ms-formlabel">
      Category:
  </td>
  <td class="ms-formbody">
      <asp:DropDownList id="txtCategory" runat="server" CssClass="ms-input" width="200px">
          <asp:ListItem>Cheap Widgets</asp:ListItem>
          <asp:ListItem>Expensive Widgets</asp:ListItem>
      </asp:DropDownList>
  </td>
</tr>


The second approach is to make the form look like the new list/site pages in SharePoint.  This is perfectly fine too, but takes up a little more space:

image

The markup for this is a little more complex, and involves the use of InputFormSection and InputFormControl sections.  A sample of the markup used for the above form is as follows:

<wssuc:InputFormSection runat="server" Title="" id="dateSection">
    <template_description>
       <b>Date</b><br />Please specify a date.
    </template_description>
    <template_inputformcontrols>
        <wssuc:InputFormControl runat="server" LabelText="Date:">
            <Template_Control>
                <wssawc:DateTimeControl  ID="txtDate" runat="server"
                    DateOnly="true" /><BR />
            </Template_Control>
        </wssuc:InputFormControl>
    </template_inputformcontrols>
</wssuc:InputFormSection>  

<wssuc:InputFormSection runat="server" Title="" id="categorySection">
    <template_description>
       <b>Category</b><br />Please specify a category
    </template_description>
    <template_inputformcontrols>
        <wssuc:InputFormControl runat="server" LabelText="Category:">
            <Template_Control>
                <wssawc:InputFormTextBox ID="txtCategory" runat="server"
                    Columns="40" class="ms-input"  /><BR />
            </Template_Control>
        </wssuc:InputFormControl>
    </template_inputformcontrols>
</wssuc:InputFormSection> 

<wssuc:ButtonSection runat="server" ShowStandardCancelButton="false">
    <Template_Buttons>
        <asp:Button runat="server" class="ms-ButtonHeightWidth"
            Text="Save" id="btnSave" />
        <asp:Button runat="server" class="ms-ButtonHeightWidth"
            Text="Cancel" id="btnCancel" CausesValidation="false" />
    </Template_Buttons>
</wssuc:ButtonSection>


As you can see, it’s lot more code, but you’re given a few extra things to work with, like the label and label description to the left, and the extra space to the right.  You’ll also notice I’m using built-in SharePoint controls for the textboxes and the date picker.  There are a bunch of controls that you can leverage, many of which I’ll cover in a future post.  If you’re ambitious though, feel free to poke around the assembly with Reflector or the Object Browser in Visual Studio.  Here’s a screenshot of what you’ll find:

image

There’s all kinds of goodies that are available for us to use in our applications.  Stay tuned for a future post that will dive into a few more of them!

Tags: , , , ,
Posted in .NET, ASP.NET, Object Model, SharePoint, SharePoint UI | 25 Comments »

Integrating a Custom ASP.NET Application into SharePoint (Part 1)

Posted by DevExpert on 18th February 2009

One of the great things about SharePoint is in addition to all cool stuff it does out-of-the-box, you can add on functionality.  More importantly though, SharePoint can be a great platform to build your own application on top of.  In this series, I will show you how to build a custom ASP.NET application and integrate it seamlessly into SharePoint.

The first thing to understand is the location at which we will deploy our custom artifacts.  Since the application will run under the context of a SharePoint site, the files will be deployed to the LAYOUTS folder within the ~12 directory.  There isn’t a need to create a new IIS web site or virtual directory, as it’s using the SharePoint site.

Now, there are different opinions on where certain artifacts should go.  I really don’t think it matters; just personal preference.  One option is to stick with the folder structure that SharePoint uses, and just place a custom folder in each of the destinations that contain your custom artifacts.  Typically this involves placing your files in the following directories:

Type Destination  Reference Path 
.aspx 12\TEMPLATE\LAYOUTS\<ProjectName>\ ~/_layouts/<ProjectName>/Page.aspx
.ascx 12\TEMPLATE\CONTROLTEMPLATES\<ProjectName>\ ~/_controltemplates/<ProjectName>/control.ascx
web.config 12\TEMPLATE\LAYOUTS\<ProjectName>\ (none)
.css 12\TEMPLATE\1033\Styles\<ProjectName>\ /_layouts/1033/styles/<ProjectName>/style.css
.js 12\TEMPLATE\LAYOUTS\1033\<ProjectName>\ /_layouts/1033/<ProjectName>/script.js
.dll Either web app’s BIN directory or GAC (none)
Resource DLLs GAC (none)
Images 12\TEMPLATE\IMAGES\<ProjectName>\ /_layouts/images/<ProjectName>/image.gif
Custom Folders 12\TEMPLATE\LAYOUTS\<ProjectName>\ ~/_layouts/<ProjectName>/MyFolder/…

 

The other option (and my personal preference) is to put everything within a custom folder in the LAYOUTS directory, and only put those files that would require other changes in their respective places.  For example, since a SafeControls entry is required in the web.config for user controls, it makes sense to keep your user controls within that folder.  You could definitely put them inside the LAYOUTS folder with everything else, but then you’d have to create another SafeControls entry.

Type Destination  Reference Path 
.aspx 12\TEMPLATE\LAYOUTS\<ProjectName>\ Page.aspx
.ascx 12\TEMPLATE\CONTROLTEMPLATES\<ProjectName>\ ~/_controltemplates/<ProjectName>/control.ascx
web.config 12\TEMPLATE\LAYOUTS\<ProjectName>\ (none)
.css 12\TEMPLATE\LAYOUTS\<ProjectName>\Styles\ Styles/style.css
.js 12\TEMPLATE\LAYOUTS\<ProjectName>\Scripts\ Scripts/script.js
.dll Either web app’s BIN directory or GAC (none)
Resource DLLs GAC (none)
Images 12\TEMPLATE\LAYOUTS\<ProjectName>\Images Images/image.gif
Custom Folders 12\TEMPLATE\LAYOUTS\<ProjectName>\ MyFolder/…

 

Now that the file locations are ironed out, let’s start getting into how to develop the pages.  I will dive into utilizing built-in SharePoint controls, permissions, and some of the fancier stuff in later posts, and will focus on just getting a page to show up within SharePoint.  Your approach to this may differ, but this has proven very effective for me.  First, I create a new web application in Visual Studio, and create a folder structure that mimics SharePoint’s 12 directory:

image

You’ll notice that I have 2 web.config files – one is created when the project is created and can be used to test the project locally, and the other is the one that will be put into SharePoint.  My web.config that goes into SharePoint is very simple and looks like the following.  For testing purposes, I added a test application setting which we’ll retrieve shortly:

<?xml version="1.0"?>
<configuration>
  <system.web />
  <appSettings>
    <add key="customKey" value="Sample Value" />
  </appSettings>
</configuration>


The next part is probably the most important part of this whole process – setting up the ASPX markup correctly.  Since this page will be integrated into SharePoint’s master page, the same master page/content page principles apply.  The master page contains content place holders which define where page content will go, and the pages themselves define the content that gets inserted in these areas.  SharePoint master pages have a ton of content place holders, most of which we don’t need in a custom application.  The ones that are important are:

  • PlaceHolderAdditionalPageHead: The content area where custom scripts and styles will be referenced.
  • PlaceHolderPageTitle: The title of the page.
  • PlaceHolderPageTitleInTitleArea: The text that shows up right above the main content area.
  • PlaceHolderMain: The main content area.
  • PlaceHolderLeftNavBar: If you want to define your own QuickLaunch or left navigation, you could place it here.

Since it’s up to us to define the content within these place holders, all we need to do is add content areas to our ASPX page and put in what we want.  I only used the top 4 aforementioned areas, as I want to utilize the existing quick launch navigation menu:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs"
         Inherits="DevExpertise.LayoutsApp.Home, DevExpertise.LayoutsApp,
                   Version=1.0.0.0, Culture=neutral, PublicKeyToken=d39eedb6cff9b1c8" %>

<asp:Content contentplaceholderid="PlaceHolderAdditionalPageHead" runat="server">
    <link rel="Stylesheet" type="text/css" href="Styles/style.css" />
    <script src="Scripts/script.js" type="text/javascript" />
</asp:Content>

<asp:Content ContentPlaceHolderID="PlaceHolderPageTitle" runat="Server">
    Page Title - Custom Application
</asp:Content>

<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Title Area - Custom Application
</asp:Content>

<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <h1>This is a custom application!</h1>
    <asp:TextBox id="txtValue" runat="server" />
    <asp:Button id="btnSetValue" runat="server" Text="Click Me!" OnClick="btnSetValue_Click" />
</asp:Content>


This doesn’t do much, but will prove the concept.  You can see that I added a custom style sheet (style.css), and also a custom script file (script.js), just so you could see where they go.  In addition, I added a textbox and a button and attached an event handler for the Click event of that button.  In this event handler, I’ll retrieve the web.config setting I mentioned above and set the textbox to this value. The code-behind for this page looks like the following:

namespace DevExpertise.LayoutsApp {
    public partial class Home :System.Web.UI.Page  {

        protected void Page_Load(object sender, EventArgs e) {
        }

        protected void btnSetValue_Click(object sender, EventArgs e) {
            txtValue.Text = WebConfigurationManager.AppSettings["customKey"].ToString();
        }
    }
}

 
Since this code will be executed under the context of SharePoint, the same code access security restrictions apply here as with web parts and custom web services.  You basically have 3 options: adding the assembly to the web application’s BIN directory and setting the trust level to at least WSS_Medium in the web.config, creating a custom code access security policy for your application, or adding the assembly to the GAC.  There are plenty of resources regarding the advantages and disadvantages to each approach out there so I’ll spare you here.  For the sake of simplicity, I added the assembly to the GAC.

Next, I deployed my files to the SharePoint 12 directory.  Since I’m doing this in a development/test environment, I created a handy copy.bat script that uses XCOPY to copy the files to the respective directories.  As soon as this project is ready to be deployed, I’ll run my solution through WSPBuilder and will generate a deployable solution package (.WSP).

After the files are deployed, it’s as simple as typing in the correct URL.  The syntax for this is as follows:

http://server/site/_layouts/<ProjectFolder>/<PageName>.aspx

The URL is extremely important when accessing your application pages, as your application runs under the context of the SharePoint site specified in the URL.  What does this mean?  Well, if you access your page at http://server/_layouts/MyProject/MyPage.aspx, then it’s running under the context of the site collection’s root site, and accessing SPContext.Current.Web will return that site.  If you access your page at http://server/sites/it/blog/_layouts/MyProject/MyPage.aspx, then it’s running under the context of the blog site under the IT site collection, and SPContext.Current.Web will reflect that.  Why is this important?  Well, since the application pages live in the 12 directory on the farm, they’re globally accessible, and not limited to a single site collection or site.  You could even get to your application at http://CentralAdminUrl/_layouts/MyProject/MyPage.aspx, and it will be running under Central Administration’s context.  Now do you see the importance?  I will show you in a later post how to implement safeguards to mitigate this, but be aware for now that your pages are out there for everyone to access.

For my development machine, I will be accessing this at the following URL:

http://server/sites/devexpertise/_layouts/DevExpertise.LayoutsApp/Home.aspx

However, when I try to access this, I get the following:

image


No worries — all this is telling me is that we forgot to specify the master page.  Since this will “inherit” the master page and styles of whichever site it’s accessed from, we must set the master page to that of the current site.  To accomplish this easily for each of my application pages, I create a base LayoutsAppPage that sets the master page:

namespace DevExpertise.LayoutsApp {
    public class LayoutsAppPage : Microsoft.SharePoint.WebControls.LayoutsPageBase {

        protected override void OnPreInit(EventArgs e) {
            base.OnPreInit(e);

            try {
                this.MasterPageFile = SPContext.Current.Web.MasterUrl;
            }
            catch { }
        }
    }
}


You’ll notice that I’m inheriting this from LayoutsPageBase – this is a base class defined in the Microsoft.SharePoint.WebControls namespace that provides us functionality for creating these types of pages.  That’s beyond the scope of this first post, but I will touch on this later in the series.  Next, I inherit each of my application pages from my custom LayoutsAppPage base class:

public partial class Home : LayoutsAppPage {

}


Now if we access the page in the browser, we should get a functioning page.  Clicking the button should retrieve the application setting from the web.config as well:

image


Pretty slick, huh?  Stay tuned for the next posts in this series where we’ll look at how to secure our application and utilize existing SharePoint controls to provide a rich and familiar user interface.

Tags: , , , ,
Posted in .NET, ASP.NET, Object Model, SharePoint, SharePoint UI | 27 Comments »