Friday 30 December 2011

Copy of Session Object

Many times we try to make copy of session object, but in case when we are modifying copied object we might noticed that session object gets updated automatically, the reason is both copied object and session object are pointing to same location, even if you tried to use "new" operator while creating object.

Scenario
Let say you have Member Class as mentioned under
public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }
}


Problem:
Member objMember = new Member();
objMember.FirstName = "Sachin";
objMember.LastName = "Tendulkar";

Then try to save object in Session
Session["MemberObj"] = objMember;

This method will work good till we are just accessing object from session, but in case if we try to update object created from session it will update value of session also.

That is,
Member newMember = new Member(); //Even though object is created using "new" keyword.
newMember = (Member) Session["MemberObj"];
newMember.FirstName = "Kapil"; //This will update session FirstName also.


Solution:
To make copies of session you need to create a clone method in class.

In above class create a method clone, to support copy of session.


public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }


public Member clone()
{
   Member cloneMember = new Member();
       cloneMember.FirstName = this.FirstName;
   cloneMember.LastName = this.LastName;
}
}

Now, while accessing session object, you can call clone method to make copy of session.

Member newMember = new Member();
newMember = ((Member) Session["MemberObj"]).clone();

now if you try to modify object copied from session, will not update session object.
newMember.FirstName = "Kapil"; //Will not update session FirstName

C# Jagged Array Examples

You need to evaluate jagged arrays in your C# programs. You have several rows of data, such as integers, and want to store them together in a single data structure. Jagged arrays are ideal for this, and this document has some examples and discussion, with code in the C# programming language.

Example

Here we see some example code that shows you how to use jagged arrays in different ways. The following code is a short but complete program you can run in a console project. It creates an array and sets values in it, then prints out the result at the end.
Example jagged array program [C#]

using System;

class Program
{
    static void Main()
    {
 // Declare local jagged array with 3 rows.
 int[][] jagged = new int[3][];

 // Create a new array in the jagged array, and assign it.
 jagged[0] = new int[2];
 jagged[0][0] = 1;
 jagged[0][1] = 2;

 // Set second row, initialized to zero.
 jagged[1] = new int[1];

 // Set third row, using array initializer.
 jagged[2] = new int[3] { 3, 4, 5 };

 // Print out all elements in the jagged array.
 for (int i = 0; i < jagged.Length; i++)
 {
     int[] innerArray = jagged[i];
     for (int a = 0; a < innerArray.Length; a++)
     {
  Console.Write(innerArray[a] + " ");
     }
     Console.WriteLine();
 }
    }
}

Output

"1 2"
"0"
"3 4 5"
Description. It declares a jagged array. The word 'jagged' doesn't even exist in the C# language, meaning that you don't need to use this word in your code. Jagged is just a descriptive variable name I use.
Initializations used. It initializes some values in the jagged array. There are lots of square brackets. This is very different from a 2D array, which uses commas instead of pure brackets.
Assigning jagged arrays. It assigns an array at the second index. Above you should see that indexes in the array are assigned to new int[] arrays. This is because the jagged array only allocates the list of empty references to arrays at first. You have to make your own arrays to put in it. We see the array initializer syntax here, which is less verbose than some other ways.
Looping over jagged arrays. You will want to examine each item in the jagged array. We must call Length first on the array of references, and then again on each inner array. The Console calls above are just for the example.
Two-dimensional (2D)

2D arrays

Here we will look at how you can choose between jagged arrays and 2D arrays. First, ask yourself the question: will every row in my collection have the same number of elements? If so, you can consider 2D arrays, but often you have varying numbers of elements.
Performance notes. Second, jagged arrays are faster and have different syntax. They are faster because they use the "newarr", vector IL calls internally. The boost is because they are optimized for starting at 0 indexes. Here is some code I compared in IL Disassembler.
Method that is reflected for MSIL test [C#]

private static void CompareIL()
{
    int[,] twoD = new int[1, 1]; // 1 x 1 array

    twoD[0, 0] = 1;

    int[][] jag = new int[1][];

    jag[0] = new int[1];
    jag[0][0] = 1; // 1 x 1 jagged array
}
Jagged array intermediate language in Visual StudioChoosing the syntax. Whichever array type you choose, don't select it because of the syntax. It is important to know that the pairs of brackets indicate "jagged," and the comma in the brackets means "2D".
Separate rows in arrays. You can allocate different arrays for each row in jagged arrays separately, which means your program must use 1D arrays in parts.

Parameters

You can use the type of the jagged array in method signatures in the C# language to use jagged arrays as parameters. You can use the same syntax as we saw above. They will be passed as references, which is important because it eliminates most copying. Only the reference is copied on each function call.
Performance optimization

Benchmark

The .NET runtime has optimizations for this specific case, and for some reason the 2D array cannot take advantage of them. My opinion is that you should always use jagged arrays when possible. They have substantial optimizations in the intermediate language level.
2D array code benchmarked [C#]

// 2D array of 100 x 100 elements.
for (int a = 0; a < 100; a++)
{
    for (int x = 0; x < 100; x++)
    {
 int c = a1[a, x];
    }
}

Jagged array code benchmarked [C#]

// Jagged array of 100 x 100 elements.
for (int a = 0; a < 100; a++)
{
    for (int x = 0; x < 100; x++)
    {
 int c = a2[a][x];
    }
}

Results

2D array looping:      4571 ms 
Jagged array looping:  2864 ms  [faster]

Summary

We saw how you can use jagged arrays in your C# programs. Jagged arrays are fast and easy to use once you learn the slightly different syntax. Prefer them to 2D arrays when performance is a consideration, and they are not more complex more to use. Investigating IL can be useful for understanding .NET internals.

Thursday 29 December 2011

C# Lambda Expression

You want to use lambda expressions in the C# programming language, allowing functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator and this specifies how the parameters and statement body of the anonymous function instance are separated, and provides a formal name to the environment variables. Here we look at lambda expressions.Lambda expression syntax
Tip: Lambda expressions use the token => in an expression context.

Example

This program demonstrates how you can insert lambda expressions and other anonymous functions into a C# method. The source text uses the => operator, which is a syntax for separating the parameters to a method from the statements in the method's body.
The => operator can be read as "goes to" and it is always used when declaring a lambda expression. In programming languages, a lambda expression allows you to use a function with executable statements as a parameter, variable or field.
Program that uses lambda expressions [C#]

using System;

class Program
{
    static void Main()
    {
 //
 // Use implicitly typed lambda expression.
 // ... Assign it to a Func instance.
 //
 Func<int, int> func1 = x => x + 1;
 //
 // Use lambda expression with statement body.
 //
 Func<int, int> func2 = x => { return x + 1; };
 //
 // Use formal parameters with expression body.
 //
 Func<int, int> func3 = (int x) => x + 1;
 //
 // Use parameters with a statement body.
 //
 Func<int, int> func4 = (int x) => { return x + 1; };
 //
 // Use multiple parameters.
 //
 Func<int, int, int> func5 = (x, y) => x * y;
 //
 // Use no parameters in a lambda expression.
 //
 Action func6 = () => Console.WriteLine();
 //
 // Use delegate method expression.
 //
 Func<int, int> func7 = delegate(int x) { return x + 1; };
 //
 // Use delegate expression with no parameter list.
 //
 Func<int> func8 = delegate { return 1 + 1; };
 //
 // Invoke each of the lambda expressions and delegates we created.
 // ... The methods above are executed.
 //
 Console.WriteLine(func1.Invoke(1));
 Console.WriteLine(func2.Invoke(1));
 Console.WriteLine(func3.Invoke(1));
 Console.WriteLine(func4.Invoke(1));
 Console.WriteLine(func5.Invoke(2, 2));
 func6.Invoke();
 Console.WriteLine(func7.Invoke(1));
 Console.WriteLine(func8.Invoke());
    }
}

Output

2
2
2
2
4

2
2
Syntax. In many of the statements in the example, you will see the => syntax, which can be read as "goes to" and it separates the arguments from the method body of a lambda expression. It is not a comparison operator. The => syntax can separate an empty parameter list, a formal parameter list or an implicit parameter list from the the body. The right side of the lambda expression can be a statement list inside curly brackets with a return statement, or an expression.
The C# programming languageOverview. The instances with identifiers func1 through func8 all denote anonymous function instances in the C# language. The Func<TResult> type indicates an anonymous function with one result value and no parameter. The Func<T, TResult> type indicates a function with one parameter and one result value. The Action type indicates a function instance that does not receive a parameter and does not return a value.
Delegate keyword. The program also demonstrates how the delegate keyword can be used to denote an anonymous function in the C# language. After the delegate keyword, you can use a formal parameter list or even omit the list if there are no parameters. Afterwards, you must specify a statement list that is executed when the anonymous function is invoked.
Invoking Func and Action instances. Finally, the program demonstrates how you can call the methods that were all specified inside the method body. The Func generic type and the Action type have an instance method called Invoke. It receives a number of parameters that depends on the type. The method body of each of the lambdas and anonymous functions is then executed.

Anonymous functions

The term anonymous function describes both delegates and lambda syntaxes in the C# language. The key part of an anonymous function is that it does not have a name and cannot be invoked with normal method lookup. For this reason, method overloading is not possible for anonymous functions.
Many experts regard lambda expressions as a complete improvement over the delegate syntax. It is sometimes advised that you use lambda expressions instead of the delegate keyword syntax when it is possible.

Specification

The C# language specification itself describes the anonymous function types in the language. The annotated edition of The C# Programming Language (3rd Edition) covers all the syntaxes available, and this article derives its example from the specification's. You can find more detail on this topic using the precise technical terminology on page 314 of this book.

Summary

We looked at the syntactic rules of lambda expressions in the C# programming language with help from the C# specification itself. We described lambda expressions with zero arguments, one argument, two arguments, and one return value. We also looked at the delegate keyword when used for anonymous functions. Finally, we explored the Func generic type in the base class library as well as the Action type, and the Invoke instance methods on these types.

Tuesday 20 December 2011

Web Site vs Web Application project


A common question by asp.net developers is what project model should I use for asp.net application? Web Site project (which introduced with VS 2005) or Web Application project (which delivered as add-in for VS 2005 and built-in within VS 2005 SP1)?
There is no thumb rule. Every project model has it's own advantages (and diss-advantages off course...). I hope this post will help you to understand better the differences between 2 of them.
Web Application project model
  • Provides the same Web project semantics as Visual Studio .NET 2003 Web projects.
  • Has a project file (structure based on project files).
  • Build model - all code in the project is compiled into a single assembly.
  • Supports both IIS and the built-in ASP.NET Development Server.
  • Supports all the features of Visual Studio 2005 (refactoring, generics, etc.) and of ASP.NET 2.0 (master pages, membership and login, site navigation, themes, etc).
  • Using FrontPage Server Extensions (FPSE) are no longer a requirement.
Web Site project model
  • No project file (Based on file system).
  • New compilation model.  (Read here or here for more details) and ...
  • Dynamic compilation and working on pages without building entire site on each page view.
  • Supports both IIS and the built-in ASP.NET Development Server.
  • Each page has it's own assembly.
  • Defferent code model.  (Read here for more details)
Ok, all is great, but you want to create your web site now. Which model should you use?
  • You need to migrate large Visual Studio .NET 2003 applications to VS 2005? use theWeb Application project.
  • You want to open and edit any directory as a Web project without creating a project file? use Web Site project.
  • You need to add pre-build and post-build steps during compilation? use Web Application project.
  • You need to build a Web application using multiple Web projects? use Web Application project.
  • You want to generate one assembly for each page? use Web Site project
  • You prefer dynamic compilation and working on pages without building entire site on each page view? use Web Site project
  • You prefer single-page code model to code-behind model? use Web Site project

"Visual Studio Tips, 251 ways to improve your Productivity in Visual Studio", courtesy of 'Sara Ford'

Total Pageviews