Monday, 22 April 2013

How to Select XML Nodes by Attribute Value using XPath expression in C#?

How to Select XML Nodes by Attribute Value using XPath expression in C#?
 
This example shows how to select nodes from XML document by attribute value. Use method XmlNode.SelectNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.
 
<Names>
    <Name type="M">John</Name>
    <Name type="F">Susan</Name>
    <Name type="M">David</Name>
</Names>
 
To get all name nodes use XPath expression /Names/Name. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M'].
 
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXMLDocPath);  //Path of XML file
XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");

foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

 
The output is:
John
David

How to get child nodes of an element in an XML in a WPF application?

How to get child nodes of an element in an XML in a WPF application? 
 
While parsing an XML in a WPF application, I fell in a need to fetch the child nodes of an element. I put the question on stackoverflow and got many responses but at last I was able to answer that question myself.
 
Lets consider the problem:
 
Suppose I have following XML
 
<Loop Name="MasterData">
  <Loop Name="SlaveData">
    <Segment Name="AAA">
      <Node1>hello</Node1>
      <Node2>john</Node2>
      <Node3>hi</Node3>
      <Node4>marry</Node4>
    </Segment>
    <Segment Name="BBB">
      <Node1>00</Node1>
      <Node2> </Node2>
      <Node3>00</Node3>
      <Node4> </Node4>
    </Segment>
   </Loop>
</Loop>  
 
Now I have to get the values of Node1, Node2, Node3, Node4 ie, hello, john, hi, marry in a list whose parent element is Segment with Name as "AAA". So first of all I will try to reach at segment with name attribute as "AAA" and then I will check whether that elements has child nodes or not. If that segment element contains child nodes, then I will fetch the innertext of all the child nodes.
 
Below is the C# code for fetching the child nodes of an element
 
public static void GetChildElements()
{
    List<string> lstChildElements = new List<string>();
   XmlDocument xmlDocument = new XmlDocument();
   xmlDocument.Load(XMLFileLocation);

   XmlNodeList xnList = xmlDocument.SelectNodes("/Loop/Loop/Segment[@Name='AAA']");
   foreach (XmlNode xn in xnList)
   {
     if (xn.HasChildNodes)
     {
       foreach (XmlNode childNode in xn.ChildNodes)
       {
          lstISAElements.Add(childNode.InnerText.ToString());
       }
     }
   }
   foreach (string childElement in lstChildElements)
   {
     Console.WriteLine(childElement);
   }
     
}

How to store and get database connection string from app.config file in WPF application in VS2012?


How to store and get database connection string from app.config file in WPF application in VS2012?

Storing and getting a database connection string from app.config is a very common practice used in every WPF application. I will make you understand this concept in following 3 steps:

Step 1: Store database connection string in your WPF app.config file like below:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="MyConnectionString"
              connectionString="Data Source=myComputerName\sqlexpress;Initial  Catalog=MY_DB;User ID=user;Password=password/>
  </connectionStrings>
</configuration>


Step 2: Now include System.Configuration namespace in your application. But note that you also have to add reference of System.Configuration file in case if you are using Visual Studio 2012. Go to references and add System.Configuration namespace from there.

using System.Configuration;

Step 3: Add following line to get the database connection string in your class file. I have used ConfigurationManager to get the database connection string from app.config.

var connectionString=ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

This concludes the article and hope you have understood the concept of how to store and get database connection string from app.config file in WPF application in VS2012?

Friday, 19 April 2013

WPF DataGrid Tutorials: DataGrid Properties and Features

WPF DataGrid Tutorials: DataGrid Properties and Features

WPF DataGrid has a lot of amazing features and properties which you can implement with ease in your application. WPF DataGrid provides a lot of properties which you can set to get your desired look and feel.

To show a basic WPF datagrid, just drop a DataGrid control to your view and bind the ItemsSource to a collection of data objects. The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the public properties of your data objects.

<DataGrid ItemsSource="{Binding Customers}"  AutoGenerateColumns="False" />

The ItemSource property of DataGrid is the key to data binding. You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects.

WPF DataGrid generates the following types of columns:

DataGridCheckBoxColumn for boolean values
DataGridComboBoxColumn for enumerable values
DataGridHyperlinkColumn for Uri values
DataGridTemplateColumn to show any types of data by defining your own cell template
DataGridTextColumn to show text values

WPF DataGrid Properties are listed below:

CanUserReorderColumns enables or disables column re-ordering
CanUserResizeColumns enables or disables column resizing
CanUserResizeRows enables or disables row resizing
CanUserSortColumns enables or disables column sorting

Grid Background, Row Background

<DataGrid ItemsSource="{Binding Customers}" Background="LightGray" RowBackground="LightYellow"/>

AlternatingRowBackground: You can define a an AlternatingRowBackground that is applied every even row. You can additionally specify an AlternationCount if you only want to ink every n-th data row.

<DataGrid ItemsSource="{Binding Customers}" AlternatingRowBackground="Gainsboro"  AlternationCount="2"/>

ColumnWidth and RowHeight properties of DataGrid are used to set the default column width and row height of DataGrid columns and rows.

GridLinesVisibility property is used to make grid lines visible. Using this option you can show and hide vertical, horizontal, all, or none lines.

SelectionMode can be set to Single or Extended to define if one or multiple units can be selected simultaneously.

SelectionUnit defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.
 
BorderBrush and BorderThickness properties are used to set the color and width of the border.

IsReadOnly property is used to make a DataGrid read only. That means you cannot edit a DataGrid.

AreRowDetailsFrozen property is used to freeze the row details area so that it cannot be resized.

FrozenColumnCount: WPF datagrid supports the feature to freeze columns. That means they stay visible while you scoll horizontally through all columns. This is a useful feature to keep a referencing column like an ID or a name always visible to keep your orientation while scrolling.

<DataGrid ItemsSource="{Binding Customers}" FrozenColumnCount="2"  />

RowDetailsTemplate: WPF datagrid provides a feature that shows a detail panel for a selected row. It can be enabled by setting a DataTemplate to the RowDetailsTemplate property. The data template gets the object that is bound to this row passed by the DataContext and can bind to it.

HeadersVisibility: You can control the visibility of row and column headers by setting the HeadersVisibility property to either None,Row,Column or All.

<DataGrid ItemsSource="{Binding Customers}" HeadersVisibility="None" />

HorizontalScrollBarVisibility and VerticalScrollBarVisibility properties of type ScrollBarVisibility enumeration control the horizontal and vertical scrollbars of the DataGrid. It has four values - Auto, Disabled, Hidden, and Visible. The default value of these properties is Auto, that means, when scrolling is needed, you will see it, otherwise it will be hidden.

How to Bind WPF Datagrid with List of Objects?

How to Bind WPF Datagrid with List of Objects?

Lets say I have a class in which I have declared properties. I want to make objects of that class and store them in the list and finally bind that list to a WPF datagrid. The ItemSource property of DataGrid is the key to data binding. You can bind any data source that implements IEnuemerable. Each row in the DataGrid is bound to an object in the data source and each column in the DataGrid is bound to a property of the data source objects.

Lets dive in detail for more clear view.

I have created following class

public class Author
{
    public int ID { get; set; }
    public string Name { get; set; }      
    public DateTime DOB { get; set; }
    public string BookTitle { get; set; }
    public bool IsMVP  { get; set; }
}

Now let's create a collection of Author objects by using the List class.

private List<Author> LoadCollectionData()
{
    List<Author> authors = new List<Author>();
    authors.Add(new Author(){
            ID = 101,
            Name = "Mahesh Chand",
            BookTitle = "Graphics Programming with GDI+",
            DOB = new DateTime(1975, 2, 23),
            IsMVP = false });
    authors.Add(new Author()
    {
        ID = 201,
        Name = "Mike Gold",
        BookTitle = "Programming C#",
        DOB = new DateTime(1982, 4, 12),
        IsMVP = true
    });
    authors.Add(new Author()
    {
        ID = 244,
        Name = "Mathew Cochran",
        BookTitle = "LINQ in Vista",
        DOB = new DateTime(1985, 9, 11),
        IsMVP = true
    });
    return authors;
}

Now the last step is to set ItemsSource property of DataGrid. The following code snippet sets the ItemsSource property of a DataGrid to List of Authors.

MyDataGrid.ItemsSource = LoadCollectionData();

I think, you would have understood the concept on binding the list of objects with WPF datagrid ItemsSource property with this simple example.

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.