ASP.Net WebForms – Global Error Handling – Application_Error and customErrors

Okay, here I am, back with a very short but an interesting tip. For a change, this tip is for a web forms project :) . At times you may want to handle your application’s errors globally and log them in to a database (using your own little logger or a logging framework). This is how you could do it using the global.asax.cs file of your project, using the Application_Error method.

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError().GetBaseException();
    // log the exception using your logger
    Server.ClearError();
    Response.Redirect("~/Error.aspx");
}

This approach would work very well in a production scenario. But this method has the following disadvantages:

  • In order to change the error page to a different .aspx file, you have to recompile your project
  • You cannot just “see” the yellow screen that you normally see in this case and identify the error. You have to go the table where the error is logged and see the exception

In order circumvent this issue, you can use the following method. First change the Application_Error method to the following:

protected void Application_Error(object sender, EventArgs e)
{
    var exception = Server.GetLastError().GetBaseException();
    // log the exception using your logger
}

Notice that I have removed the Server.ClearError(); line (line 5) and obviously line 6 (the redirect part). Then add a customErrors section to your web.config file. This should be nested within the system.web element, as shown below:

<system.web>
      .....

      <customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx">
      </customErrors>
</system.web>

After this, if the application encounters an exception, in your development machine, you will see the yellow screen (YSOD :) ) that gives you the exception information and in production it will show the custom error page set using the defaultRedirect attribute. Again, a reminder – if you don’t remove the Server.ClearError(); line from Global.asax.cs, this method won’t work and you will still see the page where the exception occurred – it will just be a blank page.

I will update the post with the repurcussions of not having the Server.ClearError(); method call some time soon. I cannot think of anything with this, but would like to check that out too! And finally, do let me know your comments!

Happy coding!!!

Share

IronRuby – A Wrapper to Execute ruby code using C#

It’s been quite a while since I posted! So, lets have some fun. In this post I am going to present to you something experimental (not path breaking by any means!) I was doing with IronRuby. I wanted to create a wrapper for IronRuby, so that I don’t have to have a lot of repetitive code to execute some ruby code within .net using the new DLR. Before getting to that, let me give a quick outlook of executing ruby code in C#. The .net world has an equivalent to ruby called as “IronRuby”. Before getting started, we need the references for IronRuby. Download them from the IronRuby site (here) and add references to the following dll’s in your project. In this example I am using the 1.1.3 (download link) version of IronRuby in this post.

  • IronRuby.dll
  • IronRuby.Libraries.dll
  • Microsoft.Scripting.dll

After this step you are ready to go the ironruby way! IronRuby, being a dynamic language uses the DLR (Dynamic Language Runtime). In order to execute ruby code in .net, you first need to create a runtime object using the CreateRuntime method in the Ruby class. Using this runtime, you then have to create a ruby engine using the GetEngine method of the ScriptEngine. Note that you have to pass the engine type "rb".

Note: Similarly if you have references to IronPython (.net equivalent of python), you can follow similar steps to create an engine for python. So in this case GetEngine‘s parameter would be "py" to create a IronPython script engine.

Once you create the ScriptEngine object, you are ready to execute any ruby script and in case they have classes, you can even instantiate an instance in .net and call their methods. Following is the fully working code that executes some ruby code to just print some text and also to register a class with the DLR. In order to get familiar with the DLR an important keyword to understand is the dynamic keyword. Let’s understand this keyword before I get in to the remaining details

public static void Main(string[] args)
{
    Console.Write("Loading sample.rb...\n\n");

    ScriptRuntime rb = Ruby.CreateRuntime();
    ScriptEngine engine = rb.GetEngine("rb");
    engine.Execute("puts 'This is a test'");

    var rbPerson = engine.Execute(@"class Person
				    def greet()
					puts 'Hello world!'
				    end
				    end");

    object persInst = engine.Runtime.Globals.GetVariable("Person");
    dynamic person = engine.Operations.CreateInstance(persInst);
    person.greet();
}

.Net framework 4 introduced the dynamic keyword. Most important thing about dynamic is that is bypasses type checking. It has other purposes too, but we are mainly concerned about the uses in the perspective of dynamic languages. In this case, I use dynamic variables to hold instances of classes created. Thus, as there is no type checking, intellisense wouldn’t work with the variables of type dynamic.

Now, let me dwelve more in to the above sample. Lines 5 & 6, create a ruby runtime object and then creates a ruby engine using theis runtime object. After this point, the engine created can be used to execute ruby code. Line 7′s results can be immediately seen as it’s a call to the put method of ruby which prints the string passed. So line 7 would just print the message. But lines 9 – 13 are interesting. These lines execute the code that defines a class. So this wouldn’t produce any output. In order to use/create an instance of Person, first you need to create a reference to the person variable (Person is also a variable) using the GetVariable method of the Globals object in the engine’s runtime. Once you have a reference to this variable, an “instance” of Person can be created, using the CreateInstance method of the Operations object, again belonging to the engine object we created earlier.

Following is the output when the above code is ran.

Loading sample.rb...

This is a test
Hello world!
Press any key to continue . . .

Now, lets get to the most important part of this post. As I said before, I created a wrapper around the concept I explained. Whenever I want to create an instance (or add a script), I don’t want to repeat the steps listed earlier. Because, whenever an instance is required, if it doesn’t exist, we have to to execute the ruby script.

Taking care of this also would require managing a set of variables. To free myself from all these nuances, I created the following wrapper. I am just going to explain the most important parts. This wrapper contains the RubyExecutor class, which is responsible for managing the adding and the executing of the ruby scripts. This class inherits from the ExecutorBase class which takes on the entire load of taking care of stuff. It contains 2 abstract methods CreateRuntime and CreateEngine which the RubyExecutor overrides to create the ruby runtime and the engine (It will be evident why these methods are abstract in the following sections). Also there is a virual method called Init which need not overridden in the derived class. Apart from this a variable isInitialize is used to keep track of the state of the object. In this case it stores whether the object has been initialized. When a user instantiates an instance of RubyExecutor the base class’s ExecuteAll method is called. This executes all the scripts added using the AddScript and AddFile methods and then sets the isInitialized variable to true. After this point, the RubyExecutor instance can still be used to add scripts or files, but only the new ones will be executed by the engine.

public abstract class ExecutorBase
{
	private bool isInitialized = false;

	protected ScriptRuntime scriptRuntime;
	protected ScriptEngine scriptEngine;
	protected List<DynamicLanguageScript> scriptList;

	protected abstract void CreateRuntime();
	protected abstract void CreateEngine();

	public void Init()
    {
	    ExecuteAll();
    }

	public ExecutorBase()
	{
	    InitiateSequence();
	}

	private void InitiateSequence()
	{
	    scriptList = new List<DynamicLanguageScript>();
	    CreateRuntime();
	    CreateEngine();
	}

	public void AddScript(string scriptContents)
	{
	    scriptList.Add(new DynamicLanguageScript { CodeText = scriptContents, Executed = false });

	    if (isInitialized)
		    ExecuteRecent();
	}

	public void AddFile(string scriptFile)
	{
	    scriptList.Add(new DynamicLanguageScript { CodeText = ReadFile(scriptFile), Executed = false });

	    if (isInitialized)
		    ExecuteRecent();
	}

	protected void ExecuteAll()
	{
	    scriptList.ForEach(s => { scriptEngine.Execute(s.CodeText); s.Executed = true; });
	    isInitialized = true;
	}

	protected void ExecuteRecent()
	{
	    scriptList.Where(s => !s.Executed).ToList().ForEach(s => { scriptEngine.Execute(s.CodeText); s.Executed = true; });
	}

	public object GetInstance(string instanceName)
	{
	    if (!isInitialized)
		    throw new NotSupportedException("Executor not initialized. Call \"Init()\" to initialize");

	    dynamic instanceVariable;
	    var instanceVariableResult = scriptEngine.Runtime.Globals.TryGetVariable(instanceName, out instanceVariable);            

	    if (!instanceVariableResult && instanceVariable == null)
		    throw new InvalidOperationException(string.Format("Unable to find {0}", instanceName));

	    dynamic instance = scriptEngine.Operations.CreateInstance(instanceVariable);
	    return instance;
	}

	public IEnumerable<string> GetInstanceNames()
	{
	    return scriptEngine.Runtime.Globals.GetVariableNames();
	}

	public bool CanInstantiate(string className)
	{
	    return scriptEngine.Runtime.Globals.ContainsVariable(className);
	}

	private string ReadFile(string fileName)
	{
	    if (File.Exists(fileName))
	    {
		    return File.ReadAllText(fileName);
	    }
	    throw new FileNotFoundException(string.Format("{0} was not found", fileName));
	}
}

public class RubyExecutor : ExecutorBase
{
	protected override void CreateRuntime()
	{
	    scriptRuntime = Ruby.CreateRuntime();
	}

	protected override void CreateEngine()
	{
	    scriptEngine = scriptRuntime.GetEngine("rb");
	}
}

public class DynamicLanguageScript
{
	public string CodeText { get; set; }
	public bool Executed { get; set; }
}

Line 7 and lines 56 – 69 is of prime importance in this wrapper. Line 7 declares a list of DynamicLanguageScript which is used to hold a reference to any file or script added and also whether or not it was executed. Lines 59 to 69 is the most important method for this wrapper GetInstance. Once the wrapper is initialized, users can call this method to get an instance of any class defined in the scripts/files added. So, let’s dig in to this method in detail.

public object GetInstance(string instanceName)
{
    if (!isInitialized)
	    throw new NotSupportedException("Executor not initialized. Call \"Init()\" to initialize");

    dynamic instanceVariable;
    var instanceVariableResult = scriptEngine.Runtime.Globals.TryGetVariable(instanceName, out instanceVariable); 

    if (!instanceVariableResult && instanceVariable == null)
	    throw new InvalidOperationException(string.Format("Unable to find {0}", instanceName));

    dynamic instance = scriptEngine.Operations.CreateInstance(instanceVariable);
    return instance;
}

In the above code snippet, when the method is called, I first check if the wrapper is initialized. Without initialization, the scripts are not executed and so I just throw and exception. If initialized, I use the dynamic keyword to declare a placeholder for the instance of the ruby object that would be created. Then, using the script engine’s Runtime method, I access the Globals instance and call the TryVariable method. This method looks at the scripts executed and tries to find a class definition. If available, I use the CreateInstance method defined within the Operations object (using the script engine) to create an instance of the name of the variable passed and return it. Enough said, let’s see an example of how this wrapper could be used.

To begin with, create an instance of the ruby executor (rExecutor). The AddScript method is then called to add a script which has the definition for a class named Person. Then I call the Init method to initialize the wrapper. From this point, the wrapper can be used to create instances of Person. To do this, I use the GetInstance method in line 12. Now, using this instance I can call the methods for the instance, for example the say method, which would just print the message “Hello”. Following this in the snippet below, there are more examples of how this wrapper could be used.

public static void Main(string[] args)
{
    Console.Write("Creating an instance of ruby executor...");
    RubyExecutor rExecutor = new RubyExecutor();
    Console.Write("done");
    Console.WriteLine();

    rExecutor.AddScript(@"class Person
			    def say
				puts ""Hello""
			    end
			   end");
    rExecutor.Init();

    dynamic inst = rExecutor.GetInstance("Person");
    inst.say();

    Console.WriteLine();

    foreach(var name in rExecutor.GetInstanceNames())
	Console.WriteLine(name);

    Console.WriteLine();

    if (rExecutor.CanInstantiate("Person"))
    {
	   dynamic inst2 = rExecutor.GetInstance("Person");
	   inst2.say();
    }

    Console.WriteLine();

    if (rExecutor.CanInstantiate("Person2"))
    {
	   dynamic inst2 = rExecutor.GetInstance("Person2");
	   inst2.say();
    }
    else
    {
	   Console.WriteLine("Can't instantiate \"Person2\"");
    }

    rExecutor.AddScript(@"class Testclass
			    def run
				puts ""The sum of 1 & 2 is #{1+2}""
				p = Person.new
				p.say
			    end
			   end");
    dynamic instTest = rExecutor.GetInstance("Testclass");
    instTest.run();
}

The output produced when running the above snippet is given below:

Creating an instance of ruby executor...done
Hello

Person

Hello

Can't instantiate "Person2"
The sum of 1 & 2 is 3
Hello
Press any key to continue . . .

To follow up, you could also create a PythonExecutor for dealing python scripts. It would work similar to the ways of the RubyExecutor. But, in this post I am not going to discuss about python, because it’s not really my forte!

public class PythonExecutor : ExecutorBase
{
	protected override void CreateRuntime()
	{
	    scriptRuntime = Python.CreateRuntime();
	}

	protected override void CreateEngine()
	{
	    scriptEngine = scriptRuntime.GetEngine("py");
	}
}

Downloads – RubyExecutor.cs and RubyExecutorVerifier.cs (rename to .cs)

Hope this post was interesting!

Share

MS SQL Profiler – Limiting trace information by database name

Okay, this is going to be a really short post about MS SQL profiler (yay, my first post about MS SQL :D ). In case you are not aware of the sql profiler (which I am sure most of the developers are aware of), it’s a tool used to view the queries issued by various applications to a database server. “SQL Server Profiler” is normally present in the following location All Programs\Microsoft SQL Server 2008\Performance Tools\SQL Server Profiler. Once you launch this executable, you can use the File menu to start a new trace session (File -> New Trace). Then you will have to enter the database server name and the login credentials. Once you click on “Connect”, you will get the “Trace Properties” dialog. When you hit on “Run”, all the queries issued by various applications to this database server can be seen. Now let me get to the most interesting part.

At times, in a database server that has a number of databases accessed by a number of applications, it may be really difficult keep track all the traced events. Of course, you can use Ctrl + F, but this is much more interesting as you pretty much get a limited amount of data to look at. The profiler has an option to limit the trace to a specific database. This post is going to discuss with images as to how this filter can be applied so as to limit the amount of trace information.

First, when you choose File -> New Trace, you get the trace window as shown below. Notice the 2nd tab “Events Selection”. Select that tab.

Initial trace properties window

In this tab, look for the “Show all columns” checkbox and check it. Then click on the “Column Filters” button.

Initial trace properties window

Now in the “Edit Filter” dialog displayed look for the “DatabaseName” and select it. Then in the right pane, in the tree displayed, expand “Like“. You now get a text box where you can enter the database name. Now click the OK button and now you are all set. You can also enter multiple database names here. You get a new text box whenever you enter a database name.

Initial trace properties window

Now, you get back to the “Trace Properties” window. When you hit on “Run”, you only see the traces for the database you selected!

If you knew this already, this could be a refresher of sorts! But I came to know of this only today :( , but still happy to know this!!!

Hope this post was helpful!

Share

Dependency Injection With Ninject And Extending It a Bit Further

In this post I am going to discuss a very interesting concept called “dependency injection (DI)” and also about extending the class that injects the dependencies further to achieve some more functionalities that I needed for a project of mine. I am going to use a mvc 3 application to explain about DI. DI is a type of interface programming that allows you to create loosely coupled systems. This increases testability and also reduces the amount of changes required to a project for adding / removing features. At this point it may be confusing, but once I discuss more about this with some examples, it will be much more clearer.

A system implementing DI could be pictured of as having 3 components:

  • Dependent Consumer
  • Dependency
  • Dependency Injector

Dependency consumer‘s are parts of the system that expects a concrete instance to implement something. Consider the following code listing (listing 1):

public class Consumer
{
    private DbAccessor _accessor;

    public Consumer(DbAccessor accessor)
    {
        _accessor = accessor;
    }

    public void DoSomething()
    {
       // -- snip --
    }
}

public class Tester
{
   public static void Main(string[] args)
   {
        DbAccessor accessor = new DbAccessor();
        Consumer consumer = new Consumer(accessor);
        consumer.DoSomething();
   }
}

If you notice the Main method, in order to create an instance of a Consumer, the method has to first create a DbAccessor instance. This is a Dependency. Thus, the method has to know about both the DbAccessor and Consumer. This is known as tight coupling. Because, if you change the name of this class to say DbType1Accessor and assuming this class is used a number of files, you have to change it in all of these files. A way better example is, say you want to replace DbAccessor with XmlAccessor you have to replace the same in all those numerous files. So with all of these facts, I am sure you understand why strong coupling is bad! Later in the post I will show how this strong coupling can be removed.

Now, let’s get to the most important component, the dependency injector. A Dependency Injector is a component that would help you to free the system from this coupling. And this post concentrates on adding a DI component for your project. I have always used “NInject” for implementing DI in my projects.

It’s extremely easy to setup and get started with NInject. To get started download, the NInject dll from here. For this post I was using NInject v2.0.0 (yeto to update to v2.2 :( ). Once you download the dll, add it to the project using “Add Reference”. Then create a class called NinjectControllerFactory and add the following code snippet to this file. This class is going to act as the principal class for implementing DI. If you notice this class inherits the DefaultControllerFactory, which is the default for the mvc framework.

A controller factory is a component of the mvc framework that helps in creating an instance of a controller as required by the mvc framework. In this case we are attempting to provide loose coupling to all the controllers. The controller factory, which is responsible for creating the controllers is overridden in this case so that when a controller is created now, the new controller factory would take the responsibility of creating an instance of the controoler and enabling the Ninject module to “inject” the dependency required by the controller.

public class NinjectControllerFactory : DefaultControllerFactory
{
	private IKernel kernel = new StandardKernel(new AplicationIocServices());

	protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
	{
	    if (controllerType == null)
        {
		    return null;
        }
	    return (IController)kernel.Get(controllerType);
	}

	private class AplicationIocServices : NinjectModule
	{
	    public override void Load()
	    {
		    Bind<IProductsRepository>().To<FakeProductsRepository>();
		    Bind<ICategoryRepository>().To<FakeCategoryRepository>();
	    }
	}
}

In the above code listing, line 3 creates an instance of StandardKernel which is required for the ninject module to work. The StandardKernel implements the IKernel interface which is used in the overriden GetControllerInstance method to return an instance of the required controller by passing the dependency needed by the controller. Note that, as this class is set to replace the DefaultControllerFactory, it’s very important to override the GetControllerInstance method to return an appropriate controller. If you notice line 3, an instance of the ApplicationIocServices instance is passed to the StandardKernel. This is a private class within the NinjectControllerFactory which is used to specify the bindings between an interface and a concrete instance. This class inherits from the NinjectModule class and overrides the Load method of the NinjectModule class.

Every line within the Load binds an interface to a concrete instance so that ninject can create a concrete type corresponding to the interface type passed when creating a controller instance. So when a controller requests a concrete type for IProductsRepository, ninject module returns an instance of FakeProductsRepository which could be used within the controller.

It’s not over if you just create this class. You have to inform the framework to use this instead of the DefaultControllerFactory using the Application_Start event in the Global.asax.cs file. This is done in line 8. ControllerBuilder class of mvc has the
Current property which is nothing but an instance of a ControllerBuilder for the current
application. The application’s controller factory is set to an instance of the NinjectControllerFactory we created earlier using the SetControllerFactory method of the ControllerBuilder instance. After this point, when a request is received for the HomeController (say), an instance of Home Controller will be created by our custom factory, by injecting in the required dependencies.

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

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

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

Following is an example of how this is put to use. Let us assume that the HomeController has an action called Products that displays a list of products that this web site offers for purchase. Without DI, I will have to create an instance of FakeProductsRepository and use it in the controller as shown below:

public class HomeController : Controller
{
	public ActionResult Products()
	{
        FakeProductsRepository repository = new FakeProductsRepository();
	    return View(repository.Products);
	}
}

The above snippet has a strong coupling of the FakeProductsRepository with the HomeController. This is not good because it reduces testability and also makes you modify this code whenever something changes with the FakeProductsRepository class. For example, in case you want the controllers to receive a concrete instance of ProductsRepository instead of an instance of FakeProductsRepository, the only change required is the change in line 9. Thus even if a number of controllers uses the IProductsRepository dependency, nothing would change, as the only change required was in the NinjectControllerFactory class.

public class NinjectControllerFactory : DefaultControllerFactory
{
	// -- snip --

	private class AplicationIocServices : NinjectModule
	{
	    public override void Load()
	    {
		    Bind<IProductsRepository>().To<ProductsRepository>();
		    Bind<ICategoryRepository>().To<FakeCategoryRepository>();
	    }
	}
}

Now that we have set up DI, we can modify the code as shown below. Note that now, the fact that the controller expects a concrete type bound to IProductsRepository could be identified by the parameter to the constructor of the HomeController, which is IProductsRepository. From this point onwards, ninject takes care of creating an instance of the Home controller including passing to it an instance of the FakeProductsRepository because IProductsRepository is bound to FakeProductsRepository.

public class HomeController : Controller
{
	private IProductsRepository productsRepository;

    public HomeController(IProductsRepository productsRepo)
    {
          productsRepository = productsRepo;
    }

	public ActionResult Products()
	{
	    return View(productsRepository.Products);
	}
}

Extending the Ninject Module:

Now, let me get to the most important part of this post. What if I need to create a concrete instance somewhere in a class where Ninject does not come in to the picture? Thats what the remainder of the post is going to deal with. For this part, I again take up one of my favorite area of C# – type constraints :) Let’s add a method called GetConcreteInstance to the NinjectControllerFactory class. This method will be used to get a concrete instance based on the interface type passed. This is a generic method which takes in an interface as a type parameter, finds a concrete instance, casts it to the type T and returns it to the caller.

So, with this method, you don’t have pass every required instance to a controller. This method uses the TryGet method of the StandardKernel to see if a concrete instance exists for the type passed. If not available this method throws an exception.

public class NinjectControllerFactory : DefaultControllerFactory
{
	// -- snip

	public T GetConcreteInstance<T>()
	{
	    object instance = kernel.TryGet<T>();
	    if (instance != null)
        {
		    return (T)instance;
        }
	    throw new InvalidOperationException(string.Format("Unable to create an instance of {0}", typeof(T).FullName));
	}

	// -- snip --
}

Let us look in to an example on how this is put in to use in a controller. Before that let us add a helper class to call this method, so that we abstract the part of getting a reference to the controller factory. Its given below:

public static class InstanceFactory
{
	public static T CreateConcreteInstance<T>()
	{
	    NinjectControllerFactory factory =(NinjectControllerFactory)ControllerBuilder.Current.GetControllerFactory();
	    return (T)factory.GetConcreteInstance<T>();
	}
}

Now, I have added the Categories method to the HomeController. Let’s assume apart from this method, no other method requires the ICategoryRepository. So instead of injecting the dependency to the constructor, within the action method, I use the new helper created earlier to get a concrete instance of ICategoryRepository by passing in ICategoryRepository as the type parameter.

public class HomeController : Controller
{
	private IProductsRepository productsRepository;

	// -- snip --

	public ActionResult Categories()
	{
	    ICategoryRepository categoryRepo = InstanceFactory.CreateConcreteInstance<ICategoryRepository>();
	    return View(categoryRepo.GetCategories());
	}

	// -- snip --
}

In the case of the CategoryController, DI is used as its more likely to be used throughout the controller. So I am just letting ninject take the responsibility for the CategoryController.

public class CategoryController : Controller
{
	private ICategoryRepository categoryRepository;

	public CategoryController(ICategoryRepository categoryRepo)
	{
	    categoryRepository = categoryRepo;
	}

	public ActionResult Index()
	{
	    return View(categoryRepository.GetCategories());
	}
}

Now that I have given you the full picture about DI, let me show how the code in listing 1 can be refactored to free it of the strong coupling.

public class Consumer
{
    private DbAccessor _accessor;

    public Consumer(DbAccessor accessor)
    {
        _accessor = InstanceFactory.CreateConcreteInstance<IDbAccessor>();
    }

    public void DoSomething()
    {
       // -- snip --
    }
}

public class Tester
{
   public static void Main(string[] args)
   {
        Consumer consumer = new Consumer();
        consumer.DoSomething();
   }
}

Given below is another high level implementation of how this new helper class/method could be used.

public class BaseClass
{
	private SomeBusinessFunction func;

	public BaseClass()
	{
	    func = new SomeBusinessFunction();
	}

	public void SomeMethod()
	{
	    func.DealWithSomething();
	}
	}

	public class DerivedClass : BaseClass
	{
	public DerivedClass()
	{

	}
}

public class SomeBusinessFunction
{
	private ICategoryRepository categoryRepo;

	public SomeBusinessFunction()
	{
	    categoryRepo = InstanceFactory.CreateConcreteInstance<ICategoryRepository>();
	}

	public List<Category> DealWithSomething()
	{
	    List<Category> categories = categoryRepo.GetCategories().ToList();

	    // -- do something --

	    return categories;
	}
}

Okay, I know that you have seen a lot code. You can download a sample project here. Hope you enjoyed this post. Happy coding!

Share

Yet Another Ruby Language Post :)

This time, I am back with a post that deals with few interesting aspects of ruby. To begin with, I am going to discuss about YAML (Guess you now know the reason why I gave this title to this post :D ). YAML is an acronym for Yet Another Markup Language. YAML is a way by which data could be serialized in a human readable format. In ruby’s context, YAML could be used to save the state of ruby objects. Ruby makes it really easy to store and retrieve YAML objects. This enables you to accomplish things with a very few lines of code. Conside the following for example:

require 'yaml'
a =['a', 'b']
y(a)

In order to use YAML in ruby, you need to import the YAML library. This is done using the require statement. Then I declare a simple ruby array called ‘a’. Now y is a method from the YAML library that prints the array ‘a’ in the YAML format. The output is given below. The first line --- indicates that this is a YAML serialized data. Then the following lines represent every entry in the array.

---
- a
- b

This technique could also be utilized for saving the state of an instance or a list of instances. Consider the following class and an instance of it.

class Appdata
	attr_accessor :id, :title, :description

	def initialize(p_id, p_title, p_description)
		@id = p_id
		@title = p_title
		@description = p_description
	end
end

i = Appdata.new(1, "Title 1", "Description 1")
y(i)

Executing this snippet would give the following output. The first line as before indicates that this is a YAML serialized data. After —, !ruby/object:Appdata indicates that what follows is an instance of the Appdata object. Following this line, every property of this instance is listed.

>ruby variables.rb

--- !ruby/object:Appdata
description: Description 1
id: 1
title: Title 1
>Exit code: 0

This could very well be put in to a number of useful implementations. For example, an application’s configuration/state could be stored/retrieved using this. Consider the class given below:

require 'yaml'

class Dataclass
	attr_writer :data_id, :data_name

	def initialize(id, name)
		@data_id = id
		@data_name = name
	end

	def getdataid
		@data_id
	end

end

a = Dataclass.new(3,"three")

if (!File.exists?("app_state.config"))
	puts "Dumping app state"
	f = File.new("app_state.config", 'w')
	YAML.dump(a, f)
	f.close
end

$config

if (File.exists?("app_state.config"))
	puts "Reading app state"
	File.open("app_state.config") { |data|
		$config = YAML.load(data)
	}
end

puts $config.getdataid

In the above listing, lines 3 – 15 represent the config class I wish to save. Line 17 creates an instance of Dataclass. Lines 19-24 checks if there is a file named “app_state.config” and if not it creates a new file with the same name and then uses the YAML.dump method to dump the instance a in to the file created using the handle f. Then to demonstrate the fact that this serialized data can be loaded back, I am using the YAML.load method. This is demonstrated using lines 28 – 33. Before this, I have defined a variable $config to store the configuration object stored. In order to do this, the file is opened using the File.open method. The data read from the file is made available to the block that will executed after the read operation using the |data| variable. Then I call YAML.load method to load the Dataclass instance in to the $config variable.

From this point onwards, $config can be used in the application as shown in line 35. I have put YAML in to use in my to-do list application. I use YAML to save / load tasks added by the user. Check out this file to see what I mean. A sample file generated by this application is here.

This greatly simplifies the amount of code required to do this. This is evident when you compare the amount of code involved in text manager which save’s / load’s the tasks in to a text file. Code for this is here. A sample file generated by this application is here.

The next thing I would like to discuss is about class & instance variables and class methods. When I was getting myself acquainted with ruby, I was stumped once even though I knew the difference between a class and instance variable, as it didn’t register well enough in my mind. After identifying the mistake it’s going to be etched forever in my memory! To begin with, in ruby, an instance variable is prefixed with ‘@’ and a class variable is prefixed with ‘@@’. A class method is similar to a c# static method and so an instance is not required to call this method. So, a class variable is similar to a static field.

I am sure you are aware about classes and objects. A class is a blueprint of an object, it’s a collection of properties (representing state) and methods (representing behavior). And, an object is an instance of a class. Every instance variable is specific to an instance as the name suggests and a class variable is common across all the instances and so is specific to the class. Let me make it clear with an example.

class Sampleclass
	@@no_instances = 0

	attr_accessor :initialMessage 

	def initialize(initMessage)
		@@no_instances = @@no_instances + 1
		@initialMessage = initMessage
	end

	def print
		puts "Hello from Sampleclass #{self.inspect}"
	end

	def Sampleclass.printInstanceCount
		puts @@no_instances
	end
end

In the above snippet, line 2 represents a class variable and line 4 represents an instance variable. And line 15 represents a class method, which is similar to a C# static method. A ruby class method, just like other instance methods, starts with the def keyword. Then the method is named in the format ClassName.MethodName as shown in the snippet above. In this case, @@no_instances is used to maintain a count of the number of instances of Sampleclass created so far. The class method in this case is used to print the number of instances created for this object. Line 2 initializes the class variable to 0. Whenever an instance of Sampleclass is created, this counter is incremented. Notice that it is not reset for every instantiation of this class. The class method provides a way by which the user can get to know the number of instances created so far. The snippet below demonstrates this.

a = Sampleclass.new("Hello")
a.print

b = Sampleclass.new("Hello")
b.print

Sampleclass.printInstanceCount

c = Sampleclass.new("Hello")
c.print

Sampleclass.printInstanceCount

When the above snippet is executed, the following is the output.

>ruby variables.rb
Hello from Sampleclass #<Sampleclass:0x5d8a78 @initialMessage="Hello">
Hello from Sampleclass #<Sampleclass:0x5d8988 @initialMessage="Hello">
2
Hello from Sampleclass #<Sampleclass:0x5d8898 @initialMessage="Hello">
3
>Exit code: 0

Notice lines 3 and 5, these are due to the calls to the class method and it displays the number of instances created. Hope this post was informative / refreshing!

Do post your comments!

Share

ASP.Net MVC Extreme – A Deep Dive Inside View Engines

I am back with another post in the ASP.Net MVC extreme series (as promised)! In this post lets dive into the internals of how a view is selected when an action method returns a View. MVC has the following default view engies – webform and razor and also lets us to add custom view engines. For more inforation on custom view engines, refer to my earlier post here. Custom view engines can be added using the Application_Start event as shown below:

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

   ViewEngines.Engines.Clear();
   ViewEngines.Engines.Add(new CustomRazorViewEngine());

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

In the above snippet, ViewEngines is a static class provided by the framework in order to manage the view engies that the framework would look for when searching for views to render. The entire action starts with the ViewResultBase class, which is the base class ViewResult which is responsible for rendering html content to the client. There are a number of other result’s such as FileResult, JsonResult, JavaScriptResult etc and all of these derive from the ActionResult class. ViewResultBase has the ViewEngineCollection property and it’s defined as given below. The engines set up in Application_Start is provided to the ViewResult class using this property. More information on how these engines are used follows soon!

// From mvc sources/reflector
public ViewEngineCollection ViewEngineCollection {
   get {
      return _viewEngineCollection ?? ViewEngines.Engines;
   }
   set {
      _viewEngineCollection = value;
   }
}

A simple action method in mvc would resemble the following:

public ActionResult SomeActionMethod()
{
   return View();
}

The action method above returns the result of the View method from the Controller class. This method returns a ViewResult instance depending upong the parameters passed from the action method. Note that it could also be a PartialViewResult instance. The Controller type has multiple overloads of the View method. Their definitions are given below:

// From mvc sources/reflector
protected internal ViewResult View() {
    return View(null /* viewName */, null /* masterName */, null /* model */);
}

protected internal ViewResult View(object model) {
    return View(null /* viewName */, null /* masterName */, model);
}

protected internal ViewResult View(string viewName) {
    return View(viewName, null /* masterName */, null /* model */);
}

protected internal ViewResult View(string viewName, string masterName) {
    return View(viewName, masterName, null /* model */);
}

protected internal ViewResult View(string viewName, object model) {
    return View(viewName, null /* masterName */, model);
}

All of these overloads eventually call the following method:

// From mvc sources/reflector
protected internal virtual ViewResult View(string viewName, string masterName, object model) {
    if (model != null) {
	ViewData.Model = model;
    }

    return new ViewResult {
	ViewName = viewName,
	MasterName = masterName,
	ViewData = ViewData,
	TempData = TempData
    };
}

Similarly, the following method takes in an IView and has the following definition:

// From mvc sources/reflector
protected internal ViewResult View(IView view) {
   return View(view, null /* model */);
}

This method eventually calls the following method:

// From mvc sources/reflector
protected internal virtual ViewResult View(IView view, object model) {
    if (model != null) {
	ViewData.Model = model;
    }

    return new ViewResult {
	View = view,
	ViewData = ViewData,
	TempData = TempData
    };
}

If you notice the implementations of View, it creates an instance of ViewResult by passing the view name, master name, view data and temp data in the case of the first method and an IView object, view data and temp data in the case of the other method.

Coding best practices(feel free to skip this if you are aware of coding best practices): When you have a method that also has corresponding overloads, make sure that you don’t repeat the same code in both (or all) the places. Consider the following case. This method of handling overloads is bad!.

// bad practice, do not use!!!
public void FooMethod(int memberForYears, string userName)
{
   int totalDaysMemberFor = memberForYears * 365; // ignoring the fact about leap years
   int _membershipPoints = GetMembershipPoints();
   Console.WriteLine("User {0} was a member for {1} days and has {2} points", userName, totalDaysMemberFor, _membershipPoints);
}

public void FooMethod(int memberForYears, string userName, int membershipPoints)
{
   int totalDaysMemberFor = memberForYears * 365; // ignoring the fact about leap years
   int _membershipPoints = membershipPoints;
   Console.WriteLine("User {0} was a member for {1} days and has {2} points", userName, totalDaysMemberFor, _membershipPoints);
}

A nicer way to do this is given below. The refactored code below does not have repetitive code but utilizes the final method to display the results to the user. If you observe the above 2 methods, the only difference is the _membershipPoints bit which gets the value using the GetMembershipPoints method (not shown). So in the snippet below, the 1st overload is called by passing in the value from the method as the 3rd parameter.

// good practice
public void FooMethod(int memberForYears, string userName)
{
   FooMethod(memberForYears, userName, GetMembershipPoints());
}

public void FooMethod(int memberForYears, string userName, int membershipPoints)
{
   int totalDaysMemberFor = memberForYears * 365; // ignoring the fact about leap years
   int _membershipPoints = membershipPoints;
   Console.WriteLine("User {0} was a member for {1} days and has {2} points", userName, totalDaysMemberFor, _membershipPoints);
}

Before we dig in to the ViewResult class lets get a deeper understanding of the how this class is put in to use.

If you can recollect from my previous post, every controller in mvc implements the IController interface and this has the Execute method. When a request arrives, the Execute method is called. Within this method a call to the ExecuteCore method of the Controller is invoked. The ExecuteCode method then handles the responsibility to the ControllerActionInvoker.InvokeActionResult method. Within this method the ExecuteResult method of the ViewResultBase class is called, after executing the content of the action method according to the request. This method itself certainly deserves a post by the way! After this step the real action starts!!! Lets get in to that :)

The ExecuteResult method is given below:

// From mvc sources/reflector
public override void ExecuteResult(ControllerContext context) {
    if (context == null) {
	throw new ArgumentNullException("context");
    }
    if (String.IsNullOrEmpty(ViewName)) {
	ViewName = context.RouteData.GetRequiredString("action");
    }

    ViewEngineResult result = null;

    if (View == null) {
	result = FindView(context);
	View = result.View;
    }

    TextWriter writer = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer);
    View.Render(viewContext, writer);

    if (result != null) {
	result.ViewEngine.ReleaseView(context, View);
    }
}

Note line 13 in the above snippet. This line calls the FindView overridden in the ViewResult (and PartialViewResult) class(es) to find a matching view. This method, uses the ViewEngineCollection in the ViewResultBase class to get a list of the available view engines. And then ViewEngineCollection type’s FindView method is called to find an appropriate view. This is where the engines added come in to play. The ViewEngineCollection.FindView method is given below:

// From mvc sources/reflector
public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName) {
    if (controllerContext == null) {
	throw new ArgumentNullException("controllerContext");
    }
    if (string.IsNullOrEmpty(viewName)) {
	throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");
    }

    return Find(e => e.FindView(controllerContext, viewName, masterName, true),
		e => e.FindView(controllerContext, viewName, masterName, false));
}

The Find method called in line 10 uses the engines defined for the application to find an appropriate view. To explore more in to this method, it’s important to see the ViewEngines class.

// From mvc sources/reflector
public static class ViewEngines {
	private readonly static ViewEngineCollection _engines = new ViewEngineCollection {
	    new WebFormViewEngine(),
	    new RazorViewEngine(),
	};

	public static ViewEngineCollection Engines {
	    get {
		return _engines;
	    }
	}
}

ViewResultBase class’s ViewEngineCollection property is set to the ViewEngines.Engines property, which is initialized with an instance of the ViewEngineCollection class created by passing the 2 default view engines available in mvc 3. If you remember (yes it’s been a long post ;) ) we use the ViewEngines.Engines property to add custom view engines. The Find method uses the engines set during instantiation to find an appropriate view. The view engine collection would either have the default engines or the custom engines or both. If this process fails, you see the generic error screen (given below) that lists all the locations searched by the framework.

As you may know, the action starts from the controller. Refer to my earlier post for more details about this. In a future post I will also try to connect the dots between these 2 posts, if I feel anything is missing. Also, I am reviewing this post to catch anything I missed, so it may be updated in the following days!

Finally, do post your comments and happy coding!

Share

ASP.Net MVC – Custom View Engines (Using the razor view engine as the base)

Okay, it’s ASP.Net MVC 3 time again! In this post I am going to discuss about custom view engines. I do not have a lot of real-time experience with custom view engines, but I wanted to try out one of my ideas of organizing the folder in a way that I feel was much more clearer. This is what I am talking about:

Views/
...Home/
......Pages/
.........Page1.cshtml
.........Page2.cshtml
......PartialPages/
........._UserControl1.cshtml
........._UserControl2.cshtml

From the textual folder structure above, I guess my intention is clear. In case you are familiar with the folder structure of MVC, There is a single “Views” folder and within this folder there are individual folders for every controller. Finally, the user controls and pages go in to these folders. If a page/user control is being shared it goes in to the “Shared” folder. In simple words, I just wanted to segregate the cshtml files further by creating a “Pages” and “PartialPages” folder.

As the name suggests, pages would go in to the “Pages” folder and user controls would go in to the “PartialPages” folder. To implement this I have created a custom view engine by inheriting the RazorViewEngine class. As the location of every file would change, we have to specify this by overriding the base string arrays that specify the possible locations of a certain type of a file (master, page, partial page).

Given below is the complete class. “%1″ in every possible path would have to be replaced with either “Pages” or “PartialPages” depending upon the method in question.

public class CustomRazorViewEngine : RazorViewEngine
{
	public CustomRazorViewEngine() : base()
	{
	    AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/%1/{0}.cshtml",
						     "~/Areas/{2}/Views/{1}/%1/{0}.vbhtml",
						     "~/Areas/{2}/Views/Shared/%1/{0}.cshtml",
						     "~/Areas/{2}/Views/Shared/%1/{0}.vbhtml" };
	    AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/%1/{0}.cshtml",
						       "~/Areas/{2}/Views/{1}/%1/{0}.vbhtml",
						       "~/Areas/{2}/Views/Shared/%1/{0}.cshtml",
						       "~/Areas/{2}/Views/Shared/%1/{0}.vbhtml" };
	    AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/%1/{0}.cshtml",
							    "~/Areas/{2}/Views/{1}/%1/{0}.vbhtml",
							    "~/Areas/{2}/Views/Shared/%1/{0}.cshtml",
							    "~/Areas/{2}/Views/Shared/%1/{0}.vbhtml" };
	    ViewLocationFormats = new string[] { "~/Views/{1}/%1/{0}.cshtml",
						 "~/Views/{1}/%1/{0}.vbhtml",
						 "~/Views/Shared/%1/{0}.cshtml",
						 "~/Views/Shared/%1/{0}.vbhtml" };
	    MasterLocationFormats = new string[] { "~/Views/{1}/%1/{0}.cshtml",
						   "~/Views/{1}/%1/{0}.vbhtml",
						   "~/Views/Shared/%1/{0}.cshtml",
						   "~/Views/Shared/%1/{0}.vbhtml" };
	    PartialViewLocationFormats = new string[] { "~/Views/{1}/%1/{0}.cshtml",
							"~/Views/{1}/%1/{0}.vbhtml",
							"~/Views/Shared/%1/{0}.cshtml",
							"~/Views/Shared/%1/{0}.vbhtml" };
	    FileExtensions = new string[] { "cshtml", "vbhtml" };
	}

	protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
	{
	    return base.CreateView(controllerContext, viewPath.Replace("%1","Pages"), masterPath.Replace("%1","Pages"));
	}

	protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
	{
	    return base.CreatePartialView(controllerContext, partialPath.Replace("%1","PartialPages"));
	}

	protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
	{
	    return (base.FileExists(controllerContext, virtualPath.Replace("%1", "Pages")) ||
		    base.FileExists(controllerContext, virtualPath.Replace("%1", "PartialPages")));
	}
}

To download the file, click here (right click – save as – remove the .txt extension).

As you see above, to implement your custom view engine, you just have to override the following 3 methods:

  • CreateView – This method is called with the corresponding parameters if the view requested is a page
  • CreatePartialView – This method is called with the corresponding parameters if the view requested is a partial page / user control
  • FileExists – This method also has to be overridden in this case because the implementation of this method in the base class won’t know where to look for the file because of the %1 in the path. If this method is not overridden FileExists would always return false which would cause view engine to fail in the process of finding a matching view even if one exists

Now, update _ViewStart.cshtml to specify the location of the master page as shown below:

@{
    Layout = "~/Views/Shared/Pages/_Layout.cshtml";
}

Once we have the class that implements the custom razor engine, and the corresponding change to the _ViewStart.cshtml file, we have to inform the framework to use this instead of the default engine, as the default engine won’t work anymore as the folder structure has changed. To do this modify the Application_Start method in Global.asax.cs to include lines 5 & 6. Line 5 clears all the engines currently added (in this case, just the default engine) and line 6 adds the new custom engine we created.

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

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new CustomRazorViewEngine());

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

Also, look forward to another post that dwelves in to internals of view engines in mvc 3!!!

Post your comments and happy coding!

Share

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