Pranay Rana: December 2012

Monday, December 31, 2012

Tuple Type in C#4.0

What is Tuple type ?
Tuple is new class type added in C#4.0. Tuple type allows to create data structure which is consist of specific type and specific number of elements. In the following post its about basic of Tuple type, how and where to use this new type in your code.

How to create Tuple type object
Following code show how you can create and use this class type.
Console.WriteLine("How to create and use");
Tuple<int, string> tuple = new Tuple<int, string>(1, "pranay");
Console.WriteLine(tuple.Item1 + "-" + tuple.Item2);
One way to create object is just make use of constructor and create the Tuple object.
Tuple<int, string> tuple1 = Tuple.Create(2, "ab1");
Console.WriteLine(tuple1.Item1 + "-" + tuple1.Item2);
Console.WriteLine();
Second way is make use of Create Static method supported by Tuple class and create object.

Refer Element of Tuple Object
As you see in both example element of Tuple get referred using name Item1 and Item2, so this is predefined name for the element by .net framework only. So to refer element in Tuple object you need to write "Item+number_of_the_element".

Constrain
You cannot change value of the the property of Tuple object.
// after creation of object this is not possible
// this gives compile time error
tuple1.Item1 = 100; 

C# allows to create Tuple object with the 7 different type element.
Create<T1>(T1) Creates a new 1-tuple, or singleton.
Create<T1, T2>(T1, T2) Creates a new 2-tuple, or pair.
Create<T1, T2, T3>(T1, T2, T3) Creates a new 3-tuple, or triple.
Create<T1, T2, T3, T4>(T1, T2, T3, T4) Creates a new 4-tuple, or quadruple.
Create<T1, T2, T3, T4, T5>(T1, T2, T3, T4, T5) Creates a new 5-tuple, or quintuple.
Create<T1, T2, T3, T4, T5, T6>(T1, T2, T3, T4, T5, T6) Creates a new 6-tuple, or sextuple.
Create<T1, T2, T3, T4, T5, T6, T7>(T1, T2, T3, T4, T5, T6, T7) Creates a new 7-tuple, or septuple.

What to do if you want to have more than 8 values ?
Last variation of Tuple creation allows to create Tuple object with more than 8 different element.
Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1, T2, T3, T4, T5, T6, T7, T8) Creates a new 8-tuple, or octuple. 
in this T8 element is of type Tuple only that means if you want to create tuple more than 8 it will be like this
var num = new Tuple<int, int, int, int, int, int, int, 
                 Tuple<int>>(1, 2, 3, 4, 5, 6, 7, 
                 new Tuple<int>(8));

Use Of Tuple type
To Pass data To methods
Sometime we just create class or structure to just pass data to method, creation of this extra class or structure in code can be avoided by using Tuple object to pass data.
Following is example of this where object of Tuple used to pass int and string data. And its shows that we can also create list of Tuple object and pass to method for processing.
ProcessData(new Tuple<int, string>(1, "Pranay"));

List<Tuple<int, String>> lst = new List<Tuple<int, string>>();
lst.Add(new Tuple<int, string>(1, "Pranay"));
lst.Add(Tuple.Create(2, "ab1"));
lst.Add(Tuple.Create(1, "abcdef"));
lst.Add(Tuple.Create(3, "cd2"));
ProcessListOfData(lst);

//Process single Tuple object
public static void ProcessData(Tuple<int, string> tup)
{
    Console.WriteLine("ProcessData");
    Console.WriteLine(tup.Item1 + "-" + tup.Item2);
    Console.WriteLine();
}
//Process list of Tuple object
public static void ProcessListOfData(List<Tuple<int, String>> lst)
{
    Console.WriteLine("ProcessListOfData");
    var data = lst.Where(x => x.Item1 == 1).Select(x => x);
    foreach (var tup in data)
    {
       Console.WriteLine(tup.Item1 + "-" + tup.Item2);
    }
    Console.WriteLine();
}

To Return From the Method 
Tuple can be used to return data from method where you want to return more than one value or list of object without creating extra class or structure for carrying data.
Following is example of returning data type.
var data = ReturnTupleData();
Console.WriteLine(data.Item1 + "-" + data.Item2);

public static Tuple<int, string> ReturnTupleData()
{
    return new Tuple<int, string>(1, "pranay");
}
As you can see it use Tuple object to return int and string data which is not possible with the normal method because we only have one return type.

To Return Anonymous Type 
Following is example of using Tuple with linq where most of the time we return anonymous type from the method because we just have to select only require number of property from set of property object have.
foreach (var tup in ProcessListOfDataAndReturn(lst))
{
     Console.WriteLine(tup.Item1 + "-" + tup.Item2+"-" + tup.Item3);
}
Console.WriteLine();

public static IEnumerable<Tuple<int, string, int>> ProcessListOfDataAndReturn(List<Tuple<int, String>> lst)
{
     Console.WriteLine("ProcessListOfDataAndReturn");
     var data = from tup in lst
                select new Tuple<int, string, int>
                    (
                        tup.Item1,
                        tup.Item2,
                        tup.Item2.Length
                     );
     return data.ToList();
}
You cannot return anonymous type from the method which is one of the constrain. There are other ways to return it from the method which is already discuss by me here Return Anonymous type.
But with the help of Tuple we can easily return Anonymous type data which you can see in above code.

Conclusion
This inbuilt Tuple class in C#4.0 can be use to avoid issue discuss above and also to simplify code at some point

Full Source code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How to crate and use");
            Tuple<int, string> tuple = new Tuple<int, string>(1, "pranay");
            Tuple<int, string> tuple1 = Tuple.Create(2, "ab1");
            Console.WriteLine(tuple.Item1 + "-" + tuple.Item2);
            Console.WriteLine(tuple1.Item1 + "-" + tuple1.Item2);
            Console.WriteLine();
         
            ProcessData(new Tuple<int, string>(1, "Pranay"));

            List<Tuple<int, String>> lst = new List<Tuple<int, string>>();
            lst.Add(new Tuple<int, string>(1, "Pranay"));
            lst.Add(Tuple.Create(2, "ab1"));
            lst.Add(Tuple.Create(1, "abcdef"));
            lst.Add(Tuple.Create(3, "cd2"));
            ProcessListOfData(lst);

            Console.WriteLine("ReturnTupleData");
            var data = ReturnTupleData();
            Console.WriteLine(data.Item1 + "-" + data.Item2);
            Console.WriteLine();

            foreach (var tup in ProcessListOfDataAndReturn(lst))
            {
                Console.WriteLine(tup.Item1 + "-" + tup.Item2+"-" + tup.Item3);
            }
            Console.WriteLine();

            Console.ReadLine();
        }

        public static void ProcessData(Tuple<int, string> tup)
        {
            Console.WriteLine("ProcessData");
            Console.WriteLine(tup.Item1 + "-" + tup.Item2);
            Console.WriteLine();
        }


        public static void ProcessListOfData(List<Tuple<int, String>> lst)
        {
            Console.WriteLine("ProcessListOfData");
            var data = lst.Where(x => x.Item1 == 1).Select(x => x);
            foreach (var tup in data)
            {
                Console.WriteLine(tup.Item1 + "-" + tup.Item2);
            }
            Console.WriteLine();
        }

        public static Tuple<int, string> ReturnTupleData()
        {
            return new Tuple<int, string>(1, "pranay");
        }

        public static IEnumerable<Tuple<int, string, int>> ProcessListOfDataAndReturn(List<Tuple<int, String>> lst)
        {
            Console.WriteLine("ProcessListOfDataAndReturn");
            var data = from tup in lst
                       select new Tuple<int, string, int>
                       (
                           tup.Item1,
                           tup.Item2,
                           tup.Item2.Length
                       );
            return data.ToList();
        }
    }
}

Leave comment if you have any query or if you like it.

Friday, December 21, 2012

Dispatcher in Silverlight


In this I am going to discuss about Dispatcher that makes Silverlight application responsive. I am going to show how Dispatcher allows to update UI of the application on the response from WCF service which is called anonymously and while continue to execute the other task.

Read More : DependencyObject.Dispatcher Property

What is the Example Application about ?
This is application which is fill up the Listbox on UI with the help of Dispather and WCF service which get called Asychronously so the actually thread do the task and doesnt get block.
Secondly On button click on UI its select the product in list which is get fetch using Dispatcher and WCF service.
So application is demonstration of how to use Dispatcher in Silverlight application which make use application more responsive and update UI without blocking other thread.

UI of the silverlight page

in the page "List of Item" item page Listbox get filled with the help of Dispatcher and by calling WCF service asynchronous.

Secondly on Button click  items get selected in listbox which are get fetched by making asynchronous WCF service call and UI get updated by Dispatcher.

Now in following article going to show detail execution of the code behind this Silverlight page and how the Dispatcher  and asynchronous WCF service combination works

Structure of the application
Above is structure of the application its consist of three project
1) DataService - project contains WCF service(s).
2) BusinessApplication1 - Silverlight application i.e. application pages developed using Silverlight.
3) BusinessApplication1.Web - It host Silverlight application.

DataService Project
WCF service
WCF file is part of "DataServicwe" project in application structure. Service file of this application contains following two methods
GetList -  this method get called to return the list of all product , once call is done on UI you can see the list of product get populated.
public List<string> GetList()
{
    List<string> lst = new List<string>
                {"Product1","Product2","Product3","Product4","Product5"};
    return lst;
}
GetSelectedList - this method get list of selected products, which is get highlighted once use press button on UI.
public List GetSelectedList()
{
    List<string> lst = new List<string>
                          {"Product1","Product3","Product5"};
    return lst;
}
Note : Right now for the demo this methods directly return list of string which is hard-coded but in actual scenario this get replace by database call i.e. call to database to get the list of product and call to database to get list of product belonging to user.

BusinessApplication1 (Silverlight Application)
WCF proxy
Proxy is class file which calls WCF service and return response to UI i.e. its bridge between Silvelright UI and WCF service.
Following variable is object of WCF client service class which is generated by visual studio from WCF service which is used in Silvelright application.
Service1Client svr;
GetData Method is called from the xaml.cs page to fill the available product list which is on UI of application.
public void GetData(Action<ObservableCollection<string>,Exception> ac)
{
    svr = new Service1Client();
    svr.GetListAsync(ac);
    svr.GetListCompleted += 
       new EventHandler<GetListCompletedEventArgs>(svr_GetListCompleted);
}
in above method first line of method create instace of WCF client class.
Second line of code call to "GetListAsync" method which is generated by Visual studio and part of WCF Client class , this method is generated from "GetList" of WCF service which we discussed earlier. "ac" is passed as argument to which is method that is used for callback i.e. its XAML.CS method which do the changes in UI.
Third line of code set the event handler which is handle the event of completion of execution on WCF service.

svr_GetListCompleted Following method get called when WCF service complete execution and return response of async call made to service.
void svr_GetListCompleted(object sender, GetListCompletedEventArgs e)
{
    try
    {
     ObservableCollection<string> str = e.Result as ObservableCollection<string>;

     Deployment.Current.Dispatcher.BeginInvoke(
          (Action)(() =>
          {
            (e.UserState as Action<ObservableCollection<string>, Exception>)(str, null);
          }));


    }
    catch (Exception ex)
    {
        Deployment.Current.Dispatcher.BeginInvoke(
           (Action)(() =>
           {
             (e.UserState as Action<ObservableCollection<string>, Exception>)(null, ex);
           }));
    }
    finally
    {
       svr.GetListCompleted -= svr_GetListCompleted;
       svr.CloseAsync();
       svr = null;

     }
}
in the above method , In try block first line get the result of execution i.e. list of product which is return from WCF service.
Now in second line of code in try block Dispatcher calls method of UI whose reference is passed as object by "GetListAsync".
In Catch block if there is any exception occurs during execution than it get sent to UI method to display user.
In Finally block it remove complete handler and closeAsync call and set WCF client class object to null.
Note : You find similar method for button click and select product in product list.

Page CS file
      public MainPage()
        {
            InitializeComponent();
            LoadList();
        }
 first line in the method Initialize the page component and second line of code make call to fill the product list.
        private void LoadList()
        {
            WCFProxy proxy = new WCFProxy();
            proxy.GetData(new Action<ObservableCollection<string>, Exception>(DispalyList));

        }
This method creates the object of Proxy class which is discuss earlier and call the "GetData" method of it, as pass the reference of function called "DisplayList".
public void DispalyList(ObservableCollection<string> data, Exception ex)
        {
            if (ex == null)
                listBox1.ItemsSource = data;
        }
code in this method fill the Listbox with the items once call to WCF service completed.

Below code works same as filling product list code, But this code actually select items in productlist which actually fetch by calling WCF service. This get called on button click of Button of UI.
private void button1_Click(object sender, RoutedEventArgs e)
        {
            WCFProxy proxy = new WCFProxy();
            proxy.GetDataSelected(new Action<ObservableCollection<string>, Exception>(SelecteItems));
        }
public void SelecteItems(ObservableCollection<string> data, Exception ex)
        {
            if (ex == null)
            {
                foreach (string s in data)
                    listBox1.SelectedItems.Add(s);
            }
        } 


Main xaml  
Following is XAML code that is for the UI of application
<UserControl 
  x:Class="BusinessApplication1.MainPage"
  xmlns="
    http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="
 http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:navigation="clr-namespace:System.Windows.Controls;assembly
=System.Windows.Controls.Navigation" 
 
 xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly
=System.Windows.Controls.Navigation"
 
 xmlns:dataControls="clr-namespace:System.Windows.Controls;assembly=
System.Windows.Controls.Data.DataForm.Toolkit" 
  
  xmlns:d="
  http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:mc="
  http://schemas.openxmlformats.org/markup-compatibility/2006" 
  mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">

  <Grid x:Name="LayoutRoot" >
        <ListBox Height="149" HorizontalAlignment="Left" Margin="152,12,0,0" Name="listBox1"
 VerticalAlignment="Top" Width="182" />
        <TextBlock Height="23" 
HorizontalAlignment="Left" Margin="39,30,0,0" 
Name="textBlock1" Text="List of Item" VerticalAlignment="Top" />
        
<Button Content="Select Item beloging to user" Height="23" 
HorizontalAlignment="Left" Margin="152,186,0,0" Name="button1"
 VerticalAlignment="Top" Width="182" Click="button1_Click" />
    </Grid>
</UserControl> 

Conclusion
So this helps to build more responsive Silverlight application using Dispatcher.

Leave comment if you have any query or if you like it.
 

Tuesday, December 11, 2012

Convert DateTime string to DateTime variable

In this post I am going to discuss about Conversion of String data in to DateTime.

Problem
For most of the beginner developer they face the problem when "Inserting or Updating" DateTime value in "Database" which is having different presentation of DateTime value than DateTime string entered in UI of Application. For Example DatTime input accept date in format "DD/MM/YYYY" i.e "26/06/2013" so when try to insert this type of DateTime data in DateTime column in database it cause problem and not allow to insert data in Database.

Solution
So to Avoid problem related to during database operation its better to convert DateTime string in DateTime variable i.e. convert entered datetime string value in datetime value. So to do it two thing require to do
1. its better to check in code that string is proper i.e. string is valid Datetime string or not.
2. And convert string of datetime in Database acceptable format to avoid error.
To achieve this in .net provide function called TryParseExact which allows to check the datetime string is valid or not and convertable to DateTime variable.

Example:
string dateTimeString = "28/08/2012";
var date=DateTime.ParseExact(dateTimeString, "dd/MM/yyyy", null).ToString("MM/dd/yyyy");
In above example is conversion take place from "dd/MM/yyyy" to "MM/dd/yyyy".

Note :
Just confirm that the format of the string representation must match the specified format exactly.

Following is code taken from MSDN which shows how this function works for different format.
    string[] dates =
    {
      "31/12/2010",
      "12/31/2010",
      "1/1/2011",
      "1/12/2011",
      "12-12-2010",
      "12-Dec-10",
      "12-December-2010"
    };
    string[] formattedDates = new string[dates.Length];

    string[] formats = { "M/d/yyyy", "d/M/yyyy", "M-d-yyyy",
                        "d-M-yyyy", "d-MMM-yy", "d-MMMM-yyyy", };
    for (int i = 0; i < dates.Length; i++)
    {
      DateTime date;
      if (DateTime.TryParseExact(dates[i], formats,
                                CultureInfo.InvariantCulture,
                                 DateTimeStyles.None, out date))
        formattedDates[i] = date.ToString("dd/MM/yyyy");
    }

You take reference of MSDN for creating custom format string. - Custom Date and Time Format Strings

Conclusion
So by using this function you avoid error of conversion of DateTime string at run-time easily.
Reference : DateTime.TryParseExact

Leave your comments if you like it.