After Thought

Archive for March 2009

Magic Strings O Magic Strings

with 7 comments

I guess we all agree that magic strings in code become very annoying to maintain in the long run.  Some of the instances where you can be using magic strings is if you are trying to get the property name using reflection

typeOf(User).GetProperty(“UserId”)

or create a Html TextBox in asp.net MVC

<%= Html.TextBox(“UserId”) %>

Enter Static Reflection to relieve us from using the quoted text or magic strings. Let us try to get the propertyname UserId in the User class below without using magic string “UserId” in the code.

public class User
{
  public string UserId { get; set; }
}

We can do this using normal reflection as shown in the beginning of this post or as shown below:

Expression expression = (User user) => user.UserId;
MemberExpression memberExpression = (MemberExpression)expression.Body;
Console.WriteLine(memberExpression.Member.Name);

You can enclose the 3 lines of code above in a method named GetPropertyName.

public static string GetPropertyName<T>(Expression<Func<T, string>> expression)
{
	MemberExpression memberExpression = (MemberExpression)expression.Body;
	return memberExpression.Member.Name;
}

You can now get the property name just by calling the method

GetPropertyName((User user) => user.UserId).

By not using  “UserId” in the code, we have eliminated any chances of rename accidents or any chance of missing the usage of the property when you do Find Usages. This post by Clinton Sheppard gives more detail on the topic.

Written by shashankshetty

March 21, 2009 at 2:44 pm

Fluent Interface

leave a comment »

The term Fluent interface was first coined by Martin Fowler and Eric Evans. Refer to this article by Fowler. There are a lot of write-ups on the web on this topic including Josh Flanagan’s blog which was my first introduction to the topic. According to the definition in wikipedia, fluent interface is implemented using method chaining where the new context is same as the last context.
Below is an example to add car accessories. When we buy a new car, we tend to add accessories like leather seats, power windows etc to the car. We can implement it using fluent interfaces to make it look more readable and clean.

public class Car
{
	public Car AddLeatherSeats()
	{
		//Add Leather Seats
		return this;
	}

	public Car AddPowerWindows()
	{
		//Add Power Windows
		return this;
	}
}

So now if you have an instance of Car named instanceOfCar you can simply say

instanceOfCar
  .AddLeatherSeats()
    .AddPowerWindows();

Extension methods lets us implement fluent interface on existing objects. Suppose, we need a method to add MoonRoof, we can simply add an extension method.

public static class CarAccessoriesExtensions
{
	public static Car AddMoonroof(this Car car)
	{
		//Add Moonroof
		return car;
	}
}

Now you can say,

instanceOfCar
  .AddLeatherSeats()
    .AddPowerWindows()
      .AddMoonroof();

One thing to keep in mind here is we shouldn’t use fluent interfaces everywhere.  We have to use it in places where its addition makes code more readable by taking out the noise. It may be a good conversation to have on when and where fluent interfaces should be used. Any comments and suggestions would be great.

Written by shashankshetty

March 9, 2009 at 4:59 pm

Using JsonResult with jquery in ASP.net MVC

with 17 comments

Action methods on controllers return JsonResult (Java Script Object Notation result) that can be used in AJAX application. With the growing popularity of jquery,  jquery is becoming the number 1 choice for AJAX. With this in mind, let us build a simple ASP.net MVC application that returns a JsonResult and we will use jquery to parse the Json and display it accordingly on the web page. Let’s say, we have a page that has 3 fields UserId, LastName and FirstName and we want to populate LastName and FirstName based on the UserId entered.

user_screen

If we type in a UserId and then press Populate User Details, we should see the LastName and FirstName textboxes filled in with the appropriate information if the UserId is found in the repository.

user_screen

If the UserId is not found in the repository, we should get an error message “No UserId found for TestUser”.

user_screen

First let us look at the javascript function that would call the controller action to get the user details. Make sure you have included the latest jquery library in your application. Add the below script to your page.


	function populateUserDetails() {
		var user = {};
		user.UserId = $("#UserId").val();
		$.getJSON("PopulateDetails", user, updateFields);
	};

	updateFields = function(data) {
		$("#LastName").val(data.LastName);
		$("#FirstName").val(data.FirstName);
		$("#Message").html(data.Message);
	};

getJSON method will load Json data using HTTP Get request.  It takes in 3 parameters:

  • url or your controller action in this case
  • data (UserId for this example)
  • callback function that is called when the data is loaded. In the above example updateFields is called when the controllerAction returns  Json data.

We can also use post instead of getJSON if your action responds to POST requests. Then your call would look something like this, with everything else remaining same:

$.post(“PopulateDetails”, user, updateFields, ‘json’);

Now let us go ahead and look at our ControllerAction method:

public JsonResult PopulateDetails(UserModel model)
{
	UserResultModel userResultModel = new UserResultModel();
	if (String.IsNullOrEmpty(model.UserId))
	{
		userResultModel.Message = "UserId can not be blank";
		return Json(userResultModel);
	}

	User user = _userRepository.GetUser(model.UserId);

	if (user == null)
	{
		userResultModel.Message = String.Format("No UserId found for {0}", model.UserId);
		return Json(userResultModel);
	}

	userResultModel.LastName = user.LastName;
	userResultModel.FirstName = user.FirstName;
	userResultModel.Message = String.Empty; //success message is empty in this case

	return Json(userResultModel);
}

The above method would return a JsonResult that would be interpreted on the client side by the script that we wrote earlier with the help of jquery library.

This is as easy as it gets. Combination of jquery and JsonResult enables us to create applications that is AJAX enabled with minimal effort. You can get the source code for the application that is discussed above here.

Written by shashankshetty

March 4, 2009 at 4:25 am