Why I Love The Microsoft Web Platform (And How I Built an Enterprise Ready Site in 48hrs)

There is no other web platform in the world that lets you build a fully functional, optimized, and scalable enterprise ready website in under 48hrs. Microsoft’s web platform provides you with a powerful set of tools, servers, and tech that can help you take an idea in your head and make it a reality within the blink of an eye.

Full Disclosure: If it wasn’t clear by the blurb next to the paper clip in the top left I work for Microsoft. Moreover, I work in DevDiv and see Scott Gu in the halls everyday. However, this really is my unbiased personal opinion of the Microsoft Web Platform.To understand the reasons behind why I’m writing this post I need to give you some background.

The Background
On a recent trip home to see family and friends I had the idea to create a 100% free dating website very similar to plentyoffish.com. Except, I decided to target it towards the Indian and non-resident Indian (NRI) audiences – I won’t bore you with why but if you’ve ever heard of Shaadi or BharatMatrimony then you know where this is going. I looked at my competition and designed a site in my head that would be able to compete with these juggernauts of Indian matrimony and dating. I called it Desi Spark (Desi means a person of Indian or Pakistani descent) and wanted it to be the first professional 100%
free Indian matrimony and dating website.

You can see the finished site here. If you know any desis please send the link their way! Smile

The Reason For Writing
Now back to the reason why I’m writing this. Put simply, it’s because I’m absolutely amazed at the raw power and robustness of what we at Microsoft offer. When you use all the offerings in concert you just have to step back and admire the beauty. Moreover, I LOVE the fact that every tool (except two) I used to create Desi Spark was for free and from Microsoft. Even more, I could have signed up for
BizSpark or WebsiteSpark and got immediate access to full-featured development tools! (If you’re a student check out DreamSpark).

Seriously, who else but Microsoft offers this?

Full Disclosure (A Little More):
Before we talk shop about how I built my own enterprise ready website I want to give a little more disclosure on my background. If you follow my blog you’ll likely have seen that 1) I don’t post regularly Smile with tongue out (more because of NDAs than anything else) and 2) I’m a big fan of ASP .NET, ASP .NET AJAX, and of course JQuery. I was a web dev for years before I turned PM so I’m pretty familiar with the technologies.

I did create Desi Spark in approximately 48hrs but I’ve subtracted away all the countless hours of design, graphics, and testing I spent. That is a pure development cost. If you’re like me you know with a good design things just work.

Dude, It’s Easy To Create A Dating Site In 48hrs
Well it is with the Microsoft Web Platform Smile. No, but seriously, I hear ya. If this was a cookie cutter site I’d fess up but it isn’t. It was created for the demographics I’m targeting and consequently has a lot of cool features like:

    1. Custom profiles depending on a user’s intent (i.e. matrimony or dating)
    2. Photo album upload with built-in cropping tool
    3. Advanced Hotmail style messaging system
        • message users
        • see sent mail
        • see who’s read or delete your messages
        • print messages
        • save messages
        • message limits
    4. Ability to see who’s viewed your profile
    5. Advanced search that finds matches on over 20 different criteria
    6. Custom matching algorithm to find compatible users
    7. Favorites system with ratings that you can sort on
    8. Contact preferences to determine who’s allowed to message you (based on multiple levels of criteria)
    9. Block users
    10. Friend referral system
    11. … and more… I’m getting tired of typing them all but I’ve taken some screen shots below so you can check it out Smile

desispark1desispark2desispark3

The Platform
OK, let’s talk shop. It’s all HTML 5 – just kidding! Let me walk you through my stack, and then through the tools I used.

The Framework
I used
ASP .NET which is free and has a rich set of features, integration with databases and makes web services a breeze (check out this post – a little dated but still enough to get you going).

Throw on ASP .NET AJAX and all their amazing rich controls and then add the Microsoft Ajax CDN to get JQuery (supported by Microsoft!) and JQuery UI and you’ve got an insane amount of UI power at your finger tips that all work seamlessly together. Don’t forget about jQuery validation for some slick client-side validation (but always always remember to validate on the server!).

So we’ve got the UI covered; what about data? Piece of cake! Easily add data-driven functionality by using the robust data controls, LINQ and LINQ to SQL. You literally just drag and drop and your entire data model is built in less than 60 seconds. No more fussing with DataSets. If you don’t know SQL then use LINQ to query your database. You don’t even need to write stored procedures anymore thanks to LINQ – it’s equally secure and probably optimizes better (although I will admit I used sprocs for any complex queries like searching and the matching algorithm, but for any simple select/create/update/delete operation I used LINQ to SQL).

We’re still not done. Finally, I used the Enterprise Library from Microsoft Patterns and Practices to implement all my exception handling and logging logic. Now I get emails when there is a P0 error, and everything else is logged to my database. Set up was simple thanks to the tools that it provides and all I had to do was implement a simple try/catch pattern to get the correct behavior.

The Database
On my local machine I installed
SQL Server Express which is free for both development and deployment. You get:

  • x32/86 or x64 support,
  • migration tools to easily import or export your data which comes in very handy when moving to a production database,
  • all the programmability support you need like full text search, CLR integration and XML support (this is very cool btw.),
  • intellisense,
  • and even reporting services allowing you to export to Excel, Word, or PDF

The Server
What else but
IIS which is again free to use! A modular and extensible platform for hosting your website. It’s has too many features to name but the most important takeaway is that it does all the work for you. It lets you host both .NET and PHP sites which was perfect for me since I wanted Desi Spark on ASP .NET but the Desi Spark blog on PHP.

Let’s Take A Breather
WOW – is it just me or is that a lot of powerful tech for zero dollars and zero cents ($0.00)! I hope you’re starting to see why I’m so excited and so proud of what Microsoft offers. The crazy thing though, is that I haven’t even mentioned the tools yet…

The Tools
I only needed four tools to create Desi Spark and 2 of them were from Microsoft, but they were all free.

Visual Web Developer Express
Visual Web Developer Express is a free development environment that you can use to create and test web applications. It has a design surface, powerful debugging, support for AJAX and jQuery, intellisense and integration with IIS.

SQL Server Management Studio Express
The
Management Studio is a free integrated environment for developing and configuring your SQL server. It had everything I needed to build an enterprise ready website.

AnjLab.SqlProfiler
During my debugging and testing an SQL profiler was the only tool I cried out for that wasn’t included. Thankfully someone has created a great tool that more than met my needs. Check it out
here.

Vault Source Control
Source control isn’t a must have but it sure makes life easier. I was unable to find a free 1 user license offered by Microsoft so I used
Vault which is straight forward to set up.

Conclusion
So there you have it. Everything I used to create Desi Spark – the first 100%
free Indian matrimony and dating website – all for free thanks to Microsoft. The framework made it possible, and the tools made it simple.

What has the Microsoft Web Platform empowered you to create?

AI

A Distributable (.exe) Silverlight OOB Application

I’ve seen a few questions regarding how to deploy a Silverlight Out of Browser application in an .exe over the past couple days. This post will show you one way of doing that.

  1. Create your Silverlight OOB app
  2. Open up a new .txt file and add:
    "%ProgramFiles(x86)%Microsoft Silverlightsllauncher.exe"
    /overwrite
    /emulate:"MyOOB.xap"
    /origin:http://www.mydomain.com
    (remove the line breaks & watch the spaces!)
  3. Save the file and change the file extension to .bat (i.e. run.bat)
  4. Run c:WindowsSystem32iexpress.exe as admin
  5. Follow the wizard until you’re prompted for the “Packaged Files”
  6. Add your .xap and .bat
  7. Continue until you’re promoted for the “Install Program to Launch”
  8. Type cmd.exe /C run.bat for the “Install Program”
  9. Complete the wizard.

You application should now be packaged in a distributable .exe.

P.S – If you’ve never heard of sllauncher.exe check out Tim’s blog post here.
P.S.S – Step 8 is only required if you’re deploying to an x64 machine. Otherwise just specify the .bat file.

Silverlight 4 Automation from A to Z

Silverlight 4 RC was released today. This post covers all you need to know about Silverlight 4 Automation.

Background

Automation (formerly called OLE Automation) is a COM-based technology that enables applications to exposes their unique and/or proprietary features to scripting tools and other applications. Consequently, by using Automation, developers can create custom applications that employ these features to automate frequent tasks.

Silverlight 4 RC

In Silverlight 4, a number of new classes have been added to the System.Runtime.InteropServices.Automation namespace to enable Automation. This allows Silverlight-based applications to play the role of an Automation client with the ability to directly access the programming model and services exposed by the Automation server.

This post will run through a simple example of how to 1) access the file system, 2) enumerate over a collection of files, and 3) handle an automation event.

Fundamentals

Before we get to the example, there are a few basic fundamentals that need to be called out:

  1. Automation is for Windows only
  2. Support for Automation revolves around late-bound COM — there is no intellisense
  3. Automation can only be run in an Out of Browser application
  4. Automation requires Elevated Trust
  5. Production trusted applications run with current user privileges and cannot elevate to admin even if the user has admin privileges
    (Note: this does not apply when debugging)
  6. COM events that return values are not supported

Example

The first step for the Automation client is to access the Automation server. This is done by ensuring the server is available and then calling CreateObject with a programmatic identifier to get a reference to the server. Since we are accessing the file system we’ll use Scripting.FileSystemObject as the prog id.

  1. if (Application.Current.IsRunningOutOfBrowser)
  2. {
  3. if (!AutomationFactory.IsAvailable)
  4. {
  5. MessageBox.Show("Automation not available.");
  6. return;
  7. }
  8. dynamic fileSystem = AutomationFactory.CreateObject("Scripting.FileSystemObject");
  9. }

(Note: If you don’t check if the server is available a NotSupportedException will be thrown on platforms where COM is not supported)

(Note: If there was a failure to load, locate or return a reference to the specific prog id an Exception will be thrown)

Now that we have a reference to our server we can directly access it and get a reference to a directory:

  1. dynamic folder = fileSystem.GetFolder("c:\program files");

One of the Automation features that wasn’t available in the beta was the ability to enumerate over an IEnumVARIANT collection returned from the server as a result, in this case, of a method call. With this support we can easily foreach to find all subfolders:

  1. foreach (dynamic subFolder in folder.SubFolders)
  2. {
  3. }

To show an example of handling COM events, let’s pump this collection into an excel spreadsheet and notify the user before they close the workbook. In C# there are three ways to attach event handlers to Automation events. You can use the +=/-= syntax that requires the specified delegate to have the same signature as the Automation event signature. Secondly, you can handle the EventRaised event if you don’t know the Automation event signature. Finally, you can use the AddEventHandler/RemoveEventHandler methods that require knowledge of the event signature. I’ve chosen to use the EventRaised event:

  1. AutomationEvent beforeCloseEvent = AutomationFactory.GetEvent(workbook, "BeforeClose");
  2. beforeCloseEvent.EventRaised += (sender, e) =>
  3. {
  4. MessageBox.Show("Closing workbook!");
  5. };

You can download a sample project here (VS2010 sln), and that’s the A to Z of Silverlight 4 Automation.

Silverlight Shortest Path Simulation

I recently accepted a PM position on the Silverlight team that I’m very excited about. I’ve always kept a close eye on Silverlight but never had the time to invest into the 1s and 0s of Silverlight development . As I slowly transition over I’ve made it a priority to get my hands dirty by building a few apps that use the core Silverlight features.

The first app I built was a simulation of Dijkstra’s shortest path algorithm. The app allows the user to create their own weighted graph (nodes connected by edges each with an associated cost) to run the simulation on. While running the simulation you’ll see the active nodes and edges changing colors as they get discovered, and chosen or rejected. You can play with the app below (source at the bottom) but one warning – this is a POC so error handling, testing, and UX are minimal.

[silverlight: http://alnurismail.com/wp-content/uploads/2011/10/ShortestPath.zip]

The UI is lacking and doesn’t have clear affordances for its use so here are the steps:
1) Make sure ‘Add Nodes’ at the top is selected then click anywhere to create some nodes
2) Make sure ‘Add Edges’ at the top is selected then click on two nodes to connect them with an edge
3) Set the weight of the edge by typing in a number in the textbox associated with the edge
4) Repeat to create a simple/complex graph

5) S
et the source and target (the value of the node) and run the simulation.

Go to the old blog to see the app in action here: http://weblogs.asp.net/alnurismail/archive/2009/12/16/silverlight-shortest-path-simulation.aspx

The goal of this POC was to create an app that showed the algorithm at work without tightly coupling the model (graph), algorithm (Dijkstra), and view (UI updates).

Here’s a high level overview:

1) Design

To avoid tightly coupling the model, algorithm, and view I used a design pattern similar to MVC. I opted for a similar pattern because with MVC it’s hard to have a controller that’s suited for an interactive UI. Instead I used the MVVM (Model-View-ViewModel) pattern which works well with Silverlight because it overcomes the interactive UI problem, and still lets you loosely couple the app.

The ViewModel sits between the View and the Model and knows nothing about the View. The View on the other hand is tightly coupled to the ViewModel because it consumes the ViewModel via data-binding.

For my app having a data-bound ViewModel didn’t make sense so instead I let the ViewModel throw events that the View would catch.

2) Graph

The graph breaks down into two logical objects: Nodes and Edges. I created a node user control, to abstract the Node logic for reusability, which gets created and added to the Canvas in response to the MouseLeftButtonUp event. I set the node-control’s position based on the mouse position using the Canvas.Left and Canvas.Top dependency properties.

  1. node.SetValue(Canvas.LeftProperty, …);
  2. node.SetValue(Canvas.TopProperty, …);

To connect the nodes with an edge I exposed an event that is called in response to the node-control’s MouseLeftButtonUp. This allows me to track which nodes the user is selecting. Once the user selects two distinct nodes I create a Line with it’s {X1,Y1} and {X2,Y2} properties set to the first and second nodes’ position respectively. To make it look “nicer” I use the Canvas.ZIndexProperty to push the edge behind the nodes.

  1. edge.X1 = edgeStart.X;
  2. edge.Y1 = edgeStart.Y;
  3. edge.X2 = edgeEnd.X;
  4. edge.Y2 = edgeEnd.Y;
  5. edge.SetValue(Canvas.ZIndexProperty, (int)edge.GetValue(Canvas.ZIndexProperty) – 1);

The final step is to add a Textbox so the user can assign a weight to the edge. This done in similar fashion to adding edges.

3) Simulation (Updating UI)

In Silverlight you can explicitly execute a method on the UI thread by calling Dispatcher.BeginInvoke(…) that accepts a delegate. However, you must ensure that you don’t block the UI thread with any lengthy computations like computing the shortest path.

Consequently, I created a new thread to run Dijkstra’s algorithm on.

  1. tAlg = newThread(newParameterizedThreadStart(FindShortestPath));
  2. tAlg.Start(newShortestPathAlgParams() { Source = txtSource.Text.Trim(), Target = txtTarget.Text.Trim() });

The algorithm updates the state of the nodes and edges in the graph which in turn raise a series of events that bubble up to the View that invokes the UI update.

  1. void ViewModelChangeEvent(object sender, ViewModelChangeEventArgs e)
  2. {
  3. Dispatcher.BeginInvoke(() => UpdateView(e));
  4. }

I’m eager to know if this was the best way to design and implement this POC in SL. If you look at the source and see anything that can be improved upon using existing SL features drop me a comment and let me know.

Source here. (Built using VS2010)

Part 2 – Object Oriented JavaScript (MS AJAX)

I recently gave a presentation on Object Oriented JavaScript (OOJ) and received some good feedback so the next few posts will be a more verbose version of that presentation.

AGENDA

Part 1 – JavaScript Review
Part 2 – How
Part 3 – Why Use OOJ?
Part 4 – Example

Part 2 – How

Custom Objects

Using what was covered in Part 1 we can start to create our own custom objects. First we need to write a constructor by using a function:

function Team(name, league) {    
    this._name = name;    
    this._league = league;
}
To create an instance of a Team we can use the function together with the new operator to create a new object and invoke the constructor
var t = new Team('Arsenal', 'EPL');
The Prototype Object

Briefly mentioned in Part 1 the prototype object defines the template of an object. It is similar to a class in C# because it holds all the properties that will be inherited by any instance. However, there is one major difference between an instance of an object in C# that inherits from a class, and an object in JS that inherits from the prototype – all objects and arrays added to the prototype are shared between all instances. Consequently, it is a best practice to store all the members in the constructor and all methods in the prototype. If you are interested in learning more about the prototype object you can [Kool-Aid alert] Bing it.

The Microsoft AJAX Library

If you’re using ASP .NET to build AJAX infused applications you’ve probably heard about and used the AJAX Control Toolkit. Maybe you’ve wondered how these MS guys create such powerful controls? Well, if you take a look at the source you’ll see that they are are using the MS AJAX library to OOJ (it’s a verb and a noun). So why the hype? Because the MS AJAX library lets you easily simulate OO constructs such as: classes, properties, interfaces and enumerations that are not currently supported in JavaScript. Let’s take a look at how to use the library…

Classes

To make the above Team object a class all we need to add is one line of code after the constructor has been declared:

function Team(name, league) {
    this._name = name;    
    this._league = league;
}

Team.prototype = {   
     getRoster : function() {        
        //..    
    }
}
//code responsible for making the constructor behave as a class
Team.registerClass('Team');
The registerClass in the above example is responsible for making the constructor behave as a class but it can do more that just that. It is responsible for:
  1. Registering the type name (ex. Team) in the constructor so you can access it at runtime (normally you declare a class by assigning it to a namespace variable so the class becomes an anonymous function which I talked about in Part 1. You always want to use the fully qualified name of the class otherwise you loose the ability to access it.)
  2. Resolving an inheritance relationship if a base class is provided
  3. Letting you specify one or many interfaces

Here is an example of how to use registerClass to do those three things :

FIFA.League.EPL.Team.registerClass('FIFA.League.EPL.Team'
                , FIFA.League.Team
                , FIFA.League.ITeam);
This translate to:
FullyQualifiedClassName.registerClass('FullyQualifiedClassName'
                                        , BaseClass
                                        , Interface);
Properties
To expose properties (aka getters and setters in C#) in a JavaScript object add two functions to the Team prototype object like so:

Team.prototype = {    
    //...    
    getName() : function () {return this._name;},    
    setName(): function (value) { this._name = value;}
}

By declaring member variables using this pattern there is no way to set private scope so although you could just directly get/set the variables you would loose the ability to perform any required logic. (Note: there is a way to make a variable private in JS using closures but it won’t work following the MS AJAX best practices. I’ll write another post about that because sometimes I’ve found MS AJAX to be overkill when you need a simple standalone object.)

Namespaces

From the registerClass example above the Team class is being accessed through a series of namespaces. To create a namespace use:

Type.registerNamespace('FIFA');
For a nested namespace use:
Type.registerNamespace('FIFA.League');

Inheritance

Remember that to accomplish inheritance in JS we need to inherit from the prototype object. We do this by using the registerClass method that was shown above. But, we also need a way to:

  1. Call the base constructor
  2. Pass parameters to the base constructor
  3. Override methods inherited from the base
  4. Call base methods

MS AJAX makes these four tasks fairly simple. To call the base class constructor and to pass it some parameters use the initializeBase(…) method that takes two parameters. The first parameter is the child class that is inheriting and the second is an array of parameters we need to pass. To override a method replace the function with your own just like in C#, and calling a base method is as easy as calling the callBaseMethod(…) method which takes three parameters: the current instance, the method name to call, and an array of method parameters.

Here is an example:

Type.registerNamespace('FIFA');

//Player Base Class
FIFA.Player = function (name, age) {    
    this._name = name;    
    this._age = age;
}
FIFA.Player.prototype = {    
    strategy : function() {        
        //Perform player logic    
    }
}
FIFA.Player.registerClass('FIFA.Player');

//Defender Derived Class
FIFA.Defender = function(name, age) {   
    FIFA.Defender.initializeBase(this, [name, age]);    
    //Perform additional logic 
}
FIFA.Defender.prototype = {   
     strategy : function() {       
         FIFA.Defender.callBaseMethod(this, 'strategy');        
        //Perform additional logic    
    }
}
FIFA.Defender.registerClass('FIFA.Defender', FIFA.Player);

Interfaces & Enumerations

Interfaces and enumerations follow a similar pattern. MS AJAX uses functions to implement both but we need to stop a user from calling the constructor to create instances of them, and also stop a user from calling the methods of the interface. This can be achieved by using Error.notImplemented() in the function body so the actions error out “by design”. We define the functions of the interface or the names of the enumeration in the prototype, and after the declaration call either registerInterface or registerEnum.

FIFA.Leagues.Teams.ITeam.registerInterface('FIFA.Leagues.Teams.ITeam');
FIFA.Results.registerEnum('FIFA.Results');

In the next and final part of this series I’ll talk about why you should use OOJ and also provide a comprehensive example that ties everything together.

Part 1 – Object Oriented JavaScript (Using MS AJAX)

I recently gave a presentation on Object Oriented JavaScript (OOJ) and received some good feedback so the next few posts will be a more verbose version of that presentation.

AGENDA

Part 1 – JavaScript Review
Part 2 – How
Part 3 – Why Use OOJ?
Part 4 – Example

Part 1 – JavaScript Review

Before we get to the good stuff I want to review the basic fundamentals of JavaScript which we will build on in Part 2.

JavaScript Objects

Believe it or not, JavaScript is a true object oriented language. However, objects in JavaScript are different than objects in C# because JavaScript doesn’t have classes which means you can’t create an instance of a class like you would in C#. Instead you need to manipulate the native Prototype object which can be though of as a template. The Prototype object will be discussed in detail a little later. So what is a JavaScript object? Put simply, a JavaScript object is no more than a collection of name/value pairs.

You can create a JavaScript object by using:

var person = new Object();

JavaScript Properties

JavaScript properties can be added at any time unlike C# where all properties are defined in the class. Properties can be added by using:

person.name = 'Alnur Ismail';

Or, to show that JS objects are really no more than a collection of name/value pairs we can use the indexed notation.
person['gender'] = male;

JavaScript Functions

In JS functions are first class objects. This is a fancy way of saying they can do everything regular objects can do such as being: instantiated, returned by other functions, stored as elements of arrays and assigned to variables. The latter, also referred to as an anonymous function, is important to understand when it comes to OOJ because when a function is assigned to a variable there is no way of getting to that function without knowing the property name. More on this later.

That’s all you really need to know about JavaScript to take advantage of OOJ. I’ll discuss the “how” of OOJ in Part 2.

Use ExpressionBuilder To Avoid “Server tags cannot contain constructs”

The ExpressionBuilder is still unknown to a lot of developers that haven’t experienced the sadistic pleasure of localizing a web application. It was introduce in ASP .NET 2.0 and allows you to bind values to control properties using declarative expressions.

I learnt about the ExpressionBuilder when I was doing some research on localization best practices in .NET. The recommendation is to use the specialized ResourceExpressionBuilder that creates code to retrieve resource values when the page is executed.

The ResourceExpressionBuilder is great for localization but what if we want to bind a control’s property to something else? Maybe a value in the Web.config’s AppSetting section. You may have tried something like this:

<asp:TextBox 
id="foo"
runat="server"
text="<%=ConfigurationManager.AppSettings["FooText"] %>"/>

Don’t be embarrassed. We’ve all done it at least once, and we’ve all been greeted with:

Parser Error Message: Server tags cannot contain <% … %> constructs.

Thankfully there is an ExpressionBuilder that can help. the AppSettingsExpressionBuilder provides access to values in the AppSettings section of the Web.config and we use it as follows:

<asp:TextBox 
id="foo"
runat="server"
text="<%$ AppSettings: FooText %>"/>

The ResourceExpressionBuilder and the AppSettingsExpressionBuilder are both derived from the ExpressionBuilder base class. That means we can create our own but I’ll leave that topic for another day.

Keep in mind that the ExpressionBuilder only works when it is assigned to the property of a control. So you won’t be able to use it, for example, to pass values to a JavaScript constructor.

Maintaining Context in a JavaScript Callback

For reference. To maintain context in a JavaScript callback use a closure and an anonymous function. For example:

var curObj = this; //closure to get context in callback
$('#foobar').animate({ height: 100 }, 1000, "jswing", function() { 
   alert(curObj.someProperty); 
});

To avoid the anonymous function use the Microsoft Ajax helper Function.createDelegate as follows:

this.animate = function() {
   $('#foobar').animate({ height: 100 }, 1000, "jswing", 
      Function.createDelegate(this, this.AnimateCallback)
);};

this.AnimateCallback = function() {
   alert(this.someProperty);
}

UI Unit Testing with WatiN – Part #2 – Tips & Tricks

In my first post about WatiN I introduced the open source API, and provided a simple demo to give a taste of what WatiN is capable off. I ended that post with a promise to write a follow up on some of the lessons I’ve learnt. Here they are:

  1. .NET control ids are not friendly
    WatiN allows you to select any DOM element based on a specified id (or a myriad of other attributes) as follows:
    _ie.TextField("controlId")

    Unfortunately, .NET control ids are rarely as friendly.You’ll quickly find your tests littered with control ids like ‘ctl00_ContentPlaceHolder_ControlId’ making the tests hard to read and overly verbose. The solution is to supply your own regular expression when selecting an element to match only the end of the control id as shown below.

    public static Regex PartialClientId(string partialClientId)
    {
       return new Regex(".*_" + partialClientId + "$");
    } 

    To use the regular expression you need to provide it as a parameter to the selector:

    _ie.TextField(PartialClientId("controlId"))
  2. Tests are linked to ids

    Finding a control by id (or name, class, etc.) creates a dependency on that id not changing. Refactoring a control’s id will break all tests relying on it causing you to make sweeping changes which takes time. The solution I use is to create a static class for each web form in my website, under my test project. The class defines constants for all control ids (or names, classes, etc.) that could be referenced in the unit tests. The unit tests use the constants instead of the actual control ids meaning that any change in the web form only needs to be made in one place.

  3. Tests repeat

    If you’re building a suite of tests for your website you’ll quickly see that you have to perform the same actions again and again. For example, if you’re testing your e-store you’ll have unit tests for searching for a product and adding products to the shopping cart. If you code these two tests from scratch, the second test would include searching for products. Again, this means if you make any changes to your search unit test you’ll need to make the same change somewhere else. A simple solution is to think of code re-use. Create helper methods for each action like searching, and then call it where appropriate. For example, my helper method would accept a search string and return the results grid.

That’s all I’ve got so far. Hope it helps.

Running WCF Ajax-enabled services on Windows Server 2008

Yesterday I was trying to run an ASP .NET website that leveraged multiple WCF Ajax-enabled services on a Windows Server 2008 box under an IIS7 application but kept running into the following JavaScript error: "Namespace.Service is undefined".

One of my co-workers had run into this recently and told me the problem was WCF Activation is turned off by default in Windows Server 2008. To turn it on:

  1. Go to Server Manager

  2. Find the Features Summary

  3. Click "Add Features"

  4. Expand the ".NET Framework 3.0 Features" node

  5. Select "WCF Activation"

  6. Hit "Install"

Problem solved.