Friday, May 29, 2015

Be observer of your mind, when it is out of your control

You may think that how can I observe myself? Because I am observing something (probably scenic beauty of nature) and I know what I am observing! In addition, at same time we cannot observe two views.



But  still you can observe yourself. The thought might be meaningless for you if you do not have thought process up to certain level. I will not say this is rocket science but still you have to schedule and set up your mind to become the viewer of your mind. You have to have vision to read your hearts.

In 2000 B.A Sankaracharja had given one sloka in Kaatha Upanishad entitle “Drig Dresya Viveka” and if you follow and practice his verses you can really became observer of yourself and you can realize who you are! At last, that is, more meaningful rather than your official activity (at last for me).
Here I have discussed “Drig Dresya viveka” .


Now, let us assume that you became observer of your mind and body.  To feel and experience this you have to think that your body is detached from your mind and you are detached from your mind.. Bit confusing!

Ok, now let us think, somehow you became observer of your mind but what is your role by becoming observer? - YOU SEE YOUR FUTURE.

Now, we agree we can see our mind! However, the question is when to see your mind? When the visibility of mind is best?  It will be visible best when you are not controlling your mind. May be I can say in heavily drunken mood.

Because at that time you are out of your mind (at least certain levelJ), your thoughts are turning to words without filter and nerves have no control over your activity.

At that moment just observe your mind (I am still assuming you are professional drunker and you have sense to observer) and summarize your whole thought. You should find your destiny! You should SEE YOUR FUTURE.





Wednesday, May 27, 2015

Load ApiController from Anonymous assembly using IAssembliesResolver

Loading Controller form App domain is very easy and MVC/Web -Api can handle it by default. How to load controller from an assembly which is build out of current project?

The use case might be like this: You want to use self hosting for you Web-API application and you want to manually load all your assemblies or you want to use some assembly from another project without adding the controller file directly.

We can override default behavour of IAssemblyResolver with our custom assembly resolver class. Here is the process to implement.
     
      1)      Create one DLL project and add MVC/WebAPI . Here is our simple controller
public class DataController : ApiController
    {
        public string Get()
        {
            return "Hello";
        }
    }

       2)      Override default behavior of IAssemblyRsolver
public class CustomAssemblyResolver : IAssembliesResolver
    {
        public ICollection<Assembly> GetAssemblies()
        {
            List<Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
            var controllersAssembly = Assembly.LoadFrom(@"C:\Controller.dll");
            baseAssemblies.Add(controllersAssembly);
            return baseAssemblies;
        }
    }

In this application I have kept dll in C:\. GetAssembly() function will pick assembly from current app domain at first and it will merge with Controller.dll.

      3)      Replace IAssemblyResolver with CustomAssemblyResolver

GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());

Add above code in Global page to register



Saturday, May 23, 2015

Database already Exists? Still chance is there for Code First!

Few days ago we were trying to implement one API which will talk to one existing database.  Now, developer/industry is very crazy with Code first approach in Entity Framework.  The general approach behind code first is , If the project is brand new.

In our case, The project was brand new but not database…!!!  .Shall we go for code first still or simply we will generate model from existing database?

Hold on, there is chance to implement your domain model from database using Entity Framework and that too automated.

Select Code First from database option in time of adding EDM file. Don’t worry It will not add that 
file in solution.


This option is available from Entity Framework 6 +


Choose your database and server here.


And once you finish model add operation , you will find that Entity classes is added in your solution. In my case my Dummy database contains test class and that is reflected here.

namespace Routing.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("test")]
    public partial class test
    {
        public int id { get; set; }

        public string name { get; set; }
    }
}

And here is scaffolding context class.

namespace Routing.Models
{
    using System;
    using System.Data.Entity;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;

    public partial class Dummy : DbContext
    {
        public Dummy()
            : base("name=Dummy")
        {
        }
        public virtual DbSet<test> tests { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<test>()
                .Property(e => e.name)
                .IsUnicode(false);
        }
    }
}

Friday, May 22, 2015

Wanted to execute Stored Procedure in Generic Repository ?

If you are familiar with Repository and Generic repository pattern then you must know the philosophy behind those patterns.

Yes, they create abstraction on top of data access mechanism and helps on CRUD for particular model. If it is generic Repository the one class serves CRUD functionality for all Entity. Now the question is , What If we want to execute stored procedure in Generic Repository. In my experience I never seen any function to execute stored procedure in Repository pattern, may be “People don’t want to fire query on top of Context directly”

That is the reason to create abstraction over DB, which we call as Repository but I think, this is not much harmful to access SP from generic repository. The choice of implementation is yours. Here is very simple was to implement this in generic repository.

Here is partial code to generic repository class. Have a look that SQLQuery function is ready to take sql query and it will return DbRawSqlQuery<T> object.

class GenericRepository<T> : IGenericRepository<T> where T : class
    {
        private ProjectDbContext entities = null;
        DbSet<T> _objectSet;

        public GenericRepository(ProjectDbContext _entities)
        {
            entities = _entities;
            _objectSet = entities.Set<T>();
        }

        public DbRawSqlQuery<T> SQLQuery<T>(string sql, params object[] parameters)
        {
            return entities.Database.SqlQuery<T>(sql, parameters);
        }
}

Location of DbRawSqlQuery is  System.Data.Entity.Infrastructure;
Here is Controller to Execute SQLQuery function.

public class CompanyController : Controller
    {
        private GenericUnitOfWork Uow;

        public CompanyController()
        {
            this.Uow = new GenericUnitOfWork();
        }

        public void ExecuteSP()
        {
Uow.Repository<Company>().SQLQuery<Company>("EXEC mySP @p1", new SqlParameter("@p1","value"));
        }
}


Inject Dependency in WebAPI using Unity IoC container

I had a misconception about Unity IoC container. I was trying to manage dependency of one Api Controller using Unity container, which was specific for MVC. So, In obvious reason It did not worked.

Then I checked in Google and realize that Unity has different package for  WebAPI. If you are interested to inject dependency in WebAPI controller , please use following package.

Install-Package Unity.AspNet.WebApi -Version 3.5.1404

It will scaffold necessary setting in your application. In this article we will see where to register your dependency in  for API controller.

Here is unity Activator class which will automatically generate for you.

public static class UnityWebApiActivator
    {
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
            GlobalConfiguration.Configuration.DependencyResolver = resolver;
        }

        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }

The Start and ShutDown functions are to up and down container in application. Here is definition of UnityConfig class.

    public class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });
        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterType<IService, Service>();
        }
    }

The RegisterType function is important one. Here we have to register our dependency. In this example we will implement IService interface in Service class and will inject to API Controller. For that, we are registering Dependency here.

Create controller to inject dependency.

public interface IService
    {
        void hello();
    }
    public class Service : IService
    {
        void IService.hello()
        {
            throw new NotImplementedException();
        }
    }

    public class DummyController : ApiController
    {
        IService obj;
        public DummyController(IService obj)
        {
            this.obj = obj;
        }
       
        public void Get()
        {

        }
    }

Once we invoke Dummy controller ,we will see that Dependency has injected to constructor.


Sunday, May 17, 2015

Catch all parameters in routing

Sometimes it is needed to catch all parameter from url. If so , how we can implement routing to catch all parameter ?

The implementation is very simple, Just add “*” before the parameter name. Have a look on blowentry in route table.

You can see that “CatchAll” entry has “*” followed by parameter name. So this entry can able to catch all parameters from url.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "CatchAll",
                url: "{controller}/{action}/{*value}",
                defaults: new { controller = "Home", action = "Index", value = UrlParameter.Optional }

            );
        }

Here is my controller.

public class DummyController : Controller
{
        public void Index(string value)
        {
           
        }
    }



We are invoking the Index action by this url http://localhost:61684/Dummy/Index/a/a/c and we are seeing that Index has invoked.