Thursday, 18 April 2013

WPF Error: Why double clicking my contorls does not generate events in WPF?

WPF Error: Why double clicking my contorls does not generate events in WPF?
 
While working with WPF application, I created a button and when I double clicked it to generate the event of the button, I found following error.
 
To generate an event handler the class 'MainWindow', specified by the x:Class or x:Subclass attribute, must be the first class in the file. Move the class code so that it is the first class in the file and try again.
 
How did I resolve this error:
 
I looked into my xaml.cs file, the structure of that file was like this:
 
namespace WPFApplication1
{
   class MyNewClass
   {
   }
   public partial class MainWindow : Window
   {
     public MainWindow()
     {
       InitializeComponent();
     }
   }
}
 
I had created my new class "MyNewClass" above the declaration of the default MainWindow class. Due to this, double clicking the button was not able to generate the event automatically. When I cut this class and pasted below the MainWindow class, everything went fine. Like below:
 
namespace WPFApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    class MyNewClass
    {
    }
}
 
Well, to be honest, I don't know the exact reason for this, but I thought sharing this situation might help others and if any of you know the exact reason for this, please share it.

How to Get Property Names using Reflection in C#?

How to Get Property Names using Reflection in C#?

In this article, I will show you how you can get the name of all properties using Reflection in C# at runtime.

To get the name of properties of a specific type use Type.GetProperties method. This method returns the array of PropertyInfo object. From this object you can find the name of property through PropertyInfo.Name property.

To get properties information of class. First of all add the following namespace in your cs page.

using System.Reflection;

For example, we have the following class

class MyTestClass
{
  public int A { get; set; }
  public string B { get; set; }          
}

Now write  the following code to get the property name of above class

MyTestClass obj = new MyTestClass();
           
//Get the type instance
Type t = obj.GetType();
           
//Get all properties on MyTestClass
PropertyInfo[] propinfo = t.GetProperties();

foreach (PropertyInfo prop in propinfo)
{
  //Write the name of the property
  Console.WriteLine(prop.Name);
}

Hope you would have enjoyed this simple article on getting the names of properties of C# class using reflections.

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