ASP.NET MVC: Create Facebook-like search box

In today’s article I will show you how to create your own Facebook-like (or LinkedIn-like) search box. If you haven’t seen what it looks like, here is an example:

You will notice that it features: autocomplete, icon, matches what you type and when you click a result item, it takes you to the appropriate page. That’s what our control in MVC will feature too. We will implement this in ASP.NET MVC2 and jQuery.

The Plan:
We will create an attribute and use it to decorate the action methods of our controllers. When we decorate an action, we will be adding metadata, such as the display name it should appear with in the search results and an optional icon. When the user types something in the search control, we will use jQuery to POST to a special controller, which will be enumerating all action methods in all controllers. While enumerating, it will be looking for a match between the search query and the metadata of each ‘indexed’ action method.


Note: You can download the working demo project from here.

The Attribute
Ok, let’s start with the attribute. In your Code folder (if you don’t have one – go ahead and create it) add a new class and name it ‘ActivitySearchAttribute’. It will have two string properties – Text and ImageUrl. Implement it like that:

This is the attribute we will be using to decorate our action methods in the controllers. That way we will mark them as ‘searchable’.

Action-Method Decorations
Let’s create a couple of dummy controllers, with a couple of actions in each of them and decorate them with the newly created attribute. Like this:

As you can see, the icon property (“group.png” in the example) in the metadata is optional. Non-decorated action methods will not be returned as search results.

The Search Controller
Now let’s implement the search controller. Basically, what it will be doing is: receive a query string (e.g. “the”, as in the first image of this post), get all controllers, enumerate the action method of each controller, match the ‘Text’ property of the ‘ActivitySearch’ attribute (which we use to decorate the action) and then return an array of the matches with the appropriate URL to each result. Just like Facebook. I won’t paste the code here, as it is big, but you will find it in the attached sample project. The file is in Controllers and is named “SearchController.cs”.

Json Response
The search will be a dynamic thing. While the user types, we will be sending a request to a controller and we will be receiving a response. We need to create a class which we will serialize to JSON and use it as a response. In your Code folder, create another class and name it ‘ActivitySearchResultItem’. It will have three properties: Text, Url and Image. Implement it like that:

The Search controller will be returning an array of those, to the jQuery UI, as a JSON response.

The JavaScript / jQuery
Now, when we have the back-end, we just need to implement the front-end in jQuery and html. Note that our solution will be using a 3rd party library – jquery.autocomplete.pack.js
Additionally, we will put our javascript, in a file named “activitySearch.js”.

The auto-complete jQuery plugin will take care of attaching to the text-box and submitting/receiving data to/from the back-end controller. We just need to process and format the results. When the user clicks a result, he will be redirected to the URL property associated with the result item (see ‘Json Response’ above). Like that:

As you can see, the jQuery code expects that if there is an Image associated with the search result it should be in the /Content/images folder.

Here is how to setup your page which will contain the search-box control.

Now, when you have everything in place, start the project and just type in the search box some phrase which you know will hit a result. You should see something like:

The search results are clickable and when clicked, it will take you to the appropriate action. You can optimize the whole solution with various caching settings and techniques.

You can download the whole demo project here –

ASP.NET MVC2 – Creating a Display Template

ASP.NET MVC philosophy is “Skinny Controller, Fat Model, Stupid View“. The focus of today’s post is “stupid view”. What does this mean? Well, it means that you should avoid writing any logic in your views. A view should be as simple as wrapping the model’s properties in html tags.

If you are cornered, and must have some kind of a login in your view, it would be nice if it is neatly wrapped in a DisplayTemplate, so your code remains reusable, easy to read and maintain. What follows now is a tutorial on how to create one.

Problem: We have a Model which has a property “RemainingTime”, which is an integer and represents the estimated remaining seconds of some operation. We want to neatly format this time in the view, so that if it has a value of, let’s say, “5”, to be displayed as “5 seconds”. If it has value of “70”, to be displayed as “1 min, 10 seconds”, etc…

Solution: Create a reusable DisplayTemplate and use it to visualize the property.

We start by creating a new ASP.NET MVC2 “empty” project template. We don’t need the default authentication and home controllers, so that would do just fine.

As a first step, let’s create our Model. We’ll call it “RemainingTimeModel” and will have the integer property “EstimatedSeconds”. We will name the DisplayTemplate “SecondsFormatting”. So we go ahead and decorate the “EstimatedSeconds” property with the UIHint attribute, passing “SecondsFormatting” (which is the name of the DisplayTemplate we want to use) in its constructor. This attribute tells ASP.NET MVC which DisplayTemplate to use by default, for this property. Your code should look like this:

Second step is to create the actual DisplayTemplate. It needs to reside in the “Views/Shared/DisplayTemplates” folder, and be named “SecondsFormatting.ascx”. So, create a “DisplayTemplates” folder in your Shared views, then right click it and Add -> View. Check the ‘create partial view’ checkbox and give it the name we mentioned above. By default, this will create non-strongly typed ViewUserControl. We will extend this, to an integer. Open the “SecondsFormatting.ascx” file and change the Inherits=”System.Web.Mvc.ViewUserControl” to Inherits=”System.Web.Mvc.ViewUserControl . Now, when you refer to the Model object in this control, you are working with an integer. The Model that will be passed to this DisplayTemplate is the “EstimatedSeconds” property of the “RemainingTimeModel” model.

Now we just need to implement some logic in the control. Let’s do this:

Ok, we have the model, which has the seconds property, and we have a DisplayTemplate for it. Now we jsut need to use it. For this purpose, we will create one simple controller, which creates a new instance of the model and initializes it, then passes the model to a view. In the view, we will have: Html.DisplayFor(model => model.EstimatedSeconds). Like that:



See how clean your View remains? No logic in there, just a DisplayFor html helper call.

We can now go ahead and try it out, with a couple of different values. It formats it accordingly. Please note that there are much easier ways to format the time and it was used here just as an example of what we should do if our view requires to have a logic. If we try with 3732 seconds, it should display “1 hours, 2 minutes, 12 seconds”.

Now you know how to encapsulate your logic in DisplayTemplates and keep your main Views clean and neat.

You can download the demo project from here.

jQuery in SharePoint

There are rumors jQuery might be included as part of SharePoint 2010. In an anticipation for that, today’s article aims to show what the integration between SharePoint 2007 and jQuery looks like, how to use it and what are the benefits.

So what is jQuery?
jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML. It was released in January 2006 at BarCamp NYC by John Resig. jQuery is free, open source software Dual-licensed under the MIT License and the GNU General Public License. Microsoft and Nokia have announced plans to bundle jQuery on their platforms, Microsoft adopting it initially within Visual Studio for use within Microsoft’s ASP.NET AJAX framework and ASP.NET MVC Framework whilst Nokia will integrate it into their Web Run-Time platform.

Simply put, it is a high performance rapid development, AJAX-enabled library on top of JavaScript.

There are a lot of articles and tutorials out there, on how to use jQuery in general. Here is the most essential documentation you will need – the jQuery API.

SharePoint integration
Integration between jQuery and SharePoint boils down to finding a smart way to get a jQuery reference in your pages.

Basically you can do this ‘manually’, which is well described here or you can use an automated integration solution (see below).

The manual approach essentially consists of two steps:
1) Deploying the libraries (js) to a location which can be accessed by the pages – that would be the LAYOUTS folder in the 12 hive
2) Loading the libraries on the pages – by modifying the master page, load the library specifically in the page you want to use it or other… It is all well described in the posted article.

The automated solution is a better one. You can get “SmartTools jQueryLoader for SharePoint” which does the integration for you. There is a good article which walks you through the installation process, so we are not going to that here. Make sure you watch the video, though.

Just try it out

If you just want to quickly try the magic of jQuery in SharePoint out, without bothering with the full integration you can do what is described here. The example in this article uses jQuery library which is hosted on Google Code (rather than in your 12 hive) and it dynamically queries the SharePoint web service to retrieve your current tasks, then visualizes them on the page. No need to develop a web part, it is just as simple as that!

You should also check this out, although for some reason I couldn’t get it to work. Basically this is supposed to let you test any jQuery code, from a small ‘editor’ on your home page.

So what are the benefits of using jQuery in SharePoint?

Well, obviously it adds AJAX functionality to your SharePoint web application. You can now retrieve and visualize data asynchronously, without putting any load on the SharePoint server. It also allows you to create more appealing and faster UI.

Page elements control and flexibility
Additionally, SharePoint allows you to change content structure for subsites, lists, libraries, views, columns, content types and the Web parts, but sometimes that’s not enough. Sometimes developers/designers or users need to make changes to the functionality and appearance of a SharePoint site in a way that is not allowed by the IT department. Since SharePoint Designer is usually restricted, we need an alternative way. That would be jQuery. Just to give you a concrete example of such situation, here is a guy who had to make the corners of the quick launch menu rounded.

jQuery saves development time
jQuery simplifies the way you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. To summarize it one sentence only: couple of lines in jQuery allow you to do better what you could do with over 20 lines of JavaScript.

Many other…

  • You don’t have to check for null objects
  • CSS3 compliant and has a great CSS selector integration
  • Huge community which supports it. Many tutorials out there…
  • Simple and fast development
  • Lightweight!
  • etc…

jQuery 1.3 is fast. As in the “fastest JS framework out there”. Here are some nice tips on how to write a fast jQuery code.

Debugging jQuery in SharePoint
FireBug is the preferred way to debug jQuery (and JavaScript in general). Here is a nice article which goes into details.

Examples “jQuery & SharePoint” website.
jQuery sparklines
Showing random images in SharePoint 2007 using jQuery
Highlight SharePoint List rows conditionally
Paging large content in SharePoint using jQuery
Many other…

SharePoint Web Services Wrapper

Recently I noticed that a common reason for developers to seek help on the MSDN forum is related to difficulties understanding and/or utilizing the SharePoint Web Services. You can’t blame the developers. It’s much more convenient to work with an Object Oriented API, rather than exchanging XML messages with a Web Service. For example, take a look at the Lists.asmx -> GetListItems. Of course it’s no rocket science, but it will sure save time if you could avoid dealing with the XML directly.

I spent some time researching if there is some kind of a library out there which provides ‘managed’ access to those Web Services. I.e. – work with .NET objects, rather than construct and parse XML elements. The closest thing I have found is this and it’s totally outdated and incomplete. At least it’s some reassurance to me that I am not missing the big picture and indeed, there might be people who would appreciate such framework.

So, I decided to start a project which will try to implement such .NET Object Oriented API around the SharePoint Web Services. Of course, for those corner weird cases (as well for the advanced developers), the underlying XML will still be accessible. Here is a good description of all the SharePoint services. My goal is to cover them all, eventually. I will start with the most commonly used ones.

It is hosted on CodePlex –
The project is not published yet, as there is no single line of code written yet. I will be doing this in my spare time. Once I shape it to my liking, it will become open source and everyone is welcome to contribute.

Got comments? Suggestions/Objections? There is a similar library already implemented? Please do let me know.


SharePoint bug udating title of uploaded xml

Another interesting case…

Programmatically upload an xml file (extension should be .xml) to SharePoint document library. As soon as you upload it, try to change the Title field of the item.

So here is the code:

// We upload the file to SharePointSPFile file = Web.Files.Add(itemUrl, buff, true);Web.Update();

string newTitle = "Sample Title";SPListItem destItem = file.Item;destItem.File.CheckOut();// Try to change the titledestItem["Title"] = newTitle;destItem.UpdateOverwriteVersion();destItem.File.CheckIn(string.Empty,SPCheckinType.MinorCheckIn);

For any non-xml extension files it works, but for xml files the Title doesn’t change – it remains the same as the original name of the uploaded file. If you try doing this with another field of the item, it would work.

I came up with the following workaround:

SPFile file = Web.Files.Add(itemUrl, buff, true);Web.Update();

string newTitle = "Sample Title";SPListItem destItem = file.Item;destItem.File.CheckOut();destItem["Title"] = newTitle;destItem.UpdateOverwriteVersion();

// Work-around startdestItem["Title"] = newTitle;destItem.Update();// Workaround end

destItem.File.CheckIn(string.Empty, SPCheckinType.MinorCheckIn);

Anyone has clue what’s going on? Original MSDN forum thread is here.

Extending SharePoint Web Part


SharePoint provides a lot of different out-of-the-box Web Parts. But sometimes we wish a particular web part behaved in a little different way, or have some small extra functionality. Or we may want to implement a heavily modified Web Part, based on already existing one.

Today, I will show you how to extend the functionality of an already existing web part.

We will take for example the SharePoint RSS Viewer. It loads an RSS feed and visualizes it in a web part on a SharePoint site. One of its visible properties in the UI is the Feed URL. It’s a static string and doesn’t allow any kind of dynamic parameters. Example:


Those placeholders in my example are fictional, but you should get the idea of a dynamic value passed as a parameter to the service.

Our goal is to override the default behavior of the Feed URL field. We want to get to a point where we actually control how the Feed URL is being interpreted. We may want to replace placeholders with actual values, or do any other kind of adjustment of the URL, based on current and dynamic conditions. So here is the plan: we create a new web part, inherit the RSS Viewer web part and extend the Feed URL property.

Let’s start. Here is how the RSS View part settings look like in edit mode:

See the RSS Feed URL field? That’s what we are interested in.

Ok, start Visual Studio 2008 with the VSeWSS plugin installed. From the menu, start a new SharePoint -> Web Part project.

Give it a full trust

Change your namespace to something you prefer (for example, I will change it to HristoYankov). Rename the folder ‘WebPart1’ to ‘RSSAggregatorWebPartDynamicParam’. It will rename all classes and files for you. In the Solution Explorer, expand Properties and open AssemblyInfo.cs. Add this to the bottom:
[assembly: AllowPartiallyTrustedCallers]

and this to the top:
using System.Security;

Your Solution Explorer should look similar to:

Right click on your project, click on Properties, go to the Debug tab and set the SharePoint site URL you will be deploying to.

Open the RSSAggregatorWebPartDynamicParam.webpart file and set Title and Description to whatever you like.

Now, after your project is setup, starts the interesting part. Let’s inherit the RSS View control! What you need to do is…

Add this file as a reference – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\microsoft.sharepoint.portal.dll. This is where the RSS View class is defined.

Open your RSSAggregatorWebPartDynamicParam.cs file and change your class from this:
public class RSSAggregatorWebPartDynamicParam : System.Web.UI.WebControls.WebParts.WebPart

to that:
public class RSSAggregatorWebPartDynamicParam : RSSAggregatorWebPart

And add this statement:
using Microsoft.SharePoint.Portal.WebControls;

Basically, we no longer inherit the basic WebPart class. Instead, we now inherit the whole functionality of the RSS Viewer web part and all of its user interface!

You can also delete this function, as we are not going to do any changes there.
protected override void CreateChildControls()

So far so good. Now let’s override the Feed URL property! Add this to your class:

[DefaultValue(""),Resources("RSSWebpart_Property_FeedUrl_Text","RSSWebpart_ToolPart_Group","RSSWebpart_Property_FeedUrl_Description"),Personalizable(PersonalizationScope.Shared),WebBrowsable(true)]public new string FeedUrl{get{return base.FeedUrl;}set{base.FeedUrl = value;}}

And add this statement:
using System.ComponentModel;

Three things to note here:
1. The FeedUrl property is the one which handles the URL which points to the RSS feed.
2. Note the attribute on top of the property. If you don’t add it, it won’t be visible in the UI
3. Note the ‘new’ keyword. This way we hide the underlying base FeedUrl property.

Ok, now we have control over the Feed URL. What we should do, is change the way FeedUrl is being returned. Change your get to look like:

get{return OverrideURL(base.FeedUrl);}

And create this function:

private string OverrideURL(string url){// TODO: Process the URLreturn url;}

So, in OverrideURL we can change any way we like the URL that is set in the User Interface and then return it modified. At this point, it is up to you how to utilize this capability.

For the purpose of the example, let’s just look for the string #current_date# in the URL and replace it with the current date.

private string OverrideURL(string url){return url.Replace("#current_date#", DateTime.Now.ToShortDateString();}

At the end, your code should look like:

using System;using System.Runtime.InteropServices;using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint.WebPartPages;using Microsoft.SharePoint.Portal.WebControls;using System.ComponentModel;

namespace HristoYankov{[Guid("03badfa9-53e4-401a-bc60-28db88b202ac")]public class RSSAggregatorWebPartDynamicParam : RSSAggregatorWebPart{   public RSSAggregatorWebPartDynamicParam()   {   }

   [DefaultValue(""), Resources("RSSWebpart_Property_FeedUrl_Text", "RSSWebpart_ToolPart_Group", "RSSWebpart_Property_FeedUrl_Description"), Personalizable(PersonalizationScope.Shared), WebBrowsable(true)]   public new string FeedUrl   {       get       {           return OverrideURL(base.FeedUrl);       }       set       {           base.FeedUrl = value;       }   }

   private string OverrideURL(string url)   {       return url.Replace("#current_date#", DateTime.Now.ToShortDateString());   }}}

Now, right click your project and do ‘Deploy’. It should add a RSSAggregatorWebPartDynamicParam assembly to your GAC. When you go to your SharePoint site and do ‘Edit Page’ -> ‘Add Web Part’

you should be able to see your newly created web part listed in the pop up. Add it to the page. Put it in Edit Settings mode and set the Feed Url to something like:

It will be replaced by:
http://servername/service/Param1=06/06/2009 (for example)

NOTE: I just noticed this – as soon as you set the URL which contains the ‘placeholder’, the web part which is still in edit mode starts showing it with a replaced value (the date). I believe that the underlying value is still http://servername/service/Param1=#current_date#. So perhaps, in the method OverrideURL we should be taking into consideration if the web part is in edit mode. And if it is – just return the original parameter that was passed. Something like:

private string OverrideURL(string url){if (this.NotInEditMode){// Not in edit mode, perform changesreturn url.Replace("#current_date#", DateTime.Now.ToShortDateString());}else{// We are in edit mode, return URL as isreturn url;}}

I will be checking this later. As usual, you can get the full source code here.

But basically that’s it. With minimum amount of code and effort, we have extended the functionality of an already existing web part, to something that serves our concrete needs.

Hope this was helpful!