Pages

Tuesday, 30 April 2013

ICommand Interface and RelayCommand Class in WPF MVVM


ICommand Interface and RelayCommand Class in WPF MVVM

ICommand Interface and RelayCommand Class in WPF are commonly used for binding. ICommand Interface and RelayCommand class is implemented in the ViewModel and is exposed to the view controls.

Every view in the app has an empty codebehind file, except for the standard code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done.

We will try to understand ICommand Interface and RelayCommand Class with following example.

Create a View and ViewModel like following:

View: Lets create the view first.  Three things to note in this view

1. In this view, I have included MyWPFSample namespace

xmlns:local="clr-namespace:MyWPFSample"

2. I have set datacontext of the winodw to the MainWindowViewModel class present in MyWPFSample namespace

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>    

3. I have done binding of the command of the button with the ButtonCommand property of MainWindowViewModel class.

Command="{Binding ButtonCommand}"

<Window x:Class="MyWPFSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWPFSample"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click"
                Height="23"
                HorizontalAlignment="Left"
                Margin="77,45,0,0"
                Name="btnClick"
                VerticalAlignment="Top"
                Width="203"
                Command="{Binding ButtonCommand}"
                CommandParameter="Hai" />
    </Grid>
</Window>


ViewModel: ViewModel has namespace MyWPFSample, class as MainWindowViewModel and property as ButtonCommand. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace MyWPFSample
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }
        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action<object>(ShowMessage));
        }
        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}

When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

RelayCommand Class

In this example RelayCommand class is used for implementing ICommad object. I think it's a simple and standard approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace MyWPFSample
{
    class RelayCommand : ICommand
    {
        private Action<object> _action;
        public RelayCommand(Action<object> action)
        {
            _action = action;
        }
        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                _action(parameter);
            }
            else
            {
                _action("Hello World");
            }
        }
        #endregion
    }
}

ICommand and RelayCommand keep track whether or not commands are available. If commands are not available, then all controls associated with that command are disabled. For example using command controls like button can be disabled if CanExecute() returns false. The Code that executes when command is invoked and is located in Execute event. handler. 

INotifyPropertyChanged Interface and PropertyChangedEventHandler in WPF


INotifyPropertyChanged Interface and PropertyChangedEventHandler in WPF

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, which a property value has changed. The INotifyPropertyChanged interface contains an event called PropertyChanged. Whenever a property on a ViewModel / Model  object has a new value, it can raise the PropertyChanged event to notify the WPF binding system of the new value. Upon receiving that notification, the binding system queries the property, and the bound property on some UI element receives the new value

public class MyClass:INotifyPropertyChanged
{
    private int _ID;
    private string _Name;

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public int ID
    {
        get
        {
            return _ID;
        }
        set
        {
            _ID = value;
            OnPropertyChanged("ID");
        }
    }
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }
}

Sunday, 28 April 2013

Difference between Events and Commands in WPF MVVM Architecture

Difference between Events and Commands in WPF MVVM Architecture

Commands are very powerful and useful feature of WPF. Cut, Copy and Paste are basic inbuilt commands in WPF. Commands and Events are related to each other to a large extent but the main concern there is that events doesn't fit well into MVVM paradigm. So we generally prefer to use commands in WPF MVVM architecture. Commands provide a lot of advantages over events. Some of them are listed below:

1. Commands in WPF allow you to move the implementation of a command handler to the buisness layer.

2. You can bind WPF command in the view (XAML) and receive the event raised. This way you do not have to use code behind which is a no-no in MVVM.

3. In events an action is tightly coupled with its source and can't be reused freely; Using commands you can easily maintain various actions in a single place and reuse them anywhere in application.

4. Commands are similar to Events except we can associate any number of UI Controls or Input Gestures to a command and bind that command to a handler that is executed when control are activated or gestures are performed.

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);
         }
    } 
}

5 things to remember during an exit interview

5 things to remember during an exit interview
 
If you have resigned from a company and you are being called by HR for exit interview, you should face HR very politely and maintain a positive attitude. Here are some points I wanted to discuss with you on exit interviews.
 
1. Maintain your composure: You might come across very trivial questions but maintaining your composure is very critical, no matter how irrelevant you feel they might be. Be graceful and witty while answering tricky questions.
 
2. Emphasis on your experience: Discuss your experiences and key learning from them. Always mention about the opportunities those were given to you and how you were able to perform on them, which has enhanced your skills for future endeavours.
 
3. Don’t be negative:  Focus on the key learning from difficult situations at the work place. You should portray that every crisis had given an opportunity for you to be adaptable in different situations and be a quick fixer to any given problem.
 
4. Comments should be constructive: Be honest but polite while putting across your grievances. Instead of accusing anyone or any process, try giving examples on how it can be improved for better results.
 
5. Don’t take out personal grudge: It’s better to express your problems in a non-personal way rather pin-pointing it to any individual. Remember, it is unnecessary for you to comment on someone (negatively) who you are not going to see for much longer.

How to crack a Telephonic Interview? Things to keep in mind while Telephonic Interview

How to crack a Telephonic Interview? Things to keep in mind while Telephonic Interview
 
A telephonic interview is usually organised to short-list candidates, to minimise the cost of conducting face-to-face interviews or to screen outstation candidates.
 
This is an important step for both the interviewer and the interviewee. Just as a personal interview, there are some basic dos and don’ts. It is very critical to follow these as the difficult task here is to impress the interviewer on the phone and hold their attention for the entire conversation.Therefore:
 
Be serious: It is a job interview at the end of the day. So first rule is that one must treat a telephonic interview just as one would treat a face-to-face meeting.This means keeping your resume handy, making sure you get the name and designation of the interviewer right and most importantly avoid multitasking.
 
The same rule also applies to an interviewer. The interviewer must spend some time before the call to study the resume and also must ensure that they are not distracted by any other work at that point in time.
 
Avoid distractions: It is important to choose a quiet place to take the call. You don’t want to be distracted by background noise. If possible use a landline to avoid call drops. If you are using your mobile phone, ensure that your call-wait facility is switched off.
 
For interviewer it is equally important to show seriousness. Don’t interrupt the call. This can be very discouraging to an interviewee.
 
Maintain the tone: The difficult task in a telephonic interview is that one needs to put forth their best voice. Yes, that’s right. That’s the only interface you have with your interviewer. So maintain a normal tone, don’t get excited and more importantly don’t raise your voice at any given point. Further it is important that the candidate speaks slowly and clearly.
 
Be positive: You have to be extra careful about expressing the right attitude. So, say your ‘hello’ with a smile. Studies have shown that smiling on the phones creates a positive image. Also, it kind of adds a spring to your voice, makes you sound professional and confident.
 
Listen intently: Listening attentively is an important aspect of an interview. This is more so in case of a telephonic interview. It is important to listen carefully and answering honestly. On a telephone any slight hesitation is evident. However, don’t jump to answer a question immediately. Listen carefully and articulate it well before saying out loud.
 
Lastly, don’t rush through the interview. Take your time, sound prepared, take notes, if required. This will help you to create a positive image. Also, remember since it’s a telephonic interview you get a chance to keep all the information you may require handy. This could be your resume, notes about the company, job profile and so on. This is your cheat sheet – use it wisely.

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.

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.