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.

Monday, November 26, 2012

Linq Query to compare only Date part of DateTime

In this post I am going to discuss about comparing the date part of the datetime in linq query. In linq query its easy to perform datetime comparison how to compare only date not time part of datetime filed of your entity.

Let have coloseure look, In Sql Server one can do something like as below to just compare date part of the field.
SELECT * FROM dbo.tbl_MyTable
WHERE 
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) = 
            CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
So in above query convert function did task of removing time part and only date part comparison happens.

Linq Queires
Following discussion about doing same task using linq queries.
Solution 1:
First way to achieve same thing (i.e. comparing date part) of entity or object is following

var data = context.t_quoted_value.Where(x => x.region_name == "Hong Kong" 
                  && DateTime.Compare(x.price_date.Value.Date, dt.Date) == 0)
                  .ToList();

Here Date property of DatTime used to get only date part of datetime property and made use of DateTime.Compare function to get matching object.

But the problem with this approach when make use of EnityFramework i.e. Linq To Entity , its gives following error at runtime

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

so to avoid above error in Linq to Entity query is modified to following

var data = context.t_quoted_value.Where(x => x.region_name == "Hong Kong")
                            .ToList()
                            .Where (x=> DateTime.Compare(x.price_date.Value.Date, dt.Date) == 0)
                            .ToList(); 

So in above query first data is get fetched from the database and than on list date comparison get applied. But the problem with this approach is need to load all data first than the date comparison get applied because entityframework doesn't support direct query.

Solution 2:
One more easy and simple solution to just compare datet part of datetime object is as following
            
var data1 = context.t_quoted_value.Where(x => x.region_name == "Hong Kong" 
                            && x.price_date.Value.Year == dt.Year
                            && x.price_date.Value.Month == dt.Month
                            && x.price_date.Value.Day == dt.Day).ToList();
its query use the year,month and day property of datetime object to compare date. Advantage of this solution is this is compatible with all flavor of Linq i.e. it works in linq to sql, linq to object and also in linq to enitity.

Conclusion
So the post is useful when you need to compare only date part of datetime property in Linq queries.

Leave your comments if you like it.

Wednesday, November 7, 2012

Read Xml with Descendants Method (XName)

This post is about understanding Descendants and avoid misconception with this method.
Recently I read one question on StackOverFlow  about reading xml using Linq To Xml to get node values. In that developer made use of Descendants Method to get the child node values.

Let see the actual problem here following is XML to read. And developer wrote code to read out value of orderid node.
<ordersreport date="2012-08-01">
<returns>
      <amount>
        <orderid>2</orderid>
        <orderid>3</orderid>
        <orderid>21</orderid>
        <orderid>23</orderid>
      </amount>
    </returns>
</ordersreport>
So code written like this
    var amount = documentRoot.Descendants("Amount")
               .Select(y => new
               {
                  OrderId = (int)y.Element("OrderId")
               });
               foreach (var r in amount)
               {
                  Console.WriteLine(r.OrderId);
               }
Ouput of above code is
 2
that is only first orderid element value which is child of Amount , So misconception here by developer of the code is Descendants("Amount") returns child element of the Amount tag i.e. all orderId element.

Now to Understand Descendants function in better way I visited to MSDN link which says something like this
XContainer.Descendants Method (XName) - Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection. So as per the defincation on MSDN problem with code
    var amount = doc.Descendants("Amount")                         
      .Select(y => new
      {
       OrderId = (int)y.Element("OrderId")
       });
will give you Element Amount and when you write y.Element("OrderId") will return you fist element of its child.
Descendants - doesn't mean than its return the child element of element name rather than method look for descendants of element or if name of elemnt specified as parameter than matching descendants.
Finally I got following solution to get it properly work
XElement documentRoot  = 
     XElement.Parse (@"<ordersreport date="2012-08-01">
                             <returns>
                              <amount>
                                  <orderid>2</orderid>                                                    
                                  <orderid>3</orderid>
                                  <orderid>21</orderid>
                                  <orderid>23</orderid>
                               </amount>
                             </returns>
                        </ordersreport>");
Solution 1
var orderids = from order in
                  documentRoot.Descendants("Amount").Descendants()
                  select new
                  {
                     OrderId = order.Value
                  };
As per the information on MSDN documentRoot.Descendants("Amount").Descendants() give list of orderId elements.

Solution 2
var orderids = from order in
                    documentRoot.Descendants("OrderId")
                    select new
                    {
                       OrderId = order.Value
                    };
or the second solution is just bit easy than this just make use of documentRoot.Descendants("OrderId") that will give all orderidelement.

Conclusion
This post is just for avoiding misconception related to Descendants and understand it properly.

Leave your comments if you like it.

Tuesday, October 9, 2012

Return Anonymous type

In this post I am going to discuss about returning the anonymous type and how to handle in code. Following is list of fact about anonymous type.  

Quick facts about Anonymous type
  • Anonymous types are reference type derived form system.objects.
  • Properties of the Anonymous type is read only.
  • If two Anonymous type has same properties and same order than compiler treats its as same type. But if both are in one assembly.
  • Anonymous type has method scope. If you want to return Anonymous type form the method than you have to convert it in object type. But is not good practice.
You can read more on blog about this: Anonymous types
As in about facts you cannot return anonymous type from the method , if you want to return you need to cast it in object.
Now in following post I am going to do same return the anonymous type as object and going to show three different way to handle it.
  • Way 1: Handle using Dynamic type 
  • Way 2: Handle by creating same anonymous type 
  • Way 3: Handle using Reflection
To Understand each way I created following method which returns anonymous type
object AnonymousReturn()
{
     return new { Name = "Pranay", EmailID = "pranayamr@gmail.com" }; 
}
Way 1: Handle using Dynamic type
dynamic newtype= AnonymousReturn();
Console.WriteLine(newtype.Name + "  " + newtype.EmailID);
As you see in above example first line of code calling method which is returning anonymous type as object and assign the return value to dynamic type. Second line of code just printing the property value of anonymous type.
Note : No intelligence support as we are using dynamic type. And need to remember the property name and type also.

Way 2: Handle by creating same anonymous type
object o = AnonymousReturn();
var obj = Cast(o, new { Name = "", EmailID = "" });
Console.WriteLine(obj.Name + "  " + obj.EmailID);
In this way return value of the anonymous type is get assigned to object. Next line of the code cast object to the same anonymous type. To accomplish this task following method does casting of object.
T Cast<T>(object obj, T type) { return (T)obj; }
This done song type conversation and provide intelligence support.

Way 3: Handle using Reflection
object refobj = AnonymousReturn();
Type type = refobj.GetType(); 
PropertyInfo[] fields = type.GetProperties(); 
foreach (var field in fields) 
{
   string name = field.Name; 
   var temp = field.GetValue(obj, null);
   Console.WriteLine(name + "  " + temp);
}
This way making use of reflection feature of .net. First line of code call the method and assign return value to refobj. Second line of code get the Type of the object and than following line of code get the property of anonymous type and print value of it.
Check out full Source code of to test all technique we discuss
using System;p
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            dynamic newtype= p.AnonymousReturn();
            Console.WriteLine("With Dynamic Type");
            Console.WriteLine(newtype.Name + "  " + newtype.EmailID);
            Console.WriteLine();
            Console.WriteLine("With Creation of same anonymous type");
            object o = p.AnonymousReturn();
            var obj = p.Cast(o, new { Name = "", EmailID = "" });
            Console.WriteLine(obj.Name + "  " + obj.EmailID);
            Console.WriteLine();
            Console.WriteLine("With Reflection");
            object refobj = p.AnonymousReturn();
            Type type = refobj.GetType(); 
            PropertyInfo[] fields = type.GetProperties(); 
            foreach (var field in fields) 
            {
                string name = field.Name; 
                var temp = field.GetValue(obj, null);
                Console.WriteLine(name + "  " + temp);
            }

            Console.ReadLine();
        }

         object AnonymousReturn()
        {
            return new { Name = "Pranay", EmailID = "pranayamr@gmail.com" }; 
        }

        T Cast<T>(object obj, T type) { return (T)obj; }

        public static void Write()
        {
            Program p = new Program();
            object obj = p.AnonymousReturn();
            
        }
    }
}
Output

Tuesday, September 4, 2012

Assign ToolTip to dynamically created colum of silverlight Gridview and How to create style for element runtime

In this post I am going to discuss about displaying tooptip for autogenerated columns of toolkit silverlight and telerik silverlight gridcongtrol. Also goint to discuss about how to create style dynamically for the silverlight control.

How to create style in codebehind i.e. runtime for control To define the style sheet for any silverlight control on runtime there you need to do following things

1. Create Style object with the type of control
var style = new Style(typeof(controlType)); 
Control type can be Grid, GridviewCell, Textblock etc. i.e any valid silverlight control.
2. Add Setter to Created Style Object
style.Setters.Add(new Setter(StylePropertyName, Value));
You need to pass property name and value now after this, below discussion you will find example for the same
3. Attach Created Style to the control type object
controlboject.stylefor = style; 
Now following describe how to user the dynamic style and display tooltip for header of autogenerated columns of gridview.

To apply the style at runtime to autogetnerated column I made use of AutoGenerated Event of the grid in both of the below example.
Telerik
Code for displaying tootip for Telerik grid
private void EditableGV_AutoGeneratingColumn
       (object sender, GridViewAutoGeneratingColumnEventArgs e)
{
   GridViewDataColumn column = e.Column as GridViewDataColumn;

   //for tooltip dispaly
   var style = new Style(typeof(GridViewHeaderCell));
   style.Setters.Add(new Setter(ToolTipService.ToolTipProperty, 
                                                column.UniqueName));
   column.HeaderCellStyle = style; 
}
As you see in above code Style is get created for the Headercell of grid view. ToolTip property style is added by using setting as we discuss above. Lastly assigned created style to headercell style.

Silverlight gridview
Same as Telerik gird,in tool grid I made use of Autogenerated column
private void dataGrid1_AutoGeneratingColumn
            (object sender, DataGridAutoGeneratingColumnEventArgs e)
{
  DataGridBoundColumn column = e.Column as DataGridBoundColumn;
  var style = new Style(typeof(DataGridColumnHeader));
  style.Setters.Add(new Setter(ToolTipService.ToolTipProperty, 
                                                column.Header));
  column.HeaderStyle = style; 
}
Just few code difference , here style is created for headercell only but the name of the class is diffrerent, which you can notice easily by comparing both code.

Saturday, August 18, 2012

Delegate and Action and Func and lamda

This post is about the new delegate types included in .net framework which are Action and Function. How to use this type and what is difference between this two type. Also to resolve confusion between Action, Function, Delegate and Lamda.

Action- This type Points to the function which return void i.e Encapsulate method which is returning void. Action is of Delegate type so its similar to delegate which is pointing to method void. Action is type which make code simple and hide the implementation of delegate.

Syntax of Action Type or Function
>public delegate void Action()
other variation check on msdn : Action

Example of Action
public class ActionDemo
{
     public void ActFunction(int a)
     {
     }
     public void ActFunction1()
     {
     }

     static void Main()
     {
        ActionDemo ad = new ActionDemo();
            

        Action act1 = new Action(ad.ActFunction1);
        act1();     
        Action>int< act = new Action>int<(ad.ActFunction);
        act();
     }
}

Func -This type to point the function which has return value.i.e Encapsulate method which is returning value. Func is of Delegate type so its similar to delegate which is pointing to method which returns value. Func is type which make code simple and hide the implementation of delegat which points to method which return value.
Syntax of Func
>public delegate TResult Func>in T, out TResult<(T arg)
other variation check on MSDN  : Func

Example of Func
public class FuncDemo
{
     public int FuncCall(int a)
     {
            return 0;
     }
     public int FuncCall1()
     {
            return 0;
     }

     static void Main()
     {
        FuncDemo fd = new FuncDemo();

        Func>int< func = new Func>int<(fd.FuncCall);
        func();
        Func>int,int< func1 = new Func>int,int<(fd.FuncCall);
        func1(2);
     }
}
Func Vs Action
Both are Delegate type. Difference between Func and Action is - Func can point to the function which must have return value, Action can point to the function which must have return type void.

Delegate vs Func , Action
 - Both Action and Function are of Delegate type, so both of this type can able to perform same function which can be perform by Delegate.
 - Delegate Can point to function which return value and not return value.
Read more about Deletegate : Delegate

Confusion between Lamda and Delegate, Action, Func
Lamda - Replacement of anonymous function i.e allows to create anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
Action>string< act2 = n => { string s = n + " " + "World"; Console.WriteLine(s); };
act2("abc");

Func>string, string< fun = (n1) => { return n1; };
fun("pranay");

del myDelegate = x => x * x;
    int j = myDelegate(5); 
Conclusion
So by this post you can able to figure out the difference between the types of C#.

Saturday, August 11, 2012

Call Sql Server inbuilt functions using Linq

The post is about the the new class introduce in .net framwork for support of built in SQL-Server function. The SqlFunctions class allows to call SQL-Server function from linq queries while using EntityFramwork.

Following describes how it works
Create Edmx file i.e EntityFramwork file

 Create connection with database

Select Table(s),view(s) and Stored procedure(s)

Created EDMX file

Use SqlFunction in query
Now after deisigning the enityframwork edmx file following is way to utilize the inbuilt sql server functions in Linq queries.
public List<person> SqlTest()
        {
            using (SchoolEntities se = new SchoolEntities())
            {
                var person = from p in se.People
                             where SqlFunctions.CharIndex("a", p.FirstName) == 1
                             select p;
                return person.ToList<person>();
            }
        }
As you see in above linq query its find out all persons whose name starts with letter "a". This is easily achievable by CharIndex function of sql server as you can see in query. This function is part of SqlFunction class avilable in .net framework.

SqlFunction class inside
#region Assembly System.Data.Entity.dll, v4.0.30319
// C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\System.Data.Entity.dll
#endregion

using System;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;

namespace System.Data.Objects.SqlClient
{
 // Summary:
    //     Provides common language runtime (CLR) methods that call functions in the
    //     database in LINQ to Entities queries.
    public static class SqlFunctions
    {
        ........list of other function that is supported by this class
        //
        // Summary:
        //     Returns the starting position of one expression found within another expression.
        //
        // Parameters:
        //   toSearch:
        //     The string expression to be searched.
        //
        //   target:
        //     The string expression to be found.
        //
        //   startLocation:
        //     The character position in toSearch where searching begins.
        //
        // Returns:
        //     The starting position of target if it is found in toSearch.
        [EdmFunction("SqlServer", "CHARINDEX")]
        public static int? CharIndex(string toSearch, string target, int? startLocation)
    }
}
As you can see SqlFuction is static class and contains static methods which calls sql server inbuilt function.
Get more information about SqlFunction class and its method on msdn at : SqlFunction

Thursday, August 2, 2012

Responsive WCF service With ICallbackEventHandler Interface

In this post I am going to discuss about the development of the WCF(duplex) callback service which replay back to consumer i.e client of service and about ICallbackEventHandler Interface implementation which provide response to the user on screen.

Here I designed WCF service which is place order for client and reply back to client that order placed successfully or not. ICallbackEventHandler interface implemented on page display response to client. Before I discuss more here is the screen that shows output

Place Order

WCF service placing order

Order placed successful or not

To accomplish this whole program get divide in two part
1) Design of callback WCF service
2) Design of WEB page with ICallbackEventHandler interface to provide response on screen

Design of callback WCF service
Config file
You need to config WCF service as below to make service reliable(duplex) i.e send response back to client once task done.
<configuration>
  <system.servicemodel>
    <bindings>
      <wsdualhttpbinding>
        <binding bypassproxyonlocal="true" name="sampleBinding" usedefaultwebproxy="true">
      </binding></wsdualhttpbinding>
    </bindings>
    <services>
      <service behaviorconfiguration="returnFaults" name="Service.DemoService">
        <endpoint binding="wsDualHttpBinding" bindingconfiguration="sampleBinding" contract="Service.IDemoService">
      </endpoint></service>
    </services>
    <behaviors>
      <servicebehaviors>
        <behavior name="returnFaults">
          <servicedebug includeexceptiondetailinfaults="true">
          <servicemetadata httpgetenabled="true">
        </servicemetadata></servicedebug></behavior>
      </servicebehaviors>
    </behaviors>
  </system.servicemodel>
  <system.web>
    <compilation debug="true">
  </compilation></system.web>
</configuration>
Thing to note in config file is used protocol called "wsDualHttpBinding" that allows to create reliable session that means it allows to send response back to client who made call to service once task get completed.
WSDualHttpBinding - A secure and interoperable binding that is designed for use with duplex service contracts that allows both services and clients to send and receive messages.

WCF Service file
After creating or modifying you can code service file as below .
using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.Serialization;

namespace Service
{
IDemoService- interface that is implemented in WCF service. whose method get called by application consuming wcf service.
[ServiceContract(CallbackContract = typeof(IClientCallBack))]
    public interface IDemoService
    {
        [OperationContract(IsOneWay = true)]
        void PlaceOrder(OrderItem item);
    }
ServiceContractAttribute.CallbackContract - This attribute allows to set callback contract when the contract is a duplex contract i.e callback interface that get called by service to inform client.
So this allows client applications to listen for inbound operation calls that the server-side service application can send to client application which is independent from client activity. Callback contracts that have one-way operations represent calls from the service that the client can handle.
IClientCallBack- interface that is get implemented on the client side i.e by the application which is consuming the wcf service. Method of this interface get called from wcf service methods which is discussed below.
public interface IClientCallBack
    {
        [OperationContract(IsOneWay = true)]
        void ISOrerPlaceSuccessfully(bool issuccess, float total);
    }
OrderItem - is datacontract class of wcf service.
[DataContract]
    public class OrderItem
    {
        float price;
        string name;
        int qty;
        [DataMember]
        public float Price
        {
            get { return price; }
            set { price = value;}
        }

        [DataMember]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        [DataMember]
        public int Quantity
        {
            get { return qty; }
            set { qty = value; }
        }
    }
DemoService - Implement service contract interface.
public class DemoService : IDemoService
    {
        public void PlaceOrder(OrderItem item)
        {
            IClientCallBack callback = OperationContext.Current.GetCallbackChannel<IClientCallBack>();
            bool success = true;
            //process order 
            float total = item.Price * item.Quantity;
            callback.ISOrerPlaceSuccessfully(success, total);
        }
    }
}
PlaceOrder - method call the callback contract method ISOrerPlaceSuccessfully.
OperationContext.Current -Gets the execution context for the current thread.
code uses the Current property and GetCallbackChannel method to create a channel back to the caller i.e to client from service method. one-way method allows service and client to communicate in both directions independently.

Design of WEB page with ICallbackEventHandler interface to provide response on screen

.ASPX file
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebClient.Default" EnableSessionState="True"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body id="formBody" runat="server" >
    <form id="form1" runat="server">
    <div style="text-align:center">
      <h1>Place Order</h1>
    </div>
    <div>
        <table>
           <tr>
             <td><asp:Label ID="lblItemName" runat="server" Text="Label">Item Number :</asp:Label></td>
             <td><asp:Label ID="lblItemValue" runat="server" Text="Label">Test</asp:Label></td>
           </tr>
           <tr>
             <td><asp:Label ID="Label1" runat="server" Text="Label">Price :</asp:Label></td>
             <td><asp:Label ID="Label2" runat="server" Text="Label">500</asp:Label></td>
           </tr>
           <tr>
             <td><asp:Label ID="Label3" runat="server" Text="Label">Qunatity :</asp:Label></td>
             <td><asp:TextBox ID="txtQunatity" runat="server" ></asp:TextBox></td>
           </tr>
        </table>
        <asp:Button ID="Button1" runat="server" Text="Place Order" OnClick="Button1_Click" />
        <asp:Label ID="lblMsg" runat="server"></asp:Label></div>
    
    </form>
</body>
</html>

.Cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebClient.DemoService;
using System.ServiceModel;
using System.Threading;

namespace WebClient
{
Implementation of Client callback interface - here all method declare in service as part of callback contract get implemented. This method is get called by the service method once task done on service side.
public class CallBack : WebClient.DemoService.IDemoServiceCallback
    {
        public string Message
        {
            get;set;
        }
        public void ISOrerPlaceSuccessfully(bool issuccess, float total)
        {
            Thread.Sleep(5000);
            if (issuccess)
                this.Message = "Order with total of : " + total + " placed successfully";
            else
                this.Message = "Order with total of : " + total + " failed to place";
        }
    }
ISOrerPlaceSuccessfully - is callback method which is get called back from the placeorder method of service. Once response is arrived Message property value get updated which is used to show the order stats on user screen.
Note - Thread.Sleep is used in code just for the delay/demo purpose i.e to show the how it actually works when longer process get called on service. Remove it when make use in project.

ICallbackEventHandler Interface - Used to indicate that a control can be the target of a callback event on the server.
The ICallbackEventHandler is a wrapper on XMLHTTP. So that it allow to call the serverside method without any postback and there is no need to wirte any javascript/jquery for making ajax call all things get handle this interface in .net framework.
public partial class Default : System.Web.UI.Page, ICallbackEventHandler
    {
        static CallBack callback;
        DemoServiceClient client;
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            setupClientSideCallback();
            callback = new CallBack();
            InstanceContext ic = new InstanceContext(callback);
            client = new DemoServiceClient(ic);
            OrderItem item = new OrderItem();
            item.Name = "Test";
            item.Price = 12;
            item.Quantity = Convert.ToInt32(txtQunatity.Text);
            lblMsg.Text = "Placing Order...";
            client.PlaceOrder(item);
        }
Here in above code callback is variable of type Callback clas which is static because on the order pace button get clicked value of callback is remain as it is i.e its not get created again for later on use in GetCallbackResult method which is discussed below.

OnCallback is method defined at client side which is used to call back once the clientscript register by serverside code and eventArg is a variable defined at the client side which holds the parameter value.
protected void setupClientSideCallback()
        {
           string ScriptRef = this.ClientScript.GetCallbackEventReference(this, "'" + 0 + "'", "OnCallback", "'" + lblMsg.ClientID + "'");
            formBody.Attributes.Add("onload", ScriptRef);
            string script = "<script language="javascript" type="text/javascript">
 " +
                         " function getResponse() " +
                         " { " + ScriptRef + " } " +
                         " function OnCallback(Result,Context) " +
                         " { " +
                         " var lbl=document.getElementById(Context); " +
                          " lbl.innerText=Result ; " +
                          " setTimeout(getResponse, 1000); " +
                          " } " +
                         " 
</script> ";
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "ClientCallback", script);

        }

Javascript code - get register when placeorder button get clicked. After that to check the response arrived from the wcf service or not it makes call at regular interval by using setTimeout function. So it works like timer which execute set of code at regular interval.

The ICallbackEventHandler interface has two methods which required to be implemented in the page.

RaiseCallbackEvent - This event is called when the call from client side (Javascript)i.e from browser to server. This is the event to handle the call back handler. Here eventArgs is a parameter which is passed from client side.
GetCallbackResult - This methos returns the result of the callback event to client side i.e from serverside to browser.
string ICallbackEventHandler.GetCallbackResult()
        {
            if (callback!=null && callback.Message != null)
            {
                return  callback.Message;
            }
            return "Placing Order..." ;
        }

        string eventArgument;

        void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
        {
            this.eventArgument = eventArgument;
        } 
    }
}
Summary
WCF reliable(duplex) service useful to inform the cosumer of service i.e client of service that task completed or not by calling the consumer i.e client from service. This kind of suff useful when we are creating modules where payment of order take place as I did in my implementation.

Note
I cannot upload code over here but if you want code of the same mail me at pranayamr@gmail.com or just follow the post step and paste code in your project.
Javascript code is currenly working on IE only which will be modified soon.

Thursday, July 26, 2012

Count() and Count property

In this small post I am going to discuss about the Count property and Count() method that used to return count of number of element in collection.
Count property
Each collection object which is inherited from ICollection<T> Interface has count property which returns number of element in collection.
Count() Function
But the things change when you make use of System.Linq namespace in you code. when you make use of this namespace you get Count() method which also returns you number of element in you collection. But the point to not here is Count() is extestion method of IEnumerable<T> class. Check the following images
Without using Linq namespace

With Using Linq namespace

IEnumerable<T> Source after query

After Converting Source to ICollection<T> type

Code on which I tested
List<string> lst = new List<string>() { "abc", "def" };
int a = lst.Count;
var b = lst.Where(x => x == "abc").Count();
List<string> ls = lst.Where(x => x == "abc").ToList<string>();
a= ls.Count;
If you are using Count() method on source which implements ICollection<T> interface than extension method make use of the Count property of it and returns no of element. If the source not implemented from the ICollection<T> than it do perform the operation on the element of source and return count of it.

Point to Note
- As per MSDN : Retrieving the value of Count property is an O(1) operation.
- Count() function perform the operation and return value, so its slower than count property.

Conclustion
Although its stated that Count() function make use of count property if the source implemented from ICollection<T> than use cont property, its better to use count property directly if source implemented ICollection<T> otherwise go for Count() get number of element in source.

Tuesday, July 24, 2012

Enhance String type to get Converted In Given Type

Problem
Recently I was working on the project where I need to read the excel file data and have to convert data of it in strong entity which is consist of number of property. For this I know the sequence of the data in excel file and name & type of property of the entity which is going to store the value. But the real problem is I need to convert the string value in property type.

Solution
One of the solution to this is create function and pass the type & string value which
return data in type which is passed. Below is implementation function
public static T ConvertData<T>(this string s)
{
     if(!sting.IsNullOrEmpty(s))
     {
        if (typeof(T) == typeof(System.Decimal))
        {
           return (T)(object)Convert.ToDecimal(s);
        }
     }
     //same code get replicated for int, float etc. 
     return default(T);
}
In above code I created on generic extension method for string type. Function convert string type to the type I want.
Cons
  • In above implementation I written code for Decimal type but same code I have to replicate for other types also i.e for int, float etc.
  • As you see in code after converting data in given type I again need to reconvert into object and than into type T again. This also add overhead of type casting.
  • Code is become long and unclear.

So to make code clean , clear and easy to understand. I fond one method in C#.net which is Convert.ChangeType which helps me to create the method i want easily.
Below is my Simpler and easy solution
public static T ConvertData<T>(this string s)
{
     if(!sting.IsNullOrEmpty(s))
     {
         return (T)Convert.ChangeType(s, typeof(T),null);
     }
     return default(T);
}
So in above solution I just need to write one line of the code which do the task for me.
Actual syntax of method is
public static Object ChangeType(
 Object value,
 Type conversionType,
 IFormatProvider provider
)
As you can see in syntax third parameter is provider which is null in my case but you can pass the formater by creating as you need.
Now following code is just show how to use this method in code i.e ConvertData method
string s = "123";
int a = s.ConvertData<int>();
So this method can be used any project and also fit in number of requirement.

Thursday, July 19, 2012

Extending Enum to return attached string

No of time there is requirement of getting string of Enum value to display purpose or to perform other task. So to deal with this requirement I wrote one extension function that get the string attached with the enum value.
Note : here attached string value is the attribute that is attached with each enum value that you are creating in enum variable.

Following is extension function to get string attached with enum.
public static class MyExtensions
{
   public static string GetEnumDescription(this Enum value)
   {            
         FieldInfo fi = value.GetType().GetField(value.ToString());

         object[] attributes = fi.GetCustomAttributes(true);

         if (attributes != null &&
            attributes.Length > 0)
                return ((DescriptionAttribute) attributes[0]).Description;
         else
                return value.ToString();
    }
}
The code above is making use of the reflection feature of .net framework. With the help of reflection it first get the information about the field and than get the attribute attached with that field. Attribute attached with enum value is DescriptionAttribute so code convert attribute object to DescriptionAttribute and return string attached with it. If there is no attribute attached with enum value it returns the interger value of enum as string.

Note : Attribute is metadata attached with the type you can attache metadata with class, function , property etc. Read More: Attributes (C# Programming Guide)

Following is simple program that is making use of extension function and to display the string attached with the enum value.
class Program
    {
        public enum WeekDay
        {
            [Description("Monday")]
            Monday,
            [Description("Tuesday")]
            Tuesday
        }

        static void Main(string[] args)
        {
            string str = (WeekDay.Monday).GetEnumDescription();
            Console.WriteLine(str);
            Console.ReadLine();
        }
    }
In above code there is enum create with the name WeekDay and as per the requirement it require to attache attribute with the each enum value to function to work properly if no attribute attached with enum value than function return value of enum i.e interger value associated with the enum.

So when code in "Main function" get executed call to function "GetEnumDescription" it return "Monday" as output on the console window which is associated with enum value.

Tuesday, July 17, 2012

Design TypeDataSet from Storedprocedure using temptable

I found one problem recently while designing TypeDataset in VisualStudio using storedproceudre which is making use of temporary table to get result.

Here is detail of the it what I did and how I resolved the issue.

Step 1: Created Procedure with Temporary table
create PROCEDURE [dbo].[GetData]
AS
begin
   create TABLE #MyTable  (
  ID int,
  Name nvarchar(50) )

 INSERT INTO #MyTable (ID, Name)
 SELECT  PersonID, FirstName + ' ' + LastName
 FROM  dbo.Person
 
 SELECT ID,
  Name 
 FROM #MyTable
end


Step 2: Add TableAdapter in the design view of TypeDataSet and create database connection


Step 3: Create Procedure or Select Existing procedure


Step 4 : Select Procedure that I created already
Note : here it's not displaying DataColumn of select statement related to proceudre


Step 5 : Click on finish it display that in valid object #table

so it doesn't able to create tableadapter for procedure and display like this

Solution
To resolve this issue you can try one of the following solution , I tried first solution because its easy and not require to change in my existing storedprocedure code

Solution 1
Just add below line at top of the procedure after begin statement
SET FMTONLY OFF
This will resolve the issue and allow to create tableadapter easily without any error. So procedure will be
create PROCEDURE [dbo].[GetData]
AS
begin
  SET FMTONLY OFF
   //code of the procedure as above
end
Solution 2
To try this solution just create table variable instead of temporary table in procedure. So procedure will be
create PROCEDURE [dbo].[GetData]
AS
begin
  DECLARE @MyTable TABLE (
  ID int,
  Name nvarchar(50) )

 INSERT INTO @MyTable (ID, Name)
 SELECT  PersonID, FirstName + ' ' + LastName
 FROM  dbo.Person
 
 SELECT ID,
  Name 
 FROM @MyTable
end

After trying the above solution tableadapter on XSD file will be like this

Friday, July 6, 2012

Align Text in Autogenerated Column of Rad Silverlight Girdview and Silverlight Gridview

In this post I am going to show how you can align data in autogenrated columns cell of Silverlight gridview and also of Rad Control Silverlight Gridview.
In both of the below Example of Gridview I want to align the numeric data left in my cell and other except numeric remain in same format.

RAD Silverlight Gridview
XAML code of Silverlight Gridview
<telerik:RadGridView  
         Name="clubsGrid" 
         ItemsSource="{Binding Clubs}"
 AutoGeneratingColumn="clubsGrid_AutoGeneratingColumn"
         Margin="5">
</telerik:RadGridView>
Thing to note down here in XAML code is I register AutoGeneratingColumn =
"clubsGrid_AutoGeneratingColumn" event which is get called when Auto columns get generated for gridview.
private void clubsGrid_AutoGeneratingColumn(object sender, GridViewAutoGeneratingColumnEventArgs e)
{
 GridViewDataColumn column = e.Column as GridViewDataColumn;
        if (column.DataType == typeof(int)
           || column.DataType == typeof(decimal)
           || column.DataType == typeof(float)
                )
       {
           column.TextAlignment = TextAlignment.Right;
       }
 }
As you see in above code I attached event called AutoGeneratingColumn on gridview control and checking DataType of each column which in turn check the datatype of the property which going to be attached with that column. So when the DataType is int or decimal or float I set TextAlignment propery of column to Right so display numeric value in right.

Output
So the output shows the column with numeric value "StadiumCapacity" is align to right.

Silvelight SDK Gridview control
There are two way to achieve this in Silverlight gridview
     1) Setting cell style from code behind file but creating Style
     2) Setting cell style from code behind file but using resource 
XAML code of Silverlight Gridview
<sdk:DataGrid   IsReadOnly="True" 
       Name="mysGrid" 
      AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"
       ItemsSource="{Binding Clubs, Mode=OneWay}">
</sdk:DataGrid>
Same as RAD Gridview here also wrote AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" which take care of Autogenerated coulmn.

First Way : Creating Sytle
 private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
 {
    if (e.PropertyType == typeof(int)
        || e.PropertyType == typeof(decimal)
        || e.PropertyType == typeof(float)
       )
    {
        var rightCellStyle = new Style(typeof(DataGridCell)); 
               
        rightCellStyle.Setters.Add(new Setter(
             Control.HorizontalContentAlignmentProperty,
             HorizontalAlignment.Right));

        DataGridBoundColumn obj = e.Column as DataGridBoundColumn;
        obj.CellStyle = rightCellStyle;
     }
}
As you see in above code same as RAD gridview control here e.PropertyType used to check the type of the autogenerated column but the change over here is need to create cell style and than assing the style to CellStyle property of gridview column.

Second Way : Using Resource
In this solution you need to register the style for the gridview cell as shown below and than you can use this to assign to CellStyle.
Resource in App.XAML
  <Style x:Key="RightCellStyle" TargetType="sdk:DataGridCell">
      <Setter Property="HorizontalContentAlignment" Value="Right" />
  </Style>
CodeBehind file
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(int)
        || e.PropertyType == typeof(decimal)
        || e.PropertyType == typeof(float)
       )
       {
           DataGridBoundColumn obj = e.Column as DataGridBoundColumn;
           var rightCellStyle = Application.Current.Resources["RightCellStyle"] as Style;
           obj.CellStyle = rightCellStyle;
       }
}
Now in this code you dont require to create any style you just need to fetch the resource that you register in the App.XAML file and need to convert in Style.

Output
So the output shows the column with numeric value "StadiumCapacity" is align to right.
Note : in both the way output remain same.

Sunday, June 17, 2012

C# State machine - Yield

Yield keyword introduced in C#2.0. Yield keyword allow to create state machine and allow to iterate through the collection of objects one by one.

yield is a contextual keyword used in iterator methods in C#. yield use like following in iterator block
public IEnumerable methodname(params)
{
      foreach(type element in listofElement)
      {
         ...code for processing 
         yield return result;
      }
}
Note : here IEnumerable can be replace by IEnumerable<T>.
What yield keyword does ? - "When you process the collection by this keyword in iterator block. It pause the execution return proceeded  element or the current element of the collection. And when you call it again it start execution with the next element which in turn become current element for that call. This thing get continue till it reach the last element of collection."

Now I am going to show how you can gain some performance when make use of yield keyword.
In this example I am checking each datarow of the datatable weather it is empty or not.

Code With Yield Keyword
static void Main(string[] args)
{
     int[] arr = new int[] { 1, 2, 3 };

     DataTable table = new DataTable();
     table.Columns.Add("ItemName", typeof(string));
     table.Columns.Add("Quantity", typeof(int));
     table.Columns.Add("Price", typeof(float));
     table.Columns.Add("Process", typeof(string));
     //
     // Here we add five DataRows.
     //
     table.Rows.Add("Indocin", 2, 23);
     table.Rows.Add("Enebrel", 1, 10);
     table.Rows.Add(null, null, null);
     table.Rows.Add("Hydralazine", 1, null);
     table.Rows.Add("Combivent", 3, 5);
     table.Rows.Add("Dilantin", 1, 6);

     foreach (DataRow dr in GetRowToProcess(table.Rows))
     {
         if (dr != null)
         {                    
            dr["Process"] = "Processed";
            Console.WriteLine(dr["ItemName"].ToString() 
+ dr["Quantity"].ToString() + " : " + dr["Process"].ToString());
            //bool test = dr.ItemArray.Any(c => c == DBNull.Value);
         }
      }
      Console.ReadLine();
}
private static IEnumerable<datarow>GetRowToProcess(DataRowCollection                                                         dataRowCollection)
{
     foreach (DataRow dr in dataRowCollection)
     {
          bool isempty = dr.ItemArray.All(x => x == null || 
(x!= null && string.IsNullOrWhiteSpace(x.ToString())));

          if (!isempty)
          {
             yield return dr;
             //dr["Process"] = "Processed";
          }
          else
          {
             yield return null;
             //dr["Process"] = " Not having data ";
          }
          //yield return dr;
     }
}
Code Without Yield Keyword
private static IList<datarow> GetRowToProcess(DataRowCollection dataRowCollection)
{
    List<datarow> procedeedRows = new List<datarow>();
    foreach (DataRow dr in dataRowCollection)
    {
        bool isempty = dr.ItemArray.All(x => x == null || 
                           (x!= null && string.IsNullOrWhiteSpace(x.ToString())));

        if (!isempty)
        {
          procedeedRows.Add(dr);
        }
     }
     return procedeedRows;
 }

static void Main(string[] args)
{
   //code as above function to create datatable 
   List<datarow> drs= GetRowToProcess(table.Rows);
   foreach (DataRow dr in drs)
   {
     //code to process the rows 
   } 
}

Now Difference between two code
In code (Code without yield keyword)
in this code there is extra list is get created which point to the rows which is matching the condition and than there is loop for processing each row.
Disadvantage with this code is extra list is get created which occupies the extra space i.e memory as well as slow down the code.
In code (Code with yield keyword)
in this there no extra list is get created , with help yield one row at a time which is matching condition is get processed.
Advantage of the code is there is no extra list is get created and also it doesn't cause any performance problem.

Following example of linq with the yield keyword
void Main()
{
   // This uses a custom 'Pair' extension method, defined below.
   List<string> list1 = new List<string>()
 {
     "Pranay",
     "Rana",
     "Hemang",
     "Vyas"
 };
   IEnumerable<string>  query = list1.Select (c => c.ToUpper())
  .Pair()         // Local from this point on.
  .OrderBy (n => n.length);
}

public static class MyExtensions
{
 public static IEnumerable<string> Pair (this IEnumerable<string> source)
 {
  string firstHalf = null;
  foreach (string element in source)
  if (firstHalf == null)
   firstHalf = element;
  else
  {
   yield return firstHalf + ", " + element;
   firstHalf = null;
  }
 }
}
There is other statement besides yeild return
yield break
stops returning sequence elements (this happens automatically if control reaches the end of the iterator method body).
The iterator code uses the yield return statement to return each element in turn. yield break ends the iteration.

Constraint
The yield statement can only appear inside an iterator block, which might be used as a body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.
  • A yield statement cannot appear in an anonymous method.
  • When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses.

Friday, June 15, 2012

String concat with null

Source : My Higest Voted answer on StackOverflow
Question This is valid C# code
var bob = "abc" + null + null + null + "123";  // abc123
This is not valid C# code
var wtf = null.ToString(); // compiler error
Why is the first statement valid?

Answer
The reason for first one working:
From MSDN:
In string concatenation operations,the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.

More information on the + binary operator:

The binary + operator performs string concatenation when one or both operands are of type string.

If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual `ToString` method inherited from type object.

If ToString returns null, an empty string is substituted.

The reason of the error in second is:
null (C# Reference) - The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.


Thursday, June 14, 2012

Concat() vs Union()

Recently I worked with the two method on my enumeration object that are Union() and Concat(). This methods used to mostly used by developer to combine two collection in single collection, but that's not true here in this post I am going to show the actual difference between this two methods.

Def. from MSDN
Enumerable.Concat  - Concatenates two sequences.
Enumerable.Union    - Produces the set union of two sequences by using the default equality comparer.

If you read the def. carefully you actually find difference between two methods. Now to understand it better way have look to below example
int[] ints1 = { 1, 2, 3 };
int[] ints2 = { 3, 4, 5 };
IEnumerable union = ints1.Union(ints2);
Console.WriteLine("Union");
foreach (int num in union)
{
   Console.Write("{0} ", num);
}
Console.WriteLine();
IEnumerable concat = ints1.Concat(ints2);
Console.WriteLine("Concat");
foreach (int num in concat)
{
   Console.Write("{0} ", num);
}
Output


The output shows that Concat() method just combine two enumerable collection to single one but doesn't perform any operation/ process any element just return single enumerable collection with all element of two enumerable collections.

Union() method return the enumerable collection by eliminating the duplicate i.e just return single element if the same element exists in both enumerable collection on which union is performed.

Important point to Note
  • By this fact we can say that Concat() is faster than Union() because it doesn't do any processing. 
  • But if after combining two collection using Concat() having single collection with too many number of duplicate element and if you want to perform further operation on that created collection takes longer time than collection created using Union() method, because Union() eliminate duplicate and create collection with less elements.

Wednesday, June 6, 2012

Format Number To Display

Number of time the end user / client require to display numeric data in different format. In this post I am going to discuss about the various type of the custom format that provided by C#.net to achieve requirement.
Here I am going to discuss each format one by one

"0" Custom Specifier
ToString("00000") - format put the leading 0 when number get display if digits in number less than the number of zero specified. when the below code is get executed output display 01234 because the number of digit less than the number of zero.
double value;
value = 1234;
Console.WriteLine("Format 1:  " + value.ToString("00000"));
Console.WriteLine();
ToString("00.00") - format do same thing as above replace zero if the number digit less , but the zero after decimal point allows to display digit equals number of zero after decimal if the number of digit less than display zero in place of that. output of the following code is 01.24 i.e only 2 digit allowed after decimal point. Note : - decimal point is display as per specified culture.
value = 1.235;
Console.WriteLine("Format 2:  " + value.ToString("00.00", 
                CultureInfo.InvariantCulture));
Console.WriteLine();
ToString("0,0") - format cause to display comma between number. here when the following code is get executed , is get display after every three digit 1,234,567,890. Note : - in this comma get replace by the culture.
value = 1234567890;
Console.WriteLine("Format 3:  " + value.ToString("0,0",
                CultureInfo.InvariantCulture));
Console.WriteLine();
ToString("0,0.0") - format is combination of above format.
value = 1234567890.123456;
Console.WriteLine("Format 4:  " + value.ToString("0,0.0", 
                CultureInfo.InvariantCulture));
Console.WriteLine();

Output

"#" Custom Specifier
This specifier does same thing as "0" specifier do but the basic difference is it doesn't anything if the number is no equal to # where as "0" specifier replace 0 if digit not exists.
ToString("#####") or ToString("#") - format allow to replace each digit by #, output of below code execution is 9867752985 which is differ from "0" specifier.
value = 9867752985;
Console.WriteLine(value.ToString("#####"));
Console.WriteLine(value.ToString("#"));
Console.WriteLine();
Below code does same as above but format number by replace each # by each digit. so the output of the code is 98-67-75.
value = 986775;
Console.WriteLine(value.ToString("[##-##-##]"));
Console.WriteLine();
Below code execution again format number and output display it as (986) 77-52985
value = 9867752985;
Console.WriteLine(value.ToString("(###) ###-####"));
Console.WriteLine();
Output


"." Custom Specifier
This specifier is already discuss with the "0" specifier this useful to display numeric number if the digit is not present than 0 get display on that place i.e at the start or end. so the output of below code is "01.20" and if I set value = 12 than the output is "12.00". But here I set culture info so that output is "01,20" so "." get replace by ",".
value=1.2
Console.WriteLine(value.ToString("00.00",CultureInfo.CreateSpecificCulture("da-DK")));

"%" Custom Specifier
Format cause the number to display with "%" and multiply number with 100. so if the number is 0.86 after applying % specifier it get display as "8.6%" if the number is 86 than output will be "8600%". Below code execution does the same thing
value = .086;
Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture));
Console.WriteLine();

value = .869;
Console.WriteLine(value.ToString("00.##%", CultureInfo.InvariantCulture));
Console.WriteLine();

value = 86;
Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture));
Console.WriteLine();
Oputput


"‰" Custom Specifier
per mille character (‰ or \u2030) format multiply the number by 1000. So the output of below code execution is 3.54‰ . But I don't think this format is useful somewhere.
value = .00354;
string perMilleFmt = "#0.## " + '\u2030';
Console.WriteLine(value.ToString(perMilleFmt, CultureInfo.InvariantCulture));

"E" and "e" Custom Specifiers
This cause number to be display in scientific notation format with the "E or e" symbol.
value = 86000;
Console.WriteLine(value.ToString("0.###E+0", CultureInfo.InvariantCulture));
Console.WriteLine();

Console.WriteLine(value.ToString("0.###E+000", CultureInfo.InvariantCulture));
Console.WriteLine();

value = -80;
Console.WriteLine(value.ToString("0.###E-000", CultureInfo.InvariantCulture));
Console.WriteLine();
Output


";" Section Separator
This allow to display number according to number sign. As you can see in below code the fmt variable which is format I am going to apply on my number here first format before ; is for positive number , second format is for negative number and last format is for the zero value.
Basically its "Positive;negative;zero" format.
You can see the what it does in output of this code.
double posValue = 1234;
double negValue = -1234; 
double zeroValue = 0;

string fmt = "+##;-##;**Zero**";

Console.WriteLine("value is positive : " + posValue.ToString(fmt));    
Console.WriteLine();

Console.WriteLine("value is negative : " +negValue.ToString(fmt));    
Console.WriteLine();

Console.WriteLine("value is Zero : " + zeroValue.ToString(fmt));
Console.WriteLine();
Output


Source :  http://msdn.microsoft.com/en-us/library/0c899ak8.aspx