Home | Blog | Screencasts | Projects
# Thursday, March 12, 2009

My last post described a really simple scenario where I used a HttpHandler to configure StructureMap, then I showed some code that is used to replace the ‘new’ operation used to create a new instance like: ObjectFactory.GetInstance<NumberPrinter>()

 

This might seem a little clunky because you need to remember to use the StructureMap ObjectFactory, not all programmers are created equal, so it might slip through the cracks. What would a framework look like if it embraced the concept of DI?

Well it turns out that the ASP.MVC framework was designed from the ground up (or a mile up as the case may be, it was started on a plane flight). To configure StructureMap with ASP.NET MVC, firstly it’s OK to modify the global.asax (since this isn’t a SharePoint solution):

 

        protected void Application_Start()
        {
           
            StructureMapConfiguration.AddRegistry(new DIRegistry());

            ControllerBuilder.Current.SetControllerFactory( typeof(StructureMapControllerFactory)   );

        }

Here we configure StructureMap with the same method as my last post by using the StructureMapConfiguration.AddRegistry method. The second line is more interesting, we tell the MVC framework that we want StructureMapControllerFactory to be the factory class that creates our controllers. So the code to this class looks like:

 

public class StructureMapControllerFactory : DefaultControllerFactory
   
{
        protected override IController GetControllerInstance(Type controllerType)
        {
            try
           
{
                return ObjectFactory.GetInstance(controllerType) as System.Web.Mvc.Controller;

            }
            catch (StructureMapException x)
            {
                System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
                throw;
            }
        }       
    }

 

That’s pretty cool, so what it means now is that we can create our controllers to take an instance of anything we want to inject. Continuing from the example with a simple Number interface:

 

public class TestController : Controller
{
        INumber _number;
        public TestController(INumber number)
        {
            _number = number;
        }

        public ActionResult Index()
        {
           
            return View(_number.GetNumber());
        }

}

 

This means that the controller has been passed an instance of INumber that has been created by StructureMap. Once you do the initial setup, it’s now pretty hard to make any mistakes in regards to not calling the proper Create methods.

Thursday, March 12, 2009 11:30:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
ASP.NET MVC | code | StructureMap

One of my favourite Dependency Injection (DI) containers is Jeremy Miller’s StructureMap, it’s full featured and light weight, but what I really like the most is the fluent configuration API which means we can write code like this:

ForRequestedType<INumber>()
                .TheDefaultIsConcreteType<Number>();

 

I also like that you don’t need to put custom attributes in your code.

 

It’s all pretty abstract so lets assume we have a simple interface, I’m deliberately keeping it simple:

   

public interface INumber
{
     int GetNumber();
}

 

A simple implementation of this interface:

 

public class Number : INumber
{      
        public int GetNumber()
        {
            return 999;
        }      
}

 

 

I’ve built a really simple (read: don’t use this in anything other than an experiment, the DI container in SharePoint gets configured for every request, including for images and scripts). This handler calls StructureMapConfiguration.AddRegistry with a class that derives from Registry which contains our fluent configuration information.

 

Why have I implemented this as a HTTPHandler?

If you read the Guidance on How to enable Unity in a SharePoint Application (unity is Microsoft’s DI container), the first step is to modify the Global.asax file. I have a problem with doing this for the simple reason that your touching the SharePoint system files, any upgrade will likely cause problems. It really is a shame that you can’t access the application onstart event using another mechanism.

I most certainly agree that the application onstart event is the perfect place to setup your DI container and if your happy to modify and deploy your changes to a global.asax file then go right ahead, put the code below into this file.

 

So it got me thinking, would a DI container like StructureMap work if it was setup in the begin request method of a HttpHandler? so my test code is:

 

namespace DIHttpModule
{
    public class DIHttpModule : IHttpModule
   
{  
        public void Dispose()
        {
          
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            StructureMapConfiguration.AddRegistry(new DIServiceRegistry());

            INumber numberGen = ObjectFactory.GetInstance<INumber>();

            ((HttpApplication)sender).Response.Write("Number: " + numberGen.GetNumber().ToString());
        }      
    }

    public class DIServiceRegistry : Registry
   
{
        protected override void configure()
        {
            ForRequestedType<INumber>()
                .TheDefaultIsConcreteType<Number>();
        }
    }
}

 

So after I deploy and configure my HttpHandler I do in fact see the number ‘999’ display at the top of each page (it also breaks JavaScript etc. because it writes this value into every request)

What has happened is that the call ObjectFactory.GetInstance<INumber>() has created an instance of Number(), we didn’t have to explicitly new up a Number() object.

That is a pretty basic example, lets expand it a little:

 

public class NumberPrinter
{
        private INumber _number;

        public NumberPrinter(INumber number)
        {
            _number = number;
        }

        public string PrintNumber()
        {
            return _number.GetNumber().ToString();
        }
}

 

Notice the constructor, it takes an INumber interface, the constructor is special as far as StructureMap is concerned, if StructureMap is asked to create an instance of NumberPrinter it will see that the constructor takes an INumber parameter and will attempt to pass in an instance of that type.

 

So assuming we changed the HttpModule to the following code:

 

NumberPrinter printer = ObjectFactory.GetInstance<NumberPrinter>();
((HttpApplication)sender).Response.Write(" Number : " + printer.PrintNumber());

 

We can see that again our output is ‘999’, StuctureMap was smart enough to create an Instance of INumber and pass it in, if you think about it, that’s pretty cool. It means that you can replace any concrete Instance of INumber with a single configuration change, that is powerful when we want to test our object in isolation, which is a whole other topic.

 

That’s a pretty trivial example, we did the StructureMap configuration and called ObjectFactory.GetInstance in the same method, now lets try it out in a web part which will be invoked later in the page life cycle (also remove the response.write from the HttpModule):

 

public class NumberWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            NumberPrinter printer = ObjectFactory.GetInstance<NumberPrinter>();
            writer.Write("Web Part: " + printer.PrintNumber());
        }
}

 

Running this web part gives the expected result:

 

image

 

Again this is a really trivial example, that’s the point, you can clearly see that we are using a DI tool called StructureMap to create instances of our objects. Sure you could do away with the HttpHandler and move the configuration into the web.config file. But I do think the HttpHandler method warrants more thought however, because its useful when you introduce NHibernate to the mix, which is another framework that needs to do some expensive start up, which is also suited to the global.asax methods, but it does have some characteristics that should be managed per request, but that’s another post.

 

For now, hopefully I’ve proved some thought around DI and how can we manage the SharePoint deployments that really yell out for Application OnStart events without modifying the system file.

 

 

Thursday, March 12, 2009 9:10:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
code | Sharepoint | StructureMap
# Sunday, March 08, 2009

I thought it might be fun to play around with the people search of MOSS. I wanted to have an auto complete like experience, where you could start typing someone’s name and a list of suggestions are displayed below:

 

image

 

I started by including JQuery and the Autocomplete JQuery plugin into a style library.

 

Next I created a Handler called PeopleSearch.ashx, I placed this in the _layouts directory (or 12 hive \TEMPLATE\LAYOUTS )

The code for this handler is simple:

 

   1: <%@ WebHandler Language="C#" Class="GenericHandler1" %>
   2: <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
   3: <%@ Assembly Name="Microsoft.Office.Server.Search, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
   4: <%@ Assembly Name="Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
   5:  
   6: using System;
   7: using System.Web;
   8: using System.Data;
   9: using Microsoft.SharePoint;
  10: using Microsoft.Office.Server.Search.Query;
  11:  
  12: public class GenericHandler1 : IHttpHandler {
  13:     
  14:     public void ProcessRequest (HttpContext context) {
  15:         context.Response.ContentType = "text/plain";
  16:     
  17:         string prefixText = context.Request["q"]; 
  18:         using (SPSite siteCollection = SPContext.Current.Site)
  19:         {
  20:             // create a new FullTextSqlQuery class
  21:             FullTextSqlQuery query = new FullTextSqlQuery(siteCollection);
  22:             query.QueryText = string.Format("SELECT Title FROM SCOPE() WHERE FREETEXT(defaultproperties, '{0}*') AND \"Scope\"='People' ", prefixText);
  23:             query.ResultTypes = ResultType.RelevantResults;
  24:             query.RowLimit = 10;
  25:  
  26:             // execute the query
  27:             ResultTableCollection queryResults = query.Execute();
  28:             ResultTable queryResultsTable = queryResults[ResultType.RelevantResults];
  29:                         
  30:     
  31:             while(queryResultsTable.Read()){
  32:                 context.Response.Write(queryResultsTable.GetString(0) +  Environment.NewLine);              
  33:             }    
  34:         }      
  35:         
  36:     }
  37:  
  38:     public bool IsReusable {
  39:         get {
  40:             return false;
  41:         }
  42:     }
  43:  
  44: }

It simply executes a full text query on the People Search Scope with the current text as the argument. Download the handler here.

 

Next I added a content Editor web part to the PeopleSearch.aspx page and included the following JavaScript (in the HTML source view):

 

   1: <script type="text/javascript" language="javascript" src="http://server/Style%20Library/jquery-1.2.6.min.js"/>
   1:  
   2: <script type="text/javascript" language="javascript" src="http://server/Style%20Library/jquery.autocomplete.min.js"/>
   3:  
   4: <script type="text/javascript">
   5:  
   6:     $(document).ready(function() {
   7:  
   8:         $("input[id*='_InputKeywords']").autocomplete("/_layouts/PeopleSearch.ashx");
   9:         $("input[id*='_InputKeywords']").attr("autocomplete","off");
  10:     
  11:     });
  12:  
</script>

 

The first thing I do is add a new attribute to prevent IE (or Firefox) from showing the previous search items. The next thing is to add the call the autocomplete plugin on the search textbox (which is found with because we know the id always ends with _InputKeywords).

 

I also added some styles from the autocomplete css to the css of the site.

 

It’s really that simple to get look ahead searching on people in MOSS. In fact this same approach could work on all the search pages.

Sunday, March 08, 2009 11:07:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [3] - Trackback
code | JQuery | MOSS
# Saturday, March 07, 2009

A few weeks ago I posted about an issue that we were having with our Windows Server 2008 machines Blue Screening, at the time I thought it was related to VMWare ESX Server, it turns out that it was a bug with Windows Server 2008. Thanks to Thomas Vochten for the pointer.

See: http://support.microsoft.com/kb/962943

 

“FIX: You receive a Stop 0x0000007e error message on a blue screen when the AppPoolCredentials attribute is set to true and you use a domain account as the application pool identity in IIS 7.0”

Note This problem typically occurs on Web servers that host Office SharePoint Server 2007. This problem occurs because of the configuration requirements of Office SharePoint Server 2007 when Kerberos authentication is used. However, the problem may occur for any kind of Web site that is using Kernel Mode authentication, Kerberos authentication, and a domain account as the custom application pool identity.”

Saturday, March 07, 2009 9:03:41 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [1] - Trackback
IIS 7 | Tip
# Thursday, March 05, 2009

I’ve worked with many ASP.NET developers who don’t really know much beyond the reach of their code. These are guys that work on top of IIS every day, but don’t really have much of an idea of some of the cool things it can do. IIS 7 is in my opinion the best web server platform around, it’s about time that all web developers took some time to learn more about the capabilities of the platform, a good way to start learning is to look at what other people (or companies) have done on the platform:

 

1. Integrated Pipeline

The integrated pipeline is the magic piece of the puzzle, it means that you can write managed code for all aspects of the request to IIS. Previously you would need to write ISAPI filters and extensions in something like C or C++, now you can write a module in c#. You could kind of get around this with previous versions of IIS, where you would map all requests to the ASP.NET ISAPI, with IIS7 this is no longer needed as a managed handler can be registered for all file types (in fact its possible to write a module that runs before a php script .. for example).

More information on managed handlers in IIS7 can be found here.

 

2. URL Rewrite (aka Mod_Rewrite)

 

The Apache web server has had Mod_Rewrite for years and it was always frustrating that IIS couldn’t match this feature. Until IIS7 the most common option for the rewriting of URL’s was to purchase a third party product such as Helicon’s ISAPI Rewrite, this changed in IIS 7 with the introduction of the IIS 7 Rewrite Module (x86 or x64).

There is a lot of valuable commentary around about the value of URL rewriting for things like Search Engine Optimisation and the ability to create ‘hackable’ URL’s or perhaps protecting your bandwidth, I don’t need to point this stuff out, every web developer should be able to understand the purpose and value of URL rewriting.

A good how-to on IIS 7 URL Rewriting can be found here.

 

3. Bit Rating Throttling Module

 

The Bit Rating Throttling module (x86 or x64) is essential for any web developer who is planning on delivering video via the web. The idea is simple, why send all the video down to the client when there is no guarantee that the client will watch all that content, wouldn’t it be better to send the first bit down fast and then slow down and progressively monitor and change the speed at which the user gets the data delivered. It doesn’t have to work with video either, you could use this module to slow down the speed of any content to certain users (maybe you have a photo site and unregistered users download stuff faster than registered ones).

A good place to start to find out more is here, also Hanselman gave this topic some coverage here.

 

4. Application Request Routing

 

The Application Request Routing feature of IIS7 (x86 or x64) might seem a little odd for the average web developer and sure it kind of borders between the realm of network engineer and software architect. This module is basically a fancy proxy, it can perform load balancing and all sorts of cool routing based on, well pretty much anything you want to define. It performs it’s routing based at the application level (as opposed to a firewall which is at the network level), it means that it can make routing decisions based on things like server variables and requested URL’s.

A good overview can be found here.

 

5. Dynamic IP Restriction Extension

 

Although still in beta, the IP restriction extension does exactly what you think it would do (and probably more). Things like blocking requests based on the number of requests they have made in a defined time period (see Jeff Atwood’s scenario). If your interested in protecting content from certain countries (like what Hulu does with it’s content) or if your just looking for some SPAM protection, you could do a lot worse than checking out the Dynamic IP Restriction Extension (x86, x64).

The best starting point is here.

Thursday, March 05, 2009 4:03:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
IIS 7 | Tip
# Wednesday, February 25, 2009

I’ve started working on a new project for work, it’s going to be a fairly large build job. Recently we started looking at various ORM’s, for a number of reasons we settled on the Telerik OpenAccess product. The Visual Studio integration is pretty nice and it has all the features that you would expect from a commercial ORM, the one complaint that I have is the limited LINQ support.

In any case I ran into a problem with some prototype code, I had setup a post build script to run that would copy the assembly to a SharePoint bin directory, but I would always get the following error message when I tried to execute any ORM related code:

 

“Telerik.OpenAccess: No enhanced assembly has been found for meta-data construction. This may be caused by a missing app.config file (use app.config as embedded resource then) or by an insufficient references section in the configuration file (add the referenced enhanced assemblies there too) or by a wrong enhancement setting; please check your configuration”

 

It turns out that the Telerik tool uses a tool called VEnhance which will inject IL into your assembly, this IL is responsible for tracking changes in your persisted entities. What was happening was the build event would run before the VEnhance tool, so it was copying the assembly without the ‘enhancements’. An easy way to tell is to compare the assembly size, obviously the ‘enhanced’ version will be larger.

Wednesday, February 25, 2009 8:50:00 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
ORM | Tip
# Wednesday, February 18, 2009

I was looking for a new smaller (i.e. lighter) laptop for out of work use, I settled on a Dell Mini 9 after reading a number of good recommendations. My only gripe so far is the keyboard, I’m still miss hitting keys and the keyboard layout still causes me to look at the keyboard more than I would like, but I can see that I will get used to it, it’s not unusable like the Asus eeepc.

 

I thought a new machine would be the perfect time to give Windows 7 a good try, so far it’s been great.

I really like the new taskbar of Windows 7, but one thing I found after a few days of using the keyboard shortcut of ‘windows key’ + m, was the ‘show desktop’ button at the far right of the taskbar, it’s a little button that when clicked will show the desktop. It seemed fairly hidden (at least for me).

 

image

Wednesday, February 18, 2009 9:26:00 PM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
Tip | Windows 7
# Thursday, February 05, 2009

I’ve been a big fan of JQuery for a long time now, as I find myself using the ASP.NET MVC framework more and more, I find that I’ll tend to look towards a JQuery plugin as my first port of call if I need some client side functionality. However I’ve worked with a number of people who really like the ASP.NET AJAX control toolkit, usually these people don’t have much exposure to the vast richness of the JQuery landscape. So I thought it might be useful to point out some JQuery equivalents to the ASP.NET Ajax control toolkit:

 

ASP.NET Control Toolkit Accordian

JQuery:

image

http://jquery.bassistance.de/accordion/demo/

 


ASP.NET Control Toolkit Always Visible

JQuery:

This control shows a section of text that is always visible.

image

http://www.west-wind.com/WebLog/posts/388213.aspx

Alternatively the following code will provide the same effect as the ASP.NET control:

 

   1: $(window).scroll(function() {        
   2:         $('#jqueryScroll').animate({ top: $(window).scrollTop() + "px" }, { queue: false, duration: 350 });
   3: });

 


 

ASP.NET Control Toolkit Autocomplete

JQuery:

When you have typed more content than the specified minimum word length, a popup will show words or phrases starting with that value, the JQuery version can be easily bound to an ASP.NET MVC view that returns JSON data.

image

http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

 


 

ASP.NET Control Toolkit Calendar

Standard calendar functionality

JQuery:

image

http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.datepicker

 


 

ASP.NET Control Toolkit Cascading Dropdown

Surprisingly I couldn’t find a prebuilt JQuery plugin, the following links do show how simple it is to create using JQuery:

JQuery: http://devlicio.us/blogs/mike_nichols/archive/2008/05/25/jquery-cascade-cascading-values-from-forms.aspx

Other notable method (http://weblogs.asp.net/stephenwalther/archive/2008/09/06/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx)

 


 

ASP.NET Control Toolkit Collapsible Panel

JQuery:

image

http://roshanbh.com.np/2008/03/expandable-collapsible-toggle-pane-jquery.html or http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/

 


 

ASP.NET Control Toolkit Confirm Button

Very similar in functionally to the modal dialog plugin and the thickbox plugin.

JQuery:

image

http://www.ericmmartin.com/projects/simplemodal/

 


 

ASP.NET Control Toolkit Drag Panel

The standard JQuery UI library has the Dialog feature which is on par with the ASP.NET control toolkit.

JQuery:

image

http://docs.jquery.com/UI/Dialog

 


 

ASP.NET Control Toolkit DropDown

Simple menu drop down navigation

JQuery:

image

http://ayozone.org/2008/02/06/drop-down-menu-with-jquery/

 


   

 

ASP.NET Control Toolkit Drop Shadow

Create drop shadows around page elements, no images needed.

JQuery:

image

http://plugins.jquery.com/project/DropShadow

 


 

ASP.NET Control Toolkit Filtered Textbox

This plugin will restrict the input of a textbox, it may be used to allow only numeric input.

JQuery:

http://www.texotela.co.uk/code/jquery/numeric/

 


 

ASP.NET Control Toolkit List Search

The implementation of the JQuery control is a little bit different to the ASP.NET Ajax control, but it may still be useful.

JQuery:

image

http://rikrikrik.com/jquery/quicksearch/#examples  or  http://ejohn.org/blog/jquery-livesearch/

 


 

ASP.NET Control Toolkit Masked Edit

Another control that prevents certain input from being entered, this control allows for a mask to be displayed to help the user.

JQuery:

image

http://digitalbush.com/projects/masked-input-plugin/

 


 

ASP.NET Control Toolkit Modal Popup

A plugin that helps create modal experiences.

JQuery:

image

http://famspam.com/facebox or http://www.ericmmartin.com/simplemodal/ or  http://jquery.com/demo/thickbox/

 


 

ASP.NET Control Toolkit Slider

Create a winforms like slider.

JQuery:

image

http://docs.jquery.com/UI/Slider

 


 

ASP.NET Control Toolkit Mutually Exclusive CheckBox

Not so much a plugin, but sample code to show the concept.

JQuery: http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html

 

 


 

ASP.NET Control Toolkit Numeric up / down

A textbox control that has buttons to increment or decrement the number, much like the numeric spin button in winforms.

JQuery:

image

http://plugins.jquery.com/project/spin-button

 


 

ASP.NET Control Toolkit Password strength

A control that will help users pick a strong password.

JQuery:

image

http://plugins.jquery.com/project/pstrength or http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/

 


 

ASP.NET Control Toolkit Rating

The star rating control is flexible enough to work on down level browsers.

JQuery:

image

http://www.fyneworks.com/jquery/star-rating/#

 

 


 

ASP.NET Control Toolkit Resizable Control

Turns any DOM element into a resizable control, the user can expand the element by dragging the corner to make the control the desired size.

JQuery:

image

http://docs.jquery.com/UI/Resizables

 


 

ASP.NET Control Toolkit Rounded Corners

Use JQuery to create rounded corners without using images (if your browser doesn’t have an extension to create them).

JQuery:

image

http://plugins.jquery.com/project/corners

 


 

ASP.NET Control Toolkit Slide Show

A number of Slide Show and image carousel plugins are around, I’ve picked a couple below:

JQuery:

image

http://malsup.com/jquery/cycle/  or http://www.gmarwaha.com/jquery/jcarousellite/

 


 

ASP.NET Control Toolkit Tabs

JQuery:

The JQuery tab plugin is very powerful, it allows you to keep tight control over the page HTML

image

http://docs.jquery.com/UI/Tabs

 


 

ASP.NET Control Toolkit Textbox Watermark

A watermark control is simply a textbox with either an image or text inside that disappears when the user clicks inside the textbox.

JQuery:

image

http://plugins.jquery.com/project/jWatermark

 


 

ASP.NET Control Toolkit Validator Callout

JQuery:

An apples for apples equivalent can be found below

image 

http://www.carnovsky.net/samples/jquery_callout_plugin.htm 

Or a more complete and extensible validation plugin (which rivals the ASP.NET validation framework) :

image

http://jquery.bassistance.de/validate/demo/

Thursday, February 05, 2009 6:47:47 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [1] - Trackback

Statistics
Total Posts: 191
This Year: 4
This Month: 0
This Week: 0
Comments: 41