Friday, July 31, 2015

What is ajax ?

AJAX(asynchronous JavaScript and XML) is an important front-end web technology that lets JavaScript communicate with a web server. It lets you load new content without leaving the current page, creating a better, faster experience for your web site's visitors. In this course, you'll learn how AJAX works and how you can use JavaScript to communicate with a web server. We'll use plain JavaScript as well as jQuery to create AJAX requests and use the response to dynamically update your web pages. Along the way, you'll build mini-projects to reinforce your learning. We wrap up the course with a small project, showing you how to apply what you've learned to pull images from Flickr and display them on your web site. 

Asynchronous JavaScript + XML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together, including: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and most importantly the XMLHttpRequest object.
When these technologies are combined in the Ajax model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.

Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in Ajax model.


<!DOCTYPE html>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>


Now, add a <script> tag to the page's head section. The script section contains the loadXMLDoc() function:  

function loadXMLDoc()
.... AJAX script goes here ...

Some advantages

AJAX, you see, is based on internet standards. It uses a combination of the following to accomplish it’s goal:
  • XMLHttpRequest Object(Modern Broswers and IE7+)
  • ActiveXObject (IE6 and below)
  • JavaScript/DOM (Used to interact browser and server)
  • XML (Returned results)
  • JSON (Returned results)
  • HTML (Returned results)
These standards are browser based, making them platform independent. It doesn’t matter where you program this in, as long as you have a browser, then this ‘should’ work. All you would need is a server with the application files, and the browser should do the rest.

Another advantage using AJAX would be a better user interactivity. This could be named the most obvious benefit of using AJAX, and why web developers and webmasters are using AJAX more and more every day. AJAX simplifies the flow of an application, thus making it have quicker interaction between user and website since pages are not reloaded for content to be displayed. This activity can be simplified, since the loading times can be reduced from websites.

The advantage above opens up for this next advantage, which you can call it, smoother navigation on a website. While using AJAX, users will not have the need to use the refresh nor the back button, thus, allowing quicker response from the server.

Some Disadvantages
Everything that has an advantage, will most likely have disadvantages, and AJAX surely has some that I will mention.

Even though the back and refresh button are not needed while navigating a website with AJAX, these two buttons can become useless. This is due to the fact that, AJAX ‘navigating’ does not change you URL, so if you were in the middle of a process, and have no direct URL to where you were, then this might be bad. In some cases, the use of Hijaxing is used, which is the use of hashing url (#) at the end.

Another disadvantage would be that it is dependant on JavaScript. While it is ok to depend on it, since most modern (if not all) already use it, but in some cases, there are users who prefer disabling JavaScript. This makes AJAX worthless. Gladly, there is a workaround this problem, as web developers must have in mind, every time they create an AJAX Website, they need to always think of this and make an optional non-AJAX version of the AJAXified website they just created.

The last disadvantage I want to point out would be the SEO factor. Since there are no SEO Friendly URL’s, then search engine tend to bypass your application, and it would appear as if that part of your site does not exist. 

Before coding your AJAX website, make sure you think of the listed disadvantages and obviously many more. Remeber, when creating a website, you have to think on customer/client satisfaction, not your own. You have to always think of all, and I mean ALL common browsers, including IE6 

“async: false” in jQuery.ajax()

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //blocks window close
            success: function() {}

Thursday, July 30, 2015

Difference between LINQ to SQL and Entity Framework

LINQ to SQL allow you to query and modify SQL Server database by using LINQ syntax. Entity framework is a great ORM shipped by Microsoft which allow you to query and modify RDBMS like SQL Server, Oracle, DB2 and MySQL etc. by using LINQ syntax. Today, EF is widely used by each and every .NET application to query to database. The difference between LINQ to SQL and EF is given below.

Domain modelling approaches in Entity Framework

A business domain is populated with related and interconnected entities which have its own properties and behavior. Most important thing is that each entity may have a state and can be bound to a possibly dynamic list of validation rules. EF allow developers to focus on the business domain and to model it in terms of classes.

Domain modelling approaches

There are three approaches of domain modelling which was introduced with Entity Framework 4.1
  1.     Code First
  2.     Model First
  3.     Database first
Code First

Code first is the domain modelling approach in Entity Framework. It enables you to describe a model by using C# or VB.NET classes and then create database from these classes. These classes are called POCO classes.
This approach enables us to work entirely in an object-oriented direction, and not worry about the structure of the database. This abstraction allow us to make a more logically and flexible application that focuses on the behaviour of the application rather than the database generated by it.

Advantages of Code First
  •     It is very popular approach since it allow you to make a more logically and flexible application.
  •     It provides full control over the code since there is no auto generated code which is hard to modify.
  •     In this approach, your code defines only the database mappings and EF will handle creation of   database with its relations.
  •     Manual changes to database schema is not preferable because your code defines the database.
  •     You can also use Code first to map your model to an existing database.
Model First

Model first is the domain modelling approach in Entity Framework. It enables you to create model’s Entities, relationships, and inheritance hierarchies on the design surface of empty model (.edmx file) by using entity designer and then create database from it. This approach is adopted by the architect and solution lead developers.
In Model First approach, while creating Entity Data Model, you must select the option “Empty Model” instead of "Generate from database" option.

Advantage of Model First

  •     It is good if you like to visualize the structure of the data in the application or you don't like writing code or SQL since it will generate for you.
  •     In this approach you have no much control over your entities (auto generated code which is hard to modify) and database. In this way it is rarely used but for small easy projects this approach will be very productive.
  •     To add extra features in POCO entities you must either T4 modify template or use partial classes.
  •     Manual changes to database schema is not preferable because your model defines the database.
Database First

Database first is the domain modelling approach in Entity Framework. It enables you to create model from an existing database (like SQL Server, Oracle, DB2 etc.). This approach reduces the amount of code that we need to write since it automatically generates code. But it also limits us to work with the structure of the generated code.

Advantage of Database First

  •     Very popular if you have Database designed by DBAs, developed separately or if you have existing Database.
  •     EDM wizard creates entities, relationships, and inheritance hierarchies for you. After modification of mapping, you can also generate POCO class entities.
  •     To add extra features in POCO entities you must either T4 modify template or use partial classes.
  •     Manual changes to the database are possible because the database defines your domain model. You can always update model from database.

Differences Between NHibernate and Entity Framework


NHibernate and Entity Framework are two of the most popular O/RM frameworks on the .NET world. Although they share some functionality, there are some aspects on which they are quite different. This post will describe this differences and will hopefully help you get started with the one you know less. Mind you, this is a personal selection of features to compare, it is by no way an exhaustive list.


First, a bit of history. NHibernate is an open-source project that was first ported from Java’s venerable Hibernate framework, one of the first O/RM frameworks, but nowadays it is not tied to it, for example, it has .NET specific features, and has evolved in different ways from those of its Java counterpart. Current version is 3.3, with 3.4 on the horizon. It currently targets .NET 3.5, but can be used as well in .NET 4, it only makes no use of any of its specific functionality. You can find its home page at NHForge.

Entity Framework 1 came out with .NET 3.5 and is now on its second major version, despite being version 4. Code First sits on top of it and but came separately and will also continue to be released out of line with major .NET distributions. It is currently on version 4.3.1 and version 5 will be released together with .NET Framework 4.5. All versions will target the current version of .NET, at the time of their release. Its home location is located at MSDN.


In NHibernate, there is a separation between the Unit of Work and the configuration and model instances. You start off by creating a Configuration object, where you specify all global NHibernate settings such as the database and dialect to use, the batch sizes, the mappings, etc, then you build an ISessionFactory from it. The ISessionFactory holds model and metadata that is tied to a particular database and to the settings that came from the Configuration object, and, there will typically be only one instance of each in a process. Finally, you create instances of ISession from the ISessionFactory, which is the NHibernate representation of the Unit of Work and Identity Map. This is a lightweight object, it basically opens and closes a database connection as required and keeps track of the entities associated with it. ISession objects are cheap to create and dispose, because all of the model complexity is stored in the ISessionFactory and Configuration objects.

As for Entity Framework, the ObjectContext/DbContext holds the configuration, model and acts as the Unit of Work, holding references to all of the known entity instances. This class is therefore not lightweight as its NHibernate counterpart and it is not uncommon to see examples where an instance is cached on a field.


Both NHibernate and Entity Framework (Code First) support the use of POCOs to represent entities, no base classes are required (or even possible, in the case of NHibernate).

As for mapping to and from the database, NHibernate supports three types of mappings:

  •     XML-based, which have the advantage of not tying the entity classes to a particular O/RM; the XML files can be deployed as files on the file system or as embedded resources in an assembly;
  •     Attribute-based, for keeping both the entities and database details on the same place at the expense of polluting the entity classes with NHibernate-specific attributes;
  •     Strongly-typed code-based, which allows dynamic creation of the model and strongly typing it, so that if, for example, a property name changes, the mapping will also be updated.

Entity Framework can use:

  •     Attribute-based (although attributes cannot express all of the available possibilities – for example, cascading);
  •     Strongly-typed code mappings.
Database Support

With NHibernate you can use mostly any database you want, including:

  •     SQL Server;
  •     SQL Server Compact;
  •     SQL Server Azure;
  •     Oracle;
  •     DB2;
  •     PostgreSQL;
  •     MySQL;
  •     Sybase Adaptive Server/SQL Anywhere;
  •     Firebird;
  •     SQLLite;
  •     Informix;
  •     Any through OLE DB;
  •     Any through ODBC.
Out of the box, Entity Framework only supports SQL Server, but a number of providers exist, both free and commercial, for some of the most used databases, such as Oracle and MySQL.

Inheritance Strategies

Both NHibernate and Entity Framework support the three canonical inheritance strategies: Table Per Type Hierarchy (Single Table Inheritance), Table Per Type (Class Table Inheritance) and Table Per Concrete Type (Concrete Table Inheritance).


Regarding associations, both support one to one, one to many and many to many. However, NHibernate offers far more collection types:

  •     Bags of entities or values: unordered, possibly with duplicates;
  •     Lists of entities or values: ordered, indexed by a number column;
  •     Maps of entities or values: indexed by either an entity or any value;
  •     Sets of entities or values: unordered, no duplicates;
  •     Arrays of entities or values: indexed, immutable.

NHibernate exposes several querying APIs:

  •     LINQ is probably the most used nowadays, and really does not need to be introduced;
  •     Hibernate Query Language (HQL) is a database-agnostic, object-oriented SQL-alike language that exists since NHibernate’s creation and still offers the most advanced querying possibilities; well suited for dynamic queries, even if using string concatenation;
  •     Criteria API is an implementation of the Query Object pattern where you create a semi-abstract conceptual representation of the query you wish to execute by means of a class model; also a good choice for dynamic querying;
  •     Query Over offers a similar API to Criteria, but using strongly-typed LINQ expressions instead of strings; for this, although more refactor-friendlier that Criteria, it is also less suited for dynamic queries;
  •     SQL, including stored procedures, can also be used;
  •     Integration with Lucene.NET indexer is available.

As for Entity Framework:

  •     LINQ to Entities is fully supported, and its implementation is considered very complete; it is the API of choice for most developers;
  •     Entity-SQL, HQL’s counterpart, is also an object-oriented, database-independent querying language that can be used for dynamic queries;
  •     SQL, of course, is also supported.

Both NHibernate and Entity Framework, of course, feature first-level cache. NHibernate also supports a second-level cache, that can be used among multiple ISessionFactorys, even in different processes/machines:

  •     Hashtable (in-memory);
  •     SysCache (uses ASP.NET as the cache provider);
  •     SysCache2 (same as above but with support for SQL Server SQL Dependencies);
  •     Prevalence;
  •     SharedCache;
  •     Memcached;
  •     Redis;
  •     NCache;
  •     Appfabric Caching.
Out of the box, Entity Framework does not have any second-level cache mechanism, however, there are some public samples that show how we can add this.

ID Generators

NHibernate supports different ID generation strategies, coming from the database and otherwise:

  •     Identity (for SQL Server, MySQL, and databases who support identity columns);
  •     Sequence (for Oracle, PostgreSQL, and others who support sequences);
  •     Trigger-based;
  •     HiLo;
  •     Sequence HiLo (for databases that support sequences);
  •     Several GUID flavors, both in GUID as well as in string format;
  •     Increment (for single-user uses);
  •     Assigned (must know what you’re doing);
  •     Sequence-style (either uses an actual sequence or a single-column table);
  •     Table of ids;
  •     Pooled (similar to HiLo but stores high values in a table);
  •     Native (uses whatever mechanism the current database supports, identity or sequence).Entity Framework only supports:
  • Identity generation;
  •     GUIDs;
  •     Assigned values.

NHibernate supports properties of entity types (one to one or many to one), collections (one to many or many to many) as well as scalars and enumerations. It offers a mechanism for having complex property types generated from the database, which even include support for querying. It also supports properties originated from SQL formulas.

Entity Framework only supports scalars, entity types and collections. Enumerations support will come in the next version.

Events and Interception

NHibernate has a very rich event model, that exposes more than 20 events, either for synchronous pre-execution or asynchronous post-execution, including:

  •     Pre/Post-Load;
  •     Pre/Post-Delete;
  •     Pre/Post-Insert;
  •     Pre/Post-Update;
  •     Pre/Post-Flush.

It also features interception of class instancing and SQL generation.

As for Entity Framework, only two events exist:

  •     ObjectMaterialized (after loading an entity from the database);
  •     SavingChanges (before saving changes, which include deleting, inserting and updating).
Tracking Changes

For NHibernate as well as Entity Framework, all changes are tracked by their respective Unit of Work implementation. Entities can be attached and detached to it, Entity Framework does, however, also support self-tracking entities.

Optimistic Concurrency Control

NHibernate supports all of the imaginable scenarios:

  •     SQL Server’s ROWVERSION;
  •     Oracle’s ORA_ROWSCN;
  •     A column containing date and time;
  •     A column containing a version number;
  •     All/dirty columns comparison.

Entity Framework is more focused on Entity Framework, so it only supports:

  •     SQL Server’s ROWVERSION;
  •     Comparing all/some columns.

NHibernate has full support for insertion batching, but only if the ID generator in use is not database-based (for example, it cannot be used with Identity), whereas Entity Framework has no batching at all.


Both support cascading for collections and associations: when an entity is deleted, their conceptual children are also deleted. NHibernate also offers the possibility to set the foreign key column on children to NULL instead of removing them.

Flushing Changes

NHibernate’s ISession has a FlushMode property that can have the following values:
  •     Auto: changes are sent to the database when necessary, for example, if there are dirty instances of an entity type, and a query is performed against this entity type, or if the ISession is being disposed;
  •     Commit: changes are sent when committing the current transaction;
  •     Never: changes are only sent when explicitly calling Flush().
As for Entity Framework, changes have to be explicitly sent through a call to AcceptAllChanges()/SaveChanges().

Lazy Loading

NHibernate supports lazy loading for
  •     Associated entities (one to one, many to one);
  •     Collections (one to many, many to many);
  •     Scalar properties (thing of BLOBs or CLOBs).
Entity Framework only supports lazy loading for:
  •     Associated entities;
  •     Collections.
Generating and Updating the Database

Both NHibernate and Entity Framework Code First (with the Migrations API) allow creating the database model from the mapping and updating it if the mapping changes.

As you can guess, NHibernate is far more extensible than Entity Framework. Basically, everything can be extended, from ID generation, to LINQ to SQL transformation, HQL native SQL support, custom column types, custom association collections, SQL generation, supported databases, etc. With Entity Framework your options are more limited, at least, because practically no information exists as to what can be extended/changed. It features a provider model that can be extended to support any database.

Integration With Other Microsoft APIs and Tools

When it comes to integration with Microsoft technologies, it will come as no surprise that Entity Framework offers the best support. For example, the following technologies are fully supported:
  •     ASP.NET (through the EntityDataSource);
  •     ASP.NET Dynamic Data;
  •     WCF Data Services;
  •     WCF RIA Services;
  •     Visual Studio (through the integrated designer).


This is another point where Entity Framework is superior: NHibernate lacks, for starters, an up to date API reference synchronized with its current version. It does have a community mailing list, blogs and wikis, although not much used. Entity Framework has a number of resources on MSDN and, of course, several forums and discussion groups exist.

Version history of ADO.NET Entity Framework

ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with various relational databases like SQL Server, Oracle, DB2, MYSQL etc. It enables developers to deal with data as business objects and entities. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects using C# or VB.NET. 

ADO.NET Entity Framework Version History 

Wednesday, July 29, 2015

How to improve Entity Framework Performance

LINQ to Entity is a great ORM for querying and managing database. It offers a lot of things, so it is mandatory to know about performance of it. These are right up to a certain point as LINQ comes with its own penalties. There are some tips and tricks that we should keep in mind while desiging and query database using entity framework ORM. Here is a list of some tips that I would like to share with you. 

1- Avoid to put all the DB Objects into One Single Entity Model
Entity Model specifies a single unit of work, not all our database. If we have many database objects that are not connected to one another or these(log tables, objects used by batch processes,etc.) are not used at all. Hence these objects are consuming space in the memory and cause performance degrades. So try to make separate entity models of related database objects.

2- Disable change tracking for entity if not needed
Whenever you retrieve the data only for reading purpose, not for modification then there is no need of object tracking. So disable object tracking by using MergeOption as below: 

NorthwindDataContext context = new NorthwindDataContext() 
context.tblCities.MergeOption = MergeOption.NoTracking;
3- Use Pre-Generating Views to reduce response time for first request
When the object of ObjectContext is created first time in the application, the entity framework creates a set of classes that is required to access the database. This set of classes is called view and if your data model is large then creating the view may delay the web application response to the first request for a page. We can reduce this response time by creating view at compile time by using T4 template or EdmGen.exe command-line tool.

4- Avoid fetching all the fields if not required
Avoid fetching not required fields from the database. Suppose I have table of Customer with 20 fields and I am interested only in three fields - CustomerID, Name, Address then fetch only these three fields instead of fetching all the fields of the Customer table.
//Bad Practice
var customer =
 (from cust in dataContext.Customers
 select cust).ToList();
 //Good Practice
var customer =
 (from cust in dataContext.Customers
 select new {
 customer. CustomerID,
 }). ToList (); 
5- Choose appropriate Collection for data manipulation
In linq we have Var, IEnumerable, IQueryable, IList type collection for data manipulation. Each collection has its importance and performance impact on the query, so beware of using all these collection for data manipulation.

6- Use Compiled Query wherever needed
Make a query to compiled query if it is frequently used to fetch records from the database. This query is slow in first time but after that it boost the performance significantly. We use Compile method of CompiledQuery class for making compiled query.
Suppose you required to retrieve customers details again and again based on city then make this query to compiled query like as 
// create the entity object
NorthwindEntities mobjentity = new NorthwindEntities();
 //Simple Query
IQueryable lstCus = from customer in mobjentity.tblCustomers
where customer.City == "Delhi"
select customer;
 //Compiled Query
Func> compiledQuery
= CompiledQuery.Compile>(
(ctx, city) =>from customer in ctx.Customers
where customer.City == city
select customer);
 In above query we are passing the string parameter city for filtering the records.

7- Retrieve only required number of records
When we are binding data to grid or doing paging, retrieve only required no of records to improve performance. This can achieved by using Take,While and Skip methods.
// create the entity object
NorthwindEntities mobjentity = new NorthwindEntities();
int pageSize=10,startingPageIndex=2;
List lstCus = mobjentity.tblCustomers.Take(pageSize)
 .Skip(startingPageIndex * pageSize)
8- Avoid using Contains
In LINQ, we use contains method for checking existence. It is converted to "WHERE IN" in SQL which cause performance degrades.

9- Avoid using Views
Views degrade the LINQ query performance costly. These are slow in performance and impact the performance greatly. So avoid using views in LINQ to Entities.

10- Debug and Optimize LINQ Query
If you want to debug and optimize your query then LINQ Pad is a great tool for this purpose. I am a big fan of LINQ Pad. It is very useful for query construction, debugging and optimization.
IQueryable lstCus = from customer in mobjentity.tblCustomers
where customer.City == "Delhi"
select customer;
Dump method of LINQ Pad give the result of above query in the result window.

Tuesday, July 28, 2015

Inheritance in Entity Framework

Inheritance in the Entity Framework is similar to inheritance for classes in C#. In Entity Framework, you can map an inheritance hierarchy to single or multiple database tables based on your requirements. In this article, you will learn how to map your inheritance hierarchy to database tables in SQL Server.

 Types of inheritance in Entity Framework
Entity Framework supports three types of inheritances as given below-

1- Table-per-Hierarchy (TPH)

The TPH inheritance states that all entities, in a hierarchy of entities, are mapped to a single table in storage schema. It means, there is only one table in database and different Entity types in Entity model that inherits from a base Entity are mapped to that table.
 C# Implementation Code for TPH
public class Course
 public int CourseId { get; set; }
 public string Name { get; set; }
 public string Details { get; set; }
 public string Trainer { get; set; }
 public class OnlineCourse : Course
 public string URL { get; set; }
 public class OfflineCourse : Course
 public string Address { get; set; }

Entity Framework Code First Mapping for TPH
     .Map<OnlineCourse >(m => m.Requires("Type").HasValue("OnlineCourse "))
     .Map<OfflineCourse >(m => m.Requires("Type").HasValue("OfflineCourse "));
Note: By default, Entity Framework supports TPH inheritance, if you don't define any mapping details for your inheritance hierarchy.

2- Table-per-Concrete-Type (TPC)

The TPC inheritance states that each concrete class (a class which can be instantiated) in the hierarchy of entities is mapped to a separate table in storage schema. It means, there is separate table in database to maintain data for each derived entity type.
C# Implementation Code for TPC

public abstract class Course //abstract class
     public int CourseId { get; set; }
     public string Name { get; set; }
     public string Details { get; set; }
     public string Trainer { get; set; }
     public class OnlineCourse : Course //concrete class
     public string URL { get; set; }
     public class OfflineCourse : Course //concrete class
     public string Address { get; set; }

Entity Framework Code First Mapping for TPC

    modelBuilder.Entity<OnlineCourse >().Map(m =>
     m.ToTable("OnlineCourse ");
    modelBuilder.Entity<OfflineCourse >().Map(m =>
     m.ToTable("OfflineCourse ");
Entity Framework Code First Mapping for TPC
  modelBuilder.Entity<OnlineCourse >().Map(m =>
     m.ToTable("OnlineCourse ");
    modelBuilder.Entity<OfflineCourse >().Map(m =>
     m.ToTable("OfflineCourse ");

NOTE:- The TPC inheritance is commonly used to inherit basic features.

3-Table-per-Type (TPT)

The TPT inheritance states that each entity in the hierarchy of entities is mapped to a separate table in storage schema. It means, there is separate table in database to maintain data for each Entity Type.

 C# Implementation Code for TPT

public class Course
 public int CourseId { get; set; }
 public string Name { get; set; }
 public string Details { get; set; }
 public string Trainer { get; set; }
 public class OnlineCourse : Course
 public string URL { get; set; }
 public class OfflineCourse : Course
 public string Address { get; set; }
Entity Framework Code First Mapping for TPT 

    modelBuilder.Entity<OnlineCourse >().ToTable("OnlineCourse ");
    modelBuilder.Entity<OfflineCourse >().ToTable("OfflineCourse ");
Note:- TPH inheritance patterns generally deliver better performance in the Entity Framework than TPT inheritance patterns, because TPT patterns can result in complex join queries.


Using T4 templates in Entity framework

T4 stands for Text template transformation toolkit which is a template-based code generation engine built into Visual Studio. It is available in Visual studio from Visual Studio 2008 and higher version of Visual Studio. T4 engine allows you to generate C#, T-SQL, XML or any other text files by using ASP.NET – ASPX template like syntax. T4 template has .tt extension.

For example, T4 template has the following code:
    <#@ template language="C#" #>
    <#@ assembly name="System.Core" #>
    <#@ import namespace="System.Text" #>
    <#@ output extension=".txt" #>
    <# Write("T4 templates with EF!"); #>
The T4 template processor will transform above T4 template code into a text file having extension .txt by executing the code and processing directives inside.
T4 templates with EF!

T4 templates with Entity framework
T4 templates in entity framework are used to generate C# or VB entity classes from EDMX files. Visual Studio 2013 or 2012 provides two templates- EntityObject Generator and DBContext Generator for creating C# or VB entity classes. The additional templates are also available for download.

To use one of these templates, right-click on the design surface of an .edmx file and select the "Add Code Generation Item".

Selecting the command will launch a dialog box allowing you to select one of the installed code-generation items, or to search for new items online.

Monday, July 27, 2015

Generate Class From JSON or XML in Dot Net with C#

There is cases application written using the .NET Framework written by a developer that receives a JSON or XML string from a web service or from another third party application. After receiving JSON or XML string data there is a need for further processing of the received data that requires deserialization of the received JSON or XML in a .Net object. And for that a .Net class structure must be created to match the JSON or XML string data so that the JSON or XML string can be deserialized correctly.

Problem Statement:
For example, a program receives the following JSON string by calling a web service or third-party program.


   {"firstName":"John", "lastName":"Doe"},  
   {"firstName":"Anna", "lastName":"Smith"},  
   {"firstName":"Peter", "lastName":"Jones"}  

And now there is the need for deserializing the received JSON or XML string to a .Net object so further processing can be done based on the received data or on the received data. 

Approach 1: Do it manually

In this approach the developer must understand JSON or XML so that he/she can understand the received JSON or XML string and its structure. Once getting the details of JSON or XML and the received JSON or XML string, the developer must convert the JSON or XML string into a meaningful class structure so desterilization can be done without a problem.

So the problem with this approach is so much work must be done by the developer, like:

    1- Requires knowledge of JSON or XML.

    2- Requires an understanding of the JSON or XML string sent by the exteranl program.

    3- Creates class strucutre for the JSON or XML structure that is a trial and error approch because usually the created structure doesn't work in the first go.

    4- If a JSON or XML string has a complex structure then its difficult and requires time to create the class structure to deserialize the JSON or XML string.

Approach 2: Automated using Visual Studio

This approach uses Visual Studio to generate a class just by copying and pasting the JSON or XML string.

The following is the procedure to generate the class:

    1- Copy JSON or XML string

 2- Go to Edit > Paste Sepcial > Paste JSON As Classes or Paste XML As Classes.

3- Visual Studio generates a class structure for the developer as in the following:
The following is an example of the class structure created by copying and pasting a JSON string.

public class EmployeeList {  
    public Employee[] employees {  
public class Employee {  
    public string firstName {  
    public string lastName {  
Below is example of class structure created by copy and pasting XML string
/// <remarks/>    
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]    
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]    
public partial class employees {    
    privateemployeesEmployee[] employeeField;    
    /// <remarks/>    
    publicemployeesEmployee[] employee {    
        get {    
        set {    
            this.employeeField = value;    
/// <remarks/>    
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]    
public partial class employeesEmployee {    
    private string firstNameField;    
    private string lastNameField;    
    /// <remarks/>    
    public string firstName {    
        get {    
        set {    
            this.firstNameField = value;    
    /// <remarks/>    
    public string lastName {    
        get {    
        set {    
            this.lastNameField = value;    
As you see in the preceding code it will generate the correct attributes for the XML in the class so the deserialization is done without problems.

The advantages of this solution are:

1- No need to understand JSON or XML
2- No effort require for creating the class

Entity Framework Code First Migrations

Code-First approach allows you to define model classes as per the Domain requirements via POCOs. Hence, you have complete control over the classes being written or Implemented. Code First Migrations allow you to create a new database or to update existing database based on your model classes by using Package Manager Console exist within Visual Studio 2013 or Visual Studio 2012.

Code First Database Initializers
Before understanding code first migrations, let's have a look at Code First Database Initializers provided by Entity Framework. When you follow EF code first approach, then you have three options for initializing database as given below–

This is the default database initializer class used by Code First. This class creates a database only if it doesn't exist. This initializer helps you to avoid any accidental deletion of the database.

This database initializer class drop the existing database and re-creates it if there is a mismatch between the model classes and table schema. This initializer is useful during starting phase of development and testing when models are changing often and there is no concern about the existing database records.

This database initializer class always drop and creates a new database, whether it is already present or not with every run of the application. This initializer is useful during testing when you want to run the application with a fresh set of data.

Why Code First Migrations?
The above three database initializing approach become fail when you add new model classes and you want to update existing database without any deletion or change. To achieve this, you need to use EF code first migrations which allow you to update existing database with new model classes changes and your existing database remains same with your database records.

Note:- You can also create custom database initializers by implementing the IDatabaseInitializer interface.

Code First Migrations in Entity Framework step by step:
Model Classes
Suppose you have the following two entities within your application.

public class Category
     public int CategoryID { get; set; }
     public string Name { get; set; }
    public class Product
     public int ProductID { get; set; }
     public string Name { get; set; }
     public decimal Price { get; set; }
     public int CatID { get; set; }
     public virtual Category Category { get; set; }
Mapping Details
DataContext class and Fluent API mapping details for above two entities are given below –
 public class DataContext : DbContext
     public DataContext():base("DefaultConnection"){ }
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     modelBuilder.Entity<Category>().HasKey(c => c.CategoryID);
     modelBuilder.Entity<Category>().Property(p => p.Name).HasColumnType("VARCHAR").IsRequired().HasMaxLength(50);
     modelBuilder.Entity<Product>().HasKey(p => p.ProductID);
     modelBuilder.Entity<Product>().Property(p => p.Name).HasColumnType("VARCHAR").IsRequired().HasMaxLength(50);
     modelBuilder.Entity<Product>().Property(p => p.Price).HasColumnType("DECIMAL").IsRequired();
     modelBuilder.Entity<Product>().HasRequired(m => m.Category).WithMany().HasForeignKey(c => c.CatID);
     public DbSet<Product> Product { get; set; }
     public DbSet<Category> Category { get; set; }

Visual Studio Package Manager Console
To create the database for these two entities within your application, go to the Package Manager Console option as shown below:

Creating New Database
Running Commands

Run the following command to configure migrations within your project and for creating new database.

   1- Enable migrations

   2- Create migration
    Add-Migration MigrationsName

   3- Create upgrade/downgrade script

When you run above listed command on the Package Manager Console windows one by one then:
1-Firstly a Migrations folder will be added into your applications having Configuration.cs file for Migrations configuration setting. 


2- Secondly a class file will be created having name suffix as MigrationsName followed by underscore and a unique generated number. This file will have all the entities to be created in the database.

3-Thirdly, a new database will be created having initial catalog name (initial catalog = YourDBName) as given in your connections string.

Updating Existing Database
Suppose you have added one more class named as Customer into your data model classes as given below:
Newly added Model Class

public class Customer
     public int CustomerID { get; set; }
     public string Name { get; set; }
     public string Address { get; set; }
Running Commands

Now for updating the database with new changes run the following commands as given below:

1- Create migration
Add-Migration MigrationsName

2- Create upgrade/downgrade script

When you run above listed command on the Package Manager Console windows one by one then

1- Firstly a class file will be created having name suffix as MigrationsName followed by underscore and a unique generated number. This file will have all the entities to be created or updated in the database.

2- Secondly, the existing database will be updated with new changes. 

Undo/Rollback a Migrations

You can also Undo/Rollback a specific migrations by using following commands:

    1- Rollback to a specific migrations
    Update-Database -TargetMigration:MigrationsName

    2- Rollback all migrations
    Update-Database -TargetMigration:0