Thursday, January 16, 2014

Entity Framework tutorial


What is Entity Framework?
Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database and working with the results in addition to DataReader and DataSet.

what is O/RM framework and why do we need it?

ORM is a tool for storing data from domain objects to relational database like MS SQL Server in an automated way without much programming.
 O/RM includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects maps to relational database objects (tables, views & storedprocedures). ORM helps us to keep our database design separate from our domain class design. This makes application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so developer doesn’t need to write it manually.

 

Entity Framework vs LINQ-to-SQL:

You may think that what is the difference between Entity Framework and LINQ to SQL which does that same thing. There are some differences between Entity Framework and L2S.Entity framework has a full provider model. It supports not only SQL Server but also other database like Oracle, DB2, MySQL etc.

·         Most of the time L2S classes must be one-to-one with database objects e.g. Customer class can be mapped only with Customer table. Where as in Entity Framework you can map your domain class with multiple tables using various inheritance strategies like table per type (class) or table per hierarchy of classes etc.

·         You can have multiple modeling techniques using Entity Framework 4.1 like code first, model first or database first.

·         Microsoft has long term strategy to support and integrate Entity Framework with multiple Microsoft products.

 Entity Framework Architecture

Entity Framework Architecture

EDM (Entity Data Model): EDM consist three main parts- Conceptual model, Mapping and Storage model.

 

 

Conceptual Model: Conceptual model is your model classes and their relationships. This will be independent from your database table design.

 

Storage Model: Storage model is your database design model which includes tables, views, stored procedures and their relationships and keys.

 

Mapping: Mapping consist information about how your conceptual model is mapped to storage model.

 

LINQ to Entities:LINQ to Entities is query language used to write queries against the object model. It returns entities which are defined in the conceptual model. You can use your LINQ skills here.

 

Entity SQL:Entity SQL is again a query language same as LINQ to Entities. However it is little more difficult than L2E and also developer need to learn it separately.

 

Object Service:Object service is a main entry point for accessing data from database and to return it back. Object service is responsible for materialization which is process of converting data returned from entity client data provider (next layer) to an entity object structure.

 

Entity Client Data Provider:The main responsibility of this layer is to convert L2E or Entity SQL queries into SQL query which is understood by underlying database. It communicates with ADO.Net data provider which in turn sends or retrieves data from database.

 

ADO.Net Data Provider:This layer communicates with database using standard ADO.Net.

 

 

Querying with EDM:

You can query EDM mainly by three ways, 1) LINQ to Entities 2) Entity SQL 3) Native SQL


 

1) LINQ to Entities: L2E query syntax is easier to learn than Entity SQL. You can use your LINQ skills for querying with EDM. Following code snippet shows how you can query with EDM created in previous step.

using (var objCtx = new SchoolDBEntities())
    {
        var schoolCourse = from cs in objCtx.Courses
                           where cs.CourseName == "Course1"
                           select cs;
        Course mathCourse = schoolCourse.FirstOrDefault<Course>();
        IList<Course> courseList = schoolCourse.ToList<Course>();
 
        string courseName = mathCourse.CourseName;

    }

 

2) Entity SQL: Another way to create a query, instead of LINQ to Entities, is by using the Entity Framework’s Object Services directly. You can create an ObjectQuery directly combined with the Entity Framework’s T-SQL-like query language, called Entity SQL, to build the query expression.



Following code snippet shows same query result as L2E query above.  

 
    //Querying with Object Services and Entity SQL
    using (var objCtx = new SchoolDBEntities())
    {
        string sqlString = "SELECT VALUE cs FROM SchoolDBEntities.Courses
                            AS cs WHERE cs.CourseName == 'Maths'";
        ObjectQuery<Course> course = objCtx.CreateQuery<Course>(sqlString);
        Course coursename1 = course.FirstOrDefault<Course>();
    }

 

 

3)Native SQL In the Entity Framework v4 new methods ExecuteFunction(), ExecuteStoreQuery() and ExecuteStoreCommand() were added to the class ObjectContext. So you can use these methods to execute Native SQL to the database as following:

 

   
    //Querying with native sql           
    using (var objCtx = new SchoolDBEntities())
        {
            //Inserting Student using ExecuteStoreCommand
            int InsertedRows = objCtx.ExecuteStoreCommand("Insert into Student(StudentName,StandardId) values('StudentName1',1)");
 
            //Fetching student using ExecuteStoreQuery
            var student = objCtx.ExecuteStoreQuery<Student>("Select * from Student where StudentName = 'StudentName1'", null).ToList();
 
        }  
   

 

 

 

 


Types of Entities in Entity Framework:

There are four types of Entities in Entity Framework 4.x,

 1) EntityObject

2) POCO

3) POCO Proxy

4) Self-Tracking Entities

Each entity can have two types of properties

1.Scalar properties

Scalar properties are properties whose actual values are contained in the entity

2.Navigation properties

Navigation properties are pointers to other related entities

 

EntityObject: By default, the ADO.NET Entity Data Model tools generate EntityObject derived entities. If you check entities created in previous step, it is of this type. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.

 

POCO (Plain Old CLR Object): POCO class is the class which doesn’t depend on any framework specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects”. The Entity Framework 4.0 enables you to use existing .net classes together with the data model without making any modifications to the existing .net classes. These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as EntityObject derived entities .


Following is a Student POCO class:

public class Student
    {
        public int StudentID { get; set; }
 
        public string StudentName{ get; set; }
 
        public Standard Standard{ get ; set; }
 
        public StudentAddress StudentAddress{ get ; set; }
 
        public IList<Course> Courses{ get; set; }
 
    }

 

POCO Proxy: POCO Proxy is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity if it meets certain requirements to enable lazy loading proxy and instant change tracking. It adds some methods at runtime to your POCO class which does instant change tracking and lazy loading stuff.
POCO entity should meet the following requirement to become POCO proxy:

1.     A custom data class must be declared with public access.

2.     A custom data class must not be sealed (NotInheritable in Visual Basic)

3.     A custom data class must not be abstract (MustInherit in Visual Basic).

4.     A custom data class must have a public or protected constructor that does not have parameters.

5.     The class cannot implement the IEntityWithChangeTracker or IEntityWithRelationships interfaces because the proxy classes implement these interfaces.

6.     The ProxyCreationEnabled option must be set to true.

7.     Each navigation property must be declared as public, virtual

 

 

Self-Tracking Entities: The EntityObject derived entities, POCO, and POCO proxy entities works well in application where the entity objects can be attached to the object context that handles change tracking on single tier. However, in n-tier application, you have to transfer entities to a tier where the object context is not available e.g. Business tier or presentation tier. So how to track changes and report those changes back to the object context? Answer is “self-tracking entities”. Starting with the .NET Framework version 4, self-tracking entities as its name suggests, can record changes to scalar, complex, and navigation properties on its own. Self-tracking entities do not depend on the Entity Framework so it can be transferred to other tier.

 

Self-Tracking entities have additional change tracking functions and it implements IObjectWithChangeTracker and INotifyPropertyChanged interface. It also mark it as DataContract to be used in WCF services.

 Entity Lifecycle:

we work on CRUD operation (Create, Read, Update, Delete), it’s important to understand entity lifecycle and how it’s being managed by EntityFramework.

 

During entity’s lifetime, each entity has an entity state based on operation performed on it via Context (ObjectContext). The entity state is an enum of type System.Data.EntityState that declares the following values:

1.     Added

2.     Deleted

3.     Modified

4.     Unchanged

5.     Detached

 

The Context not only holds the reference to all the objects retrieved from the database but also it holds the entity states and maintains modifications to the properties of the entity. This feature is known as Change Tracking.

 

The change in entity state from the Unchanged to the Modified state is the only state that’s automatically handled by the context. All other changes must be made explicitly using proper methods of ObjectContext:

 

Sr. 
ObjectContext Methods 
Description 
EntityState 
1
AddObject
Adds an entity to the context
Added
2
Attach
Attaches an entity to the context
Unchanged
3
ApplyCurrentValues
Replace currently attached entity’s scalar value with the property values of detached entity.
Modified
4
ApplyOriginalValues
It applies original database values to attached entity’s properties.
Unchanged
5
DeleteObject
Delete the object from context.
Deleted
6
AcceptAllChanges
pushes the current values of every attached entity into the original values.
Unchanged
7
ChangeState or ChangeObjectState
Change an entity from one state to another without any restrictions (except for Detached)
Based on passed state
8
Detach
Removes an entity from the context.
Detached

 
Code First development with Entity Framework 4.1

Visual Studio 2010 brought new approaches to modeling for Entity Framework 4.1.

1.     Code First

2.     Model First

3.     Database first
 

Wednesday, January 15, 2014

Event is being executed in following order

-- on load and On prerender
1.ContentPage.
2.MasterPage.
3.UsercontrolPage.
-- on unload and Init
1.UsercontrolPage.
2.MasterPage.
3.ContentPage.

PreInit event is only for content page  not for master and usercontrol

Friday, January 3, 2014

Writting and reading xml from Linq.

///writng
STVDataContext stvdb = new STVDataContext(ConfigurationManager.AppSettings["ConnectionString"].ToString());
DataTable dt = (from n in stvdb.tblCustomers select new { n.CustomerId, n.FirstName, n.PostCode, n.CreateDate }).ToADOTable();
new XElement("Employees",
from emp in dt.AsEnumerable()
orderby emp.Field<string>("FirstName") descending
select new XElement("Employee",
new XAttribute("CustomerId", emp.Field<Int64>("CustomerId")),
new XElement("FirstName", emp.Field<string>("FirstName")),
new XElement("PostCode", emp.Field<string>("PostCode")),
new XElement("CreateDate", emp.Field<DateTime>("CreateDate").ToString("MM/dd/yyyy"))
)).Save(("D:\\linqxml.xml"));
///reading
XDocument xdoc = XDocument.Load("D:\\linqxml.xml");
var countires = from country in xdoc.Descendants("Employees").Elements("Employee").Attributes("CustomerId")
select country.Value;

Bind or unbind event to control using jquery

We can bind or unbind events to controls using JQuery.

The JQuery method .on() we will use for binding events and method .off() we will use for unbind the events.



$("#btnClickMe").on("click", function () {

alert("click event added using JQuery");

});

.on() is the JQuery method to bind events,

In the above example we have passed two parameters to the method .on(),

one is event to be perforemed and another is the function to perform action when event is raised.

i.e. "click" is the argument represents the event followed by function which specifies the actions to be performed.

Bind multiple events using .on() method

We can bind multiple events using .on() method, Suppose when mouse enter or leave a div you want to fire an event,

both the events we can write at a time using .on() method.

<script language="javascript">

$("#divSample").on("mouseover mouseleave", function () {

$(this).fadeOut(1000, function () { $(this).fadeIn(); });

});

</script>







Bind events using .one() method

If you want to fire a particular event only once then use the method .one() to bind the event,

then the event fires only once. The parameters and syntax for the method .one() is same like for the method .on()

<script language="javascript">

$("#divonce").one("mouseover mouseleave", function () {

$(this).fadeOut(1000, function () { $(this).fadeIn(); });

});

</script>

UnBind events using .off() method

If you want to unbind a particular event use .off() method. In the below example click on "Bind" button to bind the

mouserover event to div to fadein fadeout and click "UnBind" to unbind the mouseover event

<script language="javascript">

$("#btnbind").on("click", function () {

$("#divbindunbind").on("mouseover", function () {

$(this).fadeOut(1000, function () { $(this).fadeIn(); });

});

});

$("#btnunbind").on("click", function () {

$("#divbindunbind").off("mouseover");

});

</script>

Thursday, January 2, 2014

Ajax Event..

Events

1:Browser Events
2:Document Loading
3:Event Handler Attachment
4:Event Object
5:Form Events
6:Keyboard Events
7:Mouse Events

1:Browser Events
.error()
Bind an event handler to the “error” JavaScript event.
.resize()
Bind an event handler to the “resize” JavaScript event, or trigger that event on an element.
.scroll()
Bind an event handler to the “scroll” JavaScript event, or trigger that event on an element.
2:Document Loading
.load()
Bind an event handler to the “load” JavaScript event.
.ready()
Specify a function to execute when the DOM is fully loaded.
.unload()
Bind an event handler to the “unload” JavaScript event

3:Event Handler Attachment
.bind()
Attach a handler to an event for the elements.
.delegate()
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
.die()
Remove event handlers previously attached using .live() from the elements.
jQuery.proxy()
Takes a function and returns a new one that will always have a particular context.
.live()
Attach an event handler for all elements which match the current selector, now and in the future.
 .off()
Remove an event handler.
.on()
Attach an event handler function for one or more events to the selected elements.
.one()
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
.trigger()
Execute all handlers and behaviors attached to the matched elements for the given event type.
.triggerHandler()
Execute all handlers attached to an element for an event.
.unbind()
Remove a previously-attached event handler from the elements.
.undelegate()
Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.

4:Event Object
event.currentTarget
The current DOM element within the event bubbling phase.
event.data
An optional object of data passed to an event method when the current executing handler is bound.
event.delegateTarget
The element where the currently-called jQuery event handler was attached.
event.isDefaultPrevented()
Returns whether event.preventDefault() was ever called on this event object.
event.isImmediatePropagationStopped()
Returns whether event.stopImmediatePropagation() was ever called on this event object.
event.isPropagationStopped()
Returns whether event.stopPropagation() was ever called on this event object.
event.metaKey
Indicates whether the META key was pressed when the event fired.
event.namespace
The namespace specified when the event was triggered.
event.pageX
The mouse position relative to the left edge of the document.
event.pageY
The mouse position relative to the top edge of the document.
event.preventDefault()
If this method is called, the default action of the event will not be triggered.
event.relatedTarget
The other DOM element involved in the event, if any.
event.result
The last value returned by an event handler that was triggered by this event, unless the value was undefined.
event.stopImmediatePropagation()
Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
event.stopPropagation()
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
event.target
The DOM element that initiated the event.
event.timeStamp
The difference in milliseconds between the time the browser created the event and January 1, 1970.
event.type
Describes the nature of the event.
event.which
For key or mouse events, this property indicates the specific key or button that was pressed.

5:Form event

.blur()
Bind an event handler to the “blur” JavaScript event, or trigger that event on an element.
.change()
Bind an event handler to the “change” JavaScript event, or trigger that event on an element.
.focus()
Bind an event handler to the “focus” JavaScript event, or trigger that event on an element.
.focusin()
Bind an event handler to the “focusin” event.
.select()
Bind an event handler to the “select” JavaScript event, or trigger that event on an element.
.submit()
Bind an event handler to the “submit” JavaScript event, or trigger that event on an element

6:Keyboard Events

.focusout()
Bind an event handler to the “focusout” JavaScript event.
.keydown()
Bind an event handler to the “keydown” JavaScript event, or trigger that event on an element.
.keypress()
Bind an event handler to the “keypress” JavaScript event, or trigger that event on an element.
.keyup()
Bind an event handler to the “keyup” JavaScript event, or trigger that event on an element.

7:Mouse Event
.click()
Bind an event handler to the “click” JavaScript event, or trigger that event on an element.
.dblclick()
Bind an event handler to the “dblclick” JavaScript event, or trigger that event on an element.
.focusout()
Bind an event handler to the “focusout” JavaScript event.
.hover()
Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
.mousedown()
Bind an event handler to the “mousedown” JavaScript event, or trigger that event on an element.
.mouseenter()
Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
.mouseleave()
Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.
.mousemove()
Bind an event handler to the “mousemove” JavaScript event, or trigger that event on an element.
.mouseout()
Bind an event handler to the “mouseout” JavaScript event, or trigger that event on an element.
.mouseover()
Bind an event handler to the “mouseover” JavaScript event, or trigger that event on an element.
.mouseup()
Bind an event handler to the “mouseup” JavaScript event, or trigger that event on an element.
.toggle()
Bind two or more handlers to the matched elements, to be executed on alternate clicks.

Wednesday, January 1, 2014

Global Ajax Event Handlers

These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery.ajaxSetup() is true, which it is by default.

Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.


.ajaxComplete()
Register a handler to be called when Ajax requests complete. This is an AjaxEvent.
.ajaxError()
Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
.ajaxSend()
Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.
.ajaxStart()
Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
.ajaxStop()
Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
.ajaxSuccess()
Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.



example:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script type="text/javascript" >
      $(document).ready(function () {
          $(document).ajaxSend(function () {
              alert(1);
              $(".log").text("Triggered ajaxSend handler.hhbfhgrthgrt");

          });
          $(".trigger").click(function () {
              alert(2);
              $(".result").load("ajax/test.html");

          });
          $(document).ajaxStart(function () {
              alert(3);
              $(".log").text("Triggered ajaxStart handler.");

          });

          $(document).ajaxSend(function (event, jqxhr, settings) {
              alert(4);            
              if (settings.url == "ajax1/test.html") {
                 
                  $(".log").text("Triggered ajaxSend handler.");

              }

          });
           $(document).ajaxStop(function () {
              alert(5);
              $(".log").text("Triggered ajaxStop handler.");

          });
          $(document).ajaxSuccess(function () {
              alert(6);
              $(".log").text("Triggered ajaxSuccess handler.");

          });
          $(document).ajaxComplete(function () {
              alert(7);
              $(".log").text("Triggered ajaxComplete handler.");

          });





      });
</script>


 <div class="trigger">Trigger</div>

<div class="result"></div>

<br />

<br />
<br /><br />
<br />
<br />
<div class="log"></div>