Pranay Rana: 2010

Friday, December 31, 2010

Explicit and Implicit Casting of object and Role of 'is' and 'as' keyword in Explicit casting

In this post I am going to discuss about the casting of object form one type to another type and what the thing require to keep in mind when casting object.

Casting basically take place we are using relating between classes i.e INHERITANCE. Classes have parent child relationship i.e is-a relationship between them.
To understand it take example of below diagram

As show in above image Employee and Manager is having is-a relationship with person i.e Inherited from person class.
Now I have one method in my main class which take Employee as argument and do processing on the property of the class.

public void ProcessData(Person p)
{
....process data 
Console.WriteLine(p.ToString());
}

Implicit conversion
Implicit conversion take place when there is is-a relation between two classes i.e Inherited form other. As per diagram Employee is Inherited from Person Class and so that as per OOD rule there is no need to convert Employee class to Person class.

Exmaple
public void testdata()
{
 Employee emp = new Employee();
 emp.Age = 25;
 emp.BirthDate = DateTime.Now;
 emp.Height = "5 ' 3";
 emp.salary = 2000;
 emp.type = 1;
 ProcessData(emp);
}

When you compile and run the code there is no error because its Implicit conversion from child to parent.

Explicit conversion
Where there is no relation between classes and if you want to pass the object of another type to method than you need to convert it explicitly.

Example
Consultant cons = new Consultant();
 cons.Age = 25;
 ....
object obj = cons;
 ProcessData((Employee) obj);

Note
Above code not give any kind of complier error but it throws runtime InvalidCastException if it not able to cast to the type

Following is solution to avoid InvalidCastException at runtime because of Explicit conversion.

Solution 1
Catch the exception and handle it.
Consultant cons = new Consultant();
 cons.Age = 25;
 ....
 try
 {
   ProcessData((Employee) cons);
 }
 catch(InvalidCastException ex)
 {
    ... process exception
 }


Solution 2
Make use of  'as' keyword of C#. It does conversion from one object to another object and return Null if it not able to convert. Use it when you want to convert object form one type to another object.
Syntax
  type t =expression as type;

Example
Employee emp = new Employee();
  Person p = emp as Person; 
  if(p!=null)
  {
   .. process data
  } 
  else
  {
   .. display error message or do antohter code
  }

Solution 3
Make use of 'is' keyword of C#. It does conversion from one object to another object and return false if it not able to convert. Use it when you want to check it convertible or not.
Syntax
  type t = expression is type

Example
Employee emp = new Employee();
  if(emp is Person)
  {
    Person p = (Person)emp;
    .. process data
  } 
  else
  {
   .. display error message or do antohter code
  }

Difference between as and is
  • as operator do conversion form one type to another type and return Null if converstion
    fails. There is no need to conversion again if its convertible as shown in example code.
  • is operator checks weather one object is convertible in another type or not and return false if not. So need to convert object to base type if it convertible as shown in exapmple code.
Summary
'is' and 'as' keyword play important role when we do the casting of the related objects Explicitly. But you need to use it according to situation as we discuss in Difference section of this post.

Friday, December 24, 2010

(Linq and Nullable Values) OR ( SQL ISNULL with LINQ)

Here in this small post I am going to show you, how you can deal with the Nullable values in LINQ queries and how you can achieve functionality like SQL ISNULL function.
Read following post before continuing with this

Problem

I am dealing with the LINQ queries, In which I have to diplay "N/A" were the value is null for the given property/column.

Solution 1
You can use ternary operator as shwon in below example. Here MobileNo = "N/A" for the null values
var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
 Id=u.Id,
 FirstName=u.FirstName,
 LastName=u.LastName,
 UserId=m.UserId,
 MobileNo = (m.MobileNo == null) ? "N/A" : m.MobileNo
};

Solusion 2
Use special Coalescing operator operator (??) as showin in below example. Here MobileNo = "N/A" for the null values
var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
 Id=u.Id,
 FirstName=u.FirstName,
 LastName=u.LastName,
 UserId=m.UserId,
 MobileNo = m.MobileNo  ?? "N/A" 
};

Summary
Above solution shows how easily we handle null value as well as achieve functionality of the SQL ISNULL function.

Coalescing operator - ??

Coalescing operator is new operator added in C#2.0. Coalescing operator is also known as ??.

How Coalescing operator works?
Note 
Here I am just going to show how coalescing operator replace ternary operator. i.e not comparing ternary operator with coalescing operator.
Ternary Operator
Syntax
Type variable = booleanCondition ? exp1 : exp2;

Ternary operator assign exp1 to variable if the booleanCondition return true or exp2 if booleanCondition return false.
Consider Case were I am coding with the nullable type using ternary opertor.

Example
Nullable<int> a = null;
Nullable<int> b = 10;
int c = a==null ? b.Value : a;

Coalescing operator
Coalescing operator work some what similar to ternary operator but it works only with the Nullable types only. so its sort hand operator to deal with Nullable types only.

Syntax
Type variable = nullalbeTypeVariable1.Value ?? nullableTypeVariable2.Value;

Operator its check value of nullalbeTypeVariable1 if its as real value rater tan null it assin value to variable else assign value of nullableTypeVariable2.

Example
Nullable<int> a = null;
Nullable<int> b = 10;
int c = a ?? b.Value;

Summary
Coalescing operator deals with Nullable type and its sort for long ternary operator expression.

Wednesday, December 22, 2010

Nullable type -- Why we need Nullable types in programming language ?

What is nullable type ?
Nullable type is new concept introduced in C#2.0 which allow user to assingn null value to primitive data types of C# language. Important to not here is Nullable type is Structure type.

Why nullable types needed in programming?
In database missing information in records represented by null values even if its primitive types of data like varchar, int, datetime etc. So the problem arises when fetch data from the data base, how to represent missing null value in our program because primitive data only stores real values in C#.
For example
Consider system where I maintaining one city people records, which stores birth date and death date to calculate the age. But database stores null value in death date field for the people who is still alive.

Pseudocode code - formula for the age calculation is
//for the people who is already dead  
age = deathdate - birthdate;       
//for the people who is till alive
age = todays date - birthdate;
  

Solution 1
Before introduction of nullable vaue in older days we use some junk value to represent value is not present. For example
int a = -99;
DateTime dt = new DateTime(1901, 1, 1);

Pseudocode code for the above problem is
//for the people who is already dead  
age = deathdate - birthdate;       
//for the people who is till alive -- check date value is equal to dt i.e 1/1/1901
age = todays date - birthdate;
 
So we compare this value and get information that value is not real value.

Problem with this is we have to remember this value and have to hardcode this value in our program structure.

Solution 2
Nullable type
Syntax
Nullable<int> variable= null;
or
int? variable= null;

Properties
Nullable types has two important property
  • Hasvalue - indicate that variable contains real values or not. It returns false if variable contains no value and true if some real values is stored in it.
  • Value - Return real value stored in variable. It throws InvalidOperationException exception.
Method
GetValueOrDefault - Return value stored by Nullable type variable or the value passed in function.
There are two overload of this function.
Syntax
  • GetValueOrDefault() - returns real value or the default value of object.
  • GetValueOrDefault(T) - returns real value or the value passed.
Pseudocode Code for above problem
//variable define
DateTime? deathdate = null;

//for the people who is already dead  
if( deathdate.Hasvalue) // checking for the nullable varialbe has value or not
age = deathdate.Value - birthdate;       
//for the people who is till alive
else
age = todays date - birthdate; 

Summary
I hope now people why the Nullable feature get included in C#2.0.

Related post

Monday, December 20, 2010

Constrain on custom generic type

Generics is most important topic included in C# 2.0. Generics are use full in number of way when we do coding in project. One of the most important use is we want to use collections with type safety and without boxing/unboxing.

But here I am going to discuss about the type of constrain we apply one the custom type we create using generics.

Reference Type
Constrain ensure that type argument is Reference Type. i.e Class, Interface, Delegates, Array etc.
Syntax
       Class A<T> where T : class 
Example
Valid InValid
A<MyClass>
A<InterfaceME>    
A<float[]>

A<int>
A<float>
Note :
Always come first when multiple constrain applied.

Value Type
Constrain ensure that type argument is Value Type. i.e int, float, struct, enum etc. But not nullable types.
Syntax
       Class A<T> where T : struct
Example
Valid
InValid
A<int>
A<float>     
A<Myclass>
A<InterfaceME>
Note :
Always come first when multiple constrain applied.

Constructor Type
Constrain ensure that type argument must have parameterless constructor to create instance of type argument. i.e any value type; nonstatic, nonabstract with parameterless constructor.
Syntax
       Class A<T> where T : new() 
Note :
Always come last when multiple constrain applied.
Derived Type
Constrain ensure that type argument must derived or implemented form specified type.
Syntax
       Class A<T> where T : MyClass
       Class A<T> where T : InterfaceME
Example
class A<T> where T : Stream
ValidInValid

A<MemoryStream> 
A<object>
A<string>
class A<T> where T : IDisposible
ValidInValid
A<DataTable> A<StringBuilder>
Points to remeber
You can specify multiple interface for type argument in this constrain but only one. Because no type can derived from more than once class.
ValidInValid
class A<T> where T : 
Stream,IDisposible,IEnumerable<T>
class A<T> where T :   
Stream,ArrayList,IEnumerable<T>
Note:
Specified class must not be struct, a sealed class
or not belonging to special type
System.Object
System.Enum
System.ValueType
System.Delegate

Summary
Its good to focus on Constrain type when you are implementing own custom types. This Constrain also applicable to generic methods with type argument.

Friday, December 17, 2010

Conversion Operators - Similarity and Difference between Cast and OfType(T)

Conversion operators use full in number of way. But here in this post I am going to talk about two use full functions Cast<T> and OfType(T) of C# that is use full when you are playing with the non generic collection or untyped object collection or untyped Sequence .  

Cast<TResult>   
TResult - type to convert element of source to.  
Example
ArrayList classicList = new ArrayList();
classicList.AddRange ( new int[] { 3, 4, 5 } );
IEnumerable<int>castSequence = classicList.Cast<int>();

OfType(T)
TResult - type to convert element of source to.
Example
ArrayList classicList = new ArrayList();
classicList.AddRange ( new int[] { 3, 4, 5 } );
IEnumerable<int> ofTypeSequence = classicList.OfType<int>();

Similarity between Cast<T> and OfType(T)
  • Implemented by using Deferred execution.
  • Allows to invoke query operator on non generic collection such as ArrayList.
  • Cannot be applied to collections tat are parameterized by IEnumerable<T>.
  • Returns the Elements in source that can be cast to type TResult ( Resulttype).
Difference between Cast<T> and OfType(T)
Cast<T> throws InvalidCastException when not able to cast all source element in Result type. Where as OfType(T) provide set of element from source which can be convertible in Result type without throwing any error or exception.

Consider below example code to understand this very well.
Add DateTime type to ArrayList with integer elements.

ArrayList classicList = new ArrayList();
classicList.AddRange ( new int[] { 3, 4, 5 } );

DateTime offender = DateTime.Now;
classicList.Add (offender);

IEnumerable<int> ofTypeSequence = classicList.OfType<int>();
IEnumerable<int> castSequence = classicList.Cast<int>();

try
{ 
   Console.WriteLine(ofTypeSequence.Count().ToString()); 
   Console.WriteLine(castSequence.Count().ToString());
}
catch (InvalidCastException ex)
{
   Console.WriteLine("Notice what the offending DateTime element does to the Cast sequence");
}

Output

When you run above code you see exception throws by code at run time when try to display count of element converted by Cast<T>. Where as OfType(T) return count 3 so OfType(T) contains {3,4,5} and eliminate DateTime element.

Thursday, December 16, 2010

SQL to LINQ ( Case 8 - Filter data by RowNumbers )

Case 8 : Filter data by RowNumbers

Here in this case I am going to show how you can filter your data by RowNumbers that you assigned to your recored(s).

So to filter data in SQL (SQL server-2005) we use RowNumber function and than we use <=, >= or BETWEEN  to filer data.

SQL query

SELECT *
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [id]) AS [ROW_NUMBER],
   [id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role]
    FROM [User] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN 11 AND 20
ORDER BY [t1].[ROW_NUMBER]

In above query as you can see ROW_NUMBER() function assign number to records and than we use that number in outer query to filter data between 11 to 20.


LINQ query
But in LINQ it make use of two functions
  • Skip: Bypasses a specified number of elements in a sequence and then returns the remaining elements. (See this link.)
  • Take: Returns a specified number of contiguous elements from the start of a sequence. (See this link.)

So LINQ query is something as below.
var users = from u in Users
select u;

var filterUsers= users.OrderBy (p => p.Id).Skip (10).Take(10);


In above code we are selecting data first and than we are applying Skip and Take to get data between 11 to 20 records.
Graphic representation

Summary
Best example of this is when you are using custom paging in you gridcontrol or list control.
more detail Example : LINQ TO SQL GridView (Enhanced Gridview)

Part - 1 :SQL to LINQ ( Visual Representation )
              SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)

Wednesday, December 15, 2010

SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)

After the the first post SQL to LINQ ( Visual Representation ). In this post I am going to show some SQLqueries and LINQ queries, but not going to show images for all cases.

Case 7 : Filter data by using IN and NOT IN clause

Most of the developer who started working on LINQ queries gets confuse when they got requirement to write IN and NOT IN query using LINQ.

SQL Query

//IN
SELECT [Id], [UserId], [IMEINo]
FROM [UserClients]
WHERE [UserId] IN (3, 4)

or

//NOT IN
SELECT [Id], [UserId],  [IMEINo]
FROM [UserClients]
WHERE [UserId] IN (3, 4)

as you see above query use IN and NOT IN clause to filter from list of records.

LINQ Query
To achieve similar task LINQ make use of Contains function of C#. which do filtering of record form the list of record.
//IN
int[] chosenOnes = { 3, 4 };
var user = from u in UserClients
where chosenOnes.Contains(u.UserId.Value)
select new  { u.id,u.userid, u.ImeiNo};

or 

//NOT IN
int[] chosenOnes = { 3, 4 };
var user = from u in UserClients
where !chosenOnes.Contains(u.UserId.Value)
select u;

Note :
IN and NOT IN use same function in LINQ query but it just use !(Not) symbol for it.

Graphical representation


Summary
Part - 1 : SQL to LINQ ( Visual Representation )  

Tuesday, December 14, 2010

SQL to LINQ ( Visual Representation )

Now a days most of the developers are moving towards new LINQ to SQL they find difficult to write down SQL query in C# to query data using LINQ. LINQ is a query language which get integrated in C# to query data form ObjectCollects, SQL, XML etc.

Before you start reading about this post its good to have look on the features which supports LINQ

Here in this post I am going to discuss about the basic SQL queries where LINQ queries are similar to SQL queries. And visual representation of LINQ queries.
Before I start discussing here is structure of the table I am using for this article.

Users

UserClient
Linq Structure

Note : In this article all LINQ queries are performed in LINQPAD application.


Case 1 - SELECT 

SQL query to get info of all user from the user table with all column
SELECT * FROM [User]

LINQ query similar to above
var user = from u in Users
select u;

Graphical representation the break down of the LINQ query that you wrote to get data form the user table.


Case 2 - SELECT WITH COLUMNS

This case is similar to above case but the change is we are not selecting all columns of the table instead of that we are going to select only two columns here for this example querying only tow column of table FirstName and LastName.

SQL query to select all row with only two column of the table
Select firstname,LastName from [User]

Now the LINQ query for the similar one is
from u in Users
select new
{
    u.FirstName,
    u.LastName
};

So you need to create new anonymous type to get only FirstName and LastName form the user object.
Graphical representation of this query is


Case 3 - FILTER SELECT DATA 

FOR INTEGER KIND OF DATA
To apply filter on the selected data we use WHERE clause with the column value.SQL query for this is
Select firstname,LastName from [User] where id = 3

same as SQL in LINQ we use WHERE clause to filter data, LINQ query is
from u in Users
where u.Id ==3
select new
{
   u.FirstName,
   u.LastName
}

Graphic representation shows breakdown of the LINQ query related to filtering of data



FOR STRING KIND OF DATA
As we can filter interger kind of data similarly inorder to filter string we use LIKE
SELECT  [Id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role]
FROM [User]
WHERE [Email] LIKE '%pranay%'

or

SELECT  [Id], [FirstName], [LastName], [Email], [DisplayName], [Address1], [Address2], [Password], [Role]
FROM [User]
WHERE [Email] LIKE 'pranay%'

To apply the filter on string datatype field you require to use Contains or StartWith function available in C# it generates same result as SQL query
from u in Users
where u.Email.Contains ("pranay")
select u

or

from u in Users
where u.Email.StartsWith ("pranay")
select u

Graphical representation of LINQ query filtering using string field


Case 4 - JOINING TWO TABLE 

INNER JOIN
Inner join is by which we can get common records between two table i.e related records form those table. SQL query for inner join is
SELECT [User].[Id], [FirstName], [LastName], [UserId], [MobileNo]
FROM [User]
INNER JOIN
[UserClients]
ON [User].[id] = [UserId]

SQL LINQ do the same thing it use JOIN keyword with EQUALS to join two collection.LINQ query for this is 
var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
select new {
  u.Id,
  u.FirstName,
  u.LastName,
  uc.MobileNo,
  uc.imeiNO,
  uc.Id,
};

Graphical representation of the Inner join for the LINQ query is as shown below. So as you can see in the image the User connection get added to UserClients and based on condition in On.. Equals



OUTER JOIN
Outer Join is by which we can get common records between two table i.e related records form that table and as well as the all record form left table and not found right table column get null value. SQL query for outer join is
SELECT [t0].[Id], [FirstName], [LastName], [UserId] AS [UserId], [MobileNo] AS [MobileNo]
FROM [User] AS [t0]
LEFT OUTER JOIN [UserClients]  ON ([t0].[id]) = [UserId]

In LINQ to achieve outer join you need to use DefaultIfEmpty() function which so the LINQ query for this is like
var user = from u in Users
join uc in UserClients on u.Id equals uc.UserId
into myuserwithclient
from m in myuserwithclient.DefaultIfEmpty()
select new {
 u.Id,
 u.FirstName,
 u.LastName,
 m.UserId,
 m.MobileNo
};

Graphical representation of the outer join LINQ query is same as inner join but there on more step for the function DefaultIfEmpty() is added


Case 5 - ORDERING DATA 

In SQL to Order  fetched data one need to apply ORDER BY clause with ASC or DESC word, SQL query for this is
--Ascending
Select * from [User] order by firstName

or

--Descending
Select * from [User] order by firstName desc

SQL LINQ use ORDER BY combine with ASCENDING and DESCENDING keyword so that final LINQ query is
//Ascending
var user = from u in Users
orderby u.FirstName
 select new
{
   u.FirstName,
   u.LastName 
}

//Descending
var user = from u in Users
orderby u.FirstName descending
select new
{
   u.FirstName,
   u.LastName 
};

Graphical breakdown of LINQ query is

\
Case 6 - GROUPING DATA

Group of the selected data allow to perform the aggregate function like SUM, MAX, MIN, COUNT etc. To Group data in SQL you need to use GROUP BY  clause but the thing to remember is you need to include select list column in your group by clause otherwise you will get an syntax error
SELECT COUNT(*) AS [test], [UserId]
FROM [UserClients]
GROUP BY [UserId]

LINQ use Group ... By to group data , query is look like
var user =  from u in UserClients
group u by u.UserId into c
select new
{
 t1 = c.Key,
 tcount = c.Count()
};


Note :
After you apply group by on collection of object in LINQ your group by column get converted in key column which you can see in above LINQ query that I am referring UserId as Key.

Graphical breakdown of the the Group..By LINQ query is



Summary
So the article shows visual representation LINQ queries. In part-2 I am going to discuss about more sql queries and related LINQ queries for that.

Monday, December 13, 2010

Time in HH:MM:SS format from the second

Problem
In my project I stored date difference in seconds but the real issue we have to display this difference of second in  form of HOURS, MINUTE and SECONDS.

Solution
So to achieve above task we use TimeSpan.FromSeconds available in the C# which takes seconds as input and gives TimeSpan as output. From which I get HOURS, MINUTES and SECOND by inputing seconds only. Below is code sample to do that

public string getFormattedTimeFromSecond(double second)
    {

        TimeSpan t = TimeSpan.FromSeconds(second);

        string formatedTime = string.Format("{0:D2}H:{1:D2}M:{2:D2}S",
                                t.Hours,
                                t.Minutes,
                                t.Seconds);

        return formatedTime;
}

Thursday, December 2, 2010

Object and Collection Initialization

What is object Initialization ?
Object initialization is new feature in C#3.0 which allow to create object without writing too much lengthy code and without invoking constructor.

Example :
class Employee
{
  public string Name { get; set; }
  public string Address { get; set; }

 public Employee(){}
 public Employee (string name) { Name= name;  }
}

To define object without object Inialization than your code is like
Employee emp = new Employee();
emp.Name="pranay";
emp.Address = "Ahmedabad";

or

Employee emp = new Employee("Krunal");
emp.Address = "Ahmedabad";


IL Code for this in ILDASM
// Code size       32 (0x20)
  .maxstack  2
  .locals init ([0] class anonymoustype.Employee emp)
  IL_0000:  nop
  IL_0001:  newobj     instance void anonymoustype.Employee::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "pranay"
  IL_000d:  callvirt   instance void anonymoustype.Employee::set_Name(string)
  IL_0012:  nop
  IL_0013:  ldloc.0
  IL_0014:  ldstr      "Ahmedabad"
  IL_0019:  callvirt   instance void anonymoustype.Employee::set_Address(string)
  IL_001e:  nop
  IL_001f:  ret


But with the object Initialization its like
Employee emp = new Employee{ Name="Pranay", Address="Ahmedabad"  };
or
Employee emp = new Employee() { Name="Pranay", Address="Ahmedabad"  };
or
Employee emp = new Employee("Hemang") { Address="Ahmedabad"  };

The thing in that all above line of code create object of Employee. But the first one create Object without calling constructor explicitly but it calls parameterless constructor where other two calls respective constructor explicitly.

IL Code for this in ILDASM for the first statment is
.entrypoint
  // Code size       34 (0x22)
  .maxstack  2
  .locals init ([0] class anonymoustype.Employee emp,
           [1] class anonymoustype.Employee '<>g__initLocal0')
  IL_0000:  nop
  IL_0001:  newobj     instance void anonymoustype.Employee::.ctor()
  IL_0006:  stloc.1
  IL_0007:  ldloc.1
  IL_0008:  ldstr      "Pranay"
  IL_000d:  callvirt   instance void anonymoustype.Employee::set_Name(string)
  IL_0012:  nop
  IL_0013:  ldloc.1
  IL_0014:  ldstr      "Ahmedabad"
  IL_0019:  callvirt   instance void anonymoustype.Employee::set_Address(string)
  IL_001e:  nop
  IL_001f:  ldloc.1
  IL_0020:  stloc

as you can see the Object Initialization code is similar to the above IL code. But the thing is parameterless constructor get generated by compiler which I have not written in first statement.

Why object Initialization is part of C#3.0?
Again this new feature is part of C#3.0 to support LINQ. You can see the this feature with Anonymous type here.

Collection Initialization
Collection Initialization allows to create collection of object using Object Initialization feature.
Example :
List<Employee> emp = new List<Employee>
      {
        new Employee { Name="Pranay", Address="Ahmedabad"  },
        new Employee { Name="Krunal", Address="Mevada"  },
        null
     };


Summary
Object Initialization allow to create objects in one line i.e just one expression. So we can create large collection of object without writing to lengthy code which we can see in Collection Initialization.

Wednesday, December 1, 2010

Anonymous types

What is Anonymous types ?

Anonymous types are the new concept in C#3.0 which allow to create new types without defining it.

Why Anonymous types introduced in C#?

Anonymous types introduce to support one of the most use full feature called LINQ. It's most use full when you are querying collection of object using LINQ query and you want to return only few property of it.

How to define Anonymous types ?

One can define Anonymous types easily by using new keyword of C#.  Here is the example of it
var pranay = new { id=1, Name= "pranay rana" };
var krunal = new { id=1, Name= "krunal mevada" };

LINQ query example
querying the object collection having property Id,Name and Age but you just want to get only Id and Name after querying data than code is like
var user = from user in Users
                select new { user.Name, user.Id}

here as you see select new i.e second line of code generate anonymous type.

Consider below code to understand Anonymous type in more detail.
To define array of Anonymous type
var persons = new[] { 
               new { id=1, Name= "pranay rana" },
               new { id=2, Name= "krunal mevada" },
               new { id=3, Name= "hemang vyas" } 
             };

          foreach (var person in persons)
            {
                Console.WriteLine("Person : " + person.id);
                Console.WriteLine("Person : " + person.Name);
            }
After compiling code. When you see your dll or exe file in ILDASM it's shows code generated by compiler.



Line of code defines the Anonymous type which is generated by compiler
locals init ([0] class '<>f__AnonymousType0`2'[] persons,
           [1] class '<>f__AnonymousType0`2' person,
           [2] class '<>f__AnonymousType0`2'[] CS$0$0000,
           [3] class '<>f__AnonymousType0`2'[] CS$6$0001,
           [4] int32 CS$7$0002,
           [5] bool CS$4$0003)

Array of the type is define is
IL_0000:  nop
  IL_0001:  ldc.i4.3
  IL_0002:  newarr     class '<>f__AnonymousType0`2'


Create instance of Anonymous type
IL_0015:  stelem.ref
  IL_0016:  ldloc.2
  IL_0017:  ldc.i4.1
  IL_0018:  ldc.i4.2
  IL_0019:  ldstr      "krunal mevada"
  IL_001e:  newobj     instance void class '<>f__AnonymousType0`2'::.ctor(!0,
                                                                                        !1)

Whole source code
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       136 (0x88)
  .maxstack  5
  .locals init ([0] class '<>f__AnonymousType0`2'[] persons,
           [1] class '<>f__AnonymousType0`2' person,
           [2] class '<>f__AnonymousType0`2'[] CS$0$0000,
           [3] class '<>f__AnonymousType0`2'[] CS$6$0001,
           [4] int32 CS$7$0002,
           [5] bool CS$4$0003)
  IL_0000:  nop
  IL_0001:  ldc.i4.3
  IL_0002:  newarr     class '<>f__AnonymousType0`2'
  IL_0007:  stloc.2
  IL_0008:  ldloc.2
  IL_0009:  ldc.i4.0
  IL_000a:  ldc.i4.1
  IL_000b:  ldstr      "pranay rana"
  IL_0010:  newobj     instance void class '<>f__AnonymousType0`2'::.ctor(!0,
                                                                                        !1)
  IL_0015:  stelem.ref
  IL_0016:  ldloc.2
  IL_0017:  ldc.i4.1
  IL_0018:  ldc.i4.2
  IL_0019:  ldstr      "krunal mevada"
  IL_001e:  newobj     instance void class '<>f__AnonymousType0`2'::.ctor(!0,
                                                                                        !1)
  IL_0023:  stelem.ref
  IL_0024:  ldloc.2
  IL_0025:  ldc.i4.2
  IL_0026:  ldc.i4.3
  IL_0027:  ldstr      "hemang vyas"
  IL_002c:  newobj     instance void class '<>f__AnonymousType0`2'::.ctor(!0,
                                                                                        !1)
  IL_0031:  stelem.ref
  IL_0032:  ldloc.2
  IL_0033:  stloc.0
  IL_0034:  nop
  IL_0035:  ldloc.0
  IL_0036:  stloc.3
  IL_0037:  ldc.i4.0
  IL_0038:  stloc.s    CS$7$0002
  IL_003a:  br.s       IL_007a
  IL_003c:  ldloc.3
  IL_003d:  ldloc.s    CS$7$0002
  IL_003f:  ldelem.ref
  IL_0040:  stloc.1
  IL_0041:  nop
  IL_0042:  ldstr      "Person : "
  IL_0047:  ldloc.1
  IL_0048:  callvirt   instance !0 class '<>f__AnonymousType0`2'::get_id()
  IL_004d:  box        [mscorlib]System.Int32
  IL_0052:  call       string [mscorlib]System.String::Concat(object,
                                                              object)
  IL_0057:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_005c:  nop
  IL_005d:  ldstr      "Person : "
  IL_0062:  ldloc.1
  IL_0063:  callvirt   instance !1 class '<>f__AnonymousType0`2'::get_Name()
  IL_0068:  call       string [mscorlib]System.String::Concat(string,
                                                              string)
  IL_006d:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0072:  nop
  IL_0073:  nop
  IL_0074:  ldloc.s    CS$7$0002
  IL_0076:  ldc.i4.1
  IL_0077:  add
  IL_0078:  stloc.s    CS$7$0002
  IL_007a:  ldloc.s    CS$7$0002
  IL_007c:  ldloc.3
  IL_007d:  ldlen
  IL_007e:  conv.i4
  IL_007f:  clt
  IL_0081:  stloc.s    CS$4$0003
  IL_0083:  ldloc.s    CS$4$0003
  IL_0085:  brtrue.s   IL_003c
  IL_0087:  ret
} // end of method Program::Main


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 mehtod 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.

Steps to Call WCF Service using jQuery

Download Code

This article illustrates how to call Windows Communication Foundation (WCF) services from your jQuery client code, and points out where special care is needed. Before you start reading and following this article, first read this blog entry which describes how to create a WCF service: Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie

Step 1

Once you are done with creating the WCF service, you need to specify the attributes on the server type class for ASP.NET  Compatibility mode, so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features. By setting compatibility mode, the WCF service will have to be hosted on IIS and communicate with its client application using HTTP.

Read more about this in detail here: WCF Web HTTP Programming Object Model

Following line of code set ASP.NET Compatibility mode
[AspNetCompatibilityRequirements(RequirementsMode =
            AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    //  .....your code
}

Service.Cs
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }


    public string[] GetUser(string Id)
    { return new User().GetUser(Convert.ToInt32(Id)); }
}

public class User
{

    Dictionary<int, string> users = null;
    public User()
    {
        users = new Dictionary<int, string>();
        users.Add(1, "pranay");
        users.Add(2, "Krunal");
        users.Add(3, "Aditya");
        users.Add(4, "Samir");
    }

    public string[] GetUser(int Id)
    {
        var user = from u in users
                   where u.Key == Id
                   select u.Value;

        return user.ToArray<string>();
    }

}

Step 2

Next you need to specify attributes at operation level in the service contract file for each method or operation. To do this, decorate the method with WebInvoke, which marks a service operation as one that responds to HTTP requests other than GET. Accordingly, your operational level code in the contract file will be as follows:

[OperationContract]
    [OperationContract]
    [WebInvoke(Method = "POST", 
BodyStyle = WebMessageBodyStyle.Wrapped, 
ResponseFormat = WebMessageFormat.Json)]
    string[] GetUser(string Id);

As you can see in the code, sub-attributes having values to support calling via jQuery are marked with Method=post, so data gets posted to the service via a POST method.

ResponseFormat = WebMessaeFormat Json indicate data return as json format.

IService.cs
[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
     ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    string[] GetUser(string Id);
}

Step 3

You need to change the default configuration created by Visual Studio in Web.Config file for WCF services, so that it works with the HTTP protocol request send by jQuery client code.

<system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="ServiceBehavior">
     <serviceMetadata httpGetEnabled="true"/>
     <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
   </serviceBehaviors>
   <endpointBehaviors>
    <behavior name="EndpBehavior">
     <webHttp/>
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndpBehavior"/>
   </service>
  </services>
</system.serviceModel>


As you can see in above config file, the EndPoint setting is changed, and EndPointBehaviors added to support WEBHTTP requests.

Note :
Endpoint settings done in the config works in conjunction with the WebInvoke attribute of the operation and the compatibility attribute set in ServiceType to support HTTP requests sent by jQuery.

Step 4

To consume web service using jQuery i.e to make call to WCF service you either use jQuery.ajax() or jQuery.getJSON(). For this I am using jQuery.ajax() method

To set the request, first define a variable. This will be helpful when you are calling multiple methods and creating a different js file to call the WCF service.

<script type="text/javascript">
         var Type;
         var Url;
         var Data;
         var ContentType;
         var DataType;
         var ProcessData;

The following function initializes variables which are defined above to make a call to the service.

function WCFJSON() {
             var userid = "1";
             Type = "POST";
             Url = "Service.svc/GetUser";
             Data = '{"Id": "' + userid + '"}';
             ContentType = "application/json; charset=utf-8";
             DataType = "json"; varProcessData = true; 
             CallService();
         }

CallService function sent request to service by setting data in $.ajax

         //function to call WCF  Service       
         function CallService() {
             $.ajax({
                 type: Type, //GET or POST or PUT or DELETE verb
                 url: Url, // Location of the service
                 data: Data, //Data sent to server
                 contentType: ContentType, // content type sent to server
                 dataType: DataType, //Expected data format from server
                 processdata: ProcessData, //True or False
                 success: function(msg) {//On Successfull service call
                     ServiceSucceeded(msg);
                 },
                 error: ServiceFailed// When Service call fails
             });
         }

         function ServiceFailed(result) {
             alert('Service call failed: ' + result.status + '' + result.statusText);
             Type = null; varUrl = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
         }

Note:
The following code checks the result.GetUserResult statement, so your result object gets the property your service method name + Result. Otherwise, it will give an error like object not found in Javascript.

         function ServiceSucceeded(result) {

             if (DataType == "json") {

                 resultObject = result.GetUserResult;
               
                 for (i = 0; i < resultObject.length; i++) {
                     alert(resultObject[i]);
                 }
            
             }
        
         }

         function ServiceFailed(xhr) {
             alert(xhr.responseText);
             if (xhr.responseText) {
                 var err = xhr.responseText;
                 if (err)
                     error(err);
                 else
                     error({ Message: "Unknown server error." })
             }
             return;
         }

 $(document).ready(
         function() {
         WCFJSON();
         }
         );
</script>

Summary

It is easy to call a WCF service from your client code you; just need to set your WCF service to serve requests through the HTTP protocol and set your client to consume it via the HTTP protocol.

Tuesday, November 30, 2010

Method overloading in WCF

Problem
I found scenario where I have to implement two method with the same name i.e Function overloading. But when I implement that I got error "System.InvalidOperationException"

System.InvalidOperationException: Cannot have two operations in the same 
contractwith the same name, methods GetData and GetData in type 
WcfServiceLibrary.IService1 violate this rule.



Solution
To resolve this issue you just need to use meaning full name for the method by using NAME field available in OperationContract attribute. So you need to give name to both or one of the method to avoid this problem. As you can see in below code that I did in control IService.cs interface

        [OperationContract(Name = "GetIntegerData")]
        string GetData(int value);

        [OperationContract(Name = "GetStringData")]
        string GetData(string value);


So after doing the change I get live service but the name of the method get change by the name specified in the  Name attribute which you can see in below image


So to consume service in my client application you need to use the method name you specified in the Name attribute. The code in my client application is

            ServiceReference1.Service1Client client = new Client.ServiceReference1.Service1Client();
            Console.WriteLine(client.GetIntegerData(5));
            Console.WriteLine(client.GetStringData("pranay"));

Summary
You can easily resolve issue of method over loading in WCF service with the help of Name field in OperationContract attribute.

Monday, November 29, 2010

Visual Representation of SQL JOINS

In this post I am going to show the types of join available in SQL by the van diagram representation


Basic types of join
  • INNER JOIN
  • OUTER JOIN
    1. LEFT OUTER JOIN
    2. RIGHT OUTER JOIN
    3. FULL OUTER JOIN
  • CROSS JOIN
Following table we are going to use in this discussion
TableA Structure
TableA Data

TableB Structure
TableB Data



INNER JOIN
A Join return tose data which are match condition applied in ON clause of the query so it display data which is common in bot TableA and TableB as you see in below image  
SELECT select_column_list FROM
TableA INNER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example:



LEFT OUTER JOIN
A Join return all rows which match condition of ON clause as well as all row form left table i.e TableA. Un-match row of right table i.e TableB replace by the NULL value which you can see in below image of output window

SELECT select_column_list FROM
TableA LEFT OUTER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example :



RIGHT OUTER JOIN
A Join return all rows which match condition of ON clause as well as all row form right table i.e TableB. Un-match row of left table i.e TableA replace by the NULL value which you can see in below image of output window

SELECT select_column_list FROM
TableA RIGHT OUTER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example:



FULL OUTER JOIN
A Join return all rows which match condition of ON clause as well as all row form both table. Un-match row of left table i.e TableA replace by the NULL value and Un-match row of right table i.e TableB replace by the
Null value, which you can see in below image of output window

SELECT select_column_list FROM
TableA FULL OUTER JOIN TableB
ON TableA.ID = TableB.TableA_Id
Example:



CROSS JOIN
A join wose result set includes one row for eac possible pairin of rows form te two tables.
SELECT select_column_list FROM
TableA CROSS JOIN TableB

Handle Printing Data with HTML

Problem :
In my project I need to implement functionality where I have to print Order print receipt. But the real thing is I have to hide some part of page when I print page i.e hide  and I have to use same page for this.


Solution:
The easy solution for this problem is you need to give one more style sheet for the print purpose by which you can hide those element which are not required. For this you require to use attribute
media = print
of the STYLE element. Following is small code for this issue 




or when you linking style sheet






Summary
So by using media type as print you can print only those element that you want. Even you can print element with the different style.

Thursday, November 25, 2010

Handling long text using TEXT-OVERFLOW : ECLLIPSIS

Problem :
1. I got requirement from the client that if the text is longer than text get truncated and display "..." at the end of the string.
2. But the twist is I have to display "..." in ASP.NET GridView control for each cell.

Example :
I am working on my blog post formatting this day.

I have to display this as
I am working on my blog post formatting this day.

Solution:

Make use of avaialbe CSS property
text-overflow: ellipsis;
which truncate text form the point where text is wraping and display "..." as we require to resolve our issue.

Solution for the fist problem :
So out css class for DIV element to get "..." will be like :
div
{
   border-bottom: 1px solid; 
   border-left: 1px solid; 
   border-right: 1px solid; 
   border-top: 1px solid;        
   overflow: hidden; 
   text-overflow: ellipsis; 
   width: 150px;
   white-space:nowrap;
}

Output:
I am working on my blog post formatting this day.

This property is that its works for div, p type element. i.e for the block element. So it resolves my first problem.

Solution for the problem 2
But the CSS text-overflow not working for the html table element directly. And GridView control get converted in table structure when its render on client browser.

So to resolve this issue we have to use another CSS property call
table-layout : fixed;
more about table-layout : http://www.w3schools.com/Css/pr_tab_table-layout.asp

table
{
table-layout: fixed; 
width: 200px;
}

table td
{
overflow: hidden; 
text-overflow: ellipsis;
white-space:nowrap;
}

Output:

My WebSite :

http://pranayamr.blogspot.com/

My WebSite2 :

http://ww.stackoverflow.com/


Support
text-overflow : ecllipsis is supported by IE6+, Google Chrome 

Summary
So text-overflow:eclipse reduce the cost of calculating no. char we can display in a given width and write some custom login to display "..." append with the string.

Wednesday, November 24, 2010

Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie

Download SourceCode


What is WCF ?

Windows Communication foundation API allows to build distributed architecture in such manner that once created service code can be utilize by the in-house application which using tcp/ip to communicate, web application using http protocol to communicate to web services, application using msmq. WCF Services also works with the application developed other than .net framework.

Create WCF Service

Follow the below listed step to create Service

Step 1:
Create service from the Visual Studio select the go to c# or vb than select project type WCF Service library or WCf service website project template.


the first one create the *.dll and app.config file for after the compilation which you can than use in your host application and expose the service to clients.


the second one create the project with the proper web.config file and *.svc file which is get hosted on IIS via virtual directly and service get explose to client via HTTP protocol. so by that service can not be expose to tcp client. The benefit of this option is no need to create host application you can directly host it on iis via virtual directory.

For this discussion first I am creating WCF service library and than I am going to discuss about iis deployment also.

Step 2:
Create contract by specifing proper attributes. This contract tells the client what are the method get expose by the service and custom type expose by the service. You can decorate your contract by the list of attribute in System.ServiceModel namespace.

you can create you own files or after selecting proper project type its create two files for you Iservcie.cs and Service.cs. If you are going to create your own files its recommanded that you can create you interface and implement it in your class.

[ServiceContract] - defines the interface participate in provided service.


[OperationContract] - defines the method going to be expose by the service.


[DataMember] - defines the property expose via service.



[DataContract] - defines the custom data type expose via service.


After you done with the creation of the web service you code should look as below


Library app.config file
This file contains infomation about the metadata exchange defines endpoint of metadata. its also contains information about the endpoints where client talk with service.

Endpoints are ABC means Address, Binding and Contract. as you see in above config file service expose for tcp communication by following line



Binding details : http://www.c-sharpcorner.com/UploadFile/pjthesedays/bindwcf05032009012251AM/bindwcf.aspx


IService.Cs file



Service.cs


Hosting WCF Service
  • Self Host
  • IIS hosting
  • Windows service
  • WAS
Demo of Self hosting and IIS hosting.

Self hosting
 Step 1:
  Create new project >> Class Library >> name this project as Host

  Step 2:
  Add referance to the host application
  Right click on Referance >> Add Referance

Step 3:
After adding referance to the host application to expose webservice for client to consume
as you see below line of the code create the object of the host and which is of type Service1 Which we created in the WCF Service library project


as you can see we used using block over so that it depose host object when we close application.

Step 4:

to start the service to hadle request coming form the client of ther service  you need to call open method
        

and to stop receiving request you need to call close method
      


Host.cs



IIS hosting
  1. To host same WCF library in your application create WCF Web application project using WCF web application template as we discuss in start.
  2. Delete the files created in the IService.cs and Service.cs file from App_Code folder
  3. Include WCF library *.dll file which we created. 
  4. Open Service.svc file and modify the single line in it 


  5. Change the web service WEB.Config file to to expose service to client. i.e you need to create Same element as listed above in in the app.config file of service library.   
Consuming WCF Service


 Step 1:
 Create new project >> Class Library >> name this project as Client as we created Host application
     If you want to consume webservice hosted in you web application start directly for the 2 step listed below.

 Step 2:
 Add Service Referance to the client by Right click on project >> Add Service Referance



















which atomatically create the proxy files to consume web service.
or
Make use of ServiceModel Metadata Utility Tool (Svcutil.exe)  the is command-line tool to generate proxy code from metadata.
   svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config

 Step 3:
  To send request to service form the client

So as you see in above code you need to create object of Service1Client and than you can easily call the method expose by the Service. If you want to see the auto-generated code press F12 on the Service1Client it show the proxy code to you.

Summary :


As you follow the process listed process step by step its quite easy to create, consume and host WCF Service.