MVC Custom Model Binders and CheckBoxList

Back to ASP.Net MVC! In this post, I am going to discuss about custom model binders and a real-time use of custom model binders in ASP.Net MVC. Before getting in to custom model binders, as the name suggests, there is also a default model binder. If you are interested in custom model binders for mvc, I am sure you are aware about the model binding capabilities of the ASP.Net MVC framework. For starters let me shortly introduce you to default model binding. Assume there is a class as given below:

public class UserInfo
{
    public string UserName { get; set; }
    public string UserEmail { get; set; }
}

With this object, you can do the following to get these 2 information from a user. A default model binder comes in to picture in this case.

  • Have an action method, called, Index
  • The action method returns a view which is strongly typed to the UserInfo class
  • Have an action method called Index decorated with the [HttpPost] attribute and taking UserInfo as a parameter
  • When user enters something and presses the “Submit” button, the action method decorated with [HttpPost] is called
  • The DefaultModelBinder takes the responsibility of mapping the route values and form values to an instance of UserInfo and then passes it to the action method

As you noticed in the listing above, default model binders make it easy in case you have a simple object as above. But, if your model is not a simple object, you may have to use custom model binders. Let us consider building a check box list. In this case, you display an arbitrary list of check box items. So the default model binder would not suffice. So in order to resolve this issue, we need custom model binders. Towards the end of the post, there is a fully working project that utilizes the check box list user control I have created. I hope it acts as a resource to explain the project more comprehensively than I could do here. Without further ado, let me get started on how custom model binders could be used.

The intention is to create a check box list which does not enforce any limits on the number of items. Every check box item could be considered as a collection of the following elements:

  • A check box itself
  • A label containing what the check box represents
  • A hidden field to store the value
  • A hidden field to store the check box state

Note: This implementation is quite different from other ways of implementing a check box list. Towards the end of this post, there are a few helpful links. Have a look at them too!

In order to create these elements, I am using a few custom html helper extensions. This is contained within a class called CustomHtmlHelpers. I am not going to list out the content of this file, but, just give a short description of what every method does.

  • CheckBoxInput – This method creates a chechbox (without a label), a hidden field to track the status of the checkbox. This is required because, if the checkbox is unchecked, there won’t be a value posted to the server when the submit button is clicked. In general, check box lists available on the internet will help you get the values checked by the user, but you will have to regenerate the mode using a database query (or something else). But in this case I reconstruct the entire list using the form values posted.
  • CheckBoxInputLabel – This method creates a label for every checkbox. Clicking on this label would also
  • CheckBoxValue – This generates a hidden field that holds the values for the checkbox
  • CheckBoxListHeader – This generates a header for every individual check box list. This contains a label and a hidden field to store the header

With these extensions, the following user control denotes a sigle check box list:

@model SampleAppForCheckBoxList.Models.CheckBoxListViewModel
@using SampleAppForCheckBoxList.Infrastructure

<div class="cpHeader">
    @Html.CheckBoxListHeader(Model.HeaderText)
</div>
<div class="cpContent">
    @foreach (var item in Model.Items)
    {
        @Html.CheckBoxValue(Model.HeaderText, item, Model.Items.IndexOf(item))
        @Html.CheckBoxInput(Model.HeaderText, item, Model.Items.IndexOf(item))
        @Html.CheckBoxInputLabel(Model.HeaderText, item, Model.Items.IndexOf(item))
        <br />
    }
</div>

If you notice in the above snippet, section under “cpHeader” denotes the header area and “cpContent” denotes the content area – where all the check boxes are listed. Line 2 imports the custom html helper described in the earlier step.

Note: This could also be added to the web.config.

Now, let us create a custom model binder. A custom model binder in ASP.Net MVC should implement the IModelBinder interface. This interface has a single method called BindModel which returns an object. Given below is the implementation of this custom model binder.

public class CheckBoxListViewModelBinder : IModelBinder
{
	public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
	{
	    List<CheckBoxListViewModel> models = new List<CheckBoxListViewModel>();

	    string[] formKeys = controllerContext.HttpContext.Request.Form.AllKeys.ToArray();

	    List<string> rootItems = formKeys.Where(s => s.StartsWith("hdrTitle")).ToList();

	    foreach (var item in rootItems)
	    {
		string hdrValue = item.Split('_')[1];
		string[] txtValues = formKeys.Where(s => s.StartsWith("lblLabel_" + hdrValue)).ToArray();
		string[] valValues = formKeys.Where(s => s.StartsWith("valValue_" + hdrValue)).ToArray();
		string[] hdnValues = formKeys.Where(s => s.StartsWith("hdnChk_" + hdrValue)).ToArray();

		CheckBoxListViewModel model = new CheckBoxListViewModel();
		model.HeaderText = Regex.Replace(hdrValue, "([a-z])([A-Z])", "$1 $2");
		model.Items = new List<CheckBoxListItem>();
		for (int index = 0; index < txtValues.Count(); index++)
		{
		    CheckBoxListItem _item = new CheckBoxListItem();
		    _item.Text = bindingContext.GetValue(txtValues[index]);
		    _item.Value = bindingContext.GetValue(valValues[index]);
		    _item.IsChecked = bool.Parse(bindingContext.GetValue(hdnValues[index]));

		    model.Items.Add(_item);
		}

		models.Add(model);
	    }

	    if (rootItems.Count == 1)
		return models.First();
	    else
		return models;
	}
}

As you can see from the code listing above, the method receives 2 parameters: a ControllerContext instance and a ModelBindingContext instance. The bindingContext can be used to get the value posted for a certain input element, but, it does not provide a method by which we can get a list of all the fields posted. So I use the Form property from the controllerContext.HttpContext.Request.Form instance. Then as you noticed from the html helper, every element uses a certain id/name format. Using this the values are gathered for every element including the header text. Following is a high level algorithm:

  • Find out the number of header elements – this denotes the number of check box lists used. The id/name format is
    hdrTitle_{header_Text}
  • Then using this every other element can be identified as given below

    • Text of the check box is identified using id/name format of lblLabel_{header_Text}_{index}
    • Value of the check box is identified using id/name format of valValue_{header_Text}_{index}
    • Check box checked status of the check box is identified using id/name format of hdnChk_{header_Text}_{index}
  • A CheckBoxListViewModel object is contructed for every check box list and returned.

Now that we have a custom binder, let us see how to put this in to use. You will have to instruct the framework to invoke this binder in case an action method has a parameter of this type. So adding the following 2 lines to Global.asax.cs Application_Start method would take care of this.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    ModelBinders.Binders.Add(typeof(CheckBoxListViewModel), new CheckBoxListViewModelBinder());
    ModelBinders.Binders.Add(typeof(List<CheckBoxListViewModel>), new CheckBoxListViewModelBinder());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Lines 5 & 6 are of prime importance. These lines indicate that if a parameter of type CheckBoxListViewModel or List<CheckBoxListViewModel> is expected, initialize an instance of CheckBoxListViewModelBinder and pass the controller context and the binding context.

Another important thing to notice is the jquery required to store the status of the check box in the hidden field created for this purpose. Following is the jquery required to do this.

$(document).ready(function () {
    $('.chkClickable').click(function () {
        if ($(this).is(':checked')) {
            $(this).next('.hdnStatus').val('true');
        }
        else {
            $(this).next('.hdnStatus').val('false');
        }
    });
});

Finally, let us put this in to use. If you look in to the DemoController this user control is put in to use as given below:

public ActionResult Index()
{
    return View(GetModel());
}

[HttpPost]
public ActionResult Index(CheckBoxListViewModel model)
{
    ViewData["Choices"] = string.Join(",", model.GetSelectedItems());
    return View(model);
}

private CheckBoxListViewModel GetModel()
{
    var model = new CheckBoxListViewModel();
    model.HeaderText = "Select Languages";
    model.Items = new List<CheckBoxListItem>{ new CheckBoxListItem { Text = "C#", Value = "CSharp", IsChecked = false },
					      new CheckBoxListItem { Text = "Ruby", Value = "Ruby", IsChecked = false },
					      new CheckBoxListItem { Text = "PHP", Value = "PHP", IsChecked = false },
					      new CheckBoxListItem { Text = "Java", Value = "Java", IsChecked = false },
					      new CheckBoxListItem { Text = "Scala", Value = "Scala", IsChecked = false }
    };

    return model;
}

GetModel is simply a method that returns a view model for the check box list. This contains a header text and the items to be displayed in the list. Note that this could very well be a call to the database. The Index action method passes this to the view and the view would in turn pass it on to the user control which would display it.

The action method Index decorated with the [HttpPost] attribute would be invoked when the user submits the form. The method has a CheckBoxListViewModel parameter. So during the post action mvc would invoke the custom binder and repopulate with the user’s choices. The model has the GetSelectedItems method which could be used to identify the items selected by the user.

The project also has another example which has 2 check box lists. This is where the following line from the Global.asax.cs class comes in to use:

ModelBinders.Binders.Add(typeof(List<CheckBoxListViewModel>), new CheckBoxListViewModelBinder());

Note that this method would post a lot more fields (data) in the request than the other method which only posts the selected values.

A demo always helps isn’t it? Here it is!!!

Download the sample app with the user control and associated code files here

Link to github for this project is here – You will be able to get the most latest from here always, because I will check in here in case I make any changes.

Some nice links:

  • Another implementation of check box list is here. I do have similar implementation that returns only the selected values. My implementation uses mvc templates instead of html extensions. When I get a chance I will post my implementation too.
  • A link about a fix for mvc check boxes is here.

Happy coding! Post your comments!!!

Share

More ruby bits

It’s ruby time again! Just for fun (or may be it’s useful) I wanted to create a class that holds a list of similar objects. I wrote this class based on the following requirements:

  • Should enable the user to specify the type the list will hold during initialization
  • Should be able to hold an arbitrary amount of similar objects
  • Should provide a method to return all the items in the array
  • Should be able to return a single element
  • Should be able to invoke an operation using a block passed to the method on each object
class List
    def initialize (defType)
        @defaultType = defType

        if (!validate_type)
          raise "Invalid type parameter: unable to create an object of type #{@defaultType}"
        end

	@objArr = []
    end

    def add(someObj)
      @objArr.push(someObj) if (someObj.class.to_s.eql?(@defaultType))
    end

    def get
      return @objArr
    end

    def getitemat(pos)
      @objArr.at(pos.to_i)
    end

    def each(&block)
      @objArr.each{|item| block.call(item)}
    end

    private
    def validate_type
      type_validation_status = true
      begin
        type = Object::const_get(@defaultType).new()
      rescue
        type_validation_status = false
      end

      type_validation_status
    end
end

In the class above, the 1st requirement is satisfied using lines 2 – 10. When a user initializes this class, a type name has to be passed. Then validate_type method is called (More information related to this is here). This verifies if a type of the name passed can be created. If unable to create such a type, I throw and exception and quit. Else an array is initialized and the instance is now available for use. This along with lines 12 – 14, satisfies the 2nd requirement as a ruby array can hold any number of items (of course limited by memory available!). Note that the add method does not add the object passed if the object is not of type @defaultType.

Requirement 3 is satisfied by lines 16 – 18. The user can use this method (get) to get all the items and use a for loop to iterate over the list. getitemat method following the get method could be used to access a single item specified by the index passed.

The final requirement is satisfied by the each method. This method is interesting of the lot. It takes in a block as a parameter. Then I iterate over each of the item in the array and then invoke this block by passing the item as a parameter.

So, as explained, this class can be used to store a list of similar objects. The following is a sample of how this could be used:

class Sampleclass
  def print
    puts inspect
  end
end

class Sampleclass2

end

list = List.new("Sampleclass")

list.add(Sampleclass.new)
list.add(Sampleclass.new)
list.add(Sampleclass.new)

# this won't be added
list.add(Sampleclass2.new)

list.add(Sampleclass.new)
list.add(Sampleclass.new)

puts "Calling the print method of every instance of Sampleclass"

list.each{|a| a.print}

puts "\n"
puts "Getting a certain item from the list"

item = list.getitemat(2)
item.print

Here is a link to github with this file.

Ruby’s blocks are something that interests me anytime. This section discusses how you can return values from within a ruby block. Firstly, ruby blocks cannot contain return statements. You may also remember that in any method, ruby returns the result of the last evaluation of an expression. This is put in to use within a block to return values.

For instance, consider the ruby snippet below. exec method takes in a block as a parameter in this case (&block). The intention here is to make the block return a value to the calling method. In order to do this, you just have to make sure that the last expression evaluated is the result you wish to return. In this case the block takes in an integer and returns as answer the value obtained by multiplying with itself. Also, notice that within the block, this is last expression being evaluated.

def exec(&block)
  result = block.call(5)
  puts result
end

exec{ |x| x * x}

The result of the expression is now returned to the method that executed this block, and is stored in result.

Hope this post was interesting! Happy coding!!!

Share

C# Tips

Okay, I am back. Seems like there is a drought in my blog ;) ! It’s been a while since I posted anything. So I figured that I could post some interesting tips that you may find useful! I have also decided that I will do this at times to fill out any gaps in my research.

Tip 1 – Global resource files

In order to include and use images within a windows forms application, there are few choices. One way is to have a folder with all the images that will be used by various forms, which will be distributed along with the application and then it could be used in the forms as:

Image image = Image.FromFile("Images/folder.png");

But this isn’t an ideal way to do this. Resource files would be a better option as we don’t have to distribute the application with image files floating around.

By using this option the images are embedded in the application itself, thereby reducing the need to distribute images seperately apart from the executable. In this post, I am going to discuss a way by which images can be shared across multiple windows forms. To do this, create a resource file and in this case, I am taking up as an the example that I used in one of my projects (directory comparer).

So, in this case, I have created a common DirectoryComparerIcons.resx file which will hold a set of icons that will be shared by many forms. Once the icons are added to this resx file, it could be used this way:

public static ImageList GetImages()
{
	ResourceManager manager = new ResourceManager(typeof(DirectoryComparerIcons));
	ImageList imageList = new ImageList();

	Image folder = (Image)manager.GetObject("folder");
	imageList.Images.Add(folder);

	return imageList;
}

Here an instance of ResourceManager is created by passing in the common type we created – DirectoryComparerIcons.

Now, the manager object can be used to get a reference to the folder icon we added to the resource file. In our case the name of the image file is “folder.png”. So passing just the name “folder” excluding the extension would get us the image. This is far better than having the image files loaded using Image.FromFile.

Tip 2 – XmlWriterSettings

I have seen that at times we need to generate XML using code. This is in contrast to web services, where in XML is generated by the compiler. In this post I would like to give some pointers about creating XML files using C# – the
XmlWriter class. Consider the following piece of code:

XmlWriter xml = XmlWriter.Create(@"c:\file.xml");

This would instantiate a XML writer and you could use various commands like WriteStartElement, WriteValue, WriteEndElement to construct the XML file dynamically. But there is a problem w/ this. A file created w/ such an instance of XmlWriter (xml) would like this:

before applying the settings

But, we may expect the XML file to have some line breaks, indentation to make it readable to others (though XML is not
meant for that! ;) ). For this we need to apply some XML writer settings using the XmlWriterSettings class as shown below:

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;

Now the XmlWriter would be instantiated as:

XmlWriter xml = XmlWriter.Create(path, xmlWriterSettings);

With this the XML generated would be indented, with line breaks as appropriate! Check out the final output after the additional settings:

after applying the settings

Check out the code in full:

void Main()
{
    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
    xmlWriterSettings.NewLineOnAttributes = true;
    xmlWriterSettings.Indent = true;

    XmlWriter xml = XmlWriter.Create(@"C:\file.xml", xmlWriterSettings);

    xml.WriteStartElement("Users");

    foreach (string client in new string[] {"user1","user2","user3"})
    {
        xml.WriteStartElement("User");

        xml.WriteStartElement("Name");
        xml.WriteValue(client);
        xml.WriteEndElement();

        xml.WriteEndElement();
    }

    xml.WriteEndElement();

    xml.Close();
}

PS – I posted this in my older blog and also in codeproject a while before

Hope you found these tips interesting! Post your comments!!

Share

dotLess-first look

In this post I am going to discuss an interesting find through a training session I attended (html 5). During this session, the instructor mentioned about dotless. This is something I was looking for a while earlier, but was either unable to find it out or didn’t pay interest at that time for some reason. In short, dotless is a dynamic css framework for .net enabling you to write less amount of css, instead of writing loads and loads of css. An important thing to note is that it’s a port of ruby’s less library.

The most interesting thing with dotless compiler is the amount of css you have to write in comparison to writing plain old css. Consider the following for example. In this case I am trying to write some css that does the following:

Apply some style

  • to a div w/ id as “header”
  • to a span w/ id as “span1″ within “header”
  • to an anchor tag w/ class as “anchor1″

And, apply some style

  • to a div w/ id as “content”
  • to a span w/ class as “span2″ within “content”
  • to a span w/ class as “span3″ within “content”
  • to an anchor w/ id as “anchor2″ within “content”

In order to do this I would have to do the following in css:

#header {
  border: 1px solid #d3d3d3;
  background: #e6e6e6;
  font-weight: normal;
  border-radius: 20px;
}

#header #span1 {
  color: Red;
}

#header .anchor1 {
  text-decoration: none;
}

#content {
  border: 1px solid #d3d3d3;
  border-radius: 20px;
}

#content .span2 {
  color: Blue;
}

#content .span3 {
  color: Maroon;
  font-size: large;
  text-transform: lowercase;
}

#content #anchor2 {
  text-decoration: none;
  font-weight: bolder;
}

This css was applied to the following html:

	<div id="header">
		<span id="span1">Title text</span> <a class="anchor1" href="javascript:void(0)">Title link</a>
	</div>
	<div id="content">
		<span class="span2">
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. In lacus metus, placerat at molestie id, laoreet at libero.
		</span>
		<br />
		<span class="span3">
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. In lacus metus, placerat at molestie id, laoreet at libero.
		</span>
		<br />
		<a href="#" id="anchor2">sample link</a>
	</div>

Just consider the amount of typing it takes. This is where dotless comes in to the picture. Following is the code for dotless to represent the same:

@color-one: Red;
@color-two: Blue;

.setradius(@rad: 5px)
{
    border-radius: @rad;
}

#header
{
    border: 1px solid #d3d3d3;
    background: #e6e6e6;
    font-weight: normal;
    .setradius(20px);

    #span1
    {
       color: @color-one;
    }

    .anchor1
    {
	   text-decoration: none;
    }
}

#content
{
    border: 1px solid #d3d3d3;
    .setradius(20px);

    .span2
    {
	    color: @color-two;
    }

    .span3
    {
	    color: Maroon;
	    font-size: large;
	    text-transform: lowercase;
    }

    #anchor2
    {
	    text-decoration: none;
	    font-weight: bolder;
    }
}

If you notice the above syntax for dotless, it takes much less in terms of typing when compared to plain old css. This example follows the mixins (line 4) and nested rules syntax of dotless (9-25 and 27-49). It also uses variables (1,2, 18 and 34) defined by dotless. Also, if you notice, it closely follows the hierarchy of the elements within the html text. Mixins are function like dotless semantics used to reduce repetition in css. As the example indicates, nested rules are used to represent the css of elements within a parent element (ex. “#header”), thereby reducing the need to specify the parent element when defining child elements (ex. we can now specify just “#span1″ instead of “#header #span1″.

To use this, you could either add this file with the less extension in your projects, with the corresponding handler mappings. Or, you could invoke the dotless compiler as shown below and include it in your project. The syntax is dotless.Compiler.exe <source_less_file> [<destination_file_name_required>]. If the destination file name is ignored the source file name is used as the name for the file generated. Thus, issuing the following command would generate a file called nested2.css.

C:\Software\dotless-v1.2.2.0> dotless.Compiler.exe nested2.less

I don’t think an elaborate discussion about the syntax of dotless is necessary in this post as the dotless site does that in a much nicer way here!

I guess the dotless documentation is detailed enough to explain the ways dotless could be used. So, apart from that I wish to discuss another method by which you could put the dotless library to use. Using this method you don’t have to add a reference to dotless.core.dll in your project, nor you have to add any handler mappings. To achieve this you could use a simple batch script that compiles your less scripts to css scripts. You may also choose to have this as a pre-build action is Visual Studio (will probably update the post with more information on this soon). By this way you get to see about the errors immediately, instead of verifying every single page in your project.

(Move your mouse over every line for some quick info)

@ECHO OFF
IF “%1″==”" GOTO Continue
    cd %1
    del *.less.css
    for /f %%a IN (‘dir /b *.less’) do dotless.Compiler.exe %%a %%a.css
    pause
    exit
:Continue
    echo “This batch file expects a folder name”
    pause
    exit



The above script can also be modified as shown below, to always compile a certain folder(less-css in this case), either manually or using a pre-build action, instead of passing a folder for it to compile.

(Move your mouse over every line for some quick info)

cd less-css
del *.less.css
for /f %%a IN (‘dir /b *.less’) do dotless.Compiler.exe %%a %%a.css
pause
exit



In a nutshell, the batch script does this: First check if there is an argument that specifies the folder that has the .less files. If not, display some help and exit. Else, change to that directory and delete the existing .less.css files. This batch file will convert .less files to .less.css files, and this is the reason for deleting the .less.css files (not mandatory though). Then for every .less file in the directory call the dotless compiler and compile the file with a .css extension.

One disadvantage in this case is that, assuming you have added the .less files in the project, the .css files will be generated “outside” the project and so won’t show up in the project. Thus using these files as a <link /> tag would be marked with a red line. To circumvent this, you may generate once and add it to the project. Then, future dotless compiles will overwrite the file and visual studio will stop identifying the css files as missing files.

In order for the above batch file to work, you need to have the dotless.Compiler.exe extracted to your hard drive and also added to the system path (environmental variable). The section below describes the steps on how to do this (feel free to skip it if you are aware about the steps).

Assuming the dotless compiler is present in “c:\Software\dotless-v1.2.2.0″, this is how you could add it to the path variable (windows vista, 7):

  • Right click on “Computer”, select “Properties”
  • Click on “Advanced System Settings” on the left
  • Click on the “Advanced” tab
  • Click on the “Environment Variables” button
  • Under “User variables for <user_name>” scroll and point the “Path” variable
  • Click on the “Edit” button
  • Towards the end add a semi-colon “;” if not present and paste the path “c:\Software\dotless-v1.2.2.0″ with a semi-colon and press on “OK”

Once you do this, the above batch file should work just fine. Else you may have to have the complete physical path of the compiler in the batch file.



I guess this post would have given you a head-start with dotless. I have started using it and in case I find out more stuff, will post it!

Share

Type constraints and ICloneable – Cloning a List

In this post, I am going to discuss an interesting feature of c# – type constraints. Yes, it’s not new, but I always find type constraints to be interesting feature in C#. In case you are in this post, I am pretty sure you know the basics of C#. Given below is a simple class:

public class Sample
{
   public int aNumber { get; set; }
   public string aString { get; set; }

   public void Print()
   {
       Console.WriteLine(string.Format("{0} and {1}", aNumber, aString));
   }
}

When you create a list of Sample objects, you actually create a list of references. So, List is a collection of references of the class Sample. To simplify, can you guess the output of the following?

public static void Main(string[] args)
{
   List<Sample> sampleList1 = new List<Sample>();
   sampleList1.Add(new Sample{ aNumber = 1, aString = "some string" });
   sampleList1.Add(new Sample { aNumber = 2, aStr

   List<Sample> sampleList2 = sampleList1;

   DisplayList(sampleList1);
   Console.WriteLine();
   DisplayList(sampleList2);
   Console.WriteLine();

   sampleList1.First().aString = "changed";

   DisplayList(sampleList1);
   Console.WriteLine();
   DisplayList(sampleList2);
}

private static void DisplayList(List<Sample> sampleList)
{
   foreach (var item in sampleList)
      item.Print();
}

It’s given below:

// before the change (added manually)
1 and some string
2 and another string

1 and some string
2 and another string

// after the change (added manually)
1 and changed
2 and another string

1 and changed
2 and another string
Press any key to continue . . .

As you noticed, as C# (in this case) works by reference, sampleList1[0] and sampleList2[0] both points to the same reference. Thats why changing the value of sampleList1 changes sampleList2 also. So, in order to create an exact copy, you can use the ICloneable interface. Other ways are having a static method that would create a new object when you pass in the old object. But, in this post, I am going to discuss creating an extension method to List that will clone a list. To achieve this lets change the Sample class to implement ICloneable as shown below and also implement the corresponding method. The Clone method calls the MemberwiseClone method, which, as the name suggests, creates a new instance by copying every member of the instance.

public class Sample : ICloneable
{
    // -- snip --

    public object Clone()
    {
       return this.MemberwiseClone();
    }
}

Now that we have changed the class, let me introduce you to the List extension and you will understand why I changed the class to be implementing ICloneable. If you notice, the extension enforces that T should be implementing the ICloneable instance (a type constraint :) ) and calls the Clone method of ICloneable to create a new instance of the object in scope.

public static class ListExtensions
{
   public static List<T> Clone<T>(this List<T> src)
     where T : ICloneable
   {
       List<T> tList = new List<T>();

       foreach (T t in src)
       {
          object c = t.Clone();
          tList.Add((T)c);
       }

       return tList;
    }
}

Now, let me put this method to use:

public static void Main(string[] args)
{
    List<Sample> sampleList1 = new List<Sample>();
    sampleList1.Add(new Sample{ aNumber = 1, aString = "some string" });
    sampleList1.Add(new Sample { aNumber = 2, aString = "another string" });

    List<Sample> sampleList2 = sampleList1.Clone<Sample>();

    // -- snip --
}

If you notice in line 7, instead of just assigning the reference, I have used the new extension to clone the list. And here is the output for this changeover:

// before the change (added manually)
1 and some string
2 and another string

1 and some string
2 and another string

// after the change (added manually)
1 and changed
2 and another string

1 and some string
2 and another string
Press any key to continue . . .

I guess the changeover is pretty obvious now! Happy coding and post your comments!!!

Share

ASP.Net MVC Extreme – How Stuff Works

You might have seen the following image, that discusses the control flow of a typical MVC request. In this post I would like to take a deep dive into every one of these blocks in “detail”, down to the last line :) I presume this post is never going to be complete as I may have a clearer notion of some things in the future, when I analyze this further!

mvc general pipeline

UrlRoutingModule class implements the IHttpModule interface, thus implicitly registering itself with IIS to receive all the requests for a certain instance running IIS. UrlRoutingModule gets the request at this method – OnApplicationPostResolveRequestCache when the user enters the url. This could be identified by having a look at the Init method of UrlRoutingModule. This method receives the HttpApplication as the parameter. The Context is retrieved from the HttpApplication object and a HttpContextBase object is created, which is a HttpContextWrapper (RemapHandler call – goes to HttpContext) object. Then UrlRoutingModule.PostResolveRequestCache is called with this object. Given below is the extract of this class from reflector.

// From reflector
public class UrlRoutingModule : IHttpModule
{
    //-- snip --

    // Methods
    protected virtual void Init(HttpApplication application);
    private void OnApplicationPostResolveRequestCache(object sender, EventArgs e);
    //-- snip --
    public virtual void PostResolveRequestCache(HttpContextBase context);
    //-- snip --

    // Properties
    public RouteCollection RouteCollection { get; set; }
}

PostResolveRequestCache does a lot of things. Some of them are: The RouteData object obtained from the RouteCollection property has a GetRouteData method. Using this method the RouteData for the corresponding HttpContextBase is obtained. This RouteData property has the MvcRouteHandler to be used as the RouteHandler property.Using this MvcRouteHandler instance, the GetHttpHandler method of the MvcRouteHandler is used to get the reference to the MvcHandler, by passing in a RequestContext object.

HttpContextBase instance passed to the UrlRoutingModule is used to remap the handler at IIS, which would now be the MvcHandler. Given below is an excercept from this method using reflector.

// From reflector
public virtual void PostResolveRequestCache(HttpContextBase context)
{
    RouteData routeData = this.RouteCollection.GetRouteData(context);
    if (routeData != null)
    {
        IRouteHandler routeHandler = routeData.RouteHandler;

        //-- snip --

        if (!(routeHandler is StopRoutingHandler))
        {
            RequestContext requestContext = new RequestContext(context, routeData);
            context.Request.RequestContext = requestContext;
            IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);

            //-- snip --

            if (httpHandler is UrlAuthFailureHandler)
            {
                //-- snip --
            }
            else
            {
                context.RemapHandler(httpHandler);
            }
        }
    }
}

HttpContextWrapper.RemapHandler gets the MvcHandler. This in turn calls the RemapHandler method in the HttpContext instance. It also has the IIS7WorkerRequest object and its SetRemapHandler method takes 2 parameters, handler type and handler name. This is where a link between the IIS and the handler is established. I am yet to dig in to this area further. Will keep this post updated! HttpContext (Context) has the WorkerRequest property which gets the MvcHandler instance.

// From reflector
public void RemapHandler(IHttpHandler handler)
{
    IIS7WorkerRequest request = this._wr as IIS7WorkerRequest;
    if (request != null)
    {
        //-- snip --

        string handlerType = null;
        string handlerName = null;
        if (handler != null)
        {
            Type type = handler.GetType();
            handlerType = type.AssemblyQualifiedName;
            handlerName = type.FullName;
        }
        request.SetRemapHandler(handlerType, handlerName);
    }
    this._remapHandler = handler;
}

Let’s dig inside the SetRemapHandler method of IIS7WorkerRequest class. Earlier, I said about the linkage to IIS. This is how it’s done. The SetRemapHadler method of IIS7WorkerRequest makes an unmanaged method call to MdgSetRemapHandler method which belongs to the UnsafeIISMethods class. An excercept from reflector is given below:

// From reflector
internal void SetRemapHandler(string handlerType, string handlerName)
{
    Misc.ThrowIfFailedHr(UnsafeIISMethods.MgdSetRemapHandler(this._context, handlerName, handlerType));
}

MvcHandler has a ProcessRequest method, just like any other handlers as it implements the IHttpHandler interface. So using the linkage between the IIS and the handler, I would guess the ProcessRequest method is called by the IIS. Then the request passes on to the MvcHandler. From this point onwards it’s upto the MvcHandler to identify the correct controller and invoke its execute method. Now, lets dig inside the MvcHandler type.

MvcHandler’s ProcessRequest method’s first step would be get an instance of the Controller and the IControllerFactory using the ProcessRequestInit method. The factory instance is required in order to release the controller after successful/failed execution of the chosen action. MvcHandler uses the Controller factory instance and tries to get a IController instance. If successful, the Execute method is called.

// From reflector
protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
    SecurityUtil.ProcessInApplicationTrust(delegate {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);
        try
        {
            controller.Execute(this.RequestContext);
        }
        finally
        {
            factory.ReleaseController(controller);
        }
    });
}

The IControllerFactory could be the default controller factory or a custom factory initiailized (set) during the Application_Start event, as shown below:

protected void Application_Start()
{
   AreaRegistration.RegisterAllAreas();
   RegisterRoutes(RouteTable.Routes);

   ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
}

All controllers inherit from the Controller base class, which in turn inherits from the ControllerBase which implements the IController interface. When the MvcHandler calls the Execute method in ProcessRequest using the IController instance, it executes the Execute method in ControllerBase, which calls ExecuteCore which is implemented in Controller as in ControllerBase its an abstract method. ExecuteCore finds the appropriate action method and proceeds. Just for the kicks here is an extract for this method from the reflector.

// From reflector
protected override void ExecuteCore()
{
    this.PossiblyLoadTempData();
    try
    {
        string requiredString = this.RouteData.GetRequiredString("action");
        if (!this.ActionInvoker.InvokeAction(base.ControllerContext, requiredString))
        {
            this.HandleUnknownAction(requiredString);
        }
    }
    finally
    {
        this.PossiblySaveTempData();
    }
}
Share

Ruby bits

Okay, in this post I am going to discuss some interesting bits of ruby. To begin with, this is a very useful feature that you could utilize in ruby, in case you are writing a mini language based on certain rules for yourself. Let us assume you need to split string in to tokens. Yes this is easy, just write a regular expression to do this.

But, oops! Suddenly you notice that the input string can also contain strings in single or double quotes. With this requirement, writing regular expressions can be tedious. So as to solve this without much hassles, you can use the shellwords module of ruby which comes as a language feature. A smaple is given below:

# split words
require 'shellwords'

data = 'some "words within quotes" to \'split into parts\''
words = Shellwords::shellwords(data)
words.each{ |word| puts word }

In order to use shellwords, I have a require statement to begin with. Then I call shellwords, which is an alias for the shellspit method. The shellsplit method itself uses some funky regexes to split the data we passed in to constituent strings and returns an array. Note that in the resultant array, “words within quotes” and ‘split into parts’ are going to be single entries and not 3 entries.I am using this in my first ever (:)) major ruby project. This is a program to manage my to-do lists. As it is evident, this is a console based application. You can view it here

Next bit is another interesting thing in ruby. You might be familiar with the reflection assembly in .Net. It is used to dynamically create types from strings that represent a type in an assembly. The following method could be used in ruby to mimic the same. The following example demonstrates this. To begin with, I have a type (class) that is called SampleType, with a method print. Let us see how we can dynamically create this type.

class SampleType
  def print
      puts "printing from sample type"
  end
end

Assuming the class name is in a variable called, create_type, we just need to use the const_get method within the generic Object type. This is because in ruby all the types (classes) are “constants“. And a quick tip, ruby classes cannot have their names starting with a lower case character, because constants in ruby cannot have a lowercase character and classes are constants in ruby. After passing in the type (class) name (which is a string) to the const_get method, we call the new method to actually create an instance of the type. If a class does not exist by the specified name, the return value is going to be ‘nil‘. Once we successfully receive the instance of the type, the type’s instance methods can be called as shown in the example below.

# create type using a string
create_type = "SampleType"
type = Object::const_get(create_type).new()
type.print

Example given below is a slight variation of the previous example. In this case, the generated type has a constructor that expects a string parameter.

class SampleTypeWithParams
  def initialize(parameter)
    @param = parameter
  end

  def print
    puts "printing from sample type with the parameter #{@param}"
  end
end

create_type = "SampleTypeWithParams"

type = Object::const_get(create_type).new("a parameter")
type.print

I am putting this into use in the same to-do list project I was talking about earlier. Every activity in this project is managed by an individual type. Like ListTask to list the tasks, AddTask to add a task and so on. So instead of using if conditions on the command entered, I use this method to generate a type. If successfull, the responsibility is handed over to the created type which has a common method called ‘execute’. The sample is here.

If you are interested at all, here is the link for the todo-list project, which can be used to manage console based applications!

PS: I am a beginner in ruby, so please correct me in case anything I have said is incorrect! Thanks for reading and happy coding!

Share

Some ruby love! – method_missing

Okay, time for some ruby love :) At this point, ruby gets the first place among my favorite dynamic languages! In this post I would like to discuss some interesting ruby facts I learned recently. First post is about method_missing. method_missing is a special method in ruby that can be used to handle calls to non-existent methods. The signature is given below and it is required that the same signature is followed in case you wish to implement this method.

For more information about the parameters, see the inline comment in the code.

class Missingmethods
   # method_missing takes 3 parameters
   # @m: method's symbol name, use to_s to convert to a string
   # @*args: variable number of arguments passed to the method
   # @&block: a block of code to be executed
   def method_missing(m,*args,&block)
	puts "Not able to find the #{m} method"

       for i in args 	do
	       puts(i)
       end

        if block_given?
	       block.call
        end
   end
end

Missingmethods.new.someMethod(1,2) { puts "Some block" }

If you notice, in the above snippet, within the method_missing method, I first print the missing method’s name. Note that m is a symbol. Then I loop through the arguments and print them. Final statement is interesting. In order to execute the block passed, I check if a block was passed. Then I can invoke the ‘call’ method to execute the block passed. I am under the impression that yield can also be used in this case. Let me try that next!

If you execute the above snippet, you will see the following:

>ruby verify.rb
Not able to find the someMethod method
1
2
Some block
>Exit code: 0

A (more) complete example is available at github!

Happy coding!

Share

Programatically accessing a web.config that does not belong to the current project

I am back! In this post I am going to discuss how you could programmatically read the web.config that does not belong to the project you are dealing with. I don’t think you are going to be wondering if there is a real time use. Nevertheless, let me explain why I needed this. For the web application I am currently working on, I needed a console application that would do additional tasks at fixed times. Yes, I could have an app.config and I am using this technique to read  as a fall-back if the app.config file is not available. This console application gets copied to the bin directory of the web application. So a folder above this bin folder would have the web application’s web.config. A lot of keys are shared between these 2 applications and that’s why we decided to do this. Even though the method in my project does something different from this by getting only the properties I need, this example tries to access and display a lot more data. The method is given below.

If you need to access the current project’s web.config, you don’t have to go through all these hassles. Just do ConfigurationManager.AppSettings["key"] for example. But, as this is a config file outside the project you have to follow these steps. Better than parsing the XML isn’t it? The first step would be to create an instance of ExeConfigurationFileMap object and then assign the fully qualified path of the web.config you wish to read.

After this step, you can get the Configuration object using the ConfigurationManager.OpenMappedExeConfiguration method, that can be used to access application settings, connection strings etc. I would like to leave the rest to explore for yourself, as I don’t want to bog you all down with the details.

public static void ProgrammaticallyReadWebConfig(string path)
{
     if (File.Exists(path))
     {
         ExeConfigurationFileMap map = new ExeConfigurationFileMap();
         map.ExeConfigFilename = path;

         Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
         string connStr_Con = config.ConnectionStrings.ConnectionStrings["AppDb"].ToString();
         Console.WriteLine(connStr_Con);
         Console.WriteLine();

         string connStr_App = config.AppSettings.Settings["ConnectionString"].Value;
         Console.WriteLine(connStr_App);
         Console.WriteLine();

         ConfigurationSection section = config.GetSection("runtime");
         SectionInformation info = section.SectionInformation;
         Type type = typeof(SectionInformation);
         type.GetProperties().ToList().ForEach(delegate(PropertyInfo prop)
         {
             string propName = prop.Name;
             object val = prop.GetValue(info, null);
             Console.WriteLine(propName + " = " + (val != null ? val.ToString() : "-"));
          });
     }
}

The above example assumes that there is a key named “ConnectionString” within the element and “AppDb” within the element. Also, note that you need to add reference to the System.Configuration assembly.

Share

Custom Error Attributes (MVC 3)

In this post, I would like to discuss about custom error attributes in MVC 3. If you are a developer, you should be familiar with the “yellow screen of death (YSOD)”. Annotating your controller with [HandleError] would take care of this.This attribute would expect a view called Error in the Shared views folder. Note that there should be a corresponding Error action method in the ‘Home’ controller. In case the view of the error is any different or you wish to have a html page you need to add a customErrors section in your web.config, but I am going to skip this as it’s out of scope for this post. This post deals with creating a custom error attribute. This attribute would do the same thing – redirect you to an error view. But it would do another thing apart from this. That is to log the error to a table. This post does not delve in to actually implementing the database layer as that part is straight forward. In order to get started, add a new class file called MyAppErrorAttribute. This class should inherit the HandleErrorAttribute and override the OnException method as shown below:

public class MyAppErrorAttribute : HandleErrorAttribute
{
  public override void OnException(ExceptionContext filterContext)
  {
     Exception exception = filterContext.Exception;

     // Call the method to log the exception
     // -- method call to log the exception

     filterContext.ExceptionHandled = true;
     filterContext.Result = new RedirectResult("~/Home/Error");
     base.OnException(filterContext);
  }
}

The OnException method gets the exception from the ExceptionContext. Now this is just a normal Exception object which could be handled anyway you wish to. In my case, I am getting the exception message, the entire exception, when the exception occurred and who was user logged in during that time. After this we need to set the ‘ExceptionContext.ExceptionHandled’ attribute to true so that the user does not see the YSOD. Also, you need to set the ‘ExceptionContext.Result’ property to specify the view to be redirected when OnException method of the base class is called. At this point, you could annotate your controllers with the [MyAppError] attribute. So when there is an exception, the exception would be logged and then the user would get to see the error view page.

[MyAppError]
public class SomeController : Controller
{
     // -- controller logic
}

But, in case you/somebody is going to be adding a number of other controllers, you/they may not remember about this attribute. So this is what you could do. Global.asax.cs has a RegisterGlobalFilters method, where you could add filters that would apply to all of the controllers. How this could be achieved is given below in the following snippet. Make sure you also have the RegisterGlobalFilters(GlobalFilters.Filters); call in Application_Start method for the global filters registered to work.

public class MvcApplication : System.Web.HttpApplication
{
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
   {
     filters.Add(new MyAppErrorAttribute());
   }

   protected void Application_Start()
   {
      // -- other code
      RegisterGlobalFilters(GlobalFilters.Filters);
      // -- other code
    }
}

After this step, any exception raised within any controller would invoke our custom error attribute, logging the exception and then redirecting to the default error view. Hope this helps and do leave your comments about this post!

Share