21 April 2015

Getting PublicKeyToken of an Assembly



Public key token of an assembly is small number representing the public key of the assembly. As the public keys are very long, the tokens allow us to refer the public key without specifying the whole key.
Public key token is the last 8 bytes of the SHA-1 hash of the public key under which the assembly is signed. The assembly must be signed to have a public key
To get PublicKeyToken of an assembly open Visual Studio command prompt and enter the following command –
sn –T NameOfDll.dll
where NameOfDll is the fully qualified name of the DLL for which you want to see the key token.

To simplify the process, we can also add this feature in Visual Studio Tool menu, so that we can get the key from within Visual Studio with just a clock of a button.
1.       From the Tools menu in Visual Studio, select ExternalTools.


2.       Add a new command say GetAssemblyToken and enter the parameters as follows.



The command is the full path of the Strong Name application i.e. sn.exe. If you do not know the full path of the application, just open the Visual Studio command prompt enter command, where sn.exe.
Make sure to check the Use Output Window so that the key is displayed in the Visual Studio output window.

Now if you need to get the PublicKeyToken of a signed assembly, just select the assembly in solution explorer and click the external tool that you have just created, and you should see the key in VS output window.
If we require getting the lengthy public key also, just do a little change while creating external tool command. In place of –T $(TargetPath), just type –TP $(TargetPath) as command argument.

30 November 2014

Dependency Injection made easy for ASP.Net MVC



If you need to implement dependency injection (DI) in your MVC.Net application, there is no easy way than using Unity Bootstrapper for ASP.NET MVC.

This is a lightweight dependency injection container which uses Microsoft Unity container. It is available as NuGet packeage. (https://www.nuget.org/packages/Unity.Mvc/)

Manage NuGet packages for you project and install, Unity Bootstrapper for ASP.NET MVC package.



The package installs some libraries to your project and you could also see the following two classes in your App_Start directory.




Lets get going. Just register your types in RegisterTypes method of UnityConfig and you are done!!





12 October 2014

XML Serialization and Deserialization using generics

I love generics, and I when I come across a requirement where I had  to serialize a variety of objects to xml and deserialize back to the object, generics was the way to go, and resulted in following methods.

        // De-Serializes the request into type object
        public static XmlDocument SerializeToXml(T objectToSerialize)
        {
            XmlDocument serializedXml = new XmlDocument();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (MemoryStream momoryStream = new MemoryStream())
            {
                XmlTextWriter xmlTextWriter = new XmlTextWriter(momoryStream, null);

                xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);
                // Rewind the Stream.
                momoryStream.Seek(0, SeekOrigin.Begin);
                // load from stream;
                serializedXml.Load(momoryStream);

            }
            return serializedXml;
        }


        // De-Serializes the request into class object
        public static T DeserializeXml(XmlNode xmlToDesearialized)
        {
            if (xmlToDesearialized == null) throw new ArgumentNullException("xmlToDesearialized");
            T deserializedObject = default(T);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (StringReader stringReader = new StringReader(xmlToDesearialized.OuterXml))
            {
                XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
                deserializedObject = (T)xmlSerializer.Deserialize(xmlTextReader);
            }
            return deserializedObject;
        }

28 September 2014

Creating directory and copying files using Build Events

If we need to create any directory while we build the project or need to copy some files, in this case the build events comes really handy. 

To specify these events, navigate to the project properties >> Build Events and write these event for Pre or Post build event.


//Create a directory
md "$(SolutionDir)SomeDirectory\Rosources"

//Copying files
xcopy "$(SolutionDir)SourceFolder\Rosources" "$(SolutionDir)TargetFolder\Rosources" /r /y /f /d

ASP.Net MVC / JQuery - Quick Tips

Setting the TemData in JQuery

    <script type="text/javascript">
        $('#aa').val("test");
        '<% TempData["Test"] = "Test";%>';
    </script>

Adding Tooltip in JQuery

         $(document).ready(function () {

            $(function () {
                $("select option").attr("title", "");
                $("select option").each(function (i) {
                    this.title = this.text;
                })
            });

Check if a request is Ajax request

            //Check if the request is an Ajax request.
            bool IsAjaxRequest = !string.IsNullOrEmpty(Request.Form["x-request-with"] ?? Request.Headers["x-request-with"]);

            //OR.. if you dont like it..use
            bool IsAjaxRequestAgain = Request.IsAjaxRequest();

 

04 February 2012

Repository Pattern simplified

In practice, Repository Pattern is generally used to separate the logic relating to the DB interaction (or any data source for that matter), and perform CRUD (Create, Read, Update, Delete) operations for the business objects or domain object or business entities, whatever you call them.
As per MSDN - The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service.

In early days, entity objects were heavier. They not only carries the properties but also the functions to perform operations on these properties.
So for example, the employee entity will have properties like Name, Department etc and then functions like, SaveEmployee, DeleteEmployee, FindEmployee etc.
As programming evolved, entities become lighter, now they just contain attributes and can be easily referenced throughout different layers. And operations on these entities moved to repositories!
Benefits:-
  •  A repository separates the business logic from the interactions with the underlying data source. This is especially important wherein the the data source may vary from dbms, webservice, sharepoint, feeds, files etc. With, Repository Pattern implemented, the business layer can easily be freed from the responsibility of knowing how the interactions to the data source are made. The respective business object repository will take care of it, making your business layer tidy.
  •  Repository Pattern makes it easy to unit test your code, with clearly defined responsibilities of different layers. You can easily test you application both with and without database (using mock/fake objects).
  •  It encourages good coding practice by its nature. With Repository Pattern implemented within the framework, it just becomes harder for the coder to break the rules and play around with the code. It is highly significant with the larger teams, big projects.
Ok...now let’s do some code works and see how this pattern works.
In repository pattern we have a repository class for every domain object, which will be responsible for data interactions with datasources. For example, if we have say, Person and Item domain entities, then there would be respective repositories for these entities.

A person like me with background of the good old 3-Tier architecture, when told to implement Repository Pattern, wrote something like this :(
    public class PersonRepository
    {
        public List<Person> GetAllPersons() { /*Implement method*/}
        public Person GetPersonById(int personId) { /*Implement method*/}
        public void CreatePerson(Person person) { /*Implement method*/}
        public void UpdatePerson(Person person) { /*Implement method*/}
        public void DeletePerson(Person person) { /*Implement method*/}
    }

    public class ItemRepository
    {
        public List<Item> GetAllItems() { /*Implement method*/}
        public Item GetItemById(int itemId) { /*Implement method*/}
        public void CreateItem(Item item) { /*Implement method*/}
        public void UpdateItem(Item item) { /*Implement method*/}
        public void DeleteItem(Item item) { /*Implement method*/}
    }

Uuummnnn…., not bad, lets improvise this, and introduce Interfaces over the top of the repository classes above to add more flexibility to the design
Now the implementation would be like:
    public interface IPersonRepository
    {
        public List<Person> GetAllPersons();
        public Person GetPersonById(int personId);
        public void CreatePerson(Person person);
        public void UpdatePerson(Person person);
        public void DeletePerson(Person person);
    }

    public interface IItemRepository
    {
        public List<Item> GetAllItems();
        public Item GetItemById(int itemId);
        public void CreateItem(Item item);
        public void UpdateItem(Item item);
        public void DeleteItem(Item item);
    }

    public class PersonRepository : IPersonRepository
    {
        public List<Person> GetAllPersons() { /*Implement method*/}
        public Person GetPersonById(int personId) { /*Implement method*/}
        public void CreatePerson(Person person) { /*Implement method*/}
        public void UpdatePerson(Person person) { /*Implement method*/}
        public void DeletePerson(Person person) { /*Implement method*/}
    }

    public class ItemRepository : IItemRepository
    {
        public List<Item> GetAllItems() { /*Implement method*/}
        public Item GetItemById(int itemId) { /*Implement method*/}
        public void CreateItem(Item item) { /*Implement method*/}
        public void UpdateItem(Item item) { /*Implement method*/}
        public void DeleteItem(Item item) { /*Implement method*/}
    }

Doing this –
  • Our code is no more dependent on the concrete class.
  • We can now use patterns like dependency injection and provide different implementation as required.
  • Automated testing will be very graceful; we can provide mock objects to the testing application, instead of messing up the actual database.
So far so good, but there is one problem, as the object increases, there will be more interfaces to manage. If we look closely, what we are doing are some generic operations for the business objects, and if we replace the interfaces with generic one, we can fix this up as well. So, the revised code will look something like:
    public interface IRepository<T>


    {
        public List GetAll();
        public T GetById(int id);
        public void Create(T entity);
        public void Update(T entity);
        public void Delete(T entity);
    }

    public class PersonRepository : IRepository<Person>
    {
        public List<Person> GetAll() { /*Implement method*/}
        public Person GetById(int id) { /*Implement method*/}
        public void Create(Person entity) { /*Implement method*/}
        public void Update(Person entity) { /*Implement method*/}
        public void Delete(Person entity) { /*Implement method*/}
    }

    public class ItemRepository : IRepository<Item>
    {
        public List<Item> GetAll() { /*Implement method*/}
        public Item GetById(int id) { /*Implement method*/}
        public void Create(Item entity) { /*Implement method*/}
        public void Update(Item entity) { /*Implement method*/}
        public void Delete(Item entity) { /*Implement method*/}
    }

With this in place, we have also standardized our repositories. Even for newer business objects, the coder will have to define the repository as per the generic interface only.  You are of course free to add more generic operations to it like finding an object against lambda expression etc.
A really beautiful abstraction of CRUD operations!!