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 :)

Monday, 28 October 2013

Scroll whole page , Ext js

Hi , during practicing I got very short code to make your page ( body ) scroll to some location , we have following options for this :

var body=Ext.getBody().el;

var el=Ext.getBody().el;
el.scrollBy(10, 10, true);
el.scrollBy([10, 10], true);
el.scrollBy({ x: 10, y: 10 }, true);
or you can use:
el.side, value, [animate] ) ; where side may be left or top , value is integer and true or false for animate or not.
And that's simply it :)

Sunday, 27 October 2013

Article CMS started in php

Hi guys, I have started Articles CMS system and decided to  make my hands dirty with php codding too , and created public repository on github at : 
 I have stared with some initial work on database read and login authentication (basic one ) , you can also participate in it :)

Bitknex , All in one FTP/SFTP/HTTP/WebDAV client

During searching for moving files and directories from workspace to the wamp server www directory , I found very niece tool BitKnex ( , which is "All-in-one FTP/SFTP/HTTP/WebDAV Client" , so from now move your code to any online url or on the network or only between your system folders.

Eclipse and php tools setup for php development

Hi all , in this post I will show you how to use eclipse for php development. First you need to download eclipse for php i.e go to : , select you favorite package ( may skip ) and download IDE according to your OS requirement, as shown in screen shot below :

That's it :)

Wamp doesn't start all services , php

Hi all , recently I have encountered a problem that I tries to start wamp server for php development but it doesn't started all of its services , when I inquired problem I got to know that there is a "Web deployment agent service " , started at windows start , which works for applications to deploy them on local server when we start our application form visual studio , actually it uses port 80 by default , and wamp also uses port 80 to start working , so every time when wamp was started , it founds port 80 busy, so simple solution is we have to configure one of them to another port so that port clashes doesn't happens.
What I do for simple solution is that , when I do need to work with wamp , I just simply stop "web deployment agent  service service" and when I finished I started that again.
It is very simple one step process.Go to start , search for services :

Then select web deployment agent  service and stop it :

And that's it, enjoy php :)

Saturday, 26 October 2013

Populate DropDownList control with enum ,

DropDownList can also be populated with enum i.e

  protected void Page_Load(object sender, EventArgs e)
            if (!IsPostBack)
                //Assigning values to dropdown form enum as news types
                var hash = Helper.GetEnumForBind(typeof(NewsType));
                hash.Add("0", "--Select Type--");
                NewsType.DataSource = hash;
                NewsType.DataTextField = "value";
                NewsType.DataValueField = "key";

Where NewsType is enum , lets say like this :
 public enum NewsType

And GetEnumForBind function converts enum to hashtable which can be bound to DropDownList,

 public static Hashtable GetEnumForBind(Type enumeration)
            string[] names = Enum.GetNames(enumeration);
            Array values = Enum.GetValues(enumeration);
            Hashtable ht = new Hashtable();
            for (int i = 0; i < names.Length; i++)
                ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
            return ht;

and finally our dropdownlist is :

    <asp:DropDownList runat="server" ID="NewsType"  AutoPostBack="True" onselectedindexchanged="NewsType_SelectedIndexChanged"> </asp:DropDownList>

and that's all what we need :) dropdown list populated with data from .xml file

In we have <asp:DropDownList> control , to populate this control with data from .xml file , you need to do straight and simple three steps.

Step#1 : Create xml file in your project , lets say we have data of countries i.e

<?xml version="1.0" encoding="utf-8" ?>

Copy paste this data as it is in your Countries.xml file.

Step#2 : Now you must have DropDownList control on your page .Put following code inside your .aspx page. 

        <asp:DropDownList ID="ddlCountries" runat="server" AutoPostBack="True" Width="183px">  

Step#3 : Now go to your code behind file and define following function there :

  public void BindDropDownListFromXml()
            DataSet ds = new DataSet();
                //Reading the data from the XML file
                DataView dv = ds.Tables[0].DefaultView;
                //Sort the DataView by "Name"
                dv.Sort = "Name";
                //Setting DataText field and DataValue field of DropDownList
                ddlCountries.DataTextField = "Name";
                ddlCountries.DataValueField = "ID";
                //Binding the DropDownList with the  DataView
                ddlCountries.DataSource = dv;
                ddlCountries.Items.Insert(0, new ListItem("-- Select --", "0"));
            catch (Exception ex)

And after this , call this function inside your Page_Load function like this :

  protected void Page_Load(object sender, EventArgs e)
            //this will run on page load
            if (!Page.IsPostBack)

And that's it :)

Saturday, 19 October 2013

Replace a single character or string or multiple occurrence of a character or string in a string , JQuery

Recently I was working on my own Syntax Highlighter plugin for JQuery ( UCodeHighlighter github ) , I go through from good experience to play with strings , its characters and sub-strings.To demonstrate the string manipulations lets say we have a string :

var text='I am a programmer , I love my field and I love codding'; 

I have face following cases while working :

  • Replace a single occurrence of a string in a string :                                                                                 text= text.replace("love","very love"); // this will replace only first 'love' in above string with 'very love'
  • Replace multiple occurrence of a string in a string                                                      text= text.replace("/love/g","very love"); // this will replace both' love' in above string with 'very love'
  • Replace multiple occurrence of a dynamic string in a string                                                              var keyword='love';                                                                                                                            text= text.replace(new RegExp(keyword, 'g'),"very love"); // this will replace both' love' in above string with 'very love'
  • Replace multiple occurrence of a character in a string :                                                                                 text= text.replace(/a/g,"e"); // this will replace all 'a' characters in above string with 'e'
  • And same are the other cases for characters manipulation as strings described above.
And that's it , I hope this will help while doing your scripting :)

Thursday, 17 October 2013

Getting stated Android , development environment setup

Welcome to android development series , this time I am going to describe that how to setup your development environment for android apps development.This is simple two step process.

  1. First step is installing java JDK from their official website i.e (
  2. Second step is to download Android ADT bundle ( sdk for android ) from this link : , and it has every thing you need to develop an android application , it has three folders, one is for eclipse containing IDE , second one is SDK and third one is SDK manager app, to start doing android , you just need to start eclipse and that's it.

Android handle onClick event ( two ways )

I recently have started to practice pure android apps , and now I am going to show how to register onclick events of controls in two ways. First way is our old java way , to associate separate onclick listener to each control like this :

  btn_1.setOnClickListener(new OnClickListener()
            public void onClick(View v)

which is good but not best way.

Second way is to define your onClick method in the current context ( class ) and while handling the onClick events just give "this" ( context ) to the setOnClickListener method of controls and apply cases inside your onClick method, like given below :


public void onClick(View v) {
      // TODO Auto-generated method stub
      final int id = v.getId();
       switch (id) {
            // your logic here
           // your logic here
       // even more buttons here

So these are the two ways for registering events for controls.

Sunday, 13 October 2013

Resharper, an awesome tool for visual studio

Recently I get experienced to use "Resharper" , which I found amazing , it actually provides codding assistance for developer to code in much efficient and fast way, it is known for :

You can get complete feature details of it from site link given above :)

Convert visual studio 2012 project to visual studio 2010

To convert visual studio 2012 project to visual studio 2010 you have to do only two changes in two files.Fist change you have to do in your .solution file , for this you have to open your project solution file into text editor and do following changes :

  • Change "Microsoft Visual Studio Solution File, Format Version 12.00" to "Microsoft Visual Studio Solution File, Format Version 11.00"
  • and "# Visual Studio 2012" to " # Visual Studio 2010"

and now right click your project file and open it in text editor and change :
  • <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> to "<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>"
And you are done , now open your project in visual studio 2010 and start codding :)

Saturday, 5 October 2013

What is "Code Re-factoring" ?

Recently I go through the process of code re-factoring, before going into detail lets have definition of re-factoring, i.e. "It is process of code restructuring without changing its behavior", first question that may arises is that why we need to restructure our code and this will not going to effect the behavior of our system and the answer will be the detail of re-factoring, now lets assume one developer work one module of the system and other work on another and both developers merge their code, so during these steps developers wrote their code consists of classes containing methods and in methods there may be instantiation of objects, so as the other developers do.
1- After merging first scenario (very common one ) can occur i.e. same general chucks of code for doing       identical work but consists of different method names.
2-Un-necessary creation of methods ( call only from one place)
3-Un-necessary creation of variables ( usually we do for debugging purposes)
4-Extra long methods ( un-necessary logic)

You can find different possible combinations from above points after reviewing your code and when you will remove things like these then this process will be called "Code Re-factoring".

Saturday, 28 September 2013

Extjs, prevent images from being cached

 In order to prevent images from being cached just do one thing, append cache buster i.e cb=new Date() (or any other dynamic value could be replaced with new Date() object) to the the image source as query string , just as given below :

myImage.setSrc('../images/myImage/name.png'+'?cb='+new Date());

Thursday, 26 September 2013

Extjs, apply class on runtime on actioncolumn of grid

we can apply class on rederer funtion of actioncolumn by checking records property easily as shown below :

                    xtype: 'actioncolumn',
                    width: 70,
                    dataIndex: 'DataIndex',
                    menuDisabled: 'true',
                    text: 'text',
                    sortable: false,
                    fixed: 'true',
                    renderer: function (value, metadata, record) {
                        if (record.get('IsEnabled')) {
                            metadata.tdCls = 'cssClass'

Extjs, create view object , with some properties at runtime

Lets say I create instance of a view and I want to apply some property on it , then this is the way I can give properties to it on runtime.

var addView = Ext.create('App.view.Add', { flex: 1 });

Disable chrome security

By excuting this command "chrome.exe --disable-web-security" in run of your windows , you can disable your browser's security , mostly used for running sencha touch apps using api calls.

Extjs, Ext.string.format used to implement mailto functionality on anchor click inside grid column using renderer funtion

columns: [
        header: 'Email',
        dataIndex: 'email',
        renderer: function(value) {
            return Ext.String.format('<a href="mailto:{0}">{1}</a>', value, value);

Extjs, UI manipulation using parent element id and get its childs from class applied

That's what use this logic on store load , one the stored load success then manipulate you UI( use this on render function of under use controll):

 onGridRendered: function (grid) {
           scope: this,
           callback: function (records, operation, success) {
               if (success) {
                   var parent = Ext.get('ID of element');
                   var elems ="div.class of elements").elements;
                   for (var i = 0; i < elems.length; i++) {
                       elems[i].hidden = true;


Scencha touch , check the OS i.e. is Desktop,Tablet etc

Following is the code snippet which tells you about current system ( actually sencha touch ):
}else if({

Extjs, how to implement delay

In order to use delay funtionality in extjs , you must create Ext.util.DelayedTask object and use its delay method which takes span of time to be delayed in miliseconds, i.e.

Following is an exmple of using delay functionality in extjs:

var task = new Ext.util.DelayedTask(function(){

Ext.get('myInputField').on('keypress', function(){

OOP concep of Shadowing , definition with example

Shadowing is very important concept of object orient programming (OOP), used with polymorphism because it involves runtime binding of objects ( pure polymorphism), it states that : " shadowing is actually stands for hiding overridden method implementation in drived class and used the implementation of parent class with drived class object", does it make sense ??, indeed but if not follwing example will make it clear for you.
This is full testable code of shadowing implementation :

class Program
        static void Main(string[] args)

            Person[] listPerson = new Person[2];
            listPerson[0] = new GoodPerson();
            listPerson[1] = new BadPerson();
            foreach (Person obj in listPerson)
            Console.WriteLine(new BadPerson().getCategory());

        public class Person
            public virtual string getCategory(){

                return "Hi I am a person";


        public class GoodPerson:Person
            public override string getCategory()

                return "Hi I am a Good Person";

        public class BadPerson:Person
            public new string getCategory()

                return "Hi I am a Bad Person";



The output of the program will be :

Hi I am a Good Person
Hi I am a person

The trip behind this is to use "new" keyword instead of "override" with your virtual methods and that's all.

Monday, 23 September 2013

Apprise V2 is rising , new features for your popups using jquery

AppriseV2 is On now , with new look and feel with amazing effects , check that out on library page :

Extjs, use function in tpl , in gridPanel's templateColumn

           header: '',
           xtype: 'templatecolumn',
           tpl: ['<div>' +
                    '<div>' +
                        '<tpl for="data">' +
                            '<tpl if="Title.length &gt; 0">'+
                                '<div>{Title}</div>' +
                            '</tpl>' +
                            '<div>{[this.shorten(values.fullName)]}</div>' +
                        '</tpl>' +
                   , {
                    shorten: function (noOfTimes) {

                        return noOfTimes;

That's how we can use functions in tpl.