Fun With Generics 1: Equality Comparers

Hello People!

I am back with an interesting post, but this is going to be short. I was bored and was thinking up something and it occurred to me that I could just start playing around with generics :) So I thought I may post a series of entries regarding stuff I get to do. In this first post I am going to show how an equality comparer could be used to filter out distinct elements in a List<T> with duplicates. This post is going to have very little explanations and more of code, we love code right? ;)

To begin with, let me consider a simple Employee class as shown below

public class Employee
{
      public string EmployeeId { get; set; }
      public string EmployeeName { get; set; }
}

And let us consider the following program that lists the entries of a List<Employee> after doing a Distinct().

    // Listing 2
    public class FunWithGenerics1
    {
        public static void Main(string[] args)
        {
            var list = GetEmployees();
            var list2 = list.Distinct().ToList();
            list2.ForEach(l => Console.WriteLine(l.EmployeeId + " : " + l.EmployeeName));
        }

        private static IEnumerable<Employee> GetEmployees()
        {
            return new List<Employee>
                       {
                           new Employee{ EmployeeId = "1", EmployeeName = "name 1"},
                           new Employee{EmployeeId = "2", EmployeeName = "name 2"},
                           new Employee{ EmployeeId = "1", EmployeeName = "name 1"}
                       };
        }
    }

Could you guess the output for this program? It would be:

1 : name 1
2 : name 2
1 : name 1

Not what we expected right? The list still has duplicates! This is because Distinct() uses the default equality comparer to filter and this comparer identifies duplicates based on the object addresses and in that way they are different! Consider the following code segment, this explains the behavior of a default comparer.

   public static void Main(string[] args)
   {
      var e1 = new Employee { EmployeeId = "1", EmployeeName = "test 1" };
      var e2 = new Employee { EmployeeId = "2", EmployeeName = "test 2" };

      // Same object is added twice!
      var list5 = new List<Employee> { e1, e2, e1 }; 

      // This displays the duplicate entry!
      list5.ForEach(l => Console.WriteLine(l.EmployeeId + " : " + l.EmployeeName));

      Console.WriteLine();
      // This won't display the duplicate, since .Distinct() will remove the duplicate e1 instance
      list5.Distinct().ToList().ForEach(l => Console.WriteLine(l.EmployeeId + " : " + l.EmployeeName)); 

      // -- Snip --
   }

The following is the output when the above snippet is ran:

1 : test 1
2 : test 2
1 : test 1

1 : test 1
2 : test 2

In order to filter a list by a property rather than an “address”, we have to create a custom equality comparer by implementing the IEqualityComparer<T>. Given below is a type specific implementation of the same:

    public class EmployeeEqualityComparer : IEqualityComparer<Employee>
    {
        public bool Equals(Employee x, Employee y)
        {
            return x.EmployeeId == y.EmployeeId;
        }

        public int GetHashCode(Employee obj)
        {
            return obj.EmployeeId.GetHashCode();
        }
    }

When using IEqualityComparer<T>, 2 methods have to implemented. The first method is the Equals method, that takes in 2 instances of Employee objects and returns the equality by comparing 2 properties, in this case the employee id. Now if you rewrite the code listing 2 as given below, you will get the desired results with duplicates filtered out!

        public static void Main(string[] args)
        {
            var list = GetEmployees();
            var list2 = list.Distinct(new EmployeeEqualityComparer()).ToList();
            list2.ForEach(l => Console.WriteLine(l.EmployeeId + " : " + l.EmployeeName));

	    // -- Snip --
        }

Here is the output if this snippet is ran:

1 : test 1
2 : test 2

But here comes the fun part. I don’t want to write 100 comparers, right? So here is “generic” version of the comparer. To implement the generic comparer without using reflection and strings for the property to compared, I declare an interface as shown below:

    public interface IComparable
    {
        string PrimaryId { get; set; }
    }

Now, I can create a generic comparer as shown below:

    public class GenericEqualityComparer<T> : IEqualityComparer<T>
        where T : IComparable
    {
        public bool Equals(T x, T y)
        {
            return x.PrimaryId == y.PrimaryId;
        }

        public int GetHashCode(T obj)
        {
            return obj.PrimaryId.GetHashCode();
        }
    }

Now, I have to change my Employee class to implement IComparable:

    public class Employee : IComparable
    {
        public string EmployeeId { get; set; }
        public string EmployeeName { get; set; }

        // Or you could just remove EmployeeId and just have PrimaryId, your choice !
        public string PrimaryId
        {
            get { return EmployeeId; }
            set { EmployeeId = value; }
        }
    }

Now, I can use the generic comparer and can do the same for any other class without having to create a new comparer every time!

        public static void Main(string[] args)
        {
            var list3 = GetEmployees();
            var list4 = list3.Distinct(new GenericEqualityComparer<Employee>()).ToList();
            list4.ForEach(l => Console.WriteLine(l.EmployeeId + " : " + l.EmployeeName));

            // -- Snip --
       }

That’s it for this post! Hope you had fun and here is the complete sample program for your perusal! Happy coding!!!

Share

Custom ConfigSection: An Alternarnative to appSettings

Hello people!

I am back with yet another interesting post about something very interesting in ASP.Net – custon configuration sections. Those of you who are familiar with ASP.Net web development will be aware various sections in web.config such as <appSettings /> and <connectionStrings />. These “sections” are supported ASP.Net itself and thus we are able to use these sections to define custom key/value based settings and connection string for our application!

But, what’s the fun in using stuff only provided to us by default? None, isn’t it? Custom configuration sections are there to provide some fun :) I was experimenting a few things for sBlog.Net and found custom configuration sections good for maintaining a few settings related to the blog, that rarely change, in the web.config, instead of having them in the database. While thinking about it, I thought why not write a post about them and so here I am with the new post!

So, let me get to the point of this post after that short introduction. I am going to show how I created a new “section” called <sblognet /> that could store some of a blog’s settings that rarely change. Here is the new section I have added to my web.config:

  <sblognet smtpAddress="mail.mysite.net"
            smtpPassword="password123"
            emailErrors="true"
            adminEmail="administrator@mysite.net"
            blogTheme="PlainClean">
    <logging enabled="true" />
  </sblognet>

With the help of custom configuration sections, we can create a class that strongly types every attribute or element within the <sblognet /> element! To do this, the first step is to add a new <section /> element within the <configSections /> element in your web.config as shown below:

<configuration>
  <configSections>
    <!-- snip -->
    <section name="sblognet" type="ConfigSectionsSample.Configuration.SblogNetConfiguration, ConfigSectionsSample" />
  </configSections>

  <!-- snip -->
</configuration>

In the above listing, the name attribute specifies the name of our section, which is sblognet. Then the type attribute specifies the fully-qualified namespace of the type that would represent a strongly typed representation of our custom section followed by the assembly that would contain this type in a comma-seperated format. Now that the “wiring” is done, let me show you the class that represents the custom type itself!

    public class SblogNetConfiguration : ConfigurationSection
    {
        [ConfigurationProperty("smtpAddress", DefaultValue = "")]
        public string SmtpAddress
        {
            get { return (string) this["smtpAddress"]; }
            set { this["smtpAddress"] = value; }
        }

        [ConfigurationProperty("smtpPassword", DefaultValue = "")]
        public string SmtpPassword
        {
            get { return (string)this["smtpPassword"]; }
            set { this["smtpPassword"] = value; }
        }

        [ConfigurationProperty("emailErrors", DefaultValue = false)]
        public bool EmailErrors
        {
            get { return (bool)this["emailErrors"]; }
            set { this["emailErrors"] = value; }
        }

        [ConfigurationProperty("blogTheme", DefaultValue = "PerfectBlemish")]
        public string BlogTheme
        {
            get { return (string)this["blogTheme"]; }
            set { this["blogTheme"] = value; }
        }

        [ConfigurationProperty("adminEmail", DefaultValue = "")]
        public string AdminEmail
        {
            get { return (string)this["adminEmail"]; }
            set { this["adminEmail"] = value; }
        }

        // -- snip --
    }

If you observe the listing above for SblogNetConfiguration class, you can immediately notice what’s going on! In listing 1, you noticed that the <sblognet /> element has a number of attributes with the corresponding values. The first attribute/value pair is smtpAddress with the value set to mail.mysite.net. This attribute is represented by the SmtpAddress property in this class, as shown below:

   [ConfigurationProperty("smtpAddress", DefaultValue = "")]
   public string SmtpAddress
   {
       get { return (string) this["smtpAddress"]; }
       set { this["smtpAddress"] = value; }
    }

Note that the property is decorated with the ConfigurationProperty annotation. This implies that this property maps to an attribute name "smtpAddress" in the section named <sblognet />. The get/set methods are pretty straight-forward by which the value in web.config is returned/set. The ConfigurationProperty annotation also has the DefaultValue property that can be used to set a default value, in case this attribute is not present in the <sblognet /> element, in this case I have set it to return an empty string.

Following this property there are other properties that represent other attributes such as smtpPassword, emailErrors, adminEmail, blogTheme and so on.

Remember, every attribute/ element within the custom section should have a corresponding property in your class, if not you will see errors on startup! Yes, I have not covered about “elements” within the custom section, that’s coming up next ;)


Now, obviously you noticed that the class does not contain any definition for the <logging /> element that is contained within the <sblognet /> element. That’s because complex elements like these have to be represented by another class themselves! Given below is the listing the highlights the property that maps to this element alone:

    public class SblogNetConfiguration : ConfigurationSection
    {
        // -- snip --

        [ConfigurationProperty("logging")]
        public LoggingElement Logging
        {
            get { return (LoggingElement) this["logging"]; }
            set { this["logging"] = value; }
        }
    }

Just like the other properties in the class, I have used ConfigurationProperty data annotation, but without the DefaultValue property, implying if not specified we will get a null. Notice the return type of this property – LoggingElement. This is another class that will represent the logging element within our custom section. The listing for this class is given below:

    public class LoggingElement : ConfigurationElement
    {
        [ConfigurationProperty("enabled", DefaultValue = false)]
        public bool Enabled
        {
            get { return (bool) this["enabled"]; }
            set { this["enabled"] = value; }
        }
    }

Note that this class inherits from the ConfigurationElement unlike the previous class, which inherited from the ConfigurationSection class. As the name implies, this class act as a representation of an element within a custom section. At this point, this element contains a single property called Enabled which is represented as shown above and is similar to other properties within the SblogNetConfiguration class! That’s it! You now have a created a custom section just for your application!!!

Let’s see how to put this in to use. Given below is a section from the HomeController class that utilzes this custom section!

    public class HomeController : Controller
    {
        private static readonly SblogNetConfiguration Configuration =
            ConfigurationManager.GetSection("sblognet") as SblogNetConfiguration;

        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            ViewData["data"] = Configuration.BlogTheme;
            return View();
        }
    }

The above snippet deserves a very short explanation, even though it’s pretty straight forward. In line 3, I have used ConfigurationMananger.GetSection method provided by ASP.Net to get a reference to the section named “sblognet”. ASP.Net does all the heavy-weight-lifting for us and so we just have to cast it to SblogNetConfiguration. It’s now ready for use, which is proven by line 10 where the BlogTheme property is passed on to the view using ViewData. I am not going to present screenshots or the part where I display it and I am just going to delegate those things to you :)

Hope this post interested you a bit and for the sake of sanity, here is a link download a sample application that implements things explained in this post!

Happy coding!

Share

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