Custom Metadata Attributes in ASP.Net MVC

Hello! It’s been a long time since I posted anything and trust me it does not feel good :) So here I am with an interesting post! This post discusses about how I put custom metadata attributes in to use for describing static information for a certain field.

I was in a situation where in I have to talk to a WCF service to update certain information. It goes like this:

  • Get a list of items that represents users belonging to different roles
  • Display a view that lists all the users in a grid and let users update them
  • Once the user is done, he/she clicks a button which finalizes the update by sending in all the users for a certain role in a sequence (synchronous)

For this task, I had booleans in order to represent the access for a certain role for a user. This would translate in to check boxes in the view and I didn’t want to ‘n’ number of partial views and model binders by making a simple boolean in to a complex field. The information related to every role is a constant and so I wanted to leverage that! So, I wanted to use the custom metadata feature, but alas, I needed some information on hard-wiring it to the framework. I went googling and found this StackOverflow answer – http://stackoverflow.com/a/5548384/312219! My idea builds on this!

The following classes are straight from the answer referred about so I am not going to detail them! The first class is the abstract class that represents a custom metadata attribute.

    public abstract class MetadataAttribute : Attribute
    {
        public abstract void Process(ModelMetadata modelMetaData);
    }

Then there is a custom model metadata provider shown below:

    public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(
            IEnumerable<Attribute> attributes,
            Type containerType,
            Func<object> modelAccessor,
            Type modelType,
            string propertyName)
        {
            var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));
            return modelMetadata;
        }
    }

Which is associated to the framework as shown below in Global.asax.cs‘s Application_Start method

        protected void Application_Start()
        {
            // -- snip --

            ModelMetadataProviders.Current = new CustomModelMetadataProvider();
        }

Now that we have the wiring done, let me get to the core of this post!

My objective is to create an attribute that could hold a custom value. So I created the CustomValueAttribute class that inherits the MetadataAttribute class as shown below:

    public class CustomValueAttribute : MetadataAttribute
    {
        private readonly int _customValue;

        public CustomValueAttribute(int customValue)
        {
            _customValue = customValue;
        }

        public int CustomValue
        {
            get { return _customValue; }
        }

        public override void Process(ModelMetadata modelMetaData)
        {
            modelMetaData.AdditionalValues.Add("CustomValue", _customValue);
        }
    }

This class could now be used to decorate any property in a class. In my case I am using this attribute to decorate a couple of booleans.

    public class SampleEntry
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [CustomValue(1)]
        public bool UserEnabled { get; set; }
        [CustomValue(2)]
        public bool NewsletterEnabled { get; set; }
    }

If you notice, UserEnabled and NewsletterEnabled are decorated with this attribute. Now, in my case the view handles the responsibility of displaying the checkboxes in a grid and I use a Session to hold all changes to an individual SampleEntry. Ignoring all those nitty gritty details, let me show how I am putting these CustomValueAttribute‘s to use.

Given below is the view model that includes a list of SamepleEntry items:

    public class SampleViewModel
    {
        public List<SampleEntry> Entries { get; set; }
    }

Here is the most interesting part! Given below is the action method that puts the custom attribute to use!

    public class SampleController : Controller
    {
        public ActionResult Index()
        {
            // Assume the view contains a list of "SampleEntry" items
            // Of which we just need the count of items that has "UserEnabled" to be true
            // And "NewsletterEnabled" to be true

            // Thus "UserEnabled" and "NewsletterEnabled" can be simple "checkboxes" in the view!
            // The reasoning is that in my case, the wcf service just needs the "id"'s of items
            // whose values are set to true

            // This would allow easy extensions and remove the necessity for if...else

            var model = GetModel();

            var requiredCustomValues = GetCustomValues();

            var props = typeof (SampleEntry).GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();

            foreach (var requiredCustomValue in requiredCustomValues)
            {
                var list = new List<int>();

                props.ForEach(prop =>
                {
                    var attr = prop.GetCustomAttribute<CustomValueAttribute>();
                    if (attr != null && requiredCustomValue == attr.CustomValue)
                    {

                        foreach (var i in model.Entries)
                        {
                            var value = prop.GetValue(i, null);
                            if ((bool)value)
                            {
                                list.Add(i.Id);
                            }
                        }
                    }
                });

                UpdateValues(list, requiredCustomValue);
            }

            return View();
        }

	// -- Snip --
}

Let me get to the fun part directly. The action method already contains some information on why I do this. GetCustomValues is a method that returns a list of values for which the wcf service expects id’s chosen by the user. In this example, it is just a dummy method that returns 2 integers as shown below:

        private List<int> GetCustomValues()
        {
            return new List<int> { 1,2 };
        }

Line 19 uses reflection to get all the properties of the SampleEntry class. Then as I said earlier for every value in GetCustomValues I loop through the properties that has CustomValue set to the required value and collect the id’s in a list. Finally, I call the UpdateValues method which would call the wcf service to report the selected values. For the sake of this post, this method does nothing:

        private void UpdateValues(List<int> list, int requiredCustomValue)
        {
            // This method would call the wcf service to update the values !!!
        }

I will be correcting this post as necessary, but, I guess you found this post interesting! I have to follow this method so as to not change the wcf service. But if I get a chance to update the service, I could find an easier way to do this!

Happy coding!

Share

GitHub: Working with Branches

Hello people! This is going to be a very quick post. For this post I am going to assume that you have some familiarity with GitHub. I am going to discuss the steps required to create a branch when you are logged on to github and how you could clone this branch to create a local working copy.

Let me take an example. Assume you have a repository called ruby-practice with only a
master branch. Now, in order to create a new branch, follow the following steps:

  • Below the Clone in Windows button in your repository, you will see a branch dropdown that has master selected.
  • Now click on the down arrow and in the text box you see enter the name of the new branch
  • Once you are done entering the new branch name, wait for a few seconds, you will see the Create branch: <your_branch_name> button appear [blue highlighted block]
  • Let us assume you entered ruby-practice-v1.0
  • Click on this button, the branch will be created and you will be redirected to this new branch

Given below is a screenshot that shows this particular section:

If you don’t get the create branch button even after waiting for a few seconds, press the space bar, you will see it now. Now remove the space added and now click the create branch button.

Now that you have created the branch, lets see how a local copy could be created in order to work on this independently apart from the master branch. I am going to use the shell to do this, since I am much more familiar with the shell than the UI.

Open the github’s shell, and cd to the folder where you would like to create the working directory for your branch. Let us assume the base folder is C:\users\karthik\GitHub. First step is to create the folder which will contain your branch ruby-practice-v1.0.

md ruby-practice-v1.0

Now enter the following command to clone the branch to your local working directory:

git clone git@github.com:karthik25/ruby-practice.git -b ruby-practice-v1.0 .\ruby-practice-v1.0

At this point, the branch is cloned and is ready for use! Just cd to the new directory to get started

cd ruby-practice-v1.0

Hope you enjoyed this short post! Have fun with github! And as always happy coding!

Share

Test Driven Development: Unit Testing a Method That Expects a StreamReader

When I write code nowadays, one thing I make sure is to write unit tests. Remember, unit tests should be written BEFORE writing the code that the unit tests verify. It is incorrect to approach unit testing the other way. Also, unit tests should be as simple as possible, so as to avoid any errors with the unit test itself.

In this post, I am just going to show a method by which a method that takes in a StreamReader could be unit tested. The actual method expects the stream of a csv file, but for unit testing, it makes sense to have an in-memory stream instead of having a separate file (or the same file). It is important to describe what this method does before I get to the approach I used for unit testing this method. This method takes in a stream that contains number of lines, where every line is a comma-separated “entry” made up of first name, last name and email address. Real time usage of this unit test is a bit more involved, but the point of this post is just to introduce to you how a method that expects a StreamReader parameter could be unit tested.

Before I get to the part of “how”, here is the class that would represent every line in the CSV file.

    public class Entry
    {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string EmailAddress { get; set; }
    }

The class that has the required method implements the following interface. Interfaces are an integral part of unit testing, as they help you form an idea of what is required.

   public interface ICsvReader
   {
      List<Entry> ReadEntries(StreamReader csvStreamReader);
   }

The next step is creating the unit test itself. Its given below:

    [TestClass]
    public class CsvReaderTests
    {
        [TestMethod]
        public void CanGenerateEntryList()
        {
            ICsvReader iCsvReader = new CsvReader();
            var stream = CreateMockStream();
            var entryList = iCsvReader.ReadEntries(stream);
            Assert.IsNotNull(entryList);
            Assert.AreEqual(3, entryList.Count);

            var entry = entryList.SingleOrDefault(e => e.FirstName == "karthik");
            Assert.IsNotNull(entry);
            Assert.AreEqual("anant",entry.LastName);
            Assert.AreEqual("karthik@mail.com", entry.EmailAddress);

            entry = entryList.SingleOrDefault(e => e.FirstName == "some");
            Assert.IsNotNull(entry);
            Assert.AreEqual("user", entry.LastName);
            Assert.AreEqual("someuser@mail.com", entry.EmailAddress);

            entry = entryList.SingleOrDefault(e => e.FirstName == "another");
            Assert.IsNotNull(entry);
            Assert.AreEqual("user", entry.LastName);
            Assert.AreEqual("anotheruser@mail.com", entry.EmailAddress);
        }

        private static StreamReader CreateMockStream()
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("karthik,anant,karthik@mail.com");
            stringBuilder.AppendLine("some,user,someuser@mail.com");
            stringBuilder.AppendLine("another,user,anotheruser@mail.com");

            var streamReader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(stringBuilder.ToString())));
            return streamReader;
        }
    }

Notice the CreateMockStream method. It mimics a stream like that of one using a csv file by using a StringBuffer! In lines 1 to 5 within the method, I create a string buffer and append 3 lines of text that conforms to the required format using the AppendLine method. Then in line 7, I create a new MemoryStream by using the bytes recovered from the StringBuilder using the Encoding.ASCII.GetBytes method call. The stream reader created is used in the CanGenerateEntryList test method that tests the required method, in line 2. Line 1 creates an instance of ICsvReader.

By having an interface you don’t even have to create the CsvReader class in order to write the unit test. Notice how in line 3 the ReadEntries method is called to get the list entries read by the method and subsequent asserts to verify whether the list returned contains all the required items with the corresponding properties.

Also notice how I didn’t have to create a physical CSV file in order to test this method!

Finally, here is the actual implementation of the method itself. It’s pretty simple and so I don’t think an explanation is warranted!

    public class CsvReader : ICsvReader
    {
        public List<Entry> ReadEntries(StreamReader csvStreamReader)
        {
            var list = new List<Entry>();

            using (csvStreamReader)
            {
                string line;
                while ((line = csvStreamReader.ReadLine()) != null)
                {
                    var splits = line.Split(',');
                    list.Add(new Entry{ FirstName = splits[0], LastName = splits[1], EmailAddress = splits[2] });
                }
            }

            return list;
        }
    }

I know there isn’t anything fancy here, but nevertheless, it’s interesting!

Happy coding! Do post your comments!!!

Share

Performing Activities Before an Application Starts Using the PreApplicationStartMethod Attribute

In this post I am going to discuss a very interesting, yet not so talked about feature of asp.net – pre application start method – PreApplicationStartMethod. I came across this feature while investigating ninject for mvc 3 and I was totally surprised about the existence of the attribute and also that I have never come across this! When you install ninject using nuget, nuget also adds a dependent package called WebActivator. This web activator is responsible for initializing ninject before the Application_Start event. Yes, you heard it right – before the application start event!

When I was looking up more about webactivator, I found this link which does a really good job of discussing about webactivator. But, I felt a few things could have been explained in detail, and so I decided to post this entry!

To begin with, let me discuss a little bit about System.Web.PreApplicationStartMethod. Before I get started here is the PreApplicationStartMethod attribute (without the methods expanded):

[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
public sealed class PreApplicationStartMethodAttribute : Attribute
{
    // Fields
    private readonly string _methodName;
    private readonly Type _type;

    // Methods
    public PreApplicationStartMethodAttribute(Type type, string methodName);

    // Properties
    public string MethodName { get; }
    public Type Type { get; }
}

Did you notice the AllowMultiple property used by the AttributeUsage attribute decorating the PreApplicationStartMethodAttribute class? This indicates that, in your application, you CANNOT use this class more than once. Also note that this class is marked as sealed, implying this class cannot be extended by using this as a base class. WebActivator uses this class to hook itself to be started before the application starts. The PreApplicationStartMethodAttribute constructor has 2 parameters – First parameter is the Type of the class required to be called before an application starts and the second parameter is a string that represents the static method within the type to be called. WebActivator uses this attribute in its AssemblyInfo.cs file as shown below:

[assembly: PreApplicationStartMethod(typeof(WebActivator.PreApplicationStartCode), "Start")]

Here is the complete listing of the AssemblyInfo.cs file. WebActivator uses this class to register itself in its AssemblyInfo.cs file. Thus when the application starts, before Application_Start is called, asp.net calls the WebActivator.PreApplicationStartCode method. Before I describe this method let me describe the WebActivator.PreApplicationStartMethodAttribute attribute. Here is the complete listing of this class and I have given below the important lines of code relevent to this post.

namespace WebActivator {

    [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
    public sealed class PreApplicationStartMethodAttribute : Attribute {

	    // -- Snip --

        public void InvokeMethod() {
	       // -- Snip --
        }
    }
}

Note the AllowMultiple property again for this class specified by the AttributeUsage attribute, which is set to true, implying this class can be used any number of times in an application. Thus, every assembly can mark a class to be started before the application starts, by using the WebActivator.PreApplicationStartMethodAttribute attribute. Given below is an example of how ninject for mvc 3 uses this attribute. Note that just like the System.Web.PreApplicationStartMethod attribute, this attribute also takes 2 parameters of the same type – thus the web activator would call the static method specified by the second parameter in the type specified by the first parameter.

[assembly: WebActivator.PreApplicationStartMethod(typeof(DependencyInjectionMVC3.App_Start.NinjectWebCommon),"Start")]

// -- Snip --

namespace DependencyInjectionMVC3.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    public static class NinjectWebCommon
    {
	    public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        // -- Snip --
    }
}

Now let me get back to the PreApplicationStartCode.Start method. This method simply gets every assembly in the web applications bin directory, if the assembly uses the WebActivator.PreApplicationStartMethod attribute, gets a reference to it and calls the InvokeMethod method to execute the code that the assembly has designated to be run before the application starts. Its given below:

public class PreApplicationStartCode {
	public static void Start() {
	    // Go through all the bin assemblies
	    foreach (var assemblyFile in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll")) {
		var assembly = Assembly.LoadFrom(assemblyFile);

		// Go through all the PreApplicationStartMethodAttribute attributes
		// Note that this is *our* attribute, not the System.Web namesake
		foreach (PreApplicationStartMethodAttribute preStartAttrib in assembly.GetCustomAttributes(
		    typeof(PreApplicationStartMethodAttribute),
		    inherit: false)) {

		    // Invoke the method that the attribute points to
		    preStartAttrib.InvokeMethod();
		}
	    }
	}
}

That’s it! I guess I have accomplished conveying what I wanted to convey!!! Hope you enjoyed this post, do post your comments!

Share

An Introduction to Node.js and Handling Post Requests

Node.js is a platform for building scalable network applications. In a few lines of code, you can create a fully functional server in node. Node uses an event based, non-blocking model. This enables the ability to write servers that serve multiple requests without having to wait for any single request. Before, I get into the actual topic of this post, let me introduce you to a very simple server written in node.js.

var http = require('http');
var url = require('url');

http.createServer(function(request, response){
	var path = url.parse(request.url).pathname;
	console.log('a request was received for: ' + path);
	response.writeHead(200, {'Content-Type': 'text/plain' });
	response.end('Hello, World!');
}).listen(8888);

console.log('Server listening at 8888...\n');

That’s all the code you need for creating a server! An explanation is in order now, before I get in to the core of this post. Lines 1 and 2 attempts to load two “modules” – http and url, which are provided by node.js itself. As the name implies, the http module creates an instance of the http module that could be used to create a http server, using the createServer method. The best thing about javascript is that you can pass around a function just like you could pass a variable. A callback is passed to this method which has to be executed when a request is received.

You can imagine it this way. When a request arrives to your server, your application starts handling them. If there is a callback encountered while preparing the response, the app calls the function, “remembers” that a callback is pending, and goes back to the event loop, waiting for other requests. Once the long running operation is complete, it “informs” your app, during which it takes the data reutrned by the method call and finishes processing the request. Remember, any method call or any activity within this callback method should also use the principle of callbacks, so that the server is not hung processing a synchronous activity.

Let me quickly add a few more words about the lines within the callback. Line 5 uses the “url” module imported to find out the path for which a request was issues. Line 6 just logs a message informing the path for which a request was received. Line 7 calls the writeHead method of the response object to set a status code for the request. In this case, we send a status code of 200, implying that the request was valid and an equally valid response follows. The second parameters is a key-value pair that indicates the content type of the response, in this case as we are just returning a hard-coded message, its “text/plain”. Line 8, ends the response by writing a message. You can also use the write method of response to write more data before calling end. Then, listen method of the server object (returned by createServer) is called by passing in the port number.

Let’s run this code to initialize the server. The last line in the snippet above prints a message saying that the server is listening in 8888 and then waits for the requests.

You can run this code by going in to the folder containing the node.js executable as shown below:

When you enter the address http://127.0.0.1:8888 in the address bar of a browser, it just displays the message “Hello, World!”. Now go back to the console, you will notice the messages logged to the console by the console.log method call. The first line will be an informational message saying that the server is listening. Then you will notice 2 entries that also specifies the path. The first time a request is received, the browser also requests for a favicon.ico that it uses to display in the browser’s title bar or the tab. In case you want to go through a comprehensive article that introduces node.js go to this link. If not, proceed further!

The main intention of this article ( at last :) ) is to introduce a way by which you could process the values posted from a form. I decided to write this article because I had to refer to a number of articles to get a clear picture as to how to do this, when I was getting started with node.js.

To begin with, let me briefly discuss the requirement: The user is presented with a form that asks for the users’ first name and last name. Once the user enters the information and clicks the “Go” button, the next page displays a hello message to the user with the name entered. Let us get started with it!

By default node does not have a module that would help us with inspecting the POSTed form values (afaik). It just provides events using which we can “collect” form data. Once all the form data is received, we can work on that. I will get to that part in jus a bit. Let me introduce you to the script that satisfies our requirement.

var http = require('http');

var postHTML =
  '<html><head><title>Post Example</title></head>' +
  '<body>' +
  '<form method="post">' +
  'Your Fist Name: <input name="first_name"><br>' +
  'Your Last Name: <input name="last_name"><br>' +
  '<input type="submit">' +
  '</form>' +

  '</body></html>';

http.createServer(function (req, res) {
  req.on('end', function () {
    res.writeHead(200);
    res.end(postHTML);
  });
}).listen(8080);

Code snippet above does a part of the task. When you run this file using node and browse to http://127.0.0.1:8080, you see a form with 2 text boxes – one for first name and one for last name. Clicking on the submit button does not do anything at this point. Let us add the ability to parse the posted data and print it to the user. The modification to the above snippet also introduces you to the concept of “modules” in node. You will understand more as I introduce the code.

var http = require('http');
var splitter = require('./splitter.js');

var postHTML =
  '<html><head><title>Post Example</title></head>' +
  '<body>' +
  '<form method="post">' +
  'Your Fist Name: <input name="first_name"><br>' +
  'Your Last Name: <input name="last_name"><br>' +
  '<input type="submit">' +
  '</form>' +
  '</body></html>';

http.createServer(function (req, res) {
  var body = "";
  req.on('data', function (chunk) {
    body += chunk;
  });
  req.on('end', function () {
    console.log('POSTed: ' + body);

	if (body != '')
	{
	    var hash = splitter.formValues(body);

	     console.log("input1 = " + hash["first_name"]);
	     console.log("input2 = " + hash["last_name"]);

	     res.writeHead(200);
	     res.write('Hello ' + hash["first_name"] + ', ' + hash["last_name"] + '!');
	     res.end();
	     return;
	}

    res.writeHead(200);
    res.end(postHTML);
  });
}).listen(8080);

Code snippet above is the updated code where I have added the ability to deal with posted form values. Line 2 includes a “custom” module, that would help us with parsing the posted form data. I will get to that part in the subsequent section. But, just like the http variable, this can be used to call a function that can be used to parse posted form values. Before that, let me discuss about the additions to the code. Lines 16-18 is used to “collect” the posted data. The on method is used to bind to a certain event. In this case, I am binding to the “data” event. A “data” event is raised when some data was posted by a form. Notice line 17, where the data handed to the callback is appended to the variable body. This is because, for a form that posts huge amount of data, this event will be raised number of times. Eventually when all the data is completely transferred, the end event is raised. At this point, the variable body contains the complete data posted. Now using the formValues method provided by the splitter module, I get a hash object that contains the values posted. For example hash["first_name"] gets the first name posted when the form was submitted.

Now, let me discuss a bit about the splitter module. Given below is line 2:

var splitter = require('./splitter.js');

http is a module provided by node. Whereas, splitter is a custom module I added. Thats why we also have to include the path where the module is present relative to the current execution directory. ./ refers to the current directory. Thus, both the application and the module exist in the same directory. Note that the addition of the extension (.js) is optional. Given below is the code for the splitter. Its pretty simple.

exports.formValues = function(data){
	var splits = data.split('&');
	var hash = [];
	console.log(splits.length);
	for (i = 0; i < splits.length; i++)
	{
		var iSplit = splits[i].split('=');
		hash[iSplit[0]] = iSplit[1];
	}
	return hash;
}

Notice the first line, the method formValues is prefixed with the exports keyword. This indicates that this method is a public (exported) method that other modules could use. Without the exports keyword, this method will be local (private) to this module. The method in itself, does not do anything great. It gets the form data passed and splits it by '&'. Then for each of the items, in the format key=value, the item is again split by '=' and then added to a javascript property and then returned to the caller. Now the properties could be accessed by the caller using the key name (e.g. first_name, last_name] - lines 24 to 27.

Now some screen shots for a clearer understanding. The first screen shot just displays the form:

User enters the first and last names, clicks on the submit button. Lines 28 - 31 takes care of this. The splitter module is used to get the form values, then the text is built displaying a message and written to the response after which the response is ended. User is now presented a welcome message as shown below:

For the sake of completeness, here are the messages in the console:

Hope you liked this blog post, which served 2 purposes, a very quick introduction to node and then a method to deal with posted form data! Have fun and do post your questions & comments!

Share

Introducing sBlog.Net – An Open Source Blog Engine

Hello people! It’s been a very long time since I posted anything in this blog, but, here I am! This blog post is regarding something I have been working for a while – it’s a blog engine and I have named it sBlog.Net. The dedicated website is for this project is:


Its experimental and I am always open to questions and suggestions Even though, at this point it supports basic features of a blog, a lot more things are in my mind, so, watch out! . I will let you go to this website and read & experiment more about this.

Given below is a link to the demo of sBlog.Net that is hosted under somee.com. The site is hosted for free, and so you will be seeing a number of ads by somee.com. This demo is just to give you an idea of this blogging engine.


But, before you go let me also introduce you to a group I created to discuss things about sBlog.Net. It is:

Post your questions and comments at the google groups site, lets discuss!

Happy coding ;)

Share

Forcing the browser to get the jscript file every time

This is going to be a very short post, but useful nevertheless. I guess all of whom who have to support multiple browsers for your web application have had the pain of checking it out in various browsers just like me. One issue I face always is that I have to clear the cache every time (or at times) to make sure I am not testing with the older version of the script (if I am testing a lot of javascript changes). For internet explorer/chrome its Ctrl + Shift + Del. This turned out to be tedious and boring for me. So I googled and found this method. If you know this already, I know you are surprised that I didn’t know this already, even I am :) ! Using this method we can force the browser to get the script every time we reload / reopen the page. Assume you have the following line in your master or an individual page.

<script type="text/javascript" src="../Scripts/ReportPage.js"></script>

Just change it to the following by adding a “version” key:

<script type="text/javascript"
        src="../Scripts/ReportPage.js?version=<%= DateTime.Now.Ticks.ToString() %>"></script>

The above change will force the browser to get the script file every time, because of the “version” key in the query string, as it’s value would change every time because of DateTime.Now.Ticks. Just make sure you remove this key once you are done with your testing!

Hope this helps! Happy coding!!!

Share

Entity Framework: Some things to know

This post discusses a few things that will prove useful to you when you are getting started with the entity framework (EF), like I am getting started. Infact, I got started with EF earlier, but didn’t dig in well-enough. I thought that now is a good time to have a deep dive! So given below are few important aspects I had to search for about the entity framework. This post is going to be short and I do not intend to discuss in detail about using the EF, as me myself is a beginner! Now, lets jump in to a few things I learnt (and had to search) apart from the basics.

But so as to ease my job of expressing what I intend to highlight, let me shortly explain about data context(s) in an application that uses the entity framework. Consider the following class:

    public class MvcAppContext : DbContext
    {
        public MvcAppContext()
        {

        }

        public DbSet<Comment> Comments { get; set; }
     }

Listing given above represents a data context that the project could use for interacting with the database. Note that this class inherits from the DbContext class which is part of the entity framework. In the project’s web.config an entry with name MvcAppContext (same as the class name) is required in the <connectionStrings /> section, for the entity framework to know which database contains the tables represented by the DbSet statements. In my sample code, DbSet<Comment> represents the items in a table called “Comments” [Hope you noticed the singular name of Comment that represents a single row in the Comments table as the generic type parameter to the DbSet statement].

Disable create/drop of database in App_Start

One not so great thing [in my opinion] when using the entity framework is that, whenever the applications starts/restarts [for example when web.config is modified and saved, the application restarts], the entity framework drops and recreates the database pointed to by the connection string in the web.config file. This behavior obviously is not something you would expect when running a real-time application. To stop entity framework from doing this, you just have to add the following statement in your Application_Start method in your Global.asax.cs file. Its given below:

protected void Application_Start()
{
    // -- snip --

    Database.SetInitializer<MvcAppContext>(null);
}

Line 5 takes care of the issue of database being dropped and created every time. It’s done by informing the framework that for the MvcAppContext instances, it should not perform any initialization routines [implied by the null], using the Database.SetInitializer<T> method call.

Multiple data contexts without multiple connection strings

When I started the post I mentioned that for a class that implements DbContext, we have to specify a connection string in the <connectionStrings /> section that matches the name of the class. But, in case you need to have multiple classes that inherits the DbContext class, you will have to define one connection string per class, which will make it error prone, as when you have to change the connection string, you may forget to change one of the connection strings. To deal with this, you can have a single connection string in the web.config file and share it across all the classes that implement the DbContext class. Given below is the modified version of my MvcAppContext class:

    public class MvcAppContext : DbContext
    {
        public MvcAppContext()
            : base("AppConnectionString")
        {

        }

        public DbSet<Comment> Comments { get; set; }
    }

Notice line 4. Instead of letting the framework identify the connection string by name from the web.config, I call a different constructor of the DbContext class that takes in a connection string name as a parameter, which, in this case is renamed from MvcAppContext to AppConnectionString. So, becuase of this, the framework no longer expects a connection string with the same name as the class’s name. Using this method you could create multiple data contexts and share the same connection string.

Delete without remove using entry state’s

Let me just detract a bit and discuss about a “faster” way of deleting an item. Assume you want to delete a certain comment from the list of comments identified by the Comments property. This is what you would do, given a unique comment id.

    public class MvcAppContext : DbContext
    {
        // --snip--	

        public void DeleteComment(int id)
        {
            var item = Comments.SingleOrDefault(c => c.CommentID == id);
            if (item != null)
            {
                 Comments.Remove(item);
                 SaveChanges();
            }
        }
    }

In the above snippet, line 3 gets the comment item from the list. Then, in line 6 I remove the item from the list and then in line 7, issuing the SaveChanges() method call deletes the item from the table. There is an alternative way which could save you from a database call to get the item. That is by using the Entry method of DbContext and setting the State of the record to be “deleted”. By this method you save one call to retrieve the item. By setting the state as deleted, the framework marks the record as deleted and once you issue the SaveChanges call, the record is deleted. Here is the modified method:

        public void DeleteNote(int id)
        {
            var note = new Comment { CommentID = id };
            Entry(note).State = EntityState.Deleted;
            SaveChanges();
        }

In line 3, instead of getting the record from Comments list, I just create an instance of Comment by just setting the CommentID. Then in the next line, I set the State of this record to be “deleted”. By doing this, the framework identifies the record, marks it as deleted and when the SaveChanges method call is issued, the record is deleted.

Hope this post helps somebody and if you don’t agree with something in this post or I am wrong, do let me know in the comments section!

Share

C# bits – HandleUnknowAction and JSON Request Behaviors

Hello! Wow, it seems like an eternity since I posted anything! Anyways, I am back! In this post, I am going to discuss a few things that not many encounter often. Nevertheless, the ones discussed here will prove to be very useful. So check it out!

HandleUnknownAction method in mvc 3

The first thing I am going to discuss is about the HandleUnknownAction method available as a virtual method in the Controller base class. As the name implies, this method is available for us to handle unknown actions. This is very similar to method_missing in ruby and I blogged about this earlier here.

To explain this briefly I need to introduce you to the mechanism of how ASP.Net MVC 3 deas with a reqest. When you enter a url, the ASP.Net MVC’s routing module identifies the controller and the action method that would receive the request, creates an instance of that controller and invokes the selected action. If you want more information on this refer to my earlier blog post here. If the specified method is not found, the framework displays the 404 page as shown below:

You could handle this in a number of ways. A few of them are:

  • Have a catch-all route in your Global.asax.cs‘s list of routes
  • Override the HandleUnknownAction method in your controller and take some action

I am just going to discuss the 2nd method as there are a lot of stuff on the internet regarding the 1st method. Before looking into an example, let me introduce you to the signature of this method in the Controller base class.

protected virtual void HandleUnknownAction(string actionName);

If you notice, this method is marked as virtual meaning you can override this method in your controllers. So let me show how I used this method in a project of mine. I normally have a single base controller that other controller’s will inherit. This base controller will have to inherit from the Controller base class. Now, I could add methods that will be shared across various controllers across the project to this base controller. Given below is the code of the BaseController class that implements the HandleUnknownAction method. This could now be shared across any controller that inherits from the BaseController.

public class BaseController : Controller
{
   protected override void HandleUnknownAction(string actionName)
   {
      var strError = string.Format("Unable to find the specified action [{0}]", actionName);

      // Call the logger and log the exception
      Logger.Log(strError);

      // Now throw an exception that could be caught in Application_Error. More on this follows
      throw new ObjectNotFoundException(strError);
   }
}

First, in this method, I log the exception in to a database table to keep track of the happening. Hope you noticed my comment in line 10. You may have custom error attributes in your project (implementing the OnException method of HandleErrorAttribute). But in this case, this wouldn’t be hit and so you may have to use the Application_Error method in the Global.asax.cs file for the web project. [If you have any comments about this particular statement, post in the comments section, because I still have to dig in to the reason of why this happens]. By default, the virtual method in Controller throws an HttpException. So you could also call the base method using the following line after logging the exception.

base.HandleUnknownAction(actionName);

Or, as in the example shown above, I throw an ObjectNotFoundException which I will catch/handle in the Application_Error as shown below:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    if (exception is ObjectNotFoundException)
    {
        Response.Redirect("/Home/Error");
    }
}

As shown above, in the Application_Error method, in line 3 I get the last error and see if it’s an ObjectNotFoundException. If it is, in line 6, I redirect to a custom error page that informs the user more information about the issue in hand. Here is the result after I implement the functionality above:

Now, you will notice that you are no longer redirected to the defaul 404 page as shown above and are redirected to the custom error page.

Let’s now move on to the next discussion:

Using Json based request / responses the correct way

You may have used jQuery’s $.ajax to issue ajax based requests in your website. As far as the data type returned is pure html you won’t have any issues. But if you want to deal with JSON using the GET method, which is a much cleaner way as you just get back the data required from the server rather than an entire chunk of html. There are a few gotchas that you have to remember. By default MVC 3 disallows JSON requests using the GET method due to avoid cross-site scripting attacks. Phil Haack has an excellent post about this here.

But, if the data you are intending to send/receive is not critical, you could still do that by just following a simple procedure. For serious purposes I would always recommend using the POST method for json. Before I get in to the problem with GET JSON requests let me briefly explain the problem. Given below is a page that just has a button. Clicking on the button would call an action method called GetProjectInfo by supplying a projectId. Just for the purposes of this post, the action method simply has a an object with fixed values (except the project id) being passed back as a JSON response for the request.

<h2>Get Json Result</h2>

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnGet').click(function () {
            $.ajax({
                type: 'GET',
                url: "/Page/GetProjectInfo",
                contentType: "application/json; charset=utf-8",
                data: { 'projectId': 1 },
                dataType: 'json',
                success: function (data) {
                    alert(data.ProjectID + ' : ' + data.ProjectName);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(thrownError);
                }
            });
        });
    });
</script>

<input type="button" id="btnGet" value="Get Project Info"/>

If you notice, in line 8, I send a GET request to the url /Page/GetProjectInfo by passing the projectId as a json object. Also note the dataType property in the request is set to JSON. Now let us look in to the GetProjectInfo action method.

[HttpGet]
public JsonResult GetProjectInfo(int projectId)
{
   var project = new Project
   {
        ProjectID = projectId,
        ProjectName = "Partial Collapsible Panel",
        ProjectCreatedBy = "Karthik",
        ProjType = ProjectType.Plugin
    };
    return Json(project);
}

The above method decorated with the HttpGet attribute simply gets the project id passed, creates an instance of a Project class and returns this as the response as a JSON object. But at this point, if you navigate to this url and click on the button, you will just see a message that says "Internal server error", implying the error callback being invoked. This is because by default GET JSON requests are denied. So you will have to change the request behavior to allow GET JSON requests. This is pretty simple. Just change line 11 to the following:

return Json(project, JsonRequestBehavior.AllowGet);

This instructs the framework that JSON GET requests are allowed and so the json content may be served if a GET request is received. Now when you click on the button you will see the intended display (alert) of the project id and the project name as "1 : Partial Collapsible Panel"! Given below is the complete method again for your reference!

[HttpGet]
public JsonResult GetProjectInfo(int projectId)
{
   var project = new Project
   {
        ProjectID = projectId,
        ProjectName = "Partial Collapsible Panel",
        ProjectCreatedBy = "Karthik",
        ProjType = ProjectType.Plugin
    };
    return Json(project, JsonRequestBehavior.AllowGet);
}

There isn't anything path-breaking in this post, but, still I hope you enjoyed this.

Happy coding!

Share

Generating an “Archives” menu in MVC 3

Hello! I am back! In this post, I am going to discuss a method using which you could generate a menu that lists the archives for your website. You would have seen this in number of website / blogs, even this blog for that matter, check out the section labelled “Archives” to your right. The intention of this post is to generate something similar.

The requirements of this archive list are as follows:

  • It goes in the reverse chronological order, begining with current month / year
  • An entry for a month/year can be present only if there are any items for that particular month/year
  • (At this point) lists all the month/year’s for which there is an item

To implement this I am going to use 2 interfaces (IEnumerator and IEnumerable) provided in the System.Collections assembly. Note that this post does not dwelve in to explaining this as MSDN does a really good job :) Here is the link to the MSDN article!

The IEnumerator interface is implemented so as to support simple iteration using the for loop. To facilitate simplicity (and to reduce the amount of code), I have also implemented the IEnumerable interface as it enables us to use the foreach method of looping, thus making the class that supplies the month/year combinations to be a collection.

To begin with, let use create a plain old simple c# object to represent an archive entry. A sample entry that a user would see is January 2012, and the corresponding Archive entry would have the following properties

Year = 2012, Month = 01 and MonthYear = January 2012.

public class Archive
{
   public string Year { get; set; }
   public string Month { get; set; }
   public string MonthYear { get; set; }
}

Then let’s create the class that would represent an item that a website would present to a user. I am calling it a Post. As stated before, the intention is to present a list of month/year, clicking on which would present a user with a list of post’s added during that date/time. So this class should necessarily contain a date/time apart from other fields. Here it is:

public class Post
{
  public string PostName { get; set; }
  public DateTime AddedDateTime { get; set; }
}

Now let’s get to the most interesting part! Let us create the collection class that will implement the functionality we wish to implement. Here is the code listing, some explanation follows the listing.

    public class ArchiveCollection : IEnumerator, IEnumerable
    {
        private readonly List<Post> _srcList;
        protected List<Archive> Archives = new List<Archive>();
        int _current = -1;

        public ArchiveCollection(List<Post> listToBeGrouped)
        {
            _srcList = listToBeGrouped;
            AddArchives();
        }

        public object Current
        {
            get { return Archives[_current]; }
        }

        public bool MoveNext()
        {
            _current++;
            return _current < Archives.Count;
        }

        public void Reset()
        {
            _current = -1;
        }

        public IEnumerator GetEnumerator()
        {
            return Archives.GetEnumerator();
        }

        protected virtual DateTime GetDateTime()
        {
            return DateTime.Now;
        }

        private void AddArchives()
        {
            var dateTime = GetDateTime();
            var currentYear = dateTime.Year;
            var currentMonth = dateTime.Month;
            var dateTimeFormatInfo = new DateTimeFormatInfo();

            var lastEntry = _srcList.OrderByDescending(p => p.AddedDateTime).LastOrDefault();

            if (lastEntry != null)
            {
                var endYear = lastEntry.AddedDateTime.Year;
                var endMonth = lastEntry.AddedDateTime.Month;

                // Probably could simplify using GroupBy !
                while (currentYear >= endYear)
                {
                    if (currentYear == endYear && currentMonth < endMonth)
                        break;

                    if (_srcList.Any(p => p.AddedDateTime.Year == currentYear && p.AddedDateTime.Month == currentMonth))
                    {
                        Archives.Add(new Archive
                        {
                            Year = currentYear.ToString(),
                            Month = currentMonth.ToString("00"),
                            MonthYear = string.Format("{0} {1}", dateTimeFormatInfo.GetMonthName(currentMonth), currentYear)
                        });
                    }

                    if (currentMonth - 1 < 1)
                    {
                        currentMonth = 12;
                        currentYear--;
                    }
                    else
                    {
                        currentMonth--;
                    }
                }
            }
        }
    }

Line 3 declares a readonly list of Post's that the collection would use to generate a list of month/year's. Remember, this list cannot have an entry where there are no posts, and that's why we expect a list of posts to look through. Then in line 4 a new list is created which will hold the archive entries. In the constructor, check out the AddArchives. This is the method that adds all the possible entries in to the list created in line 4. Lets get to this method directly, as other method's are simple, straight-forward and just implements the methods required by the interfaces.

Now, let's get to the most interesting method in this class which is the AddArchives method. In line 46, I first get the earliest entry in the list passed to this class. For example, current month/year is July 2012. If the earliest entry in the list was on 1st January 2011, that entry would be fetched by this line and the end year is thus assumed to be 2011 (line 50) and end month in line 51 will be 1.

Then in the while loop an archive entry is generated for each month/year starting from the current month/year going back to the last month/year in the list. Lines 55 - 56 is used to break the loop if for the end year, the loop crosses the end month.

Now that we have this collection ready, let me show you an example of how this could be used. To do this, I created a controller called the ArchivesController with the following action methods. There is also a static method that returns a list of Post entries that will be used by the collection. As shown in line 5, to use the collection, just instantiate an instance of ArchiveCollection passing the list of posts using the GetPosts method. The index view uses the collection passed as a model to list all the archive entries.

    public class ArchivesController : Controller
    {
        public ActionResult Index()
        {
            var archiveCollection = new ArchiveCollection(GetPosts());
            return View(archiveCollection);
        }

        private  static List<Post> GetPosts()
        {
            var posts = new List<Post>
                                   {
                                       new Post { PostName = "Post 1", AddedDateTime = DateTime.Parse("1/1/2012") },
                                       new Post { PostName = "Post 1", AddedDateTime = DateTime.Parse("12/1/2011") },
                                       new Post { PostName = "Post 1", AddedDateTime = DateTime.Parse("11/1/2011") },
                                       new Post { PostName = "Post 1", AddedDateTime = DateTime.Parse("10/1/2011") },
                                       new Post { PostName = "Post 1", AddedDateTime = DateTime.Parse("9/1/2011") },
                                       new Post { PostName = "Post 1", AddedDateTime = DateTime.Parse("8/1/2011") }
                                   };
            return posts;
        }
   }

Now, displaying the month/year's is not the only intention. We need to provide a link using which users will be able to drill-down and check out the posts for the selected month/year. To do this, lets add a route to the Global.asax.cs file. Here is that route:

routes.MapRoute("Archive", "archives/{year}/{month}",
                new { controller = "Archives", action = "ListByMonthYear" },
                new { year = @"\d{4}", month = @"[0-9]{1,2}" });

In the above snippet, first parameter is the route name, second parameter is the url format for the links generated is "archives/{year}/{month}", third parameter is the controller and action methods to be used for a request that follows this url format. The last parameter just indicates how the year & month parameters should be using a regular expression. "\d{4}" indicates that year should be a 4 digit number and "[0-9]{1,2}" indicates that month should be a 1/2 digit number. Now lets put this route to use in the Index view.

Here is the view listing for Index:

@model ArchiveCollection

@{
    ViewBag.Title = "title";
}

@foreach (Archive archive in Model)
{

@Html.RouteLink(archive.MonthYear, "Archive", new { year = archive.Year, month = archive.Month })

}

Line 7 loops through the model, using the Html.RouteLink helper method to generate a url using the url format specified in the Global.asax.cs file (line 9). The label used is the values in the MonthYear property.

Finally, lets add the ListByMonthYear action method that will take care of returning the posts for the requested month/year combination. When the user clicks on any of the archive links, this action method gets called, passing it the year and month. I leave the implementation to you, as it's out of scope for this post! The action method is given below:

public class ArchivesController : Controller
{
   // -- cut for brevity --

   public ActionResult ListByMonthYear(string year, string month)
   {
       // implementation omitted
       return View();
   }
}

Now, when you launch the application and navigate to /Archives/Index, you will be able to see a list of archive entries, clicking on which would take you to the action method that in turn returns the entries for the selected month/year! Here is a screen shot from a sample run:

This is from a current project of mine and yes, I did write some unit tests, but I am yet to add them to this sample project.Here is the mock class that can be used. The sample project does not contain any unit tests, but feel free to use the following mock to create unit tests! If you recall from the listing of ArchiveCollection class, the GetDateTime method was marked as virtual. This is to assist us in writing mocks for this class. Note that it's not good to just have a public method and override it using the new keywork in the mock. Soon, I will also update the post with some unit tests in the coming days!

    public class MockArchiveCollection : ArchiveCollection
    {
        public MockArchiveCollection(List<Post> posts)
            : base(posts)
        {

        }

        public Archive Single(Archive archive)
        {
            return Archives.SingleOrDefault(a => a.Month == archive.Month && a.Year == archive.Year && a.MonthYear ==
archive.MonthYear);
        }

        protected override DateTime GetDateTime()
        {
            return DateTime.Parse("4/1/2012");
        }
    }

Here is a sample project for your perusal.

If you think that this could be improvised or you have any other comments, post them here! Happy coding!

Share