Pranay Rana: July 2012

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.