DevExpertise

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

Implementing a LINQ version of SQL’s LIKE Operator

Posted by DevExpert on 25th September 2009

One of the requirements of one of my recent projects was to implement a search page which allowed the user to enter a search term that supported wildcards.  The search term could contain any number of wildcards in any position within that term.

If you’ve done anything like this before, you probably know there’s nothing built-in to LINQ that supports this type of behavior.  Sure, you could use a combination of String.StartsWith, String.EndsWith, or String.Contains, but this could quickly become too cumbersome if there are many wildcards and/or they are scattered throughout the search term.  Let’s look at a couple simple examples to illustrate…

Pretend for a second I was doing this in SQL, and I needed to get all values that start with the letter T.  I would do this:

select * from SomeTable where SomeField LIKE 'T%'


The .NET/LINQ equivalent would be this:

var results = (from v in values where v.StartsWith("T") select v);


Not too difficult.  However, what if you wanted to do the SQL-equivalent of this:

select * from SomeTable where SomeField LIKE '%a%a%'


You’d have do a little creative parsing.  It gets even worse when you as the developer doesn’t know what search term will be entered, how many wildcards will be included, and where in the term they appear.  It all has to be dynamic.

I did a little poking around to see if anyone has done this before, and the only thing I could find was recommendations on using StartsWith/EndsWith/Contains, which I already ruled out.  I also found the SqlMethods.Like() method which sounded perfect.  However after further research, discovered it can only be used on an entity directly retrieved from a DataContext, such as this:

using (DemoDataContext db = new DemoDataContext()){
    var results = (from v in db.SomeTable where SqlMethods.Like(v.SomeField, "*a*a*") select v);
}


If you try to use the SqlMethods.Like() method on anything except a DataContext’s Table<T>, you’ll get the following message:

“Method ‘Boolean Like(System.String, System.String)’ cannot be used on the client; it is only for translation to SQL.”

So much for that.  I decided to write my own extension method.  I figured I could write one fairly easily using a regular expression, and I was right!  I checked out a trusty RegEx cheat sheet and found the following relevant metacharacters:

  • ^     Indicates the start of a string
  • $     Indicates the end of a string
  • *     Indicates zero or more of previous expression

Knowing this, I wrote the following extension method:

public static bool Like(this string value, string term) {
    Regex regex = new Regex(string.Format("^{0}$", term.Replace("*", ".*")), RegexOptions.IgnoreCase);
    return regex.IsMatch(value ?? string.Empty);
}


Which I can then use like this:

var results = (from v in values where v.Like("*a*a*") select v);


I can even simplify this by wrapping it up in another extension method:

public static IEnumerable<string> Like(this IEnumerable<string> source, string expression) {
    return (from s in source where s.Like(expression) select s);
}


Now all I have to do is the following:

var results = values.Like("*a*a*");


Finally, a quick usage example to prove it works:

var values = new List<string>(){
    "Widget", "Gadget", "Whatchamacallit", "Gizmo",
    "Thingamabob", "Thingamajig", "Doodad", "Doohickey"};

var results = values.Like("*a*a*");

foreach (string result in results) {
    Console.WriteLine(result);
}


Which outputs:

image

 

Hopefully you’ll find this useful!

Tags: , , ,
Posted in .NET, LINQ, SQL Server | 3 Comments »

SharePoint Tip/Trick: Specifying a Relative Portal Site Connection Link

Posted by DevExpert on 5th May 2009

There are a variety of reasons why you’d want to create multiple site collections – to avoid recommended capacity limits, to provide a logical site structure, etc.  One of the drawbacks with creating multiple site collections is the lack of out-of-the-box functionality to access and share content across site collections.  While portal site connections don’t do anything to access or pull content, it does allow you to specify a “connection” to another site collection, which appears in the global breadcrumb.  This makes logical navigation easier.  Consider the following example:  a company needs to have separate site collections for each department (HR, accounting, IT, etc.), but there is also a “top-level”, shared area of the environment, which will be a separate site collection.  When you’re in each of the departmental site collections, it would make sense to have a link back to the top-level site collection, to insinuate a logical hierarchy. Simply put, a portal site connection gives you a breadcrumb link to another site collection.

Let’s take a look at the above example.  I created a root site collection (http://intranet.devexpertise.com), and also an accounting site collection (http://intranet.devexpertise.com/sites/accounting). When you’re on the accounting site collection, there’s no visual indication or link back to the “root” site collection:

image

By simply adding a portal site connection, we can provide a visual indication of the logical hierarchy and link back to the root site collection.  To add a portal site connection, navigate to Site Settings > Site Collection Administration > Portal site connection, and specify a URL and a friendly name for the link:

image

Now, the breadcrumb will show a link to the root site collection:

image

Great! …as long as you’re always going to access your sites from a single URL.  What if you have multiple URLs set up, such as the situation if you allow external access to your environment and have a separate external URL (http://extranet.devexpertise.com).  The logical thing would be to just specify a relative link for the portal web address, however SharePoint won’t let you, and pops up a nice “Please enter a URL for the portal site” error:

image

Why is this really a problem?  Well, let’s say you left it as http://intranet.devexpertise.com, and accessed it from http://extranet.devexpertise.com.  The portal site connection link would still point to the intranet!

image

Lovely, huh? Fortunately, you are able to easily set this to a relative link using a few lines of code:

using (SPSite siteCollection = new SPSite("http://intranet.devexpertise.com/sites/accounting"))
{
    siteCollection.PortalUrl = "/";
}


That’s it!  Now, no matter what URL you access the accounting site from, the portal site connection link will jump you back to the correct root site collection:

image

Tags: , ,
Posted in .NET, Object Model, SharePoint | 7 Comments »

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

Posted by DevExpert on 1st April 2009

At the end of my last post in the Integrating a Custom Application Into SharePoint series, I had completely forgotten that I promised to describe how to package everything up into features and solution packages, and how to deploy that to SharePoint in a simple and streamlined fashion.  I received a couple comments asking me to make good on my promise, so here it is! Ask and ye shall receive :)

In my last three posts here, here, and here, I began describing how to integrate a custom ASP.NET application into SharePoint.  The first post focused on the essentials, and detailed how to get your application into the SharePoint LAYOUTS folder structure, specifically where to place your files and how to inherit SharePoint’s look and feel by using its master page.  The second post focused on configuring permissions for your application and also demonstrated a few handy built-in controls that you can leverage to give your application that true SharePoint-like integrated look and feel.  The third post focused on navigation and how to integrate that with the out-of-the-box navigation that is provided with SharePoint.

The concept of SharePoint features and solutions packages is not a secret, and there is no shortage of articles, blogs, and how-to’s that document them.  Instead of reinventing the wheel and writing something up that describes what each of these are, here are a few excerpts I stole…err…borrowed from other sources:


Features

From MSDN:

“Features allow you to test, deploy, and activate custom functionality inside Office SharePoint Server 2007 and provide a way to make functionality available across your server farm. This functionality can be custom workflows, content types, modifications to the user interface, or new templates for lists and document libraries.”

From the SharePoint Developer Blog:

“A SharePoint feature is a module of functionality that can be enabled at specific scopes within a SharePoint farm, namely the farm level, web application level, site collection level, and site level.  SharePoint itself uses features for nearly everything it provides out of the box – the standard list definitions, the built-in site columns & content types, built-in web parts, and they are even used to define what is displayed on the Site Settings page and the Site Actions menu.  Each of the features, both built-in and custom ones, live within the “12” hive at 12\TEMPLATE\FEATURES, and each is contained within its own unique folder, whose name reflects the feature’s purpose.  Within this folder there is one and only one required file, whose name must be feature.xml.  This file defines the basic characteristics of the feature including its ID, name, description, activation scope, and visibility.  Additionally this XML file can define additional information that is specific to the feature itself, such as a receiving assembly, and potentially one or more element manifests.  Each element manifest that is defined is represented by an additional XML file that is also contained within the feature’s folder, and within these files is where the uniqueness of the feature comes out, as they can be used to define the set of files that the feature is going to inject into a given site, or the custom actions the feature will add to the Site Actions menu, or the site columns and/or content types that the feature will add to its targeted site, just to name a few.  Finally, in addition to the element manifest XML files, the feature’s folder can contain any number of other files and folders that are needed for the feature itself, based upon its intended purposes.”


Solution Packages

From MSDN:

“Microsoft Windows SharePoint Services 3.0 introduces a deployment mechanism named "solution packages." A solution package is a CAB file with a .wsp file-name extension that contains all the files that must be deployed on the front-end Web server and a set of XML-based installation instructions. Windows SharePoint Services provides a rich infrastructure that simplifies deployment of solution packages in a Web farm environment.”

From Bill Baer:

“Solution packages are designed to provide the ability to develop and deploy reusable  site and feature definitions, web part files, templates, assemblies, and code access security policies across one or more server farms.  A solution package is a cabinet file that can contain, site and feature definitions, web part files, templates, assemblies, and code access security policies.  A solution package contains a web manifest that that defines the list of features, site definitions, resource files, Web Part files, and assemblies to process when the solution is deployed.  The directory structure within the cabinet file dictates the resulting structure on the web front-end computer when the solution is deployed.”

 
In the simplest terms, a feature is used to deploy something to SharePoint.  One or more features can then be packaged up into a solution package, and that solution package can then be deployed to SharePoint.  Got it?

So, what can you use a SharePoint features to deploy?  Pretty much any custom development artifact.  Here are just a few of the items that come to mind:

  • Web Parts
  • Event Handlers
  • User Controls
  • Visual Studio-authored Workflows
  • Site Columns
  • Content Types
  • Site Definitions
  • List Templates
  • CSS style sheets
  • JavaScript files
  • LAYOUTS application pages
  • THEMES (I describe how here)
  • Custom Actions
  • Delegate Controls
  • Master Pages/Page Layouts/Files/Documents/List Items
  • Site Definitions
  • Web Services
  • WCF Services
  • HTTP Modules
  • HTTP Handlers
  • Executing custom code when the feature is activated/deactivated/installed/uninstalled
  • Staple other features onto existing site definitions

If you’ve developed any of these items, then you should know that many of these artifacts are deployed to somewhere in SharePoint’s “12 Hive” folder structure.  Certain types of files belong in certain places in the 12 Hive.  For example, images belong in the ~12\TEMPLATE\IMAGES folder, application pages belong in teh ~12\TEMPLATE\LAYOUTS folder, etc.  If you’re building a custom web part, you will be placing your web part assembly either in the GAC or in SharePoint’s bin directory.  If you’re deploying style sheets, then you need to place that in a different location.  What am I getting at here?  9 times out of 10 when we’re deploying custom development artifacts to SharePoint, we will be placing many files in multiple locations.  This is very troublesome and error-prone, because 1.) it’s very easy to miss one, or put a file in the wrong directory, 2.) it’s a tedious manual process, and 3.) it’s not the right way to do it.

To illustrate what I’m talking about, let’s examine the Visual Studio project I put together for this blog series.  If you take a look at the following screenshot of how I have my solution set up, the important thing to notice is my folder structure, which mimics that of the 12 Hive.  Inside these standard SharePoint folders, I place custom folders specific to the project I’m working on.  There’s a very good reason for this.  Let’s say you’re deploying a custom image to the IMAGES directory.  There are over 2,000 images in that folder, and adding yours into that folder makes it hard to find and is much less maintainable.  A better practice is to add your own sub-folder, then add your images to that which will isolate your files that belong to their respective solution.

image

As you can see, I’m deploying a lot of different files. I have some images, a script file, a style sheet, etc.  I also have a feature that will be used to provision Custom Actions, as I describe here.  Remember, a feature is just an XML file that describes what the feature does and what should be included with it.  My feature for the above solution is pretty simple, and only includes the CustomActions.xml manifest file reference:

<?xml version="1.0" encoding="utf-8"?>
<Feature
  Id="5856617E-BED2-4705-B030-735F7483225E"
  Title="DevExpertise Layouts Application"
  Description="Contains the necessary components for the DevExpertise custom LAYOUTS application."
  Version="1.0.0.0"
  Scope="Web"
  Hidden="false"
  ImageUrl="DevExpertise\devexpertiseLogo.png"
  ReceiverAssembly="DevExpertise.LayoutsApp, Version=1.0.0.0, culture=neutral, PublicKeyToken=d39eedb6cff9b1c8"
  ReceiverClass="DevExpertise.LayoutsApp.FeatureReceiver"
  xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="CustomActions.xml" />
  </ElementManifests>
</Feature>


Now it’s time to deploy everything.  While I could just copy all of these files to the file system manually, then install the Custom Actions feature on the SharePoint site, I instead bundle everything up in a single deployable solution package. Enter WSPBuilder.

Without getting into the nasty details of actually how to create a solution package from scratch, I will say that it’s a nightmare.  A solution package is a .WSP file, which is really a .CAB file.  To create .CAB files, you use MakeCab.exe, which involves creating your own .DDF file and XML manifest.  It’s ugly, trust me.  WSPBuilder eliminates the need to manually build these files, and offers a simple command-line interface to build the package, which traverses a 12 Hive folder structure and creates the solution automatically.

Most anything I do frequently, I have a script for.  Creating solution packages is no exception.  First, in my VS solution folder on the file system, I created a Solution folder that my script will generate the package in.  In addition, I included a 12 folder and a GAC folder.  The 12 folder will obviously contain the folder structure for the 12 Hive, and the GAC folder will contain all assemblies that will need to be deployed to the GAC.  WSPBuilder automatically builds this into the solution package for us.  To manage my solution creation and deployment, I use 2 scripts: wsp.bat to build it, and install.bat to deploy it.

My wsp.bat is as follows (NOTE, the last command that builds the package should all be on one line.  I had to break it up to fit into this post):

@SET WSPPBUILDER="C:\Tools\WspBuilder\WspBuilder.exe"
@SET SOLUTIONNAME=DevExpertise.LayoutsApp.wsp
@SET URL=http://server
@SET BUILD=Debug

ECHO Copying Files to Temporary Solution Directory
  xcopy bin\DevExpertise.LayoutsApp.dll Solution\GAC\ /y /r

ECHO Building Solution Package
  %WSPPBUILDER% -CreateWSPFileList wspfiles.txt -outputpath solution
    -12path Solution\12 -gacpath Solution\GAC -Excludepaths bin
    -createfolder true -wspname %SOLUTIONNAME%


This script only generates the .WSP file; I still need a script to install it.  My install.bat file is as follows:

@SET STSADM="C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\STSADM"
@SET SOLUTIONNAME=DevExpertise.LayoutsApp.wsp
@SET URL=http://server/

ECHO Removing Existing Solution
  %STSADM% -o retractsolution -name %SOLUTIONNAME% -url %URL% -immediate
  %STSADM% -o execadmsvcjobs
  %STSADM% -o deletesolution -name %SOLUTIONNAME%

ECHO Installing Solution
  %STSADM% -o addsolution -filename Solution\%SOLUTIONNAME%
  %STSADM% -o deploysolution -name %SOLUTIONNAME% -url %URL%  -immediate -allowGacDeployment -force
  %STSADM% -o execadmsvcjobs 

ECHO Recycling App Pool
  iisapp /a "Sharepoint - 80" /r

 
Now, you could just as easily fold both of these scripts into 1, but I like to be able to generate the solution package without actually deploying it sometimes.  Whatever floats your boat I suppose.

Once your feature is installed, you will see it appear in Central Administration > Operations > Solution Management:

image

Remember, this particular solution package is essentially responsible for 3 things: deploying files to the file system, adding an assembly to the GAC, and creating a web-scoped feature.  Once the solution is deployed, these will automatically be done for you:

Some of the files that were deployed to the LAYOUTS folder:

image

The assembly installed in the GAC:

image

And finally the web-scoped feature:

image


Good stuff, huh?  Hopefully you can see how easy it is to create features and solution packages, and understand why it is Microsoft’s recommended best practice for deploying custom SharePoint artifacts.  I know it seems like a lot of work, but once you do this once or twice and realize the benefits of what features and solution packages provide, I guarantee you’ll never look back.

 

Here are a few tools that may help:

Tags: , , ,
Posted in .NET, SharePoint, Visual Studio | 8 Comments »

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 3)

Posted by DevExpert on 4th March 2009

In my last two posts here and here I began describing how to integrate a custom ASP.NET application into SharePoint.  The first post focused on the essentials, and detailed how to get your application into the SharePoint LAYOUTS folder structure, specifically where to place your files and how to inherit SharePoint’s look and feel by using its master page.  The second post focused on configuring permissions for your application and also demonstrated a few handy built-in controls that you can leverage to give your application that true SharePoint-like integrated look and feel.

This post will explain how to add custom navigation for your application.  There are a few different approaches that I like to take depending on the application, and I’ll demonstrate a couple of them for you.  These can be used in any combination in order to achieve the navigation you’re aiming for.  In fact, I recommend a combination of these to achieve a fully integrated navigation structure.

Approach #1: Quick Launch Navigation
Now, modifying the Quick Launch navigation menu is a trivial task.  Simply go to Site Actions > Site Settings and find the settings to modify the navigation (Quick Launch on team sites, and Navigation on publishing sites), and add and remove nodes to your heart’s content.  While this manual method works just fine, it’s just that: manual.  I always have the mindset of if I’m already deploying an application somewhere, I might as well automate as much of the setup steps as I can.  Luckily through the use of features we are able to accomplish this easily.

For the sake of brevity, I am going to assume you know what a SharePoint feature is, what a solution package is, and how to create and deploy them.  If not, there are plenty of great resources out there that will help you out.  Anyways, the first step is to create the feature and associated feature receiver that will execute when the feature is activated on the site.  The feature receiver is going to utilized the SharePoint Object Model to create navigation items.

The first step is to create the feature receiver, which must inherit from the SPFeatureReceiver class and must implement the standard 4 feature operations: FeatureActivated, FeatureDeactivated, FeatureInstalled, and FeatureUninstalled.  For this post I’m only adding the items in the FeatureActivated event, but it’s probably a good idea to clean these up in the FeatureDeactivated event in case the feature is ever deactivated.  My feature receiver looks like this:

namespace DevExpertise.LayoutsApp {
    public class FeatureReceiver: SPFeatureReceiver {
        public override void FeatureActivated(SPFeatureReceiverProperties properties) {
            using (SPWeb site = (properties.Feature.Parent as SPWeb)) {
                // create the nodes
                SPNavigationNode widgetManagementNode = new SPNavigationNode("Widget Management",
                    SPUrlUtility.CombineUrl(site.Url, "DevExpertise.LayoutsApp/WidgetMgmt.aspx"), true);
                SPNavigationNode viewWidgetsNode = new SPNavigationNode("View Widgets",
                    SPUrlUtility.CombineUrl(site.Url, "DevExpertise.LayoutsApp/WidgetList.aspx"), true);
                SPNavigationNode addWidgetNode = new SPNavigationNode("Add Widget",
                    SPUrlUtility.CombineUrl(site.Url, "DevExpertise.LayoutsApp/AddWidget.aspx"), true);
                SPNavigationNode widgetSettingsNode = new SPNavigationNode("Modify Widget Settings",
                    SPUrlUtility.CombineUrl(site.Url, "DevExpertise.LayoutsApp/WidgetSettings.aspx"), true);

                // add the Widget management node to the menu (must be done first)
                site.Navigation.QuickLaunch.AddAsLast(widgetManagementNode);

                // add the sub-items to the Widget Management node
                widgetManagementNode.Children.AddAsLast(viewWidgetsNode);
                widgetManagementNode.Children.AddAsLast(addWidgetNode);
                widgetManagementNode.Children.AddAsLast(widgetSettingsNode);

                // update the site
                site.Update();
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
            // do nothing
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties) {
            // do nothing
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties) {
            // do nothing
        }
    }
}


As you can see, it’s not complicated at all.  Simply add as many SPNavigationNodes as you like!  The next step is to tell the feature to execute the custom feature receiver.  For that just add the ReceiverAssembly and ReceiverClass elements to your feature definition file:

<?xml version="1.0" encoding="utf-8"?>
<Feature
  Id="5856617E-BED2-4705-B030-735F7483225E"
  Title="DevExpertise Layouts Application"
  Description="Contains the necessary components for the DevExpertise custom LAYOUTS application."
  Version="1.0.0.0"
  Scope="Web"
  Hidden="false"
  ImageUrl="DevExpertise\devexpertiseLogo.png"
  ReceiverAssembly="DevExpertise.LayoutsApp, Version=1.0.0.0, culture=neutral, PublicKeyToken=d39eedb6cff9b1c8"
  ReceiverClass="DevExpertise.LayoutsApp.FeatureReceiver"
  xmlns="http://schemas.microsoft.com/sharepoint/">
</Feature>


Once the feature is properly installed, it will show up under Site Features (note that this is scoped at the site level, and will need to be activated on each site):

image


Cross your fingers, activate it, and you should the new navigation items:

image


Not too shabby for a few lines of code, huh?  You’re just as able to add items to the top navigation if you so desire too. 


Approach #2: Custom Actions

One of my favorite things about SharePoint is the ability to extend just about anything, making it a true application development.  Menu items are no exception, and they’re painfully simple to implement.  You are able to add a custom link to the Site Actions menu, Site Settings menus, list menus, individual item menus, Central Administration menus, etc.  If SharePoint has a menu somewhere, chances are you’re able to add your own item to it.  There are 2 ways to do this and I’ll only be demonstrating it one way.  In a future blog post I’ll show how to do all this stuff programmatically for an even more robust navigation structure.

For this sample Widgets application, I would like to take the navigation a bit further and add an item to the Site Actions menu and also create a group in Site Settings that will allow me to manage my application.  To accomplish this, I added a new element manifest to my feature called CustomActions.xml, which will define our custom actions.  Per MSDN, custom action files are included as part of a feature and deployed as XML element descriptions, and structured with a CustomAction element, which serves as the core definition for a single action of a link or toolbar item. The following is my CustomActions.xml file, which defines a single action for the Site Actions menu:

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="ManageWidgetAction"
    GroupId="SiteActions"
    Location="Microsoft.SharePoint.StandardMenu"
    Sequence="1"
    Title="Manage Widgets"
    Description="Manage your company's widget catalog."
    ImageUrl ="/_layouts/images/actionssettings.gif"
    Rights="ManageWeb,ManageLists">
    <UrlAction Url="~site/_layouts/DevExpertise.LayoutsApp/ManageWidgets.aspx" />
  </CustomAction>
</Elements>


Let’s break this down a little bit:

  • Id.  The ID of your custom action.
  • GroupId. A pre-defined or custom that determines what group it will be placed into.  A comprehensive list of built-in values can be found here.
  • Location.  The location at which your custom action will be applied.  A comprehensive list of built-in values can be found here.
  • Sequence.  The order in which your custom action will appear in relation to other custom actions.
  • Title.  The display title of the action.
  • Description.  The description of the action, if applicable.
  • ImageUrl. The image that is displayed next to the action, if applicable.
  • Rights.  A comma delimited list of SPBasePermission enumeration items.  A comprehensive list of values can be found here.
  • RequireSiteAdministrator.  A true/false value indicating if this option is only visible to the site collection administrator.
  • UrlAction: This element defines where the link will take you.  Be sure to specify either the ~site or ~sitecollection token which tells SharePoint to build the URL relative to either the site or site collection, respectively.

Simply modify the feature to include this element manifest, redeploy it, reactivate it, and you should see the following in your Site Actions menu:

image


Easy, huh?  Let’s take this a step further and add a few items to the Site Setting page.  You can either add items to existing groups on that page, or create your own.  I created my own by specifying CustomActionGroup in my CustomActions.xml file, as well as a few CustomAction elements that will be a part of my custom group.  The XML is fairly straightforward:

<CustomActionGroup
  Id="LayoutsAppCustomActionGroup"
  Title="Widget Application Settings"
  Sequence="1"
  Location="Microsoft.SharePoint.SiteSettings">
</CustomActionGroup>

<CustomAction
  Id="UserGroupAdminLinkForSettings"
  GroupId="LayoutsAppCustomActionGroup"
  Location="Microsoft.SharePoint.SiteSettings"
  Rights="ManageWeb,ManageLists"
  Sequence="1"
  Title="Manage Widget Categories">
  <UrlAction Url="~site/_layouts/DevExpertise.LayoutsApp/Categories.aspx" />
</CustomAction>

<CustomAction
  Id="UserGroupAdminLinkForSettings"
  GroupId="LayoutsAppCustomActionGroup"
  Location="Microsoft.SharePoint.SiteSettings"
  RequireSiteAdministrator="TRUE"
  Sequence="2"
  Title="Modify Widget Permissions">
  <UrlAction Url="~site/_layouts/DevExpertise.LayoutsApp/Permissions.aspx" />
</CustomAction>


The only notable thing to point out here is for the CustomAction elements, the GroupId is that of the CustomActionGroup I specified first.  This tells SharePoint to put these actions in the custom group.  Redeploy and reactivate your feature, and you will now have this in your Site Settings page:

image


Hopefully you can see from this post that it’s pretty easy to build navigation for your custom application and have that created when your application is deployed via a custom feature.  In the next and final post in this series, I will show my approach to packaging everything up into features and solution packages, and how to deploy that to SharePoint in a simple and streamlined fashion.  Stay tuned!

Tags: , , , , ,
Posted in .NET, Object Model, SharePoint, SharePoint UI, XML | 10 Comments »