Technology News

April 13, 2011

Differed Execution (vs) Immediate execution in LINQ

Filed under: 2011, April, C# 3.0, Code, LINQ, Tips, Wednesday — చక్రవర్తి @ 8:56 pm

Recently while understanding LINQ, many things unfurled from MSDN. The main theme of .NET is lazy binding (or) lazy loading. And it is evolving in all the ways within the .net Framework. I recollect in one of my previous posts about the mainly concentrated theme for every version that is released. I could be wrong from the insider perspective, but what I’ve observed is what I’ve written.

Anyhow, coming back to the main purpose of this post, which is all about the lazy loading and the point behind various execution mechanisms that are available within LINQ. Before I proceed further, one point is very certain that, choosing LINQ is costlier from the point of “Response Time” from DB to any connected system. This statement is true when compared the LINQ with any traditional mechanism of database connectivity.

Traditionally, every developer writes code with Connection object for connecting to the Data Store and then disposes the connection. This method can be by various objects that are provided within .net framework. One of the mechanism is that

  • Use a connection object and DataAdapter
  • Use a connection object along with Command and use either DataReader or DataSet

These mechanisms are pretty neat and straight, while connecting to the datastore. Where as they don’t provide the query mechanism to the developer against the returned results from the datastore. Ofcourse, you still could do the “Filter” method for the dataset or datatable object. This again doesn’t give the generic way to query from the data in the dataset / datatable.

LINQ, in this context provides a great flexibility for the developer to query against the data schema and provides a decent means of all kinds of DataBase querying techniques. In other words, I could say that LINQ gives the power of Database Querying to the C# developer. If your applications are developed using LINQ, you don’t need to have a DB developer. But you need the DB administrator to understand the health of the database and fine tune the queries used by LINQ. Hence, by choosing LINQ for your projects you are saving cost to the project owner. So, To LINQ or NOT to is upto you to decide. Let me not write more here about  LINQ and jump to the execution mechanisms within LINQ.

As titled in the post, there are 2 mechanisms for the execution of LINQ Results, I say it is about LINQ RESULTS. They are differed execution as well as Immediate execution. The main difference between these two are the lazy loading (or) JustInTime loading at the run time. To make simple this entire story, let me give you some code snippet, so that you would understand. For this am trying to query the Northwind Database.

Requirement:

Display all the employee names along with the product names and total of sold quantity

 

Solution 1 : In this solution am trying to use the LINQ as an Expression.

var empCounts = from eachEmpData in
 (from eachSale in
   (from eachEmp in nwDB.Employees
      join eachOrder in nwDB.Orders on eachEmp.EmployeeID equals eachOrder.EmployeeID
      join eachOrderDetails in nwDB.Order_Details on eachOrder.OrderID equals eachOrderDetails.OrderID
     join eachProduct in nwDB.Products on eachOrderDetails.ProductID equals eachProduct.ProductID
     where eachOrder.OrderDate > dtStart && eachOrder.OrderDate < dtEnd
                          select new
                          {
                              FirstName = eachEmp.FirstName,
                              LastName = eachEmp.LastName,
                              ProductName = eachProduct.ProductName,
                              OrderQuantity = eachOrderDetails.Quantity
                          }
                        )
    group eachSale by new { eachSale.FirstName, eachSale.LastName, eachSale.ProductName } into groupSales
                     select new
                     {
                         groupSales.Key.FirstName,
                         groupSales.Key.LastName,
                         groupSales.Key.ProductName,
                         Sold = groupSales.Sum(qty => qty.OrderQuantity)
                     })
                select eachEmpData;
 
// the below line binds the data from LINQ Expression

bsLINQData.DataSource = empCounts;

In this solution, you could see that I’ve written all the joins similar to that of the Database SQL joins. If you are familiar with all such queries, then it is very easy to write. But this kind of writing is also expensive. The alternative for such queries is the next solution.

Solution 2: In this solution am trying to use the same above LINQ as methods

var empCounts = nwDB.Orders
    .Where(eachOrder => eachOrder.OrderDate > dtStart && eachOrder.OrderDate < dtEnd)
                    .SelectMany(eachOrderDetails => eachOrderDetails.Order_Details)
                    .GroupBy(od => new { od.Product, od.Order.Employee })
                    .Select(od => new
                    {
                        FirstName = od.Key.Employee.FirstName,
                        LastName = od.Key.Employee.LastName,
                        ProductName = od.Key.Product.ProductName,
                        Sold = od.Sum(q => q.Quantity)
                    })
                    .OrderBy(s => s.Sold);

                // the below line binds the data from LINQ Expression
                bsLINQData.DataSource = empCounts;

In this solution, you find less coding and much usage of LINQ as methods. This kind of coding is much better than the previous solution. For the records, the above solution has taken about 3 milliseconds on my laptop where as the current solution took about 1 millisecond to query. See below for the stats and comparison.

Solution 3: The above two solutions are Differed execution, where as the current one is all about Immediate execution.

var empCounts = nwDB.Orders
    .Where(eachOrder => eachOrder.OrderDate > dtStart && eachOrder.OrderDate < dtEnd)
    .SelectMany(eachOrderDetails => eachOrderDetails.Order_Details)
    .GroupBy(od => new { od.Product, od.Order.Employee })
    .Select(od => new
    {
        FirstName = od.Key.Employee.FirstName,
        LastName = od.Key.Employee.LastName,
        ProductName = od.Key.Product.ProductName,
        Sold = od.Sum(q => q.Quantity)
    })
    .OrderBy(s => s.Sold).ToList();

// the below line binds the data from LINQ Expression
bsLINQData.DataSource = empCounts;

Here you have to observe the query ended with .ToList() and that is the trick of this query. When you see the statistics, it is very surprising that the time taken to query is very negligible when compared with binding the query results to the binding source. Which means that it is evident to say, LINQ doesn’t fetch the data when it is queried, but it fetches data when it is actually binded to any source.

Finally, the results when compared the above all the three solutions are as mentioned below

  Query Bind
Expression 3 60
Methods 1 44
InList 35 9

 

Conclusion :

Solution 1 and Solution 2 are the examples for Differed Execution, where as the 3rd solution is an example for Immediate execution. Any comments?

November 29, 2010

Visual Basic is the Core attention by Microsoft

Filed under: 2010, 29, Monday, November, VB.NET — చక్రవర్తి @ 10:00 pm

Workflow foundation is currently at 4th version. The main coding syntax that is expected for any of the code activities are more from the VB code syntax. Hence, it is proven that Microsoft considers VB as primary language while doing any kind of Research.

Apart of this, there is one more fact that there is a recent toolkit released from Microsoft, just yesterday, ie., 28th Nov 2010. It is RTW for Windows Phone developer. This release enables Visual Basic developers to create Silverlight applications for Windows Phone 7 using the final version of the windows phone developer tools.

You can download the Windows Phone developer tools RTW from this link.

December 6, 2007

Calling .NET Component from a classic ASP page

Filed under: Code, COM, JavaScript, Tips, VB.NET — చక్రవర్తి @ 4:12 pm

After a long time, today, got a requirement from ASP page. Our current client has a major application written in classic ASP 2.0, and we have given him an extension functionality written in .NET with VB as programming language.

Now, we have 2 different applications running at the same box with 2 different technologies, ie., an ASP application and an ASP.NET application. For both of the applications, there is a common functionality talking to the database via a webservice written in Java. The current situation demand a common library that will be reused at both ASP.NET pages as well as ASP pages. Apart of the requirement, the one point that led me to post here is “How to call a .NET Assembly in a Classic page”

Creating .NET Assembly

Imports System
Imports System.Runtime.InteropServices
Public Class MyLibClass
    Public Function MyLibFunction() As String
        Return " Invoked the method from COM successfully .."
    End Function
End Class

With the above code, you can generate a .NET DLL after compiling with either Visual Basic Command Line Utility, VBC.EXE or from the Visual Studio Environment. While compiling this code, give extra attention at the assembly attribute to make the DLL Visible to COM as mentioned below.

<Assembly: ComVisible(True)> 

If you are using the Visual Studio Environment, go to the Project Properties, at the Compile section don’t forget to check the “Register COM interop” check box. This check box will be by default unchecked, indicating that the DLL will not be exposed to COM.

Now the assembly is ready to reuse. But before we start the actual implementation, if you want the Assembly should be register with the GAC, you have to take the assistance from StrongNameKey file. You can create a Strongname Key file with the command utility SN.EXE or from the Visual Studio as well. The command to create the Strongname Key file is as mentioned below

> sn -k strongnamekeyfile.snk

Once you are done with the strong name key file generation, you can attach the key file either with the /keyfile:strongnamekeyfile.snk option or with the assembly attribute as <Assembly: AssemblyKeyFile(“strongnamekeyfile.snk”)>

Now it is the final time to compile your code and do the calling stuff from ASP page. Once you compile the code from Visual Studio, you will have 3 files, .PDB / .TLB / .DLL. The .DLL is the actual file. You have to do 2 things to share this DLL.

Register as COM as well as with GAC

Now that the DLL is ready, we will take the assistance of REGASM command line utility to register as public assembly.

> regasm /codebase /tlb:a.tlb OurAssemblyFile.dll

With this command, the DLL will be registering at the registry. Please don’t forget to use the /codebase option. To register the same with GAC use the following command

> gacutil /if OutAssemblyFile.dll

This command will register with the GAC and is available as reference within the .NET Framework. With the first command, the object is ready to invoke from ASP code. You can use the COM component with Server.CreateObject(“OurAssemblyFile.ClassName”) command from ASP page. The actual implementation at any ASP page will look like as mentioned below

 dim objCom 
 set objCom = Server.CreateObject("libraryNameSpace.libraryClass")
 objCom.DoSomeWork() ' this method doesn't return any value

Finally, if this page throw any kind of error as Unindentified Class name, then the only solution is to reset the IIS.

September 15, 2007

The importance of JavaScript ‘return’

Filed under: Code, JavaScript, Tips — చక్రవర్తి @ 6:14 pm

Recently, while coding for a Text Field value padded with left zeros, realised the importance of the RETURN key word for the FUNCTION written in JavaScript. Before i mention the actual importance, let me describe you the situation.

Scenario: A Text box need to be padded with zeros and should have the length of 7 digits, even the data entered is less than 7.

Ex: When the key board input being 88, the text box should show 0000088. Note the ZEROs padded on left.

So, started with a JavaScript function as mentioned below

function PadZeros(x)
    {
        var v = x.value;
        while(v.length<7)
        {
            v = '0' + v;
        }
        var ss = document.getElementById(x.id);
        ss.value = v;
    }

After this, the text box is padding with ZEROs and the code is perfectly running. To allow this to code execute for any given text box, all you have to do is, add the ATTRIBUTE to that text box. And while adding keep one thing in mind that, we would be calling this function on BLUR, ie., LOST FOCUS of the text box. The code is as mentioned below.

            this.txtPCode.Attributes.Add("onblur", "PadZeros(this);");

Please note the ‘this’ keyword. The usage of ‘this’ keyword has many possibilities. Let me see that, one day will post where the ‘this’ keyword is used and their context. And also note that, neither the function is returning any value nor the text box is added with the code that handles the output of the function. Will come to that in short.

 

Every thing is working perfectly well and going on smooth. But suddenly, i realised that the text box is just padding ZEROs when there is no Input. I see all ZEROs in the text box as 0000000. Then came the real trick to the function.

function PadZeros(x)
    {
        var v = x.value;
        if(v.length == 0)
        {
            var vTe = document.getElementById(x.id);
            vTe.focus();
            alert('Please enter Provider Code .. ');
        }
        while(v.length<7)
        {
            v = '0' + v;
        }
        var ss = document.getElementById(x.id);
        ss.value = v;
    }

What do you see here is the mechanism to set the focus back to the text box. Great… but that even is not solving my purpose of leaving the text box blank when there is no input. This function is still adding ZEROs to no input and showing all ZEROs. Then came the purpose of the ‘return’ keyword. The entire requirement is simply solved by this keyword. All i’ve done is.. changed the code as mentioned below.

function PadZeros(x)
    {
        var v = x.value;
        if(v.length == 0)
        {
            var vTe = document.getElementById(x.id);
            vTe.focus();
            alert('Please enter Provider Code .. ');
            return false;
        }
        while(v.length<7)
        {
            v = '0' + v;
        }
        var ss = document.getElementById(x.id);
        ss.value = v;
        return true;
    }

At the code behind added ‘return’ as shown here

            this.txtPCode.Attributes.Add("onblur", "return PadZeros(this);");

That’s all.. hoollaa… What do you say ?

Technorati Tags: , ,

August 24, 2007

C# 3.0 – What’s New : {Implicit}-Part1

Filed under: C# 3.0, Code, First, Tips — చక్రవర్తి @ 10:52 am

Recent development in my technical life is that, started working out with Orcas Beta 2. So, thought to blog about the latest happenings with C# language. The idea emerged to start a series of posts related to C# new features. This is the first of ever such kind of blogging specific to a topic.

C# 3.0 has many-a-new features. To start with, let me take a concept of Implicitly Typed Variables.

Implicitly Typed Variables

In the good old days, the developer has to worry about the type of the variable. Say for instance, whether to use long or double for a counter. Here all that we observe is that the language that is built upon is the type specific. Hence forth the developer is not required to define the type of the variable at the time of declaration, but it is the task of the compiler to decide what type of the object the variable is. All that the developer has to do is that, use the var keyword while declaring the variable, similar to that of JScript or Visual Basic style. Hey!!! Stop!!!!! don’t get confuse with the type of VAR variables declared at JScript or Visual basic.

Let’s first discuss the difference between VAR variables at JScript and VAR variables of C#

VAR JScript VAR C#
This is of no type The type of the variable is defined by the value declared and decided at the compile time
Technically have no type. Can consider of limited types, namely, string literal, numeric, boolean Type agnostic, have specific predefined formats
Type conversion is coercion Type casting is simple and handled by CLR
No mechanism for parsing explicit functions for parsing to specific type

Now, let us see the difference between the language specific VAR of VisualBasic 6.0 and C# 3.0

VAR in VB (but not .NET) VAR in C# 3.0
By definition, these are Variant Type of the variable is defined at the compile time
Could be any allowed type from with in the known types of the language Type is decided by the value associated with the variable
Largest among all the known data types Size depends on the type of the value initialised

To summarize, the variables declared in C# 3.0 are type specific, thou used the key word VAR, during the declaration. Thus, we can conclude that the compiler is the responsible point to decide the type of the variable. Hence we can say with comfort that, the variables from C# 3.0 are Implicitly Typed variables.

Some examples as mentioned below.

            var vIntVal = 10; // This will be the System.Int32 type
            var vLongVal = 10000000000; // This will be the System.Int64 type
            var vDoubleVal = 10.0; // This will be the System.Double type
            var vFloatVal = 10.0f; // This will be the System.Single type
            float vFlVal = 10.0f; // Thou defined using float key word, but inherits from Struct System.Single 
            var vStrVal = "String Value ";  // This will be the System.String type

So, from the above declarations, it is pretty clear that the variable is defined by the value associated during the declaration. The type is not just limited to the kind of data types as explained above, but you can extend this to any type of the variable that you use while writing code for iterations, similar such as foreach. Below is the example for other known types.

            foreach (var vTable in ds.Tables) // Implicitly declared a variable of Data Table Type
            {
                foreach (var vRow in ((DataTable) vTable).Rows) // Implicit declaration of DataRow variable
                {

                }
            }

By using such, one can extend any extent. The limit is the imagination of the developer. What do you say?

Source:

1) http://cobdev.cob.isu.edu/psb/jscript/306.htm for JScript
2) http://www.1sayfa.com/1024/diger/vb/ch07.htm for Visual Basic 6.0 Datatypes

del.icio.us Tags: , , , ,

June 26, 2006

Designing Apps with .NET

Filed under: C# 3.0, Code, Design Patterns, Presentations, Self, Tips — చక్రవర్తి @ 5:51 pm

A presentation that i recollected from my old mails. Can you talk about this?

May 20, 2006

B.NET session PPT

Filed under: Code, Presentations, Self, Tips — చక్రవర్తి @ 11:16 am

On 19th May 2006, spoke about “Working with XML in .NET Application” at B.NET groups offline meeting.

Here comes the Presentation for the same.

Blog at WordPress.com.