Search

May 27, 2009

Using let in LINQ to Objects – Performance killer if used wrong way

C# 3.0 LINQ has one more hidden and powerful feature; which provides you to store result of sub-expression in order to use subsequence clause. You can achieve this with the help of let keyword. The variable created using let is readonly; once initialized it can’t use to store another value only good this is it can be queried.

Let’s see this with example. We have employees details in text file delimited my ‘:’, also each employee have it’s own details separated by ‘,’.

string strEmployees = "1, John, Methew:2, Nick, Althoff:3, David, Oliver:4, Sam, Peterson";

Lets write query to grab all the employee details.

string strEmployees = "1, John, Methew:2, Nick, Althoff:3, David, Oliver:4, Sam, Peterson";

//Split with :
var query = from empData in strEmployees.Split(':')
select empData;

//Split with ,
foreach (var q in query)
{
var e = q.Split(',');
Console.WriteLine("Id - {0}, First Name - {1}, Last Name - {2}",
e[0], e[1], e[2]);
}

As you can see we have to write two different logic to split one more time employee details, now let’s use let keyword and make coding easy.

string strEmployees = "1, John, Methew:2, Nick, Althoff:3, David, Oliver:4, Sam, Peterson";

var query = from empData in strEmployees.Split(':')
let emp = empData.Split(',')
select new { Id = emp[0], FName = emp[1], LName = emp[2] };

foreach (var q in query)
{
Console.WriteLine("Id - {0}, First Name - {1}, Last Name - {2}",
q.Id, q.FName, q.LName);
}


In both query output will be same.

output

emp is intermediate enumerable type which we are using in next line! This is very simple example, now what compiler treats the code above? Compiler will create one sub-query that returns the anonymous type composed of the original value along with new value specified by the let.

As its creating sub-query if you write bunch of let statements, it will kill your performance. If its implemented in proper way let is very good option to go with, the scenario where you need some function which operates on your select clause more then 2-3 times, you can create let variable and use them into your select which makes your faster.

static void SummOfferNoLet()
{
var q = from c in Products
where SumOffers(c) < 10000 && SumOffers(c) > 1000
select c;
int count = q.Count();
}
static void SummOfferWithLet()
{
var q = from c in Products
let offerValue = SumOffers(c)
where offerValue < 10000 && offerValue > 100
select c;
int count = q.Count();
}


In this case SummOfferWithLet will faster as you can see SummOfferNoLet we need to call SumOffers twice.

Conclusion: Using let is powerful but if you used wrong way then it will kill the performance.

May 25, 2009

Issues with Web.config in IIS 7 and Modules (in Vista)

A simple web application runs fine on internal web server, but the time we put it on IIS7 specially in Windows Vista, its start giving configuration error, first and foremost is issue with Modules.

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

And its points to <handlers> section under <system.webServer> section. The issue related to IIS don’t have ASP.NET installed. You can check your Windows feature, although you have installed IIS7 and compatibility for IIS6, ASP.NET is not getting installed automatically. Here is the Windows feature should look like as in following image.

No_ASP.Net

You can find this window from Control Panel –> Programs and Features –> Turn Windows features on or off [Left panel]

TurnWindowsFeaturesOnOrOff

If you have ASP.NET installed on your IIS 7.0 then you have to change the configuration from applicationHost.config file, which resides in %windir%\system32\inetsrv\config\applicationHost.config. You can find the entry for handlers and it has value Deny for property overrideModeDefault, change it to Allow.

<section name="handlers" overrideModeDefault="Deny" /> to <section name="handlers" overrideModeDefault="Allow" />

While saving file I am pretty much sure that it asks for Administrator account although your role is Administrators as you are not owner of that file you can’t make change to file, so solution for this is login as Administrator and do the changes. For vista Administrator is not active for login so find my post which help you to login as Administrator.

May 23, 2009

How to login as Administrator in Windows Vista

Hi All,

In working with Visa, you always get Alert saying “You don’t have permission to access this folder, click continue to get access”, or “Windows needs your permission to continue” or “Destination Folder Access Denied” or due to security you are not able to save file or change who owned by System…. Lots more. Although you have Administrative privileges still its says sometime “You should have administrative permission”. Or if a program needs Admin permission then you can run that application using “Run as Administrator”!!!!

So we need to do login using Administrator account, but the question is from where?

In Vista, the Administrator (or an administrator) is no longer the most trusted object in the operating system. Yes this is to "ostensibly" protect the system, and is part of a general concept of protecting the integrity of the system. The Administration is not activated and you don’t find any User Interface [Up to now, I didn’t fine] which make it active!!! Does it means you can’t make it Active? NO.

To make it active, you have to run command prompt with Administrator permission. Go to Start –> All Programs –> Accessories –> Command Prompt [right click and RUN AS ADMINISTRATOR]

RunAsAdmin

Write following commands to make Administrator active and set the password.

CommandPrompt 

First command will make Administrator account active and another will set yourpassword as Administration account password. Last command Exit.

Now, reboot or switch user or logoff from current user; you can see it will ask for Administrator account password.

USE AT YOUR OWN RISK.

This application has failed to start because the application configuration is incorrect – Solution

I have migrated Vista Home to Vista Premium and my SQL Server and Visual Studio 2008 was not able to start and giving me error ‘This application has failed to start because the application configuration is incorrect, the application has failed to start because its side-by-side configuration is incorrect’. I then check the Event Viewer and find some Dependent Assembly were missing.

Activation context generation failed for "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\LanguagePackage.dll". Dependent Assembly Microsoft.VC80.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.1833" could not be found. Please use sxstrace.exe for detailed diagnosis.

Solution: If you are using VS2005 then download vcredist_x86.exe, and for 2008 download vcredist_x86.exe. No need to do any registry entry or any manifest file.

Apr 17, 2009

User Group Meeting [18-Apr-09]

Its time to announce the user group meeting for Ahmedabad SQLServer UserGroup for the month of April.

The main focus of the meeting will be XML features of SQL Server 2008. You can read more on http://ahmedabad.sqlpass.org/

I would like you to join and gain lots of knowledge and also there will be QA session where you can ask any question related to topic or SQL Server

Hope to see many of you tomorrow!!!

Apr 2, 2009

Enum in JavaScript


We are using enum in server side scripting language, recently I come across requirement where I have to write lots of if-else if clause, then I found the interesting thing which is enum.

Lets see how we can declare enum.

var Technology = 
{
Microsoft: 0,
PHP: 1,
ROR: 2,
Java: 3
}

Minor change in declaration, now lets see how we can use enum.

function Show(tech) {

var msg = 'Welcome to the world of {0}';
switch (Number(tech)) {
case Technology.Microsoft:
alert(String.format(msg, 'Microsoft'));
break;
case Technology.PHP:
alert( String.format(msg, 'PHP') );
break;
case Technology.ROR:
alert(String.format(msg, 'ROR') );
break;
}

}


//And here is the function call
Show(0);
Show(Technology.PHP);
Show(Technology.Microsoft);
Show(2);



Mar 27, 2009

Anonymous Types in C# 3.0

We all know about Abstract Type, generally we are creating Class which are Abstract Type, A Class has name assigned with it. Anonymous Type are Class without specifying the name to it. You can create Anonymous class by using new operator. Consider the following example.

class AnonymousType
{
public string Name { get; set; }
public int Age { get; set; }
public string Country { get; set; }
}
.
.
.
AnonymousType a1 = new AnonymousType { Name = "Marco" };
var a2 = new AnonymousType { Name = "Paolo" };
var a3 = new { Name = "Tom", Age = 31 };
var a4 = new { a2.Name, a2.Age };
var a5 = new { a1.Name, a1.Country };
var a6 = new { a1.Country, a1.Name };



The variables a1 and a2 are of the AnonymousType, but the type of variables a3, a4, a5, and a6 cannot be inferred type, see more on Local Type Inference. The var keyword get the type based on assigned expression which must with new keyword and without a type specified.



The variables a3 and a4 are of the same anonymous type because they have the same fields and properties. Even if a5 and a6 have the same properties (type and name), they are in a different order, and that is enough for the compiler to create two different anonymous types.



You can use anonymous type in array initializer too, lets see and example.




var ints = new[] { 1, 2, 3, 4 };
var arr1 = new[] {
new AnonymousType { Name = "Marco", Country = "Italy" },
new AnonymousType { Name = "Tom", Country = "USA" },
new AnonymousType { Name = "Paolo", Country = "Italy" }};
var arr2 = new[] {
new { Name = "Marco", Sports = new[] { "Tennis", "Spinning"} },
new { Name = "Tom", Sports = new[] { "Rugby", "Squash", "Baseball" } },
new { Name = "Paolo", Sports = new[] { "Skateboard", "Windsurf" } }};



While ints is an array of int and arr1 is an array of AnonymousType, arr2 is an array of anonymous types, each containing a string (Name) and an array of strings (Sports). You do not see a type in the arr2 definition because all types are inferred from the initialization expression. Once again, note that the arr2 assignment is a single expression, which could be embedded in another one.



You can read more features from my older post, Automatic Properties, and Object-Collection Initialization, Local Type Inference and Partial Methods.

Mar 25, 2009

Local Type Inference in C# 3.0


There are list of new features added in C# 3.0, I already cover Automatic Properties, and Object-Collection Initialization and Partial Methods in my older posts, here one more new feature which allow you to write more relaxed code. In another work you can define variable and use them without worrying about too much about their type, leaving it to the compiler to determine the correct type of a variable by inferring it from the expression assigned to the variable itself.

The price for using type inference might be less explicit code against the types you want to use, but in our opinion, this feature simplifies code maintenance of local variables where explicit type declaration is not particularly meaningful.

This might seem to be equivalent to defining a variable of type object, but it is not. The following code shows you that an object type requires the boxing of a value type (see b declaration), and in any case it requires a cast operation when you want to operate with the specific type (see d assignment):

var a = 2;       // a is declared as int
object b = 2; // Boxing an int into an object
int c = a; // No cast, no unboxing
int d = (int) b; // Cast is required, an unboxing is done

C# 3.0 offers type inference that allows you to define a variable by using the var keyword instead of a specific type. When var is used, the compiler infers the type from the expression used to initialize the variable.

The var keyword calls to mind the Component Object Model (COM) type VARIANT, which was used pervasively in Visual Basic 6.0, but in reality it is absolutely different because it is a type-safe declaration. The following code shows some examples of valid uses of var: x, y, and r are double types; d and w are decimal; s and p are string; and l is an int. Please note that the constant 2.3 defines the type inferred by three variables, and the default keyword is a typed null that infers the correct type to p.

public void ValidUse(decimal d)
{
var x = 2.3; // double
var y = x; // double
var r = x / y; // double
var s = "sample"; // string
var l = s.Length; // int
var w = d; // decimal
var p = default(string); // string
}

The next sample shows some cases in which the var keyword is not allowed:

class VarDemo
{
// invalid token 'var' in class, struct or interface member declaration
var k = 0;
// type expected in parameter list
public void InvalidUseParameter(var x) { }
// type expected in result type declaration
public var InvalidUseResult()
{
return 2;
}
public void InvalidUseLocal()
{
var x; // Syntax error, '=' expected
var y = null; // Cannot infer local variable type from 'null'
}
// …
}

The k type can be inferred by the constant initializer, but var is not allowed on type members. The result type of InvalidUseResult could be inferred by the internal return statement, but even this syntax is not allowed .

Partial Methods in C# 3.0

In C# 2.0 Partial Class has been added, which was I personally believe very good features to work in multi-developer environment.

One more new feature added in C# 3.0; Partial Method. I already talked about Automatic Properties, and Object-Collection Initialization which also introduced in C# 3.0. Partial Method is a method which must reside [only signature] into Partial Type [Partial Class] and if define somewhere then will get executed. This basically a rule created by one, if other want to implement then go ahead or leave it blank. I can compare it with Interface method; although its major difference between Interface method and Partial method. In Interface method if you does not implement then the type which implement that interface MUST be abstract; but in the case of Partial Method, its not abstract but its Partial.

There are few rules if you want to work with Partial Methods:

  • A method must be declared within Partial Class or Partial Structure
  • A method cannot have access modifiers. [virtual, abstract, new, sealed...]. They are always private
  • A method must return void
  • A method cannot have out parameter
  • A method definition hast to end with ';'
Here is the simple example of Partial Methods

partial class PartialMethods
{
partial void DoSomeWork();
}

If you build with this code, it will work fine although we haven't write body of this function. If you see the Manifest you wont find this method anywhere. The only constructor will part of PartialMethods class.

PartialMethod1

Now let me write body for the method and check manifest again

partial class PartialMethods
{
partial void DoSomeWork();
}

public partial class PartialMethods
{
partial void DoSomeWork()
{
//Do your work here
}
}


PartialMethod2

Now we can see the method, this class is not full class but as partial methods are private, you cant not access from outside, you have to call within that class. Partial method allow developer to create rule which can be implemented later but only once.

Mar 14, 2009

Object and Collection Initialization in C# 3.0

My last post I speak about Automatic Properties, and how we can use them. Here we will discuss the Object and Collection Initialization in C# 3.0. In general we are do initialize our property either inside constructor [standard method] or by calling some methods or assigning value directly to public property. Let's see how.

public class Test
{

public class InitializeTest
{
public int Id { get; private set; }
public string Name { get; private set; }

public InitializeTest()
{

}

//Initialize using constructor
public InitializeTest(int intId, string strName)
{
Id = intId;
Name = strName;
}

//Initialize using method
public void SetId(int intId)
{
Id = intId;
}
}

static void Start()
{
//Initialize using constructor
InitializeTest objInitializeTest1 = new InitializeTest(1, "a");

//Initialize using method
InitializeTest objInitializeTest2 = new InitializeTest();
objInitializeTest2.SetId(1);
}
}

Lets talk about initialize using constructor, we have two constructor, one is default and another is accepting two arguments. so far so good. Lets say I have added new property into my class, then? have to create new overloaded constructor? or modify two argument constructor with three which will raise few more errors!!! First one will be better option.

public char Sex { get; set; }

//Initialize using constructor
public InitializeTest(int intId, string strName) : this(intId, strName, 'M') { }

//Initialize using constructor
public InitializeTest(int intId, string strName, char cSex)
{
Id = intId;
Name = strName;
Sex = cSex;
}

Now to avoid this lets see what is in Object Initialization provided by C# 3.0. We can simply use single argument constructor to initialize the member of class, lets add one more property to class name Birthdate.

public class InitializeTest
{
public int Id { get; set; }
public string Name { get; set; }
public char Sex { get; set; }
public DateTime Birthdate { get; set; }
.
.
.
.
}

You may notice here that I have removed private scope why? I will explain it later.

static void Start()
{
InitializeTest objInitializeTest3 = new InitializeTest() { Id = 1, Birthdate = DateTime.Now, Name = "Name", Sex = 'M' };
}

That's it!!! initialize the value of property right after constructor inside the curly braces. You can also assign few or complete list. Now if we make Id property private we can't use here [outside of the class] that is the reason for removing private to get accessor. How it works?

The syntaxes used to initialize an object (standard and object initializers) are equivalent after code is compiled. Object initializer syntax produces a call to a constructor for the specified type (either a reference or value type): this is the default constructor whenever you do not place a parenthesis between the type name and the open bracket. If that constructor makes assignments to the member fields successively initialized, the compiler still performs that work, although the assignment might not be used. An object initializer does not have an additional cost if the called constructor of the initialized type is empty

This can be done on parameterize constructor as well.

We seen object initialization, same was we can achieve collection initialization. Let's see how. First lets add one generic collection to out class and then will do initialization.

public class InitializeTest
{
.
.
public List<string> FamilyMembers { get; set; }
.
.
}
.
.
static void Start()
{
InitializeTest objInitializeTest4 =
new InitializeTest() { FamilyMembers = { "First", "Second", "Third" } };
}
.
.

Its really easy and we have eliminated quite a bit of typing.