Sunday, December 20, 2015

Action injection in MVC6

Dependency injection is very flexible in MVC6 architecture. Now, it’s possible to inject dependency only in action level.

Earlier, if there was need to inject dependency then there were three possible ways

1) Constructor injection
2) Function injection
3) Property injection

Now, the common part of these technique is, it will resolve dependency in class level. So, if there is need to resolve dependency only in one function those techniques are not best fit.
In MVC6 Microsoft has introduce injection in function level. Just we need to use [FromService] 

attribute in parameter and it will resolve dependency from IoC container.

Let’s implement small example to understand the same. Here is implementation of Message service.

    public interface IMessage
    {
        string Message { get; set; }
    }

    public class Message : IMessage
    {
        string _message;

        string IMessage.Message
        {
            get
            {
                _message = "System message";
                return _message;
            }
            set
            {
                _message = value;
            }
        }
    }

Message class has implemented IMessage interface. Now, we have to register those in IoC container of MVC6. I am using default IoC container in this example.

public void ConfigureServices(IServiceCollection services)
   {
                services.AddTransient<IMessage, Message>();
   }


All done, now we are allowed to resolve dependency from action using “FromService” attribute.

public IActionResult Index([FromServices] IMessage Today)
   {
            string message = Today.Message;
            return View();

   }


Friday, December 18, 2015

Another story of a great mother.


Few days ago I have been in my hometown, went as routine visit from my workplace. Time is really fast when you spent it with your dearest person. I could not even imagine how 10 days passed just like 10 minutes.

Anyway, one evening my mom told that she has one marriage invitation from our neighbor village on this evening and started preparation to attend.

When she came back from marriage ceremony I was watching TV by sitting on sofa. I casually asked, whose marriage it was? Mom replied, it is the marriage of her friend’s house (I personally don’t know her but hear her name many times in time of conversation with mother). Mon started to tell how she became mate with her and why she respect and value to my mom!

It’s been very early when her husband passed away by leaving few kids along with her. She has no Idea to manage her and sons life. She took maid’s job and started to earn their living which was not really sufficient. Just to secure food for same day, she accepted hard work in a brick factory where physically strong people normally deny to work due to heavy labor.

In spite of being illiterate, she has great desire that her son will get good education. It seems that education is nothing but there day dream.

She decided, “I don’t have enough resource to educate all of my children but can educate one among them”. Now, the question is, to whom to choose?  She found that, the youngest one has real interest in education. She send him in a nearest Government school.

Situation became worst, now a large part of earning started to go behind his education (though government school is free, but there is expenditure of private tuition and education materials). To collect additional money she started begging door to door.

 Once she came to our house too. My mother asked, why she is begging (casually! just to know the reason). She replied, she wish “AT LEAST ONE OF HER SON WILL BE EDUCATED” and for sake of it, she started begging.

My mother got surprised (me too! when, I hear from my mother). Mother gave few books (English grammar etc., as my father is teacher of English subject and used to get book in free as specimen copy) copy/note of mine and get her promise that “In any situation , she will not stop her son’s education”.

She said Didi ! (Elder sister in Bengali, she used to call my mom like this) I faced that day, when alms is not enough for all family member, I distributed rice of my part among my children and drunk water at night. If I can handle this situation, I can handle any situation.

What is great sacrifice! Yes, she kept her promise, she never stopped her son’s education. Today her son became teacher of a government school and and and…? Yes, my mother just return by attending his marriage.


I asked, how the bride looks like. Replied: very nice... hahhah... 

Inject service to View in MVC6


This is new feature of MVC6, you can inject service to view directly. It will help to push/pull data from UI to business logic directly by skipping controller layer.

Here, we will implement small example to demonstrate the concept.
      
     1)      At first we will create one simple service like this.

namespace MVC6Web.Services
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class DataService
    {
        Person _person;
        public DataService()
        {
            _person = new Person
            Id = 1, Name = "Sourav Kayal" };
        }

        public Person GetPerson()
        {
            return _person;
        }
    }
}

DataService is simple C# class containing GetPerson() function which will return an object of Person class.
      
      2)      Make the service visible to MVC environment.
 In this point we will attach DataService to environment of current project. So, modify the ConfigureService function like below.

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MVC6Web.Services.DataService>();
}
      
      3)      Inject DataService to view.
This is the final step, here we will inject the service to view. Here is the procedure to get it done.

@inject MVC6Web.Services.DataService DataService   

<ul>
    <li>Item : @DataService.GetPerson().Name</li>
</ul>

The format to inject to Service is like this.

@inject <ServicePath> <Identifier>

Once we inject service, we are allowed to call GetPerson() function from view itself, though the function is not part of controller.


 




Saturday, November 28, 2015

Struggling with Node package installation behind proxy?

Recently Microsoft has released kit for node.js application development on top of Visual Studio. I have been exploring this from last few days. I was getting proxy related error which is something like this

NodeJS ETIMEOUT ERROR

In time of package installation of node. It was saying that, as you are behind proxy you cannot install package without setting proper proxy.

Anyway, I spent a single day with every possible solution from stack overflow and other site too by configuring node configuration file as per there suggestion but no luck.

At last, I found one answer in stack overflow( Which was not marked as answer though ! ) which suggesting to delete the proxy setting and the command is here.

    npm config delete proxy

Ohhhhhhhhhhhhh…… !!!!!! That works’ for me. After a long search I could able to solve the issue.
 

Saturday, November 21, 2015

Populate real time data for testing using GenFu API C#

We need test data very often for sake of testing in Test or UAT server. There are Few API’s available which can generate random data. Fixture and AutoFixture is such kind of library but the limitation is, It will generates random string.

The beauty of GenFu is, it will provide you real time value. Here is one example.

public class Contact
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAdress { get; set; }
        public string PhoneNumber { get; set; }

        public override string ToString()
        {
            return $"{Id}: {FirstName}
              {LastName}
              {EmailAdress} - {PhoneNumber}";
        }
    }

The class definition is very simple and self-explanatory. Now, we will call API function to Generate random objects for the class.

        public static void Main(String[] args)
        {
            //Generate 25 random 
            //Information by default
            var people = A.ListOf<Contact>();
            foreach (var person in people)
            {
              Console.
              WriteLine(person.ToString());
            }

            Console.ReadLine();
        }

GenFu to load real time data

Please read more about GenFu in below link.

 

Avoid multiple If-else Or Switch in decision making flow.

Sometime multiple if-else or switch can increase code smell. It’s always Good practice to avoid those to decrease confusion and increase code readability.

In this article we will implement some pattern which can replace simple if-else or switch case. Let’s take one small example to implement same.

    public interface IMessage
    {
        void Send();
    }

    public class SMS : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("SMS Sending..");
        }
    }
    public class Mail : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("Mail Sending..");
        }
    }

We have implement IMessage in SMS and Mail classes. Now, here is an Enum to choose the Message type.

enum MessageType { Sms, Mail };

Here is the actual logic to call appropriate class.

      public static void Main(String[] args)
        {
            Dictionary<MessageType, IMessage> ObjectFactory =
new Dictionary<MessageType, IMessage>
            {
                { MessageType.Sms, new SMS() },
                { MessageType.Mail, new Mail() }
            };

            System.Console.WriteLine("0: For SMS, 1: Mail");

            int ReadType = Convert.ToInt32(
            System.Console.ReadLine());

            ObjectFactory[(MessageType)ReadType].Send();
           

            System.Console.ReadLine();
        }

The implementation is very simple one. Just we are maintaining one dictionary by containing object of concrete implementation of the IMessage interface.

Once user input some value, we are getting appropriate object and calling respective function. Here is Full code implementation with output.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Console
{
    public interface IMessage
    {
        void Send();
    }

    public class SMS : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("SMS Sending..");
        }
    }
    public class Mail : IMessage
    {
        public void Send()
        {
            System.Console.WriteLine("Mail Sending..");
        }
    }

    enum MessageType { Sms, Mail };
    class Program
    {
        public static void Main(String[] args)
        {
            Dictionary<MessageType, IMessage> ObjectFactory 
                  = new Dictionary<MessageType, IMessage>
            {
                { MessageType.Sms, new SMS() },
                { MessageType.Mail, new Mail() }
            };

            System.Console.WriteLine("0: For SMS, 1: Mail");

            int ReadType = Convert.ToInt32(
            System.Console.ReadLine());
            ObjectFactory[(MessageType)ReadType].Send();
           

            System.Console.ReadLine();
        }
    }
}


Saturday, November 14, 2015

This 12 changes you will encounter in ASP.NET 5 at first time.

If you keep an eye on movement of ASP.NET5/VNext then probably you know that recently the 8th beta version has released (at the time of writing this post). Anyway, it looks like it will take another year to be stable and production ready.

It’s good time to update our thought along with Microsoft. Here is few changes you will notice in time of your first ASP.NET5 development.

     1) First time ASP.NET has become open source
Yes, though this is not part of ASP.NET5/VNext but this is great news for developer. Now, then can study source code and process as per license and agreement. Microsoft has made this wonderful decision to get better support from community.

2) First time running on Linux and MAC or in self hosted process
      This is another great news. Now, it’s not necessary to host your application only in IIS. This became possible because new ASP.NET pipeline is no more dependent on System.Web. People can choose other than Windows (hopefully, I doubt how many will really choose. Now a days windows hosting too coming in cheap package like linux) to host there ASP.NET application.

3) First time developers are using Other than VisualStudio(most probably)
 Probably, Microsoft too encourage people to choose their own IDE. Officially you can use Sublime, Vim,Emacs etc. But again, I doubt whether those IDE is best fit for enterprise!

4) First time .NET is served as two modes(core and Full)
      Yes, Core and Full. If you don’t want backward compatibility then blindly got for core CLR. Otherwise Full CLR. The full CLR is nothing but the Old .NET Framework. The core CLR is only 11 MB in size and very lean in design. This will help to execute unnecessary code in time of HTTP execution.  

5) First time in built DI container (You can bring your own as well)
      Dependency Injection is common buzz in modern software development. By keeping this mind Microsoft has provided one simple DI container along with scaffolder template. Anyway you are welcome with your favorite IoC container
  
6) First time JSON based project setting structure.
      Yes, World is slowly adopting JSON as data encoding scheme rather than XML. Same has reflected in project structure. In ASP.NET 5 project structure, you will find all JSON based setting file.

7) First time MVC and WebAPI are merged in same project.
      No more confusion between MVC controller and API controller (Although, I never feel that it was confusing personally) Anyway, It will bring uniformity in code base.

8) First time Controller will work without controller keyword.
      One common interview Question has reduced. Probably in time of MVC6 interview there is no scope to as Why “Controller” suffix in name of controller blab la..J

9) First time Output of server code change will reflect without build
      It’s a great help for developer. Those who love/has background server side parsing language (like PHP) they will fall in love of ASP.NET another time. The miracle happen by Roslyn compiler.

10) You will get clear View of pipeline in Startup.cs file (I will not say this is first time :))
Yes, this is not first time feature but more clear then old MVC pipeline. The components of MVC is very much pluggable now. Probably it’s time to say Goodbye to HTTP handler and HTTP module.

11) Your application will not more depend on System.web(If you wish)
Yes, OWIN and KATANA will take care the communication between your application and Web Server. So, it’s no longer need to get help of bulky System.Web assembly.

12) The default Unit test framework is XUnit.
    The earlier framework was Visual Studio Unit test framework (vstest sometime). The XUnit framework has shipped along with ASP.NET5. I did not find much change or feature in XUnit framework other than some syntactical change.