Friday, December 30, 2011

Make your code Speak by using C# Region

Post for the beginner developer or for the developer who want their code to speak and easy to understand to other developer who is going to maintain the code, review the code etc.

To achive this thing most of the people talks about commenting class,method, property etc.but no one talks about the making region in the code which make code compact and easy to understand in form of regions. Region allow to block of the code which you can expand and minimize.

Syntax to define the region in you code is
#region Properties
//your code
#endregion Properties
So above code defines the region with name Properties. What ever code you write between between region and endregion get minimize and expand in visual studio you can see the + when minimize and - when maximize the code block.

Example of the file with the region related to BAL or DAL layer of code  :

Example of Aspx file i.e presentation layer file

Why to use Region in your code
  • It allow to group the member which is related to same functionality 
    • For Example in above code : Insert/Update method , Get Method
  • It to group Class members (private, public, methods, properties, etc.) , which you can easily see in above image
  • With the help of region long code blocks can be minimize to small block, which you can expand when you want to see the code and minimize when work done with it.
SortCut keys and  Context menu for Region
  • Shortcut key for  region is (MSDN link for this : http://msdn.microsoft.com/en-us/library/td6a5x4s.aspx )
    • CTRL+M CTRL+M (that's two key presses!) - collapse/open the current parent region
    • CTRL+M CTRL+L - Collapse/Open all regions in document recursively (meaning you might get only one line in the document - one big namespace region which is collapsed or you'll see the entire page code uncollapsed
    • CTRL+M CTRL+O - Collapse all regions not recursively
  • You can also make use of Context menu for that in you text editor
When not to use Region in your code
  • To Hide 'ugly code' that is more complicated.
  • To hide misc. code so that lazy reviewers don't look and ask about that part of code.
  • Make region to hide the Commented code.

Saturday, December 17, 2011

Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function

In this post I am going to show how you can insert bulk data by using DataTable of C# and OpenXML function available in Sql Server.

I got requirement that "Read data from the Excel file and than after validating data
push all record in the database table". Other thing is when inserting data in database if there is failure during insertion of record, I have to rollback all inserted record.

To achieve the task I did as following

OpenXML
I created procedure which make use of OpenXML function of the sql server which allow to insert multiple record in one time. OpenXML require xml string of record to insert data in the database.
ALTER PROCEDURE [dbo].[Ins_Employee]    
(    @XmlString text    )    
AS    
BEGIN    
 SET NOCOUNT ON    
 BEGIN TRANSACTION    
 Begin Try    

  DECLARE @XMLDocPointer INT    
  EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @XmlString    

   INSERT INTO Employee
   (Name, Email, PhoneNo)    
   SELECT Name,Email,PhoneNo   
   FROM OPENXML(@XMLDocPointer,'/ROOT/DATA',2)    
   WITH  (Name VARCHAR(50),-- '@Name',     
         Email VARCHAR(50),-- '@Email',     
         PhoneNo VARCHAR(50) --'@PhoneNo')     

   EXEC sp_xml_removedocument @XMLDocPointer    
   COMMIT TRANSACTION    
   Return 0;     
 End Try    
 Begin Catch    
   ROLLBACK TRANSACTION    
 End Catch    
END 
As you see in above procedure OpenXML make use of xmlDocument as input which is get created by system define procedure sp_xml_preparedocument which take xmlString as input and return XmlDocument.
Once OpenXML done task of insertion sp_xml_removedocument system proceudre is require to remove that element.
All record get inserted in once by the OpenXML function as I used transaction if the one record insertion fails all inserted record get rollback.

Following line of the code used to execute code i.e stored procedure
As you see in I am passing Element centric xml to the proceudre.
Exec Ins_Employee
 '
  
    pranay
    pranayamr@gmail.com
    99007007
  
 '
Note
If you are passing XML string as Attribute centric in it as in procedure than you need to define variable so the select statement in procedure will be
SELECT Name,Email,PhoneNo   
   FROM OPENXML(@XMLDocPointer,'/ROOT/DATA',2)    
   WITH  (Name VARCHAR(50) '@Name',     
         Email VARCHAR(50) '@Email',     
         PhoneNo VARCHAR(50) '@PhoneNo')
Exec Ins_Employee
  '     
       
  '

Now after done with the database , code part of the application is as below.

Uploaded Excel File which contains Employee data


Presentation layer
Following function in presentation layer read data from the excel file, which is uploaded on server.
private void ReadAndInsertExcelData()
{
     int i;
     bool blValid = true;
     OleDbCommand ocmd;
     OleDbDataAdapter oda;
     DataTable dtDetails;
     DataSet dsDetails;

     OleDbConnection oconn = new OleDbConnection     
          (@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + 
               Server.MapPath("~/Upload/MonthlyActual.xls") + ";Extended 
               Properties='Excel 8.0;HDR=YES;IMEX=1'");
     try
     {
          ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);
          oda = new OleDbDataAdapter(ocmd);
          dsDetails = new DataSet();
          oda.Fill(dsDetails, "DATA");
          dtDetails = dsDetails.Tables[0];
          dsDetails.DataSetName = "ROOT";
          i = 0;

          DataRow[] drLst = dtDetails.Select("(Name is null) or (Email is 
                              null) or (PhoneNo is null)");
          if (drLst.Count() > 0)
               blValid = false;
          if (blValid)
          {
               XMLController xMLController = new XMLController();
               xMLController.Ins(BaseLineType, dtDetails);
          }
     }
     catch 
     {
          lblMsg.Text = ex.Message;
          lblMsg.ForeColor = System.Drawing.Color.Red;
     }
     finally
     {
          lblMsg.Text = "Data Inserted Sucessfully";
          oda = null;
          dtDetails = null;
          dsDetails = null;
     }
}

Business Layer
Function below takes DataTable as input and generate XML string, As you see below I used StringWriter which use StringBuilder object, DataTable make use of StringWriter and write XML string in StringBuilder object.
public int Ins(DataTable pImportTable)
{
     int IsSuccess = -100;
     try
     {
          StringBuilder sbXMLString = new StringBuilder();
          System.IO.StringWriter sw = new System.IO.StringWriter
                                                  (sbXMLString);
          pImportTable.WriteXml(sw);

          DALXML dALManualCost = new DALXML();
          dALManualCost.Ins(sbXMLString.ToString());
          IsSuccess = dALManualCost.IsSuccess;
     }
     catch
     {
          throw;
     }
     return IsSuccess;
}
Note:Above method generate Element centric XML string.

Now if you want to write out the Attribute centric xml file you just need to replace the line of datatable.WriteXml with the below code for loop also you dont require to use the StringWriter object.
sbXMLString.Append("");
          for (int i = 0; i < pImportTable.Rows.Count; i++)
          {
            sbXMLString.Append("<DATA ");
            sbXMLString.Append("Name='" + 
                         pImportTable.Rows[i][0].ToString().Trim() + "' ");
            sbXMLString.Append("Email='" + pImportTable.Rows
                         [i][1].ToString().Trim() + "' ");
            sbXMLString.Append("PhoneNo='" + 
                         pImportTable.Rows[i][2].ToString().Trim() + "' ");
            
            sbXMLString.Append(" />");
 
          }
          sbXMLString.Append("");

DataLayer 
Now this layer call the stored procedure which pass the xmlstring of employee to database. Return parameter will tell that its successfull insert or not.
public void Ins(string pXMLString)
{
     try
     {
          Database db = CommonHelper.GetDataBaseInstance();
          DbCommand cmdXML = db.GetStoredProcCommand
                         (SP_INSERT_STAGINGMANUALCOSTMONTHLY);

          db.AddInParameter(cmdXML, "XmlString", DbType.String, 
                                                       pXMLString);
          db.AddParameter(cmdXML, "ret", DbType.Int32,                     
          ParameterDirection.ReturnValue, "", DataRowVersion.Current, 
                                                            IsSuccess);

          db.ExecuteNonQuery(cmdXML);
          IsSuccess = Convert.ToInt32(db.GetParameterValue(cmdXML, "ret"));
     }
     catch
     {
          IsSuccess = -100;
          throw;
     }
}

Note : This is the one technique I found useful to enter bulk amount of data in database in one transaction. There are also other available which might be more efficient than this.

Sunday, December 4, 2011

Month and Year Picker UserControl

I am going to discuss about the pop-Up calender control created by me for selecting Month and Year. By this post you will get to know how to easily you can create pop-Up window using jQuery as well as little about how to use it as Asp.Net user control. Well that's not it you can also utilize this thing in you web project develop in any other language.

Below is the picture of the control


Now following is step by step Explanation of control created and how to use that control in your application.

Step 1 : Control Design i.e ASCX file
To create user control you need to left click on the solution and click on Add New Item >> than in screen select WebUserControl as below

After you click on Add button one ASCX file is get created , than you can add the following line of code to get display as show in the fist image above
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DateBox.ascx.cs" Inherits="DateBox" %>

lblText : - Label to hold the text to display with the text box.
txtDate : - TextBox to hold the text get selected by user from the pop-Up calender window shown in the second image above.
btnDate : - Button control, when get clicked it display the pop-Up calender window.

Step 2 : Control Code-Behind i.e .CS file
Once you done with the control design you can paste the following code in the codebehind i.e. .cs file
public partial class DateBox : System.Web.UI.UserControl
{
    public string LabelText
    {
        get
        {
            return lblText.Text;
        }
        set
        {
            lblText.Text = value;
        }
    }

    public string TextData
    {
        get
        {
            return txtDate.Text;
        }
        set
        {
            txtDate.Text = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (lblText.Text == string.Empty)
                labelContainer.Visible = false;

            this.btnDate.Attributes.Add("OnClick", "return buttonClick(this,'"+ txtDate.ClientID +"');");
        }
    }
}
Property
LabelText : - Used to get/set the text for the label control.
TextData : - Used to get/set the text of the textbox conrol which is going to display selected date.

Method 
Page_Load : - method get executed when page load check, if the label control don't have text make the container div set to visible off. Adding client script on button control and passing button control itself and textbox control client id which going to use by the jQuery/javascript to display selected date.

Step 3 : Code to create popUp Calender i.e. .JS file
After you done with Stpe 2, Add new javascript file to your solution and paste the following code in it
jQuery(document).ready(function ($) {

    var divContainer = $("");

    var divButtonHolder = $("
"); var buttonOk = $("
"); var buttonCancel = $("
"); var divSelectHolder = $("
Select Month and Year : 
"); var ddlmonth = $("    "); var ddlyear = $(""); var i = 0; var month = 1; for (i = 1985; i <= 2020; i++) { ddlyear.append(''); } i = 0; for (i = 1; i <= 12; i++) { if (i < 10) { month = "0" + month; } ddlmonth.append(''); month++; } divSelectHolder.append(ddlmonth); divSelectHolder.append(ddlyear); divContainer.append(divSelectHolder); divButtonHolder.append(buttonOk); divButtonHolder.append(buttonCancel); divContainer.append(divButtonHolder); $('body').append(divContainer); }); var txtDate; function buttonDoneClick() { var month = $("#ddlmonth").val(); var year = $("#ddlyear").val(); $(txtDate).val(month + year); Close_Popup() } function buttonClick(obj,id) { txtDate = ('#' + id); var position = $(obj).position(); $('#window').css({ top: position.top, left: position.left }).fadeIn('fast'); return false; } function Close_Popup() { $('#window').fadeOut('fast'); }
Variables
divContainer : - Main container which contains all controls of pop-Up.
divButtonHolder : - Hold button controls of the window i.e Done and Cancel.
buttonOk : - Hold reference of button control called Done.
buttonCancel : - Hold reference of button control called Cancel.
divSelectHolder : - Hold Select control i.e Month and Year combo.
ddlmonth : - Hold reference of select control called Month.
ddlmonth : - Hold reference of select control called Month.
ddlyear : - Hold reference of select control called Year.

jQuery method
.append : - allows to append control to the control selected by filter.
.ready : - method contains the code for initialize the variable, add the option to select control and attach all created control to body of the page.
.position : - method to get the location of the control which selected by selector.

Method
buttonDoneClick : - Get the selected value of the Month and Year combo box and display text in the textbox attached with the calender control.
buttonClick : - Display calender popUp window , the method make use of position method of jquery to get the location of button and assign it to popUp window.
Close_Popup : - To close the popUp window called when the Cancel button of the popUp window clicked.

Step 4 : popUp window Style sheet i.e .Css file
Add following style shit to Css file which you can able to add from the solution.
#window {
margin: 0 auto;
border: 1px solid #000000;
background: #ffffff;
position: absolute;
left: 25%;
width:250px;
height:50px;
padding:5px;
}
Style is get attached with the the div which is having id called window i.e the popUp window.

Step 5 : How to use control in your project ASPX file
<%@ Register  Src="~/DateBox.ascx" TagPrefix="UC" TagName="DateBox"   %>



So to use control in your application you just need to register the user control, need to include jquery, created js and css file. And you can make use of Lable property to display text with control.

Summary
So its quite easy to create popUp control and use it as User Control in your application. But if you are working on other than .net than just you need to use .Js and .Css file and need to create control on your page.

Monday, November 7, 2011

AJAX presentation

Monday, October 24, 2011

DataLoadOptions and How to use in Compiled Linq query

DataLoadOption in LINQ allows immediate loading and filtering of related data. The DataLoadOption allow to load related object so this remove need of the firing subquery every time you ask for the related object(s).

Consider below case

If you do code like this
var distlist = (from d in edb.Distributors select d).ToList();
            foreach(Distributor d in distlist)
            {
              var clientlist = d.Customers;
              foreach( Customer c in clientlist)
              {
                   //do the code 
              }
            }
each time inner for loop fire query on database to get the customer related to distributor which in turn decrease the performance. But if you know in advance that you are need to use the related list when you are loading main list i.e you need to load data of related entity eagerly make use of DataLoadOptions.

Modified code is something like
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Distributorgt;(d => d.Customers);
dataContext.LoadOptions = dlo;
Note
  • Be careful when you use DataLoadOption because it may decrease the performance if you are not going to use related objects. Use only in situation when you want to load related object early and going to consume it all.
  • You an only attach DataLoadOption once with the instance of datacontext.

The above DataLoadOption runs perfectly when you use regular Linq Queries. But it does not work with compiled queries. When you run this code and the query hits the second time, it produces an exception:

DataLoadOptions in Complied queries
First to get more info about Complied look this post : Increase Linq query performance by Compling it
Now when you attache DataLoadOption to complied query as we did above it give you an exception at run-time
Compiled queries across DataContexts with different LoadOptions not supported

To avoid the exception you need to create the static DataLoadOption variable because as the compiled linq queries are the static one it not consume the DataLoadOption which is not static.

So for that I have created below code where GetDataLoadOpt() static function returns DataLoadOptions object and I store it into static variable dlo and than attach this dlo1 with the compiled version of query.

public static DataLoadOptions dlo1 = GetDataLoadOpt();

    public static Func<DataLoadTestDataContext, string, IQueryable<Product>>
        ProductByCategory =
        CompiledQuery.Compile((DataLoadTestDataContext db, string category) =>
        from p in db.Products where p.Category == category select p);

    public static DataLoadOptions GetDataLoadOpt()
    {
        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<Product>(p => p.ProductWithCategory);
        return dlo;
    }

    public static void testfunction()
    {
        DataLoadTestDataContext context = new DataLoadTestDataContext();
        context.LoadOptions = dlo1;
        var productlist = ProductByCategory(context, "mobile");

        foreach (Product p in productlist)
        {
            Console.WriteLine(p.ProductWithCategory);
        }
    }
If you want to get the above exception try code removing static from the function testfunction and variable dlo1 than assign it to compiled version of query you will get the run-time exception.

Monday, October 17, 2011

Increase Linq query performance by Compling it

Each time when we fire any Linq to SQL or to any other data-source using Entity Framework query run-time convert query to expression tree and than into t-SQL statement. So if the query get fired number of time in application it get converted in the expression tree to t-SQL statement by run-time this conversion increase execution time which in turn affect performance of the application. To avoid this cost Microsoft .net framework introduce concept of the complied queries which allows compilation and caching of queries for reuse.

Now, there is shopping website which list of the product by the category basically it allows filtering of product by the category. So if I have 100 no of user who logged in to system and do the filter the product by category they basically fire
from p in db.Products where p.Category == category select p
query to get the result they want. So this will increase the execution cost as this query get fire no of time and get converted in the expression tree and in turn get the result.

With the help of CompiledQuery class of .net framework I can rewrite my code and it's like as below
public static Func<DataLoadTestDataContext, string, IQueryable<Product>>
  ProductByCategory =
    CompiledQuery.Compile((DataLoadTestDataContext db, string category) =>
     from p in db.Products where p.Category == category select p);
Static Variable
Static variable is used to store the so its not thread safe and global to all. Because of static variable compilation will only occur once per AppDomain and will remain cached through the rest of the application's lifetime. If you don't use the static variable query get complied each time which increase the cost and decrease the performance of the application.

Constrain and Use
Cannot use to store the queries which returns Anonymous type, because the anonymous type doesn't have any type to assign generic argument of function.

Useful when query is used heavily and you want to reuse the query, by using this way increase the performance of the application.

Where to include the code ?
Better place to include above code is partial class, its extended partial class to the partial class generated by ORM tool.More:Extenend ORM generated class

Tuesday, October 11, 2011

Extenend ORM generated class

In this post I am going to show how you can extend the class generated by the ORM tools. To demonstrate I am using Linq To Sql ORM.

When you make use of ORM tool like Linq to Sql or Entity-Framework it generate the classes from the database structure given as input. For example consider below example
Now I want to display the list of product in my grid but I have to display product name with categoryname for example productname(categoryname) or consider situation where I have ordertable and I have to display one more extra column in grid with display total = quantity * price.

To achieve this make look to the class generated by ORM tools, when you see the class definition you see its decorated with the partial keyword. C#2.0 partial class allow us to create class which expands in two different file and at the time of compile both file get compile in one class. So by making use of same rule I have added one more class file and its partial as below.
public partial class Product
{
   public string ProductWithCategory
   {
      get
      {
         return this.ProductName + "(" + this.Category +")";
      }
   }
}
Now to we can consume property in the presentation or businesslayer like as below.
var productlist = (from p in context.Products select p).ToList();
foreach (Product p in productlist)
{
   Console.WriteLine(p.ProductWithCategory);
}
So by above way adding property to partial class we can easily achieve the task.

Summary
By using partial class we can add the custom logic to the class created by the ORM tool(s).

Monday, October 3, 2011

Log your LINQ query


Most of the beginner developer who are using LINQ to SQL as there back-end to talk with the database (i.e to perform the database CRUD operation), don't have idea what the query get fire to database out of LINQ query.

Lastly I asked to log the query that fire to database out of my LINQ query. So as solution I found one make use of SQL Server Profiler to check fire query. But with the profiler I can not able to log the queries.

I fond one solution is to make use of Log property of DataContext object. Log property allow me to log the queries in the file. Consider the below code

//created temp file 
using 
(System.IO.StreamWriter sw = new System.IO.StreamWriter(@"e:\tempdatacontext.log"))
{
    EmployeeDataContext edb = new EmployeeDataContext();
    //assigned streamwriter to the log property of datacontext
    edb.Log = sw;
    var cust = from c in edb.Customers
              join d in edb.Distributors on
                new { CityID = c.CityId, StateID = c.StateId, 
                      CountryID = c.CountryId, Id = c.DistributorId }
                equals
                new { CityID = d.CityId, StateID = d.StateId, 
                      CountryID = d.CountryId, Id = d.DistributorId }
              select c;

    List<customer> custList = cust.ToList();
}

So once the code get executed it's time to check the temp file. As I opened up the file I found following query get fired on my database.


It's fun to find the query get fire to database and you get to know if there is any problem in the LINQ query you wrote.

Saturday, October 1, 2011

Linq Join on Mutiple columns using Anonymous type

I was working on the project using LINQ. I got the requirement to join the two entity on multiple column.

For example consider the following image. There are two entity Distributor and Customer related to each other.

Now I want to find out all customer who lives in same city where the distributor living.
So to find out that I have to make join between Customer and Distributor. And to achieve this I need to join by using multiple columns City,State,Country,ID. (Note: I am using id in join because later on I want to get which distributor near to customer).

Now with the LINQ you can join two entity on multiple columns by creating one anonymous type.
EmployeeDataContext edb= new EmployeeDataContext();
var cust = from c in edb.Customers
           join d in edb.Distributors on
             new { CityID = c.CityId, StateID = c.StateId, CountryID = c.CountryId, 
                   Id = c.DistributorId }    
           equals
             new { CityID = d.CityId, StateID = d.StateId, CountryID = d.CountryId, 
                   Id = d.DistributorId }    
           select c;
Note : As anonymous types used to join entity on multiple column, so for that make sure that both are equal and they must have the same properties in same order. Otherwise it don't get complied and you get error.

Once you are done run the code and you see the following query in your sql profiler or you can also use the visual studio feature to get the query.
SELECT [t0].[Id], [t0].[Name], [t0].[EmailId], [t0].[CityId], [t0].[StateId], 
[t0].[CountryId], [t0].[PinCode], [t0].[DistributorId]
FROM [dbo].[Customer] AS [t0]
INNER JOIN 
[dbo].[Distributor] AS [t1] ON 
([t0].[CityId] = [t1].[CityId]) 
    AND ([t0].[StateId] = [t1].[StateId]) 
    AND  ([t0].[CountryId] = [t1].[CountryId]) 
    AND ([t0].[DistributorId] =[t1].[DistributorId])

Saturday, September 3, 2011

My MVB Certificate

Thursday, August 11, 2011

Build your silver light application

Any Mehtod

Here I am oging to discuss about Any method. One purpose of this method is to check either the collection has elemetn or not.
Example
List<string> members = 
         new List<string>() { "pranay", "Hemang" };
   bool ISCollectionEmpty = members.Any();             
So by using method I get to know my collection has any element or not.
So when I run above coe I get true in my boolean variable if there is not element it return flase.

Now cosider the below Database Table and  LINQ to SQL dbml file

Department table

Employee table


As you can see there is one to many relationship between Department and Employee.

Problem Statement
Now Here I want to list out only those department whihc has employee.

Solution
Most of the people do the gorup by and make use of the join and then try to find out the department which has solution.

But the better solution to this is make use of Any() method available in the System.Linq for the collection as below
var deptList = from dept in dbcontext.Departments
                           where dept.Employees.Any()
                           select dept;

   foreach (var item in deptList)
   {
      Console.WriteLine(item.Name + " : " + item.Employees.Count());
   }
Output:

As you can see the above query fetch the those department only which has employee and remove the department those doesnt have any.
I can easily able to get the cout of the employees in department using count method.

Sql query :
When you see the Sql profiler or get the query in visual studio by watching variable.
SELECT [t0].[Id], [t0].[Name]
FROM [dbo].[Department] AS [t0]
WHERE EXISTS(
  SELECT NULL AS [EMPTY]
  FROM [dbo].[Employee] AS [t1]
  WHERE [t1].[DeptId] = [t0].[Id]
)

Saturday, August 6, 2011

SqlMethod LIKE

In this post I am going to discuss about the special method available in .NET framework which allows to perform the like operation as we do in the t-sql to when searching data with string.

In sql to search string data query is
--Searching string contains abc i.e prabcfg, abcpr
Select * from table name where columnname like '%abc%'
--Searching string starts with abc i.e abcpr, abcrana
Select * from table name where columnname like 'abc%'
--Searching string ends with abc i.e prabc, ranaabc
Select * from table name where columnname like '%abc'
--Searching string with wildcard char _ i.e abec,abfc
Select * from table name where columnname like 'ab_c'
Now in LINQ to achieve same thing we have function like StartsWith, EndsWith and Contains. So LINQ query is
//Searching string contains abc i.e prabcfg, abcpr
var user = form u in users where u.Name.Contains("abc");
//Searching string starts with abc i.e abcpr, abcrana
var user = form u in users where u.Name.StartsWith("abc");
//Searching string ends with abc i.e prabc, ranaabc
var user = form u in users where u.Name.EndsWith("abc");
But with the LINQ I cannot able to achieve the last case(wildcard char _ ) and many more that I can do in like condition of the t-SQL.

SqlMehtod class has static method Like which allows to perform the same function as the like keyword of t-sql. So the query with the LINQ is
var emplist = from emp in dbcontext.Employees
where SqlMethods.Like(emp.FirstName, "pr_nay")
select emp;
When you execute the statement you can see the the t-sql statement same as above i.e wildcard statement listed above, you can view the query in the sql profiler.
But the the Like method work when you do the query using LINQ TO SQL only.

Friday, August 5, 2011

LINQ presentation

Linq
View more presentations from pranayamr

Saturday, July 30, 2011

Generate thousand of request

Lastly I was working on the project where I have to designed web page which is exposing some set of the functions and which is get consume by some external application like java and flex. It's worked fine and providing the output I want.

But now I want to perform the load test, so for that I want to generate thousand of request which consume the page and show me how it works. But the problem is how to generate the request because I don't have that many people who can make request at given time.

Solution for this problem I make use of the Thread class and loop it to the no. of request I have to generate as you see in below code.
for (int i = 0; i < 100; i++)
{
    Thread thread1 = new Thread(new ThreadStart(WorkThreadFunction1));
    thread1.Start();
}
Now the secondly I made use of HttpWebRequest class which allow me to call the page and to get the response. You can get more information about HttpWebRequest.
public void WorkThreadFunction1()
{
   try
   {
     string param = string.Empty;
     HttpWebRequest oWebReq =     
      (HttpWebRequest)WebRequest.Create("http://mywebsite/WebForm1.aspx" + param);
     HttpWebResponse oWebResp = (HttpWebResponse)oWebReq.GetResponse();
     StreamReader oStream = new StreamReader(oWebResp.GetResponseStream(),     
                                                     System.Text.Encoding.ASCII);
     Console.WriteLine(oStream.ReadToEnd());
   }
   catch (Exception ex)
   {
      // log errors
   }
}
As you can see in the above code I am making the call to the my page and writing the response to the console window.
Note:
Here WebForm1 is entry point based on the parameter passed to it , it calls the different function and may be the pages in your site.
Here I am making request to one single page but you can write you own script to call the different page and pass the parameter to it.

Summary
So you can easily make no. of request without need of the no. of people. But this thing depends on the requirement in you case.

Friday, July 29, 2011

Difference between Object, Dynamic and Var

In this post I am going to write the points about the three type of the variable Object, Var and Dynamic. Most of the developer not able to get what is difference between this three kind of variable.
ObjectDynamicVar
Can able to store any kind of value, because object is the base class of all type in .net framework.Can able to store any type of the variable, similar to old VB language variable.Can able to store any type of value but it require to initialize at the time of declaration.

Compiler has little information about the type

Compiler doesn't have any information about the this type of variable.

It's compiler safe i.e compiler has all information about the stored value, so that it doesn't cause any issue at run-time.

Object type can be passed as function argument and function also can return object typeDynamic type can be passed as function argument and function also can return object typeVar type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.

Require to cast object variable to original type before using it. So this assigning to object type and converting to original type called as Boxing and Un-Boxing for primitive data type and for the reference type its casting of types. It's actually increasing the overhead when we do this both operation.

Allows to perform operation of given type once it get cast any user defined or primitive data type.
Casting is not require but you need to know the property and methods related to stored typeNo need to cast because compiler has all information to perform operation.
Cause the problem at run time if the stored value is not get converted to underlying data type.

Cause problem if the wrong method or property accessed because all the information about stored value is get resolve only at run time

Doesn't cause problem because compiler has all info about stored value.
Useful when doesn't have more information about the data type.Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.

Thursday, July 21, 2011

Handle Exception Carefully

Handle Exception carefully means I am not going to discuss some rocket science about exception handling but I am going to discuss not to shadow the exception in your program. Not going to discuss more I am starting my example
class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Program p = new Program();
                p.MethodA();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();
        }

        public void MethodA()
        {
            try
            {
                MethodB();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void MethodB()
        {
            try
            {
                MethodC();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void MethodC()
        {
            int a = 10;
            int b = 0;
            int c = 0;
            try
            {
                c = a / b;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
When execute the program you will get the following output as result. Yes you can able to handle the exception thrown by the method and displayed on the console.
Output
But the actual thing is you hiding the stack trace and each time you throw the exception by writing throw ex you are creating new stack trace. So you are not able to get the actual path from where the exception get thrown.

Now to understand the thing properly, write the program again and now replace throw ex by the throw
class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Program p = new Program();
                p.MethodA();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            Console.ReadLine();
        }

        public void MethodA()
        {
            try
            {
                MethodB();
            }
            catch
            {
                throw;
            }
        }

        public void MethodB()
        {
            try
            {
                MethodC();
            }
            catch
            {
                throw;
            }
        }

        public void MethodC()
        {
            int a = 10;
            int b = 0;
            int c = 0;
            try
            {
                c = a / b;
            }
            catch
            {
                throw;
            }
        }
    }
When execute the program get the following output
Output
Now as you see when you replace the line there is no new stacktrace get created and you get actual path from where exception get thrown.
Summary
So make use of the throw to get the actual path of the exception rather than using throw ex.

Sunday, July 17, 2011

String Split Utility

Note: Split function has more no of overload method but the below two I found useful. You may found other overloads helpful in your code.

In this post I am going to discuss about two important thing about Split function of String class. Split function of the string class split the string in array of string.

Split function to split string in array
String.Split( char[])
For example
string words = "stringa,stringb, ,stringc,stringd stringe.";
string [] split = words.Split(new Char [] {' ', ','}); 
Above code create a string array which has
//output
split[0]=stringa
split[1]=stringb
split[2]=
split[3]=stringc
split[4]=stringd
split[5]=stringe
but What If I want to remove empty string from the array when I split string.
Solution to this problem is to make use of second overload method of the the string Split where you can specify the option to remove string. So above code is rewritten as

Overload method with option
String.Split(Char[], StringSplitOptions)
string words = "stringa,stringb, ,stringc,stringd stringe.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries); 
Created string array is
//output 
split[0]=stringa
split[1]=stringb
split[2]=stringc
split[3]=stringd
split[4]=stringe

Now consider case where I have to limit no of return string. Consider for example
string a = "key:mykey, Value : test1,test2";  
Now I have to get the key:mykey in string 1 and Value : test1,test2 in string 2.
Overload function to split string in limited no. of string
Split(Char[], Int32)
So the code for this is
string a = "key:mykey, Value : test1,test2";
string [] split = words.Split(new Char [] {','},2);   
Now the split array have
//output
split[0]= "key:mykey";
split[1]= "Value : test1,test2";
Summary
There are also other variable of Split method which you can refer form the msdn link :String.Split. But I fond above two more useful than others.

Tuesday, July 12, 2011

ForEach Method for the collections

In this small post I am going to discuss about the new method introduce in the .net framework ForEach which allow to perform the action on the each set of element.

Syntax
public void ForEach(Action<t> action)
Action<t> is delegate or function to perform on each element of the List.

To get in more detail how it works check check the following code.
Below is Employee class which has property related to employee of the company.
public class Employee
{
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public int Id { get; set; }
}
and now in following line of code I am initializing list of employees
class Program
    {
        static void Main(string[] args)
        {
          List<employee> emplst = new List<employee> { 
          new Employee() { Name="pranay", Address = "Ahmedabad", Id=1, Salary=1234},
          new Employee() { Name="Hemang", Address = "Ahmedabad", Id=2, Salary=2348},
          new Employee() { Name="kurnal", Address = "Himmatnagar", Id=3, Salary=8999},
          new Employee() { Name="Hanika", Address = "Ahmedabad", Id=4, Salary=7888}
        };
Now I want to increase salary of each employee by 10%, so with the the help of new ForEach construct I can easily achieve it by using following line of code.
emplst.ForEach(new Program().incSalary);
     }

  private void incSalary(Employee emp)
  {
     emp.Salary += (emp.Salary * 10)/100; 
  }
}
As you can see in above code I have written new Program().incSalary as action, in the incsalary method as you see I increase the salary of each employee 10%.
This thing can easily also done by making use of the foreach loop available but if you see the the ForEach in reflector it does the same thing.
ForEach method make code more simple and easy to understand.

Friday, July 8, 2011

Jquery Ajax Calling functions

Download Code

Recently I am working on Website with the asp.net and jQuery. While working with jquery library I found that there are 5 diffrent function that used to make ajax call to page and to fetch data. I am going to discuss about that five function one by one.

Following is list of that five function availale in jquery libaray to make ajax call.
  1. Load
  2. getJson
  3. GET
  4. POST
  5. Ajax
Load
Method allow to make ajax call to the page and allows to send using both Get and Post methods.
var loadUrl = "TestPage.htm";
$(document).ready(function () {
   $("#load_basic").click(function () {
     $("#result").html(ajax_load).load(loadUrl, function (response, status, xhr) {
                    if (status == "error") {
                        var msg = "Sorry but there was an error: ";
                        $("#dvError").html(msg + xhr.status + " " + xhr.statusText);
                    }
                }
                );
                return false;
});
As you can see in above code you can easily make call to any page by passing it Url. The call back function provide more control and allows to handle the error if any by making use of the Status value.
One of the important thing about the load method is its allow to load part of page rather than whole page. So get only part of the page call remains same but the url is
var loadUrl = "TestPage.htm #dvContainer";   
So by the passing above url to load method it just load content of the div having id=dvContainer. Check the demo code for detail.



Firebug shows the repose get return by when we call the page by Load method.

Important Feature
  • Allow make call with both Get and Post request
  • Allow to load part of the page.
getJson
Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed. One more thing this method treat the respose as Json.
var jsonUrl = "Json.htm";
            $("#btnJson").click(function () {
                $("#dvJson").html(ajax_load);

                $.getJSON(jsonUrl, function (json) {
                    var result = json.name;
                    $("#dvJson").html(result);
                }
                );
                return false;
            });
Above code make use of getJSON function and displays json data fetch from the page.
Following is json data return by the Json.htm file.
{
"name": "Hemang Vyas",
"age" : "32",
"sex": "Male"
}

Following image displays the json Data return as respose.


Important Feature
  • Only send data using get method, post is not allowed.
  • Treat the response data as Json only

get
Allow to make ajax request with the get method. It handles the response of many formats including xml, html, text, script, json, and jonsp.
var getUrl = "GETAndPostRequest.aspx";
            $("#btnGet").click(function () {
                $("#dvGet").html(ajax_load);

                $.get(getUrl, { Name: "Pranay" }, function (result) {
                    $("#dvGet").html(result);
                }
                );
                return false;
            });
As in code I am passing Name parameter to the page using get request.
On server side you can get the value of the Name parameter in request object querycollection.
if (Request.QueryString["Name"]!=null)
{
    txtName.Text = Request.QueryString["Name"].ToString();
} 

The firebug shows the parameter passe by me as Get request  and  value of the parameter is pranay



Important Feature
  • Can handle any type of the response data.
  • Send data using get method only.

post
Allow to make ajax request with the post method. It handles the response of many formats including xml, html, text, script, json, and jonsp. post does same as get but just send data using post method.
var postUrl = "GETAndPostRequest.aspx";
            $("#btnPost").click(function () {
                $("#dvPost").html(ajax_load);

                $.post(postUrl, { Name: "Hanika" }, function (result) {
                    $("#dvPost").html(result);
                }
                );
                return false;
            });
As in code I am passing Name parameter to the page using post request.
On server side you can get the value of the Name parameter in request object formcollection.
if (Request.Form["Name"] != null)
{
    txtName.Text = Request.Form["Name"].ToString();
}

The firebug shows the parameter passe by me as Get request  and  value of the parameter is Hanika



Important Feature
  • Can handle any type of the response data.
  • Send data using post method only.

ajax
Allow to make the ajax call. This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter.
var ajaxUrl = "Json.htm";
            $("#btnAjax").click(function () {
                $("#dvAjax").html(ajax_load);


                $.ajax({
                    type: "GET", //GET or POST or PUT or DELETE verb
                    url: ajaxUrl, // Location of the service
                    data: "", //Data sent to server
                    contentType: "", // content type sent to server
                    dataType: "json", //Expected data format from server
                    processdata: true, //True or False
                    success: function (json) {//On Successfull service call
                        var result = json.name;
                        $("#dvAjax").html(result);
                    },
                    error: ServiceFailed// When Service call fails
                });


                return false;
            });
In above code you can see the all the parameter and comment related to each parameter describe the purpose of each one.

Fire bug shows the called page return json data and Ajax function treat the respose as Json because in code datatype = json


Important Feature
  • Provide more control on the data sending and on response data.
  • Allow to handle error occur during call.
  • Allow to handle data if the call to ajax page is successfull.

Summary
So each method of jQuery ajax is different and can use for the difference purpose.

Tuesday, July 5, 2011

Get time of Code Execution Using StopWatch

During Development of the application/product or after deployment of the application/product there might be a situation where you want to find out the the how much time is taken by you code to execute ? Is it too much slow ?

Answer to this problem is make use of StopWatch class of System.Diagnostics namespace which is usefull to find out the time taken to execute given line of code. The class is helpfull to find out how efficient code develop by measuring the time of execution.

To understand how to use it consider the below demo
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//instead of this there is line of code that you are going to execute
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime);
Console.ReadLine();
Stopwatch class has method Start() and Stop(), So the as name suggest call start when you want to start your watch and call Stop when you want to stop the watch. Once you stop the watch i.e called stop method of the StopWatch class you can get the value of time of execution by using Elapsed property of the class which return TimeSpan object.

Output



There are also other important methods which are very usefull you can get the more infomation about those on the MSDN documentation over here : StopWatch Class
Methods
StartNew - Initializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.
Restart - Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
Reset - Stops time interval measurement and resets the elapsed time to zero.

Properties
ElapsedMilliseconds - Gets the total elapsed time measured by the current instance, in milliseconds.
ElapsedTicks - Gets the total elapsed time measured by the current instance, in timer ticks.

Advantage
  • Easy and Simple to use.
  • Useful when want to find out the time take by the line of code to execute.
  • By using the class there is no need of any third party tool because it part of the .net framework.

Monday, July 4, 2011

Lazy initialization of object in C# with Lazy<T> class

Lazy<T> is class introduced in the .Net framework 4.0 to initialize the object later on i.e allow to initialize object when we are going to utilize or assigning value to the object.

To understand Lazy initialization consider below class.
public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public int Id { get; set; }
    }
In the following code I am using the Employee class. As you can see I have initialize the class to null
Employee emp1=null;
     Console.WriteLine(emp1);
     ///Code do perform other task
     if(Condition)
     {
      if (emp1 == null)
        emp1 = new Employee();
     }
In above code I am initializing class when I need it rather than initializing before using it same way we can do in the Singleton design pattern, by this way we are lazing initializing the object and consume memory when need it rather than initializing it in the first line of the method.

But now .net 4.0 framework provide the new class to do this thing easily. The class is Lazy<T>. So the above code is something like as below
Lazy<employee> emp = new Lazy<employee>();
     Console.WriteLine(emp);

     emp.Value.Id = 1;
     emp.Value.Name = "pranay";
     emp.Value.Salary = 123;
     emp.Value.Address = "Ahmedabad";
     Console.WriteLine(emp);
Output of the program
As you can see in output window it display no value is defined.

Important Properties
Object is get created when we access property Value and assign value to it. To find out the detail I used reflector and which shows that the object get created when I access property.

Another the important property is IsValueCreated-Gets a value that indicates whether a value has been created for this Lazy instance.

Thursday, June 23, 2011

Calling Cross Domain WCF service using Jquery/Javascript

This post is about to call the cross domain WCF service from you page i.e Calling WCF service hosted on one domain and calling the service form jquery/javascript of page which is hosted on some other domain.
But before we start its better to get understand about the format of the data get exchange from one server to other server.

JSONP
Ajax allows to get data in the background without interfering with the display. Ajax call done by using XMLHttpRequest object, which is allow the client side javascript code to make HTTP connections.

But Ajax call does not allow to get data from cross-domain because of restrictions imposed by the browser. Security error get issued when requesting data from a other domain. one way to avoid security errors is to control remote server where data resides and every request goes to the same domain, that rise question what's the fun if data come form own server only? What to do if data require to get form the other server?

There is one way to come out form this limitation is to insert a dynamic script element in the Web page, one whose source is pointing to the service URL in the other domain and gets the data in the script itself. When the script loads, it executes. It works because the same-origin policy doesn't prevent dynamic script insertions and treats the scripts as if they were loaded from the domain that provided the Web page. But if this script tries to load a document from yet another domain, it will fail. Fortunately, you can improve this technique by adding JavaScript Object Notation (JSON) to the mix.

JSONP or "JSON with padding" is a complement to the base JSON data format, a pattern of usage that allows a page to request data from a server in a different domain. As a solution to this problem, JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element. Taking advantage of the open policy for <script> elements, some pages use them to retrieve Javascript code that operates on dynamically-generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.

Calling Cross Domain WCF service
Now in following discuss I am going to show you how easily you can call the WCF service hosted on the other domain from the page hosted on the other domain.

Following is list of article you should look first before moving further

Create, Host(Self Hosting, IIS hosting) and Consume WCF servcie
Steps to Call WCF Service using jQuery

To start first create new solution and Add new Project which is WCF service and follow below steps

Step 1
In new release of .net 4.0 the WCF developer team added support for JSONP. There is a new property added which enable to call WCF service from other domain by setting its true.
CrossDomainScriptAccessEnabled - Gets or sets a value that determines if cross domain script access is enabled.

Change your WCF servcie config file as below


  
    
    
  
  
    
  
  
    
    
      
        
      
    
  

As you can see in above config code I have set crossdomainscriptaccessenabled to true and aspnetcompatibilityenabled is to true so that the WCF service works as a normal ASMX service and supports all existing ASP.NET features.
Step 2

SVC file of the service should be like as below

<%@ ServiceHost Language="C#" Debug="true" 
Service="WcfService1.Service1" 
CodeBehind="Service1.svc.cs"
Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"  %> 
Don't forget to add Factory attribute because it cause error if you remove it. Following are the reason to add Factory attribute
1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.
2. This is useful when we need to implement the event handlers for opening and closing the service.
3. WCF provides ServiceFactory class for this purpose.
Step 3

CS file for the WCF file is

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
{
    
    [DataContract]
    public class Customer
    {
        [DataMember]
        public string Name;

        [DataMember]
        public string Address;
    }


    [ServiceContract(Namespace = "JsonpAjaxService")]
    [AspNetCompatibilityRequirements(RequirementsMode =   AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1
    {
        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        public Customer GetCustomer()
        {
            return new Customer() { Name = "Pranay", Address = "1 Ahmedabad" };
        }
    }

}
As you can see in the above code I have created Service class which is service contract which servs data and Customer class is DataContract which get served as respose.
In the service class GetCustomer method service data in Json format.

Once the WCF service created to move further Add new project >> Asp.Net service. So that both the WCF service and website runs on tow different like both hosted on different domain.

There is two solution to call the Cross Domain WCF service.

Solution 1 : Call WCF service by using JQuery
Jquery already have support to handle the jsonp. Jquery library provided function ajax and getJson which can allow to call the WCF service which send jsonp data in response.

CallService - Generic function is used to call the WCF servcie, which get called by other javascript function to get and display data

var Type;
        var Url;
        var Data;
        var ContentType;
        var DataType;
        var ProcessData;
        var method;
        //Generic 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
            });
        }
ServiceFailed - is get called when call to service fail.

function ServiceFailed(xhr) {
            alert(xhr.responseText);
            if (xhr.responseText) {
                var err = xhr.responseText;
                if (err)
                    error(err);
                else
                    error({ Message: "Unknown server error." })
            }
            return;
        }
ServiceSucceeded - is get called when the service successfully return response. As you can see in the function I am checking DataType is jsonp which is just to demonstrate that service is returning jsonp data.

function ServiceSucceeded(result) {
            if (DataType == "jsonp") {
                
                    resultObject = result.GetEmployeeResult;
                    var string = result.Name + " \n " + result.Address ;
                    alert(string); 
            }
        }
GetEmployee - is function that get called to request data from WCF service hosted on other domain. As you can see in code DataType value is get set to jsonp.

function GetEmployee() {
            var uesrid = "1";
            Type = "GET";
            Url = "http://localhost:52136/Service1.svc/GetCustomer"; 
            DataType = "jsonp"; ProcessData = false;
            method = "GetCustomer";
            CallService();
        }

        $(document).ready(
         function () {
            
             GetEmployee();
         }
);
Solution 2 : Call WCF Service by Javascript

To call the service using javascript make use of ScriptManager


        
            
        
    
in above code I set the servicereferance to the WCF service hosted on other domain.
makeCall - is function that get called to request data from WCF service hosted on other domain.

function makeCall() {
                      var proxy = new JsonpAjaxService.Service1();
                     proxy.set_enableJsonp(true);
                     proxy.GetCustomer(onSuccess, onFail, null);
                 }
onSuccess - is called when the result from the service call is received and display data.

function onSuccess(result) {
                     alert( result.Name + " " +result.Address);
                 }
onFail - is called if the service call fails

function onFail(){
                     alert("Error");
                 }
Summary
So after the addition to the special property by the WCF team its quite easy to call cross domain WCF service.
References
JSONP - WIKI
Cross-domain communications with JSONP


Saturday, June 18, 2011

Dictionary Object (ContainsKey Vs. TryGetValue)

Here I am going to discuss about two important method of the Dictionary<tkey, tvalue> class to play with the data of the Dictionary.

Dictionary<tkey, tvalue> class allows us to create key , vlaue pair collection. The Dictionary<tkey, tvalue> generic class maps of keys to a set of values. Dictionary consists of a value and its associated key. Value can be retived by using its key is very fast, close to O(1), because the Dictionary>tkey, tvalue< class is implemented as a hash table.
Now to understand what I am going to discuss in this post

I am creating Dictionary object
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary Class has method Add which allows to add the key, value pair data in the dictionary object
dic.Add("Pranay",  "Rana");
dic.Add("Hemang", "Vyas");
dic.Add("Krunal", "Mevada");
dic.Add("Hanika",  "Arora");
Now after adding the key,value pair it's need to take out the value out of the dictionary object and use that values because after all dictionary object used to store the values and to get it back.
To take value back from the Dictionary object , it require to make use of key
Type value = dic[key];
But the problem with this is it throws KeyNotFoundException if the key is not exists in dictionary.

ContainsKey 
Dictionary class provide methods ContainsKey which used to check where the key is present or not.
Signature bool ContainsKey(<TKey> key)
So most of the developer use this method to check value and if the value is exits they get the value back.
if (dic.ContainsKey(key))
{
     string result = dic[key];
     Console.WriteLine(result);
}
TryGetValue
But Dictionary object provide one more method TryGetValue which check key is present in dictionary present or not and if present return value by out parameter.
Signature bool TryGetValue(<TKey> key,out <TValue> val)
By using the method code is like
if (dic.TryGetValue(key, out val))
{
   Console.WriteLine(val);
}
By using two method one can avoid throwing the KeyNotFoundException.

But the question is What is the difference between two approach related to ContainsKey and TryGetValue ?
The first diffrence is ContainsKey approach only checks weather key is present or not and than get the value , but the TryGetValue not only check key is present or not but also get the value for that key.
So the TryGetValue make code easy and simple.

The second difference is TryGetValue approach is faster than ContainsKey.
To check out I wrote following code and executed on my machine.
Note : Stopwatch class exists in System.Diagnostics Namespace to get the time require to execute the line of code.
Dictionary<string, string> dic = new Dictionary<string, string>();
      dic.Add("Pranay",  "Rana");
      dic.Add("Hemang", "Vyas");
      dic.Add("Krunal", "Mevada");
      dic.Add("Hanika",  "Arora");

      //First method ContainsKey
      Stopwatch st = new Stopwatch();
      st.Start();
      foreach (string key in dic.Keys)
      {
          if (dic.ContainsKey(key))
          {
             string result = dic[key];
             Console.WriteLine(result);
          }
      }
      st.Stop();
      TimeSpan ts = st.Elapsed;
      Console.WriteLine("RunTime " + ts.Milliseconds);


      //Second method TryGetValue
      string val = string.Empty;
      Stopwatch st1 = new Stopwatch();
      st1.Start();
      foreach (string key in dic.Keys)
      {
          if (dic.TryGetValue(key, out val))
          {
              Console.WriteLine(val);
          }
      }
      st1.Stop();
      ts = st1.Elapsed;
      Console.WriteLine("RunTime " + ts.Milliseconds);

After the test I got following output
As you can see in the image the first one take 4 millisecond to get the values and the later one take 1 millisecond.

Note :
TryGetValue approach is faster than ContainsKey approach but only when you want to check the key in collection and also want to get the value associated with it. If you only want to check the key is present or not use ContainsKey only.

Wednesday, June 15, 2011

Help yourself in Debugging by using Call Stack and Immediate Window

In this post I am going to show you the two important window of the Visual Studio which is useful when you debugging the project and to get the result on the fly during debug.

Call Stack Window
Most of the developer get confuse when they are debugging application "From which function call came from up to my debug point", this happens when they are working the code design by some one else or debugging code of the dll.

Following is one common scenario which I notice number of time developer does.
In the three tier application developers always put the break point in presentation layer when the break point get hit they always check the data and the do wonder that which business layer method called >> database layer method get called by presentation layer to get this data.

The Solution is Call Stack Window which is part of the Visual Studio. Shortcut for it is
Ctrl + Alt + C or go to menu Debug >> Windows >> Call Stack









As you can see the image with the help of the Call Stack Window you will get information about the method get called, what is parameter value, line no of the method in file, is it external call or internal, programming language in which method written.

Immediate Window
It always happen that in middle of debugging you want to execute some set of statement or some set of function or want to check the value of the variable. But as beginner you don't know how to do it at time of debug ?

You can open up the Immediate window by shortcut Ctrl + Alt + I or go to menu Debug >> Windows >> Immediate Window






Immediate window has intelligence support as we have in the Coding window of the Visual Studio so that you can easily make use of the function, which makes you task easy.

Sunday, June 12, 2011

Ordering data in LINQ Queries by more than one column

In this post I am going to show how to do ordering when you require to order data by using the multiple columns.

By using .Orderby(x=>x.Columnname) in the LINQ query we can easily order data of the source collection. So most of new developer make use of the same function two time .Orderby(x=>x.Columnname).Orderby(x=>x.Columnname) and thinks that will do the ordering on the multiple columns.
IEnumerable<Employee> emp = dc.Employees
                                 .OrderBy(x => x.Name)
                                 .OrderBy(x => x.Desc); 

But its always does the order by the column you specified in the last OrderBy() method.

Following is two solution to achieve
Solution 1:
Always make use of ThenBy() after OrderBy() because  OrderBy() returns an IOrderedEnumerable which then exposes the Methods: ThenBy() and ThenByDescending(). This means that we can OrderBy on multiple Fields by chaining the OrderBy() and ThenBy() together.
IEnumerable<Employee> emp = dc.Employees
                                  .ThenBy(x =< x.Name)
                                  .OrderBy(x => x.Desc);

Solution 2:
If you don't want to go for the Lamda expression where you can easily achieve the multiple ordering
var emp = from e in dc.Employees
          orderby e.Name, e.Desc
          select e;
As you can see in above statement after order by you can add the multiple columns and do the ordering on multiple columns.

Thursday, June 9, 2011

IQueryable Vs. IEnumerable in terms of LINQ to SQL queries

Few days ago I am working on my project which is having Linq to Sql as database layer. I got requirement to get the first of all employee who's designation starts with "soft".

I get fired below query and got the result in IEnumerable varible
IEnumerable<employee> emp = 
         dc.Employees.Where(x => x.Desc.StartsWith("soft"));
emp = emp.Take(1);
But later on I found there it’s taking too much time to get the count.

So to try something else I use IQueryable to store the result and to get the count.
IQueryable<employee> emplist = 
         dc.Employees.Where(x => x.Desc.StartsWith("soft"));
emplist = emplist.Take(1);

After using IQueryable I found I get result faster than previous one.

So to find out this I used SQL Profile to find out the SQL Query fired by the code.

First block of code  fire following query i.e which use IEnumrable to store output of the LINQ query
SELECT [t0].[Id], [t0].[Name], [t0].[Address], [t0].[Desc] AS [Desc]
FROM [dbo].[Employee] AS [t0]
WHERE [t0].[Desc] LIKE @p0
Second block of code  fire following query i.e which use IQuerable to store output of the LINQ query
SELECT TOP (1) [t0].[Id], [t0].[Name], [t0].[Address], [t0].[Desc] AS [Desc]
FROM [dbo].[Employee] AS [t0]
WHERE [t0].[Desc] LIKE @p0

Major difference between both query is First one doesn't contain the TOP clause to get the first record but second one make use of the TOP to get the first record.

When I explore further I fond following difference between both ?

The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements, or even do other things, based on a query. In case of IQueryable Linq Query get used by IQueryProvider  which must interpret or compiled in order to get the result.
i.e Extension methods defined for IQueryable take Expression objects instead of Func objects (which is what IEnumerable uses)., meaning the delegate it receives is an expression tree instead of a method to invoke.

IEnumerable is great for working with in-memory collections, but IQueryable allows for a remote data source, like a database or web service.