Thursday, 18 April 2013

How to Bind XML Data in WPF DataGrid using Dataset and List?

How to Bind XML Data in WPF DataGrid using Dataset and List?

In this tutorial I will try to bind XML data in WPF DataGrid by using Dataset and List. Lets say you have XML file from which you have to read data and show in the WPF datagrid. You can do this task by two methods.

Method 1: Using Dataset

In this approach, I wll read XML file into a dataset and then make a dataview from that dataset and then I will assign that dataview to datagrid. Following is the simple C# code for this.

 private void BindGridUsingDataSet()
 {
     string sampleXmlFile = @"C:\MyWPFApp\MyXMLFile.xml";
     DataSet dataSet = new DataSet();
     dataSet.ReadXml(sampleXmlFile );     
     DataView dataView = new DataView(dataSet.Tables[0]);
     dataGrid1.ItemsSource = dataView;
 }


Method 2: Using List

I will load XML file into XElement and then I will go on adding all the elements into list and finally I will bind the list to the datagrid. Have a look at following C# code for this.

class college
{
   public string name { get; set; }
   public string roll { get; set; }
   public string marks { get; set; }
}

private void BindGridUsingList()
{
     string sampleXmlFile = @"C:\MyWPFApp\MyXMLFile.xml";
     XElement xElement = XElement.Load(sampleXmlFile);
     IEnumerable<XElement> students = xElement.Elements();
     List<college> lstCollege = new List<college>();
     // Read the entire XML
     foreach (var student in students)
     {
          lstCollege.Add(new college {name=student.Element("name").Value,roll=student.Element("roll").Value,marks=student.Element("marks").Value});
     }    
     dataGrid1.ItemsSource = lstCollege;
}


Here is the code of datagrid in XAML file

<DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="276,21,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" >
    <DataGrid.Columns>
         <DataGridTextColumn Header="name" Binding="{ Binding  name}" />
         <DataGridTextColumn Header="roll" Binding="{ Binding  roll}" />
         <DataGridTextColumn Header="marks" Binding="{ Binding  marks}" />
    </DataGrid.Columns>
</DataGrid>


Here is the sample XML file

<college>
  <student>
      <name>ABC</name>
      <role>12</role>
      <marks>90</marks>
  </student>
  <student>
     <name>XYZ</name>
     <role>13</role>
     <marks>98</marks>
  </student>
</college>

Wednesday, 17 April 2013

Object Relational Mapping: Frameworks and Advantages

Object Relational Mapping: Frameworks and Advantages

ORM (Object Relational Mapping) wraps your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.

There are a lot of frameworks available for implementing ORM (Object Relational Mapping) in different programming languages.

Based on abstraction, ORM (Object Relational Mapping) manages the mapping details between a set of objects and underlying relational databases, XML repositories or other data sources and sinks, while simultaneously hiding the often changing details of related interfaces from developers and the code they create.

ORM (Object Relational Mapping) hides and encapsulates change in the data source itself, so that when data sources or their APIs change, only ORM needs to change to keep up—not the applications that use ORM to insulate themselves from this kind of effort. This capacity lets developers take advantage of new classes as they become available and also makes it easy to extend ORM-based applications. In many cases, ORM changes can incorporate new technology and capability without requiring changes to the code for related applications.

Example of ORM (Object Relational Mapping)

Lets say you fire following SQL query using traditional way:

String sql = "SELECT ... FROM persons WHERE id = 10";
DbCommand cmd = new DbCommand(connection, sql);
Result res = cmd.Execute();
String name = res[0]["FIRST_NAME"];

ORM enables you to write same logic on the objects and classes like this:

Person p = repository.GetPerson(10);
String name = p.FirstName;

Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:

Person p = Person.Get(10);

Some also implement complex query systems, so you could do this:

Person p = Person.Get(Person.Properties.Id == 10);

Advantages of ORM (Object Relational Mapping)

1. You can hide the SQL away from your logic code.

2. ORM has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to "get me all persons edited the last 24 hours" might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.

3. You can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the "plumbing" necessary to talk to the database.

ORM (Object Relational Mapping) Frameworks:

In .NET, ADO.NET Entity Framework is the widely used ORM Framework. There is a long list of ORM frameworks supported in different programming languages. You can read this list from wikipedia.

Commonly Asked WPF Interview Questions and Answers (Part 1)

Commonly Asked WPF Interview Questions and Answers (Part 1)

In this aritcle on "Commonly Asked WPF Interview Questions and Answers (Part 1)", I will focus on very simple and basic WPF interview questions which a WPF developer should know. These WPF interview questions are based on general introduction of WPF, XAML, MVVM Pattern, Comparison of WPF and Silverlight, Layout Panels in WPF and WPF UserControls / CustomControls.

1. What is WPF?

The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

2. What is XAML?

Extensible Application Markup Language, or XAML (pronounced "zammel"), is an XML-based markup language developed by Microsoft. XAML is the language behind the visual presentation of an application that you develop in Microsoft Expression Blend, just as HTML is the language behind the visual presentation of a Web page. Creating an application in Expression Blend means writing XAML code, either by hand or visually by working in the Design view of Expression Blend.

3. What is MVVM Pattren?

Model-View-ViewModel (MVVM) pattern splits the User Interface code into 3 conceptual parts - Model, View and ViewModel.

Model is a set of classes representing the data coming from the services or the database.

View is the code corresponding to the visual representation of the data the way it is seen and interacted with by the user.

ViewModel serves as the glue between the View and the Model. It wraps the data from the Model and makes it friendly for being presented and modified by the view. ViewModel also controls the View's interactions with the rest of the application

4. What is the difference between MVVM and MVC patterns?

MVVM Model-View ViewModel is similar to MVC, Model-View Controller.

The controller is replaced with a View Model. The View Model sits below the UI layer. The View Model exposes the data and command objects that the view needs. You could think of this as a container object that view goes to to get its data and actions from. The View Model pulls its data from the model.

5. What are the similarities and differences between WPF and Silverlight?

Similarities between Silverlight and WPF

1. Silverlight and WPF both use XAML.
2. Silverlight and WPF share same syntax, code and libraries.


Difference between WPF and Silverlight

1. WPF  is tool for writing full-featured desktop applications that run on Windows while Silverlight is for web application.

2. WPF competes with Windows Forms only for writing desktop applications while Silverlight competes with Flash, Java web apps etc.

6. What is the need of layout panels in WPF?

Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich set built-in layout panels that help you to avoid the common pitfalls.

7. What are the different types of layout panels in WPF?

There are mainly 5 types of layout panels in WPF. These are:

Grid Panel
Stack Panel
Dock Panel
Wrap Panel
Canvas Panel


8. How to create a User Control and then how to use it in a WPF application?

User Controls are commonly used in a WPF application. So you should know this concept and you should be able to write a simple program to show how usercontrols are created and used in WPF application. I am sharing a link which created and uses usercontrol in very simple manner. Have a look:

9. What is the difference between UserControl and CustomControl in WPF?

UserControl (Composition)

Composes multiple existing controls into a reusable "group"
Consists of a XAML and a code behind file
Cannot be styled/templated
Derives from UserControl


CustomControl (Extending an existing control)

Extends an existing control with additional features
Consists of a code file and a default style in Themes/Generic.xaml
Can be styled/templated
The best approach to build a control library


Update: For Part 2 of this post, click here.

How to create Gridview Hierarchy (Expandable Grids) or Child Grid into Parent Grid in .NET?

How to create Gridview Hierarchy (Expandable Grids) or Child Grid into Parent Grid in .NET?
 
Gridview is used to display data in a tabular form in ASP.NET and C#? To be more accurate Gridview is displays linear data. But sometimes you need to show hierarchy of data in the grid.
 
For example, you show parent records in each row of the grid and expanding each row displays child data. In this case you have to show a child grid under the parent row of the parent grid. You should be able to hide and show the child grid.
 
I had this requirement in one of my .NET project. I googled a lot and found some informative articles on telerik, codeproject and devexpress. I thought I should share it with you.

Expandable Grid Links
 
1. Telerik:
 
 
2. Codeproject
 
 
3. DevEx
 
 
Other Links
 
 

Tuesday, 16 April 2013

Difference between Singleton and Factory Design Patterns: Purpose and Implementation

Difference between Singleton and Factory Design Patterns: Purpose and Implementation

In this article we will try to understand difference between singleton and factory design patterns. What is the need of these design patterns and how do we implement singleton and factory design patterns in real life? Lets start with singleton design patterns.

Singleton design pattern is a design pattern that restricts the instantiation of a class to one object. The Singleton pattern ensures that only one instance of the class exists and  provides a global point for accessing it.

What is the purpose of singleton design pattern?

The purpose of the singleton design pattern is where you want all calls to go through the same instance. Singleton design pattern ensures that no matter how many times a client (or multiple clients) ask for an instance of this specific Type to be created (instantiated) for them, they will always get the exact same one and only one instance of the type. It guarantees that only one instance of the type can ever be instantiated.

This is useful when exactly one object is needed to coordinate actions across the system. There is a Type which is managing a 200 MB in memory cached copy of some data structure - you only want one copy to exist.

How to implement singleton design patterns?

Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.

The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

For example: You may like to use this design pattern to implement Cache of an application. How do we implement the singleton Design Pattern? The easiest way is to have a static variable storing the refence of the shared instance and keeping the constructor(s) private so that the users can't call the new operator to create instances. Such an implementation provides a static public method to the consumers to get the shared instance.

class SingletonImpl{
...
private static singletonInstance = null;
...
private SingletonImpl(){
...
}
public synchronized static getSingleton(){
if(singletonInstance == null) singletonInstance = new SingletonImpl();
return singletonInstance;}
...
}

Limitation of singleton design patterns

Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.

Read in detail on DZone

What is Factory Design Pattern?

The purpose of the Factory method is to provide a new instance of the object whenever the Factory method is being called. When you are dealing with lot of different interrelated classes, it is better to use the Factory to streamline the object creational.The Factory pattern defines an interface for creating objects (no limitation on how many) and usually abstracts the control of which class to instantiate.

What is the purpose of factory design pattern?

The Factory design pattern is used to return an instance of one of several possible classes depending on what parameters are actually passed by the consumer.

How to implement factory design patterns?

We normally use inheritance to implement this. Suppose we have a base class named 'Base' and two chilldren of this base class named 'Child1' and 'Child2'. Now the Factory class which is the decision making body based on what the consumer provides decides whether to return an instance of the class 'Child1' or 'Child2'. We can easily set the return type of the method of the Factory (which is exposed to the consumers) as the Base Class type and then the method can easily return instances of either of the two children.

class BaseClass {
...
}
class Child1 extends BaseClass{
...
}
class Child2 extends BaseClass{
...
}
public class FactoryImpl{
...
public BaseClass getChild(String parameter){
...
if(parameter.equals("Child1")) //... sample cond impl
return new Child1();
else return new Child2();
}
...
}


Read Factory Pattern in detail on DZone and ASPAlliance

Why to use Entity Framework in .NET? Advantages of Entity Framework

Why to use Entity Framework in .NET? Advantages of Entity Framework
 
Entity Framework is an Object Relational Mapping (ORM) Framework for the .NET Framework. Entity Framework  returns the data in your database as an object.
 
Entity Framework is actually written on top of ADO.NET, meaning under this framework, we are still using ADO.NET. So we cannot say that Entity Framework is a replacement of ADO.NET.
 
Entity Framework basically generates business objects and entities according to the database tables.
 
Advantages of Entity Framework: There are lot of reason why should you use entity framework over LinqToSql and ADO.NET.
 
1. Database performance is improved. Updating your EDM based on your DB changes would take less time rather than the conventional methods. Database operations like select, insert, update, delete will work faster as you don't have to hit database again and again as you would be working with objects not with database tables.
 
2. Entity Framework performing basic CRUD (Create, Read, Update, Delete) operations. So most of the time you don't have to write any SQL yourself. When you make any changes to the object, the ORM will usually detect this, and mark the object as 'modified'. When you save all the changes in your ORM to the database, the ORM will automatically generate insert/update/delete statements, based on what you did with the objects.
 
3. Entity Framework works on databases other than Microsoft SQL Server, like Oracle, MySQL etc. While Linq is limited to MS SQL Server. It is easy to add support for another database (like Oracle) as we are programming against a model.
 
4. Easily managing "1 to 1", "1 to many", and "many to many" relationships.
 
5. Ability to have inheritance relationships between entities.

Monday, 15 April 2013

What is the use of persistence layer in any application architecture?

What is the use of persistence layer in any application architecture?
 
Recently, I fell in a .NET project whose architecture was prepared by one of our senior .NET person who is architect here in .NET. I was confused with pesistence layer he had created in the application architecture. I searched it on google but found on consolidated answers from anywhere. At last I came to get help from Stackoverflow .NET experts. I asked following question on stackoverflow and got valuable responses.
 
My question on persistence layer architecture:
 
I have to create an application in which I am asked to create an persistence layer in the application. The application is in .net. I have created business layer and presentation layer but I don't know how and why to create persistence layer.
 
I googled and came to know that persistence layer is used for storing and retrieving data usually from a database.
 
Can anybody explain in detail?
 
Responses I got:
 
Davide Piras Response which I accepted later on:
 
The reason for you to build a DAL ( Data Access Layer ) or any other kind of intermediate layer between database engine and Business / Application logic, is that by adding this layer in the between you isolate the rest / upper layers of your application from the specific database engine / technology you are using right now.
 
This has several advantages, like easier migration to other storage engines, better encapsulation of database logic in a single layer ( easier to replace or modify later depending on how well you have designed your cross-layer interfaces etc...)
 
See my most rated answer here, it is an example about ASP.NET MVC and EF but the structuring of solution and projects is actually technology independent: MVC3 and Entity Framework
 
Also read some articles to better understand this matter, for example: http://www.developerfusion.com/article/84492/net-and-data-persistence/
 
Renan's Response
 
If you're not saving your data somewhere, it won't be there again when your app is opened again. You can save it to a database as you said (SQL, Oracle, PostGRE etc.), or directly to disk (serializing in binary format, or plain text etc.).
 
Using a layer to do that is a good practice. It reduces coupling (i.e. spaghetti code), and makes maintenance much easier.
 
I suggest you read about Hibernate and it's .NET cousin, NHibe
 
Kenneth Garza's Response:
 
Persistance layer otherwise known as a Data Access Layer or other terminology.
 
It seperates the guts of getting and saving the data from the business layer. The reason you do this is so your business logic (the part of the application that does the heavy lifting for your data manipulation) is not tied to a specific type of data source.
 
The data layer will need to be written to be database specific. So if you're using MySQL to access all your data then you will write the dataLayer for that use.
 
If at some point you decide to move to MongoDB, then instead of rewriting your entire application. You can rewrite just the data access parts to get the data from MongoDB. Since the business logic doesnt care how you get the data, only that you do, it and the Presenation layer can remain intact.
 
Hope this helps.
 
Belogix Response:
 
In very simple terms a persistence layer is a way to SAVE and RETRIEVE items that your application uses.
 
A simple example is you have a class that represents a person (name, age and gender). While your application is running this is held in memory. But, say you want that information available if you close and open your application again. Well, you need some way to SAVE that person and then later on RETRIEVE it again. This is where a persistence layer comes in and will write your person somewhere "permanent".
 
That could be a database, a flat file, registry depending on the life-time and requirements etc.
 
In your persistence layers you will perform CRUD (Create, Read, Update, Delete) operations. Often against a database so you would Create a new person (Fred Bloggs). Say they change their name another user of your system might Read the record and change to Fred Miggins and Update the database. That customer then leaves the country so you Delete them.
 
Please refer to stackoverflow page for details.