Saturday, 16 November 2013

WPF ( Windows Presentation Foundation ) an introduction

.Net framework which is Microsoft's next generation UI framework for creating applications with rich user experience. It is part of .Net from 3.0. WPF is famous because of UI's, 2D graphics , 3D graphics , documents and multimedia usage , makes UI faster , scalable and resolution independent. It loosely couples the implementation ( behavior ) from appearance ( UI ) using XML based graphic designing tool. 

So its key characteristics are :
  • Separation of appearance and behavior 
  • Rich composition ( through xaml based UI )
  • Highly customize-able
  • Resolution independence

WCF ( windows communication foundation) an introduction, characteristics , why should we use this Framework

WCF is .net framework ships with .net  for building service oriented applications , used to send data asynchronously from one service end point to another. Service endpoint may be an independent service available all the time or a part of another application ( hosted in it ). The data which it sends could be a text, xml or complex such as binary stream etc.We can use WCF for real time data exchange, polling , business transactions etc.

Some key characteristics of WCF are :

  • Service Orientation
  • Interoperability
  • Multiple Message Patterns
  • Service Metadata
  • Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions
  • Ajax and Rest Support
  • Extensibility

Why to use WCF instead of conventional Web Services:

WCF ServiceWeb Service
-> Communication can happen over HTTP,TCP, IPC or even MSMQ.
-> It can be configured to have simplex,request-response or even full duplex communication.
-> Can be hosted inside web server or event self hosted.
-> Communication can happen over HTTP only.
-> Only simplex and request-response    communication is possible.
-> Work in stateless fashion over HTTP and hosted inside a web server.

That was very simple introduction to WCF , stay tuned :)

Monday, 11 November 2013

BDD (behavior driven development) implementation .net

After my first post on "What is behavior driven development" this is an extension to this post as implementation and practical of BDD. We are going to use following libraries/frameworks in this tutorial :

  • SpecFlow : BDD library/framework , works on Given, When and Then keywords where Given relates to preconditions, when represents occurrence of an event and Then is testable outcome. Provides facility to write testing scenarios in human language ( DSL , domain specific language ).
  • Resharper : To run unit tests.
  • NUnit : Unit testing framework
  • Coypu:  Provides fast browsing of web applications to access elements i.e. buttons, links , fields and etc on a web page.This is irrelevant from above exercise( just in-case you are interested in UI testing).

To start practicing you first need to download/install following :
  • Install specflow ide integration from their official website :
  • Install library package for specflow from nuget ( open package manager console and run  "Install-Package SpecFlow" command  from your visual studio i.e. Tools-->Library Package Manager-->Package Manager Console ) 
  • Same as above run these commands "Install-Package NUnit","Install-Package Coypu" for installation of NUnit and Coypu libraries respectively.
And that it , you are ready to go.

Now when you are going to add new file into your project , you will see three more file extensions in add new file popup window as shown in following figure:

Now start with adding Specflow feature file , this will contain following default data in it :

Feature: SpecFlowFeature1
    In order to avoid silly mistakes
    As a math idiot
    I want to be told the sum of two numbers

Scenario: Add two numbers
    Given I have entered 50 into the calculator
    And I have entered 70 into the calculator
    When I press add
    Then the result should be 120 on the screen
Where "@mytag" is used for scope i.e. in step definition file we can specify the scope of definition by declaring [Scope(Tag = "mytag")] on top of the class.

By default the color of Given,when and then statements will be pink and that means there is not binding yet for these steps as shown in figure below :

now right click inside this view and select Generate step definition as shown in figure :

This will generate steps definition file for your scenrio , now you can use tag above your class binding like this :
  [Scope(Tag = "mytag")]
    public class FirstSecenrio
Now you are ready to run your tests , open re sharper test window and start running your tests.
To work with coypu , you must configure your browser settings in BeforeTestRun method of your binding class and start accessing your webpage controls, see page for this.
Your binding class after coypu browser settings will look like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Coypu;
using Coypu.Drivers;
using Coypu.Drivers.Selenium;
using NUnit.Framework;
using TechTalk.SpecFlow;

namespace SpecflowCypu.Tests.StepsDefinitions
    [Scope(Tag = "mytag")]
    public class FirstSecenrio
        private static BrowserSession browser;
        public static void BeforeTestRun()
            SessionConfiguration sessionConfiguration = new SessionConfiguration();
            sessionConfiguration.AppHost = "localhost";
            sessionConfiguration.Port = 5555;
            sessionConfiguration.SSL = false;
            sessionConfiguration.Browser = Browser.Firefox;
            browser = new BrowserSession();

        public static void AfterScenario()

        [Given(@"I have entered 50 into the calculator")]
        public void GivenIHaveEntered50IntoTheCalculator()
            // ScenarioContext.Current.Pending();

        [Given(@"I have entered 70 into the calculator")]
        public void GivenIHaveEntered70IntoTheCalculator()

        [When(@"I press add")]
        public void WhenIPressAdd()

        [Then(@"the result should be 120 on the screen")]
        public void ThenTheResultShouldBe120OnTheScreen()

That was very short and to the point tutorial on BDD using specflow , will explain more very soon.

Saturday, 9 November 2013

XML Serialization in c#

According to MSDN definition "Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization".

After serialization data can be stored into a file,database,memory etc. This is simple three step process:

First step is to create a class which's object you want to serialize into xml file i.e.

public class Movie
        // Default ctor
        public Movie()

        [XmlAttribute(AttributeName="MovieTitle")]  // stores element in xml file with this name
        public string Title
        public string Director
        [XmlElement(ElementName ="ReleaseDate")]
        public DateTime Year
        public double Budget
Where  [XmlElement(ElementName ="ReleaseDate")] is used to change the name of the property on run time and save this property in xml file with new name.

Second step is to write a function which will be used to serialize above class's object into xml. i.e.

 private static void SerializeMovieXML(List<Movie> movies)
            // Step 1
            XmlSerializer serializer = new XmlSerializer(typeof (List<Movie>));
            // Step 2
            TextWriter txtWriter = new StreamWriter(@"D:\Movies.xml");
            // Step 3
            serializer.Serialize(txtWriter, movies);
            // step 4
This function store Movies.xml file in D drive , you can change this location.

Third step is to create object of movie class and use above method to create xml.

 Movie m = new Movie();

            m.Title = "BOL";
            m.Director = "Shoiab Mansoor";
            m.Year = new DateTime(2011, 09, 05);
            m.Budget = 10000000;

            Movie m1 = new Movie();

            m1.Title = "Forrest Gump";
            m1.Director = "I Dont Know";
            m1.Year = new DateTime(1990, 09, 05);
            m1.Budget = 50000000;

            List<Movie> movie = new List<Movie>();



In result of above code , this xml will be produce in Movies.xml file.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="" xmlns:xsd="">
  <Movie MovieTitle="BOL">
    <Director>Shoiab Mansoor</Director>
  <Movie MovieTitle="Forrest Gump">
    <Director>I Dont Know</Director>

Now if you want to de-serialize above xml into object , following method will be used :
   private static List<Movie> DeserializeMovieXML()
            // step 1
            XmlSerializer serializer = new XmlSerializer(typeof (List<Movie>));
            // step 2
            TextReader txtReader = new StreamReader(@"D:\Movies.xml");
            // step 3

            List<Movie> m = serializer.Deserialize(txtReader) as List<Movie>;


            return m;
and you can use this method in this way to get your object back :

            List<Movie> movies = DeserializeMovieXML();
That's it, do code and enjoy :)

My Syntax Highlighter V1.0.0 , beautify your source code on html page

I got some free time during holidays , so I decide to write my own syntax highlighter to beautify my code on html pages, its first version is done and pushed on my github account right here :

To use this you must follow following four steps :

1) First include scripts and style sheet in header of your page :

<title>jQuery plugin: code highlighting demonstration</title>
<script src="published/jquery-1.6.3.min.js"></script>
<!--<script src="published/UCodeHighlightner.js"></script>
<script src="script/uhighlight.js"></script>
<link href="published/hilightstyle.css" type="text/css" media="screen" rel="stylesheet">-->
<script src=""></script>
<link href="" type="text/css" media="screen" rel="stylesheet">


2) Second step is , place you code in a <div > with display none , i.e.

<div id="data" style="display:none;" >

your code here........


3) Third step must be , use following chunck of code on your page:

<div id="line_number" class="counting_div_wrap"></div>
<div id="main" class="main"></div>
<div style="clear:both;"></div>

4) The last step is to use js to process your code i.e.

<script type="text/javascript">
// script for on page code processing

That's all , you are done :)

Friday, 1 November 2013

DataGridView , show custiom column and row headers , win forms .net

Recently one of my friend requested to show how to use custom header for columns for DataGridVew in WinForms , I worked on that and not only customize column headers but also row headers. Let's start this , first step is we required a model to show data into grid ( what are the fields in our collection or in database).
Our model :

    class CustomModel
        public string Title {  get;set; }
        public string Detail  { get;set;  }

These are two fields we want to show in gridview.

Now second step is to create a collection to bind to our gridview, and here is the all remaning code ,put it into your Form1_Load method like this :

   private void Form1_Load(object sender, EventArgs e)
            List<CustomModel> dataList=new List<CustomModel>();

            dataList.Add(new CustomModel(){Title = "title1", Detail = "detail1"});
            dataList.Add(new CustomModel(){Title = "title2", Detail = "detail2"});

            DataGridViewTextBoxColumn title = new DataGridViewTextBoxColumn();
            title.DataPropertyName = "Title";
            title.HeaderText = "Title";      

            DataGridViewTextBoxColumn description = new DataGridViewTextBoxColumn();
            description.DataPropertyName = "Detail";
            description.HeaderText = "Detail";  
            dataGridView1.DataSource = dataList;

            /* Create the row headers */
            int rowNumber = 1;
            foreach (DataGridViewRow row in dataGridView1.Rows)
                row.HeaderCell.Value = "R" + rowNumber;

            // set rows headers width according to its text

And that's simply it , enjoy :)