Friday, December 26, 2014

How to build dynamic lambda expression

I recently came across a requirement where I had to filter entity objects. Consider the following scenario:

I have a class called - Product.

public class Product
{
    public string Name { get; set; }
    public string Code { get; set; }
    public string Type { get; set; }
    public bool IsTaxable { get; set; }

    public Product(string name, string code, bool isTaxable)
    {
        this.Name = name;
        this.Code = code;
        this.IsTaxable = isTaxable;
    }

}

Let’s first create list of products and populate it.

List<Product> products = new List<Product>();
products.Add(new Product("ABC", "a", true));
products.Add(new Product("PQR", "p", false));
products.Add(new Product("XYZ", "x", true));

If I want to filter Products which are taxable, I can just get them by using the following Lambda expression statement:
List<Product> filteredList = EntityFilter.FilterRecords(prods, "IsTaxable", true).ToList();


Very easy, isn’t it?

The above requirement is pretty much straightforward. Let’s go beyond it. Consider, you’re making a search webpart and you need to allow user to filter products based on any attribute. They should be able to filter by Name or Code or any other attribute. In this scenario, you don’t know on which attribute the user is going to filter the records.

So will you write the code as follows?

if (attributeName == "Name")
    filteredProducts = products.FindAll(p => p.Name == attributeValue);
else if (attributeName == "Code")
    filteredProducts = products.FindAll(p => p.Code == attributeValue);
else if (attributeName == "IsTaxable")
    filteredProducts = products.FindAll(p => p.IsTaxable == Convert.ToBoolean(attributeValue));

Don’t do this!!  You’ll end up making a mess of your existing code.

Then how shall we proceed? Well, this is where the blog starts:

Let’s create a class, called “EntityFilter”.

public class EntityFilter
{
    public static IQueryable<T> FilterRecords<T>(IQueryable<T> source, string propertyName, object value)
    {
        ParameterExpression parameter = Expression.Parameter(typeof(T));
        Expression predicate = Expression.Constant(true);

        Expression expProperty = Expression.PropertyOrField(parameter, propertyName);
        Expression expFilter = Expression.Equal(expProperty, Expression.Constant(value));
        var lambda = Expression.Lambda<Func<T, bool>>(expFilter, parameter);
        return source.Where(lambda);
    }
}


That’s all. You’re done. 
Now just fire a following statement to filter records:

filteredProducts = EntityFilter.FilterRecords(products.AsQueryable(), "Name", "ABC").ToList();

OR

filteredProducts = EntityFilter.FilterRecords(products.AsQueryable(), "Code", "x").ToList();

OR

filteredProducts = EntityFilter.FilterRecords(products.AsQueryable(), "IsTaxable", true).ToList();

  
Looks amazing, isn't it?

Let's go ahead and dissect each statement one at a time.

You first start off with a parameter expression of type “T”. Here, “T” can be any type or class:
ParameterExpression parameter = Expression.Parameter(typeof(T));

The next line is to define, predicate:
Expression predicate = Expression.Constant(true);

The next step is to build the body of lambda expressions which happens to be property expression and filter:
Expression expProperty = Expression.PropertyOrField(parameter, propertyName);
Expression expFilter = Expression.Equal(expProperty, Expression.Constant(value));


Now, we need to build the lambda expression which combines the body with the parameter as follows:
var lambda = Expression.Lambda<Func<T, bool>>(expFilter, parameter);


The final step is to filter the source with the dynamic lambda expression:
return source.Where(lambda);

Isn’t this completely dynamic? You can filter any entity with any attribute. Why not have this utility class in every solution you build!

There are always different ways to write code but there is only one way to write awesome code!!

Tuesday, December 10, 2013

The Great Magic Trick of Software Consulting

Every great magic trick of software consulting consists of three parts or acts.

The first part is called “The Pledge”.


The magician (a software consultant) shows you something that is achievable easily with a presentation and a project plan. He shows you he understood your requirements and he is the best guy to implement it in best possible way. Perhaps he asks you to inspect it to see if it is indeed practical to execute within given timeline. But of course… it probably isn't.

The second act is called “The Turn”.



The magician takes the ordinary something and makes it do something extraordinary.  The magician, study and understand your requirements and extract your needs out of it. He probably understand your system better than you. Now you’re realizing that you’re being dependent on him, you look for alternatives but you won’t find it, because of course you’re not really looking. You don’t really want to know. You want to be with what you have. But you wouldn’t clap yet. Because creating dependency isn't enough; you have to execute the plan and make the deliverable possible.


That’s why every magic trick has a third act, the hardest part, the part we call “The Prestige”.


Thursday, June 6, 2013

IoC (Inversion of Control) in SharePoint Projects

According to Wikipedia “Inversion of Control (IoC) is a programming technique, in which object coupling is bound at run time by an assembler object and is typically not known at compile time.
It is basically, abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming.
Inversion of control is sometimes facetiously referred as the "Hollywood Principle: Don't call us, we'll call you"

One of the ways to achieve IoC is Dependency Injection.
Dependency injection is a software design pattern that allows removing hard-coded dependencies and making it possible to change them, whether at run-time or compile-time. It injects the depended-on element (object or value etc) to the destination automatically by knowing the requirement of the destination.
In simple terms, Dependency injection means giving an object its instance variables.

Two most common ways to achieve Dependency Injection are:
  1. Constructor Injection, in which the dependencies are provided through the constructor.
  2. Setter Injection (Property Injection), in which the dependencies are set onto public properties exposed by the object in need.


In Dependency Injection each component must declare a list of dependencies required to perform its task. At runtime, an IoC Container performs binding between these components.
Some other benefits of Inversion of control are as follows:
  • There is a decoupling of the execution of a certain task from implementation
  • Every module can focus on what it is designed for
  • Modules make no assumptions about what other systems do but rely on their contracts
  • Replacing modules has no side effect on other modules


Well, Inversion of Control is all about getting freedom, more flexibility, and less dependency.
So now, we have understood how good it is to use IoC while building enterprise level applications. Now being SharePoint developer, I was wondering how I use it in SharePoint Projects. Let's explore!!

Here, I have used StructureMap as IoC container to inject my dependency to SharePoint.

Before we begin, we need to know where we can inject objects. In an MVC or WebForms app, I’d just add code to the appropriate place in Global.asax.cs, but in the territory of SharePoint, it is different case. We have to do some dark magic and that’s where HttpModule comes in picture.
So the first step is, add class called “ContainerBootstrapper” and add static method in it called, “Bootstrap()” as follow:


public class ContainerBootstrapper
{
    public static void Bootstrap()
    {
        ObjectFactory.Initialize(x =>
        {
            x.For<IMyRepository>().Use<MyRepository>()
                .Ctor<string>("cArg").Is("Constructor Argument Value");
            x.For<IMyService>().Use<MyService>();
        });
    }
}


Now, it’s time to add HttpModule to your project.
Open HttpModule and in Init() Method, just call your function to initialize container.

public void Init(HttpApplication context)
{
    InitializeContainer();
}


The InitializeContainer() function goes as follows:

private void InitializeContainer()
{
    ContainerBootstrapper.Bootstrap();

}

Well, HttpModule can be called multiple times during application lifetime (a bad thing), so we need to protect our container from being re-initialized. So let’s add a condition with static variable “_HasAlreadyInitialized” and set it to true once we initialize our dependencies. We also need to lock the method so other processes can’t access at the time of initialization. After all these consideration, our InitializeContainer () function will go as follows:

private void InitializeContainer()
{
    if (!_HasAlreadyInitialized)
    {
        lock (_InitProcess)
        {
            ContainerBootstrapper.Bootstrap();
            _HasAlreadyInitialized = true;
        }
    }

}

The complete class code will be as follows:

public class BootstrapInitializer : IHttpModule
{
    private static bool _HasAlreadyInitialized = false;
    private readonly static object _InitProcess = new object();

    /// <summary>
    /// You will need to configure this module in the web.config file
    /// of your web and register it with IIS before being able to use it.
    /// For more information see the following link:
    /// http://go.microsoft.com/?linkid=8101007

    /// </summary>
    #region IHttpModule Members

    public void Dispose()
    {
        //clean-up code here.
    }

    public void Init(HttpApplication context)
    {
        InitializeContainer();
    }

    #endregion

    #region Custom Methods

    private void InitializeContainer()
    {
        if (!_HasAlreadyInitialized)
        {
            lock (_InitProcess)
            {
                ContainerBootstrapper.Bootstrap();
                _HasAlreadyInitialized = true;
            }
        }
    }

    #endregion

}

That’s all!!
I hope you guys have enjoyed the new flavor of SharePoint Soup!!

Sunday, November 14, 2010

Wisdom of Work

I was going to write about technical topic. I was half way through and suddenly something touched my mind and I hold backspace till I get complete white background again. The topic I want to discuss here is about business acumen. More specifically work we are doing every day. The 8 hours which we are spending to make our next 16 hours bright and pleasurable. Let’s think about what you did yesterday. What has exactly it added to one’s life for whom you worked?

It’s very important to know what we are going to give to the end user from our daily struggling 8 hours or may vary positively typically in IT field. You know, engineers always like to come up with formula for any topic. And as being one of them, let me derive a formula on this:

Successful Work = Value added to End User / Effort spent

It’s very important to understand the formulae. The success of any work is proportional to the value it has added to the end user.  Some people usually do their work just for shake of completing it. Very few realize why they are spending their valuable time for output that no one wants. Many times, it’s attitude that changes human mind. And this attitude depends on many factors. Let’s take an example. You have been assigned the work and you know from the beginning that it won’t be finished within the time assigned. Actually that makes our mind to complete the stuff anyhow. At that time, we don’t care what we are doing. Our aim is just to complete what has been asked for. My point of taking this example is to prove that it’s not just the one who is doing the work, is responsible for bad work but there is hierarchy. The supervisor is also responsible who has assigned the work which is not at all feasible in the timeline. The manager is also equally responsible who has promised to the client. And same thing applies to client also, in turn left him with what he never wanted. Actually this is everyone’s responsibility and should be taken care from top to bottom level.

Think through your heart once!!!