Thursday, August 24, 2017

Setting up XUnit, Moq, Fluent Assertions, Auto Mapper

We know why do we write Unit Test cases. If you are still not clear you can refer to below link
https://itsmevaibhav007.blogspot.in/2017/01/why-do-we-need-write-unit-test-cases.html where I have briefed about why we need to write unit test cases.

Before we jump into setting up the XUnit, Moq and Fluent Assertions. Let’s first understand what are these in brief

What is XUnit.?
Ans. XUnit is  a Unit test case framework for writing unit test cases against the code that is been written.

Why do we need to choose XUnit. When there are other Unit Test Cases Framework like NUnit, Visual Studio Tools  that are already available in the Market.?
Ans. There are multiple reasons choosing XUnit as Framework. Below are some points.

XUnit is Data Driven Test framework.
Written by the original inventor of NUnit v2
ASP.Net Core framework Unit testing is done by XUnit.

Where can I compare the features of XUnit with Other Frameworks.?
Ans. Here is a Link that will give you clear differences - https://xunit.github.io/docs/comparisons.html

Where can I learn more about XUnit.?
Ans. Here is the link where you can learn more about XUnit- https://github.com/xunit/xunit

What is Moq.?
Ans. Moq is a mocking framework for C#/.NET. It is used in unit testing to isolate your class under test from its dependencies and ensure that the proper methods on the dependent objects are being called.

Why we need to use Moq.?
Ans. Moq framework will help us decouple the dependencies.

For ex say there are multiple Database call that are a part of your code and code intern calls the repository layer. Every time you run a unit test case it would refer to repository which would delay the whole purpose. With Moq we just do that. We Setup the data as if the code is calling the repository and giving the data back.

Where can I learn more about Moq.?
Ans. Here is the link where you can learn more about Moq - https://github.com/moq/moq4

What is Fluent Assertions.?
Ans. With Fluent Assertions, the assertions look beautiful, natural and most importantly, extremely readable.

Why do we need to use Fluent Assertions.?
Ans. By using fluent assertions you could write assert as you say it.

For ex if you want to assert the following the count in the list should be equal to 4.

In Normal case scenario you would write Assert.Equal(employee.count,4);
With Fluent assertion you would write employee.Count.ShouldBeEquivalentTo(4).

Where can I learn more about Fluent Assertions.?
Ans. Here is the link where you can learn more about the Fluent Assertions - http://fluentassertions.com/

What is Auto Mapper.?
Ans. Auto Mapper is a simple little library that will help us to get rid of Old style of mapping one object to another.

Why do we need to use Auto Mapper.?
Ans. If there is situation where you would want to map one object consisting 20 properties with another object consisting 20 more properties the code would look more complicated as you would do old style mapping. One to One. Auto mapper help us get rid of the same.

Where do I learn more about Auto Mapper.?
Ans. Here is the link where you can learn more about the Auto Mapper - https://github.com/AutoMapper/AutoMapper

I have also written how to setup Auto Mapper using reflection you could read more on that in this link - https://itsmevaibhav007.blogspot.in/2016/11/adding-auto-mapper-500-profile.html

Happy Coding :) :) :)

Thursday, January 12, 2017

Why we need to write Unit test cases

Alright so there is been a lot of discussion on writing Unit Test Cases.

First question that a developer asks me is why do we write unit test cases and how does it help us.

My only answer to the question is that It helps you to fail faster than later.

Let me explain you what do I mean by that - So before 3 years I used to have an excel sheet in which I used to put all the conditions and test against those conditions which was very MANUAL in nature.

World was quickly moving forward and I was stuck in the world of manual era.Needed to adopt to moving world and then I started exploring the automotive world that is when I realised the rest of the world writes Unit test cases using frameworks like Ms Test, Nuint

So why do we write Unit test cases - Every developers  job is to ensure that he writes code in a way that it delivers required business value. Essentially the code that a developer writes. Needs to be the best piece of code and a quality one.

So we just refereed to quality keyword above. So what do we mean by that and how do we measure quality.

The answer to this is writing Unit test cases - Tan ta daaa. Wow so do I mean by writing test cases we achieve quality code or build quality product - NO NO NO obviously No. It depends on how you write the code.

You can write bad code and still be able to write unit test cases for the same - Some of my colleagues write Unit test cases without assert and explain me saying that it is at-least covering the code -Management will be happy if there are more unit test cases and code is covered

Alright let come to the point. According to me why do we  write unit test cases.

1.It will help you think like a end user.

2.It will help you have control on the code you write.

3.It will help you have grip on the functionality that you are working on and also helps in delivering the required business functionality.

4.Your thinking capability would grow to another level thus you will get a zeal to write better code.You will refactor the code yourself.

5.Important thing You would understand what SOLID principle mean and how you use them which working in the project.

According to me a piece of code that is non testable is not the best piece of code that is written.

Happy Coding :) :) :)




Tuesday, December 6, 2016

Solving CORS issue for WebAPI and Angular JS In Chrome Browser

I had taken up an new assignment of working with WebAPI and Angular JS 1.5.7. The application used to work only in the Internet Explorer but not in the Chrome browser.

Chrome browser is pretty advanced and hence debugging is easy. In total its easy to work on chrome brower rather than working on any (For Me- Strictly)

You need to understand CORS - What it is and what is the problem. To know more check this website.

https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api


We were hosting the application in IIS. So the WEBApi was hosted on the port 7000 and the Angular JS Code was hosted on the 7709

So what You have to do to solve this issue.

In the Application Start add the below code.



        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            //HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }

        }

And add the CORS plugin that you get in the Chrome app store.


Simple works :D

Wednesday, November 23, 2016

Adding Auto Mapper 5.0.0 Profile Dynamically using Autofac

Introduction.

We would create profile dynamically using reflection and using Autofac we would inject the auto-mapper.

Problem

When we create a lot of profiles. We need to add them in the configuration file as shown below.


Example.

public IMapper ConfigureMapper()
{
   var config = new MapperConfiguration(cfg =>
   {
     cfg.AddProfile<Employee>();
     cfg.AddProfile<Author>();
     cfg.AddProfile<Title>();
                       .
                       .
                       .
                       .
                       .
     cfg.AddProfile<Book>();
                       .
                       .
     //30 more profiles

   });
   return config.CreateMapper();
 }

As the project size grows adding the profiles become tedious and maintainability takes a hit.

Solution 

We would create the profile and them dynamically using reflection code and use Autofac to inject them.

By creating auto-mapper profiles dynamically what do we achieve.

1.Open Closed Principle is not violated.
2.Developers would not add any profiles manually.
3.Code is neatly maintained.

So let’s achieve the same.

Step 1.Create a Common Library in the solution which would be referred by all the other projects in the application.

Step 2.Create a class in Common Library called Auto Mapper Profile which extends a base class “Profile” which is under the auto-mapper dll 

  public class AutoMapperProfile: Profile
  {

  }

3.Now the next step we would create required profiles which extends “AutoMapperProfile” so you would create profiles as given below. 

   public class EmployeeProfile : AutoMapperProfile
    {
       public EmployeeProfile()
       {
           CreateMap<Employee, EmployeeModel>();
       }
    }

Note : If any Profiles that do not extend AutoMapperProfile class then the code would not work.

Step 3.We then need to add the AutoMapperConfiguration class. Where we create a Method that returns IMapper.

public class AutoMapperConfiguration
    {
        public IMapper Configure()
        {
            var profiles =AppDomain.CurrentDomain.GetAssemblies()
              .SelectMany(s => s.GetTypes())
              .Where(a => typeof(AutoMapperProfile).IsAssignableFrom(a));

            // Initialize AutoMapper with each instance of the profiles found.
            var mapperConfiguration = new MapperConfiguration(a =>                                                                  profiles.ForEach(a.AddProfile));

            return mapperConfiguration.CreateMapper();
        }
        
    }


In the above code we have used the reflection to find all the profiles where "AutoMapperProfile" class is extended

If you closely observe in the above code we have used ForEach. We have created an Enumerable extension which create an actionable item for each found profile.

public static class EnumerableExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> enumerable,
                Action<T> action)
        {
            foreach (T item in enumerable) { action(item); }
        }
    }


Step 4: Once we are done with the Creating the Mapper we will return the IMapper to the Autofac object where we create instance for the mapper.

            //Creating an Instance for the Mapper
            builder.RegisterInstance(new AutoMapperConfiguration().Configure()).As<IMapper>();

Step 5: After doing the above steps register the Auto-mapper in the Autofac.

            //Creating an Instance for the Mapper
            builder.RegisterInstance(new AutoMapperConfiguration().Configure()).As<IMapper>();

Step 6:To use the Automapper in the Project just Inject the IMapper in the constructor and it works automatically.
public EmployeeManager(IEmployeeLogic employeelogic, IMapper mapper)
        {
            if (employeelogic== null) throw new ArgumentNullException(nameof(employeelogic));
            _employeelogic = employeelogic;

            if (mapper == null) throw new ArgumentNullException(nameof(mapper));
            _mapper = mapper;
        }

     private async Task<EmployeeModel> GetEmployeeModel(Employee employee)
        {
            var employeeInfoModel = await _exampleCode.GetEmployeeRepo(employee);
            return _mapper.Map<EmployeeModel>(employeeInfoModel );
        }


Just follow the above steps and everything would work seemelesly.

Code is available in the below repository.
https://github.com/BatIronMan007/AutoMapperReflection

Tuesday, November 15, 2016

Creating Dynamic Instances Using Custom Attributes with Constructor Values.

During refactoring of the code. I came across Switch Statement and one of my architect suggested me to use Strategy Pattern to refactor the code.

I did understand the Strategy Pattern and implemented the same. I was a little unhappy with the set of new objects that we were creating in the Context Class of Strategy Pattern.

Every time a  new case is added I had to create a class for the newly added type and add the dictionary value in the Context  class code.

Something struck to my mind and I thought lets use the Reflection Powered by Custom Attributes.

Although Reflection is a powerful tool. We should use it in places where it is really required. (Its like With great power comes great responsibility 😈)

Lets have a quick look at the problem in hand.

   public enum ePassengerTitle
  {
            Mr,
            Mrs,
            Doctor,
   }


    ePassengerTitle title = ePassengerTitle.Doctor;
    switch (title)
    {
                case ePassengerTitle.Mr:
                    // do something
                    break;
                case ePassengerTitle.Mrs:
                    // do something
                    break;
                case ePassengerTitle.Doctor:
                    // do something
                    break;
                default:
                    break;
    }


In the above code there are 3 case conditions and if the cases keep growing the maintainability of the code takes a hit.

Solution to the problem

1.There are multiple ways this problem could be solved. I am going to show how we use custom attributes powered with reflections.

We create different classes for all the "Case" Statements- A little Smell of Strategy Pattern.

An Interface defined.

 public interface IPassengerTitleStrategy
  {
        void DoSomthing(string title);
  }

  [AutoResolve("Mr")]
    public class MrPassengerTitleStrategy : IPassengerTitleStrategy
    {
        public void DoSomthing(string title)
        {
            Console.WriteLine("The Title is" + title);
        }
    }


    [AutoResolve("Mrs")]
    public class MrsPassengerTitleStrategy : IPassengerTitleStrategy
    {
        public void DoSomthing(string title)
        {
            Console.WriteLine("The Title is" + title);
        }
    }

    [AutoResolve("Doctor")]
    public class DoctorPassengerTitleStrategy : IPassengerTitleStrategy
    {
        public void DoSomthing(string title)
        {
            Console.WriteLine("The Title is" + title);
        }
    }

If you closely Observe on each classes we have a Custom Attribute. That Attribute is the Key to the Solution.

Lets Define it now.

 public class AutoResolveAttribute : Attribute
 {
        public AutoResolveAttribute(string name)
        {
            
        }
 }

It has a constructor. Its an important aspect.

Next we need to write Reflection logic which will find you all the classes where the attribute is decorated.

 public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : System.Attribute
  {
            return from a in AppDomain.CurrentDomain.GetAssemblies()
                   from t in a.GetTypes()
                   where t.IsDefined(typeof(TAttribute), inherit)
                   select t;
   }

So what does the above method do. It searches through all the assemblies in the AppDomain and finds those classes that are decorated with AutoResolve attribute. It is a generic method so you can pass any Attribute of your choice.

Once we get all the classes we need to loop through those classes to find out which class has been decorated with the string value that we are looking for.

   private static string GetAttributeName(string value)
        {
            var getAttribute = GetTypesWith<AutoResolveAttribute>(true);
            foreach (var iAttributeValue in getAttribute)
            {
                var attributeValue = iAttributeValue.CustomAttributes.Select(x =>       x.ConstructorArguments[0].Value).First();
                if (attributeValue.ToString().Contains(value))
                    return iAttributeValue.FullName;
            }
            return string.Empty;
        }


So the above method takes the string as parameter and return the FullName of the assembly.

Once we get the full name of the assembly we now need to get an instance. So we use below code for creating an instance.

   public static object GetInstance(string strFullyQualifiedName)
        {
            Type type = Type.GetType(strFullyQualifiedName);
            if (type != null)
                return Activator.CreateInstance(type);
            return null;
        }

So finally what do we do now.

We use the code. That is so obvious.

  ePassengerTitle title = ePassengerTitle.Doctor;

 var typeCode = GetAttributeName(title.ToString());
 var getInstance = GetInstance(typeCode) as IPassengerTitleStrategy;
 getInstance?.DoSomthing(title.ToString());

 So we get an instance of the specific switch value and you use it ☺☺

Finally what did achieve by doing so.

Pros

1. Eradicated the need to write switch case.
2. Wrote more cleaner more maintainable and scalable code.
3. Code that adheres to  SOLID principles

Con

1.Reflection Code - A powerful tool need to use with care.

Happy Coding 😈😈😈





Log History in Visual Studio Code

It was challenging to find out the log history of what was checked in and who checked in File.

Below is the Extension and Command which we could use for Checking the history and files.

Steps 1. Install the Git History Extension from the market place.

 

Steps 2. Use Ctrl + P and type History and select the 3rd item.



And then you see the History as Shown below.


This gives developers a clear view of the log history.

Happy Coding 😈😈😈