05 Jun 2008

Give Your ASP.NET Applications Velocity

6 Comments Uncategorized

Scaling ASP.NET Application just got easier with a new technology that Microsoft has just released that they have dubbed codename “Velocity”. This product is still in the early stages of development, but it is meant as a direct competitor against memcached. If you are not familiar with memcached, here is how it is described in Wikipedia:

memcached (pronunciation: mem-cache-dee) is a general-purpose distributed memory caching system that was originally developed by Danga Interactive for LiveJournal, but is now used by many other sites. It is often used to speed up dynamic database-driven websites by caching data and objects in memory to reduce the number of times the database must be read. Memcached is distributed under a permissive free software license.

So basically it allows you to create a distributed memory cache across your server farm, that allows any computer in the server farm to access the data in the cache. So there is no more issues with storing session data on server farms, or worrying about setting up common SQL stores of temporary data. This is also very practical for reducing database stress on Web 2.0 sites, many of the top Web 2.0 sites use this to reduce reads on the database.   The biggest user of memcached to date is Facebook.  This diagram below gives a basic idea of how distributed caching works.

Diagram of Velocity

There have been many Open Source projects for getting memcached working on C#, and most have been pretty successful, but because memcached was designed for the UNIX environment, porting memcached to a Windows Service has always lagged behind the actual releases of the required libraries to get memcached working. Enter Velocity, as the Velocity team describes:

Velocity is intended to provide distributed caching (in memory) for all .NET applications – from enterprise scale to web-scale. We believe that there are many applications that need a distributed caching mechanism, and that there is, therefore, a need for distributed caching as a core part of the .NET platform. We expect to have more integrated support for this functionality with other parts of the .NET platform in our upcoming releases.

There is also a pretty nice Velocity writeup on MSDN that goes in depth about how Velocity works as well as providing some basic code examples on how to get data into and out of your Velocity Cache. The current set of features looks pretty nice, and I can’t wait for Velocity to become more stable so I can introduce it in to the IdeaPipe mix.

Here is a breif overview of the Current Features:

  1. Support for different cache types, partitioned and local
  2. Support for different client types, simple and routing
  3. Load Balancing & Dynamic Scaling
  4. ASP.Net Integration, currently there is only a Session Provider
  5. Key and Tag based Access

And Beyond

  1. Availability – support for Failover when machines go down
  2. Replicated Cache – another cache type
  3. Embedded Topology – run the cache embedded within you application instead of as a cache service
  4. Notifications – Get notified when a object in the cache is updated
  5. Consistency Models – Support for both weak and strong consistency when doing reads/writes
  6. Native client access to the cache service (E.g – PHP, C++ etc)
  7. Manageability & Administration
27 May 2008

ASP.NET MVC Preview 3 Released

2 Comments Uncategorized

The ASP.NET MVC Team has released an refresh of MVC. To all those that are interested the new Preview Release is posted at:

http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=13792

The new release contains many new features over the 2nd Preview Release and the Interim Release from a month a half ago. In this post I am going to outline the features that are new from the Interim Release to Preview Release 3.

Action Method and Result Changes

As you remember from the previous release, you are now required to return an ActionResult. Many of the ActionResults were renamed to the following types:

  • ViewResult: Renders the specified view to the response.
  • EmptyResult: Does nothing. Returned if the action method must return a null result.
  • RedirectResult: Performs an HTTP redirect to the specified URL.
  • RedirectToRouteResult: Given some routing values, uses the routing API to determine the URL and then redirects to that URL.
  • JsonResult: Serializes the specified ViewData object to JSON format.
  • ContentResult: Writes the specified text content to the response.

There were also new helper methods added to the Controller class for these new ActionResult types.

  • View: Returns a ViewResult instance.
  • Redirect: Redirects to the specified URL. Returns a RedirectResult instance.
  • RedirectToAction: Accepts an action (and optionally a controller) and redirects to another controller action. Returns a RedirectToRouteResult instance.
  • RedirectToRoute: Redirects to a URL that is determined by the routing API. For example, this method lets you specify a named route. Returns a RedirectToRouteResult instance.
  • Json: Returns a JsonResult instance.
  • Content: Sends text content to the response. Returns a ContentResult instance.

One of the more interesting ActionResults is the JsonResult which returns a serialized form of your ViewData object using the JavaScriptSerializer class. I don’t know why they didn’t use the DataContractJsonSerializer, but the team probably had their reasons.

View Data Changes

There is also the addition of implicit conversion for Action methods that return anything other than an ActionResult.

If an action method returns null (or has a return type of void), the action invoker implicitly provides an EmptyResult instance, which does nothing. If an action method returns anything other than an ActionResult instance, the action invoker calls ToString(CultureInfo.InvariantCulture) on the instance and then wraps the return value with a ContentResult object, which writes the content to the response.

A Model property was added to ViewDataDictionary. For ViewDataDictionary, the type of this property is System.Object. For ViewDataDictionary<T>, the type of this property is T.

The ViewData property of ViewPage<T> is no longer replaced by T. In Preview 2, the MVC framework replaced the ViewData property with the specified strongly typed view data (that is, the T in ViewPage<T>). In Preview 3, the Model property of ViewData is set to the instance of type T.

Route Changes

An IRouteConstraint interface was added.

If a constraint value is specified as a string, the string is interpreted as a regular expression. If the constraint value is specified as an instance of IRouteConstraint, route processing calls the Match method of IRouteConstraint.

A new HttpMethodConstraint type was added, which changes the way you constrain routes on the HTTP method. Unlike previous versions of ASP.NET routing, in this release, the constraint name “httpMethod” is no longer special. Instead, use the HttpMethodConstraint to add a constraint based on HTTP verbs. The following example shows how to use the HttpMethodConstraint type.

routes.MapRoute(
    "route-name",
    "{controller}/update",
    new {action = "update"},
    new {httpMethod = new HttpMethodConstraint("PUT", "POST")}
);

Other Changes

The versions of the System.Web.Abstractions and System.Web.Routing assemblies that are included with the MVC project template have been changed to version 0.0.0.0. The versions that are included in the Preview 3 release are newer than those that ship in the .NET Framework version 3.5 Service Pack 1 Beta. Therefore, they were assigned a private version number so that no conflict occurs between the assemblies in this release and the assemblies installed by the .NET Framework 3.5 SP1 Beta release.

And a ton of bug fixes

So in conclusion the ASP.NET MVC team has released another great release. Many of the new features have been on the request list of many of the active MVC developers. I still have to try out a couple of my requests to see if they are included, but I will make sure to provide a new post with those details.

Update: ScottGu has just released his notes on the MVC Preview Release 3, which I must admit are more in depth than my own.

Update 2: I have also updated IdeaPipe to reflect the latest PR3 changes. It took me about an hour to go through all my code and then test it. I am pleased to report the default page is now working, so that you don’t need the Default.aspx page anymore.

23 May 2008

How to create a non-Native jQuery event

1 Comment Uncategorized

Today I had the need to create a custom event using jQuery, in order to launch a customized form validation event from a global submit event. I did this so I could focus in on the first form field that had an error. My event from the global.js script, that is included on every page of IdeaPipe, looks like this:

$("form").submit(function () {
	var valid = $(this).validate();
	
	// if the form didn't validate then focus the input on the first error
	if (!valid) 
		$(this).find(":input[error]:first").focus();
		
	return valid;
});

This is pretty standard jQuery. What this code above does is set a custom function for the submit event for any <form /> tag on the page. The submit event will only be allowed to continue if a return value of true is returned from the function.

I was able to create this custom jQuery event with the following code:

jQuery.fn.extend({
	validate: function (fn) {
		if (fn) {
			return jQuery.event.add(this[0], "validate", fn, null);
		} else {
			var ret = jQuery.event.trigger("validate", null, this[0], false, null);
			
			// if there was no return value then the even validated correctly
			if (ret === undefined)
				ret = true;
			
			return ret;
		}
	}
});

There are two different states to this method. Primarily because in JavaScript all parameters are optional for functions. So the two states of this function are:

  • validate(fn) – sets the event
  • validate() – fires the event

An example of setting the event is:

$("form.user-login").validate(function () {
	var userNameValid = ValidateLoginUserName();
	var passwordValid = ValidateLoginPassword();

	return userNameValid && passwordValid;
});

In this example the form is valid if both the login user name and password validate.

An example of using the event is the same as the method above.

$("form").submit(function () {
	var valid = $(this).validate();
	// do some stuff	
	return valid;
});

This may not be the standard bind() and trigger() that most jQuery programmers are use to, but I needed an event that would return a value of true or false, so that I my submit event handler knows if it should focus on errors or continue the submit process.

Hope everybody finds this useful.