I’ve been looking at and learning the Bing 2.0’s API recently, and comparing it to Google’s API. While browsing Google’s AJAX Search API I noticed that Google is focusing on letting their users embed simple apps/controls that take advantage of their search API which provide a lot of value for minimal time invested. I tried to find a similar offering from Bing but came up empty. That’s a pretty smart tactic because if I were an end user (read: not a power user) deciding to leverage an API for my site I would lean heavily toward Google because the barrier to entry is just a few lines of JavaScript. One of Google’s apps that I really liked was the NewsShow which lets users see rotating headlines and previews of Google News Search based on queries that you select. In an attempt to become familiar with the Bing 2.0 API and drink the MS Kool-Aid I decided to recreate that functionality using Bing as the search provider.
Google’s NewsShow
Alnur’s Some What Ghetto NewsShow Using Bing
I’ve copied the code into this blog post since it’s just JavaScript so what you’re, hopefully, seeing below is the actual control running. The code is straight forward: a loop that grabs news head lines for a specific topic, shows the first 4, and then repeats for the next topic.
Toronto Star
FORT COLLINS, COLO. – The Larimer County sheriff's department in Colorado says they have no indication a family was carrying out a hoax when they reported their 6-year-old son was in a helium balloon that floated away from their home. The boy was found hiding in the home's garage Thursday ...
The Ghetto NewsShow in full flight
Feel free to SAM (steal and modify) but if you end up using/improving it let me know!
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:
- 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.)
- Resolving an inheritance relationship if a base class is provided
- 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:
- Call the base constructor
- Pass parameters to the base constructor
- Override methods inherited from the base
- 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.
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.
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.
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.
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);
}
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:
- .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"))
- 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.
- 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.
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:
-
Go to Server Manager
-
Find the Features Summary
-
Click "Add Features"
-
Expand the ".NET Framework 3.0 Features" node
-
Select "WCF Activation"
-
Hit "Install"
Problem solved.
We've all used, and unfortunately some people continue to use, alert() to help debug JavaScript. Thankfully the Microsoft Ajax Library has a Sys.Debug class that exposes methods for logging messages to the browser’s JavaScript console. For reference:
To log a message to the console use: Sys.Debug.trace(“Log this message to the console”);
To dump an object use: Sys.Debug.traceDump(someObject);
If you don’t have a JavaScript console download the Web Development Helper for IE, and Firebug for Firefox, or add the following textarea element to your page:
<textarea id=”TraceConsole” rows=”50” cols=”50”></textarea>
This will display all your trace messages in the textarea.
There is an arsenal of tools readily available for unit testing web applications. Unit testing both the data access and business logic tiers is a common best practice and a requirement for developing complex web applications. Solutions typically contain hundreds of unit tests exercising every possible use case and edge case covering the data access and business logic tiers but the UI tier is consistently ignored because the tools to create UI unit tests are not robust enough and hard to use.
If you are familiar with VSTS you may be wondering if Web Tests can fit the bill. Although it is possible to exercise the UI using Web Tests they don’t really help you get down to the granularity of being able to assert that clicking a button causes a textbox to reset, and in this crazy world of AJAX and Web 2.0 we need a tool that handles dynamic changes to the DOM without breaking a sweat.
Enter WatiN (pronounced as what-in); a fantastic open source API that leverages the browser to conduct web tests instead of emulating it. WatiN integrates easily with the VSTS framework and tests can be coded using C# or VB.NET. Currently WatiN uses IE7 but a CTP has been released that allows you to test with Firefox as well.
The most impressive feature of WatiN is the level of access you have to the DOM. Web tests are able to find elements by id, index, name, text, CSS class, etc., iterate through collections of elements, and invoke any event.
The following is an example and explanation of how to use WatiN using VSTS. The source code is available at the end of the post.
Environment Setup
-
-
Extract the files and if you are using Vista unblock the assemblies
Creating the Project
The downloadable source consists of a C# Test Project that contains a single Unit Test. Be sure to add a reference to the WatiNCore.dll and also copy the Interop.SHDocVw.dll into your /bin. The code I’ll be showing below will differ from the downloadable source to save some space.
The Test
I’ll show the test first and then explain what’s going on.

Figure 1 – “Hello World” test
The test first creates an instance of IE and instructs it to navigate to live.com on a separate process. By creating the test on a separate process the session will not be stored across IE instances. The next instruction, which WatiN will call only after the entire page has loaded, queries the DOM to find a text field with the specified Id and once found enters the text. Next, the DOM is queried again to find a button with the specified name and the click event is triggered. Finally we assert true if the page contains our search text, and our IE object is disposed.
This test is very simplistic and very similar to the example test shown on the WatiN homepage except I’m searching live.com instead of google.com (Yes I like Kool-Aid!). In my next post I’ll cover some more advanced scenarios and some tips and tricks to help make your own WatiN experience a little easier.
Source code here
Unless you've been living under a rock you know that Microsoft has recently partnered with jQuery and will be shipping jQuery with future versions of Visual Studio. When the announcement was made I didn't know much about jQuery, how it would work with ASP .NET AJAX, or how it would interface with Visual Studio. I decided to do some research to fill in those gaps and then apply what I learnt by creating a very basic cascading CheckBoxList.
After I learnt jQuery (I read jQuery in Action -- and highly recommend it) and set up VS2008; building the app was very natural and required very few lines of code. Sufficed to say I’ve become a fan of jQuery and will be using it going forward for all my JavaScripting.
Environment Setup
Ok, first things first. The environment needs to be setup to use jQuery and the jQuery IntelliSense.
- Install the VS2008 patch to enable the jQuery IntelliSense here
- Download jQuery here and the jQuery IntelliSense here
- Create a scripts folder under the project and add both the jQuery and jQuery IntelliSense files to it
Creating the App
The app consists of two files: a web form that contains the HTML and jQuery code, and an Ajax-enabled WCF web service that returns JSON (JavaScript Object Notation) that will be rendered client side.

Figure 1 - Cascading CheckBoxList (Don't judge a book by its cover..I know it looks horrible!)
The Wiring
To start, create a new web form and place a ScriptManager on the page. Adding the ScriptManager will register the ASP .NET AJAX library for the page and allow the app to make web service calls. The app also needs to use jQuery so add a new ScriptReference to the ScriptManager and set the path to the jQuery file.

Figure 2 - Hooking up jQuery
The Markup
We’ll need two divs, with unique ids (I used chklstSelectLeauge and chklstSelectTeam), to hold the checkboxes. The first div will have two static checkboxes that can be added at design time. The second div’s checkboxes will be added by passing the div to a jQuery function that will load it with the JSON returned from the web service.

Figure 3 - Required HTML
That’s the entire HTML so it’s time for the fun stuff.
The jQuery
The benefit of using jQuery is that we’re able to embrace “Unobtrusive JavaScript” which means the behavior is separated from the structure. In order to achieve this paradigm the JavaScript needs to run after all the DOM elements on the page are loaded. Because we are using ASP .NET AJAX we’ll need to use its pageLoad() event instead of jQuery’s ready() event.
Building the cascading CheckBoxList breaks down into three smaller problems:
- Finding the checked league checkboxes
- Calling the web service
- Creating the team checkboxes
Let’s tackle these problems one at a time.
In order to find the checked league checkboxes we need to find all checkboxes under the div, iterate through them to find which ones are checked, and maintain a list of checked values. Well, that’s the traditional JavaScript way of solving the problem. The beauty of jQuery is that we can use a selector to do most of the work for us. Here is the code:

Figure 4 - Selecting checked checkboxes
The above jQuery selector finds all checked checkboxes that are contained in the specified div. It then applies a function that will run for each item in the set of checkboxes. This function appends, using Sys.StringBuilder which doesn’t suffer from the inefficiencies of string concatenation, the checkbox’s value to our list of values.
Now the app knows which leagues have been selected but when should we call this function? It makes sense to call it whenever we check or uncheck a league checkbox. jQuery makes that a breeze:

Figure 5 - Adding a click event
The click event needs to be set as soon as the page finishes loading so the code above goes in the pageLoad() function.
The next mini-problem is to call the web service. We’ll see the web service later but for now trust me that the following code is all you need to hit a WCF web service:

Figure 6 - Calling the web service
The code looks at the TeamServices namespace, then looks for a class called TeamService, and then calls the GetTeams method which accepts a list of leagues. The final parameter in the function call tells jQuery that after we make the call to GetTeams, and it is successful, to call the getTeamsComplete function. This is also known as the callback function. The getTeamsComplete function is used to fill the team div with the JSON. It expects the JSON returned from the web service and will then load the data into the div.

Figure 7 - The callback function
The final mini-problem revolves around the loadCheckboxList function that gets called in getTeamsComplete. I’ll show you the code first and explain it after.

Figure 8 - Working with JSON
Looks a lot like the getSelectedLeagues code right? The code first clears the div of any HTML using another function (you can check it out in the attached code at the end) and then starts building up a string, by appending the html needed for a checkbox, for each item in the object. After we have the string we stuff it into the div and we’re good to go. But what is inputData.First and inputData.Second? The answer lies within the web service.
The Web Service
I’m not going to show the entire web service but take my word that it contains a static list (_teams) that contains Triplet objects i.e. (leagueId, teamId, teamName) . The interesting code is the GetTeams method that we are calling from the populateTeams function in our web form. Here it is:

Figure 9 - GetTeams(...)
The method takes a comma separated list of leagues and performs a split resulting in a List of Strings (List<String>). Then for each item (or leagueId) we use LINQ to query _teams for a match and then return a List of Pairs i.e. (teamId, teamName). The web service takes the Pair object and serializes it to JSON so it looks something like {“First”:”foo”, “Second”:”bar”} and this explains why we used those properties in the loadCheckboxList function
We’re almost done. The final step is to go back to the web form and add a ServiceReference to the ScriptManager so it knows what web service to call.

Figure 10 - Hooking up the web service
That’s it! Hopefully this post has helped explain what is required to use jQuery and ASP .NET AJAX in a web app, and has given you some new ideas on how to illuminate the mind and dazzle the eye (bonus if you know where that line is from!).
Source code here
More Posts
Next page »