Saturday, 27 April 2013

Difference between WPF and Window Forms in .NET

Difference between WPF and Window Forms in .NET

I have been asked the difference between WPF and Window Forms. my times by my juniors whenever I suggest them to learn WPF. So, today I am trying to clear this doubt and make my opinions clear about this.

There are a lot of differences between WPF and Window Forms. WinForms is past and WPF is the latest technology equipped with advanced features which Window Forms lack. WPF supports UI, media, documents, hardware acceleration, vector graphics, scalability to different form factors, interactive data visualization, and superior content readability. Lets have a look on the features and benefits that WPF provides over the Window Forms.

1. WPF is a Vector Graphics based UI Presentation Layer

WPF is a vector graphics based UI presentation layer where WinForms is not. By being vector based, it allows the presentation layer to smoothly scale UI elements to any size without distortion.

2. Enhanced Custom Controls Support

WPF is also a composable presentation system, which means that pretty much any UI element can be made up of any other UI element. This allows you to easily build up complex UI elements from simpler ones.

3. Enhanced DataBinding Support

WPF is also fully databinding aware, which means that you can bind any property of a UI element to a .NET object (or a property/method of an object), a property of another UI element, or data. Yes, WinForms supports databinding but in a much more limited way.

4. WPF is "skinable" or "themeable"

WPF is "skinable" or "themeable", which means that as a developer you can use a list box because those are the behaviors you need but someone can "skin" it to look like something completely different.

Think of a list box of images. You want the content to actually be the image but you still want list box behaviors. This is completely trivial to do in WPF by simply using a listbox and changing the content presentation to contain an image rather than text.
 
5. Supports Window Forms

WPF does support Windows Forms and Windows Forms can be included in WPF project by adding dlls of Window Forms.

Conclusion:

WPF is a replacement for WinForms. What Window Forms can do, WPF can, but what WPF can do, Window Forms cannot do all.

Thursday, 25 April 2013

Types of Entities in Entity Framework: EntityObject, POCO, POCO Proxy and Self-Tracking Entities


Types of Entities in Entity Framework: EntityObject, POCO, POCO Proxy and Self-Tracking Entities

There are four types of Entities in Entity Framework: 

1) EntityObject 
2) POCO (Plain Old CLR Object)
3) POCO Proxy 
4) Self-Tracking Entities

EntityObject

By default, the ADO.NET Entity Data Model tools generate EntityObject derived entities. 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.

POCO (Plain Old CLR Object)

POCO class is the class which doesn’t depend on any framework unlike EntityObject specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects”. The Entity Framework 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.

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 (Not Inheritable in Visual Basic)
3. A custom data class must not be abstract (Must Inherit 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

Difference between POCO and POCO Proxy Classes

Main difference between POCO and POCO Proxy lies in save changes mechanism. POCO entities use Snapshot mechanism. So before saving changes POCO entities, you must use DetechChanges method of ObjectContext to synchronize data with ObjectStateManager. Whereas POCO Proxy entities use instant change tracking. It synchronize with ObjectStateManager as soon as something changes in the POCO Proxy entity. So it’s more efficient than snapshot mechanism and you don’t have to use DetechChanges method of ObjectContext. Thus POCO Proxy has a same functionality as EntityObject.

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”. 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.

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX play a vital role and you must understand the purpose of these. Context contains all the logic for interacting with database and Entities represent database tables. Entites region contain public partial classes and public properties. Lets discuss it in detail:

When you create any EDMX file, follwing files are generated with it.

Model1.edmx
Model1.tt
Model1.Context.tt
Model1.Designer.cs
Model1.edxm.diagram
Model1.Designer.cs

Automatic code is generated in this file which contains context and entities if the "Code Genereation Strategy" is set to Default from None.

Also some points to note for this file

1. Manual changes to this file may cause unexpected behavior in your application.
2. Manual changes to this file will be overwritten if the code is regenerated.


Contexts and Entities in Model1.designer.cs

ObjectContext

If you open Model1.designer.cs, you can see two main regions, Contexts and Entities. expand contexts region. You can see partial class with suffix ‘entities’ and derived from ObjectContext class.

This class represents EntityContainer which you can see from XML view of Model1.edmx or from EDM property window. You can call this as context class.

This class is the primary class for interacting with entity objects and database. An instance of the ObjectContext class encapsulates the connection to the database, metadata that describes the model, and an ObjectStateManager object that tracks objects during create, update, and delete operations.

ObjectSet

Each EntitySet in context class is a type of ObjectSet<> that wraps the entity. e.g. ObjectSet.

EntityType

If you expand ‘Entities’ region, you can see many partial classes that are derived from EntityObject. This classes are EntityTypes of you model.

EntityType is a datatype in the model. You can see each EntityType for your conceptual model in XML. If you expand EntityType node in XML, you can see each properties and its type and other info.

EntityContainer

EntityContainer is a wrapper for EntitySets and AssociationSets. It is critical entry point for querying the model.

EntitySet

EntitySet is a container for EntityType. It is set of same entitytype. You can think it like db table.

AssociationSet

AssociationSet defines the relation between each EntitySet.

Model1.Context.tt is a context template file and Model1.tt is entities template file. 

Model1.tt and Model1.Context.tt templates, generate model entities and context. 

Model1.Context.tt: It produces a strongly typed ObjectContext for the Model1.edmx

Model1.tt: It is responsible for generating a file for each EntityType and ComplexType in the Model1.Context.tt.

Wednesday, 24 April 2013

How to convert an XML document into String in C#?

How to convert an XML document into String in C#?
 
Sometimes we come into the need where we have an XML file and we have to save that file in form of C# string. Well, converting XML document in string in C# is very easy. I will use XDocument class to do this job. With following steps you can easily do this with few lines of code in C#?
 
Step 1: Include namespace System.Xml.Linq.
 
using System.Xml.Linq;
 
Step 2: Load XML file in XDocument using following line of C# code.
 
var xDocument = XDocument.Load(@"C:\MyXMLFilePath.xml");
 
Step 3: Convert the xml into string
 
string xml = xDocument.ToString();
 
Now you can use this xml string wherever required.

Scaler and Navigation Properties in ADO.NET Entity Framework


Scaler and Navigation Properties in ADO.NET Entity Framework

Entities in ADO.NET Entity Framework can have two types of properties, Scalar properties and Navigation properties. 

Scalar Properties: Scalar properties are properties whose actual values are contained in the entity. 
Navigation Properties: Navigation properties are pointers to other related entities. Basically it is equivalent to a foreign key relationship in a database. 

Example of Scaler and Navigation Properties:

I will take an example here to make my defination more clear. Suppose there is Student table in database which has columns like StudentID, StudentName and StandardID. There is another table Standard which has StandardID, StandardName columns. Here StandardID is the forieng key. Now lets create and EDMX from these two tables. EDMX will have two entities Student and Standard which will look like following:

EDMX Entity of Student

Student              --Entity Name
-----------
StudentID          --Scaler Property
StudentName   --Scaler Property
StandardID       --Scaler Property
-----------
Standard           --Navigation Property

EDMX Entity of Standard

Standard               --Entity Name
-----------
StandardID           --Scaler Property
StandardName    --Scaler Property
-----------

Student entity has scalar properties e.g. StudentId, StudentName, StandardID. These correspond with the Student table columns.  

The Student has Standard property as navigation property that will enable application to navigate from a Student to related Standard entity. 

Modelling Approaches for Entity Framework: Database First, Model First, Code First


Modelling Approaches for Entity Framework: Database First, Model First, Code First

While working with ADO.NET Entity Framework, you have 3 types of modelling approaches which are:

1. Database First
2. Model First
3. Code First

Lets discuss these Entity Framework modelling approaches in detail.

1. Database First Modelling Approach

When you generate EDMX from existing database, then it is a Database First approach. So in Database First approach, when you add ADO.NET Entity Data Model, you should select ‘Generate from database’ instead of ‘Empty Model’.

2. Model First Modelling Approach

In Model First approach, you create Entities, Relationships, and Inheritance hierarchies directly on the design surface of EDMX. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’ instead of ‘Generate from database’.

After creating required entities, associations and inheritance on design surface of the empty model, you can use designer’s context menu option ‘Generate database from model’. It will not generate new database from model. It will only give you DDL to execute in existing database and it is up to you to execute this DDL.

3. Code First Modelling Approach

In Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles, prefer to begin by coding their classes first and then generating the database required to persist their data.  

DbContext and DbSet: There are two new types introduced for Code First approach, DbContext and DbSet. DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model in Code First approach.

Tuesday, 23 April 2013

How to show value of attributes of child nodes of an element in C#?

How to show value of attributes of child nodes of an element in C#?
 
Lets say you have following XML and you have to fetch IDs of Element tags which are under Segments/Segment/Elements. In this case you have to use SelectNodes method to reach upto desired nodes and then take it to the XMLNodeList. Iterate the list check its child nodes and get the attributes of child nodes. I think below code can clear what I am trying to say.
 
My XML File
 
<?xml version="1.0" encoding="utf-8"?>
    <Segments>
        <Segment ID="AAA">
            <Elements>
                <Element ID ="11" />
                <Element ID ="22" El/>
                <Element ID ="33" />
            </Elements>
         </Segment>
    </Segments> 
  
My C# code
 
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(MyXMLFileLocation);
XmlNodeList xnList = xmlDocument.SelectNodes(/Segments/Segment[@ID='AAA']/Elements);
foreach (XmlNode xn in xnList)
{
    if (xn.HasChildNodes)
    {
        foreach (XmlNode childNode in xn.ChildNodes)
        {
            Console.Writeline(childNode.Attributes["ID"].Value);
         }
    } 
}