Faqs on asp.net,c#,vb.net and sqlserver2005

this blog covers all the Faqs related to .net technologies like asp.net,vb.net,c#.net,ajax,javascript and sqlserver2005.

Apr 2, 2008

Windows Drive not opening directly

Sometimes it happens in windows XP that you are not able to open drives on your hard disk. When you double clicking on the drives icons or right click on the drive>>explore in My computer ,the drive does not open.

This problem is generally caused by most of the viruses which infect windows XP system. They block or restrict your access to any of the drives.

But don’t worry this is not a big trouble it can be fixed easily.


Normally when a virus infects a windows system which causes a drive opening problem, it automatically creates a file named autorun.inf in the root directory of each drive.

This autorun.inf file is a read only ,hidden and a system file and the folder option is also disabled by the virus. This is deliberately done by the virus in order to protect itself. autorun.inf initiates all the activities that the virus performs when you try to open any drive.

You have to just delete this file and restart your system to correct this problem.

Follow the set of commands below to show and delete the autorun.inf

1. Open Start>>Run and type cmd and press enter. This will open a command prompt window. On this command prompt window type the following steps.

2. type cd\

3. type attrib -r -h -s autorun.inf

4. type del autorun.inf

5. now type d: and press enter for d: drive partition. Now repeat steps 3 and 4. Similarly repeat step 5 for all your hard disk partition.

Restart your system and your trouble will be fixed.

Mar 17, 2008

Validating Images before Upload by Checking the File Stream

Validating Images before Upload by Checking the File Stream

Rather than just checking for valid file extensions, there are more advanced ways of checking that your users are not uploading rubbish to your image file store (we currently use MOSS for storage at Lend Lease).
/// Added to validate that an image is being uploaded - not just any document
/// summary
private bool IsImage(byte[] data)
//read 64 bytes of the stream only to determine the type
string myStr = System.Text.Encoding.ASCII.GetString(data).Substring(0, 16);
//check if its definately an image.
if (myStr.Substring(8, 2).ToString().ToLower() != "if")
//its not a jpeg
if (myStr.Substring(0, 3).ToString().ToLower() != "gif")
//its not a gif
if (myStr.Substring(0, 2).ToString().ToLower() != "bm")
//its not a .bmp
if (myStr.Substring(0, 2).ToString().ToLower() != "ii")
//its not a tiff
myStr = null;
return false;
myStr = null;
return true;
public Response> AddAssetImageToSession( string fileName, Stream contentStream, IWebPageView currentView, string parentWindow)
Response response = GetAssetImageSingle();
if (string.IsNullOrEmpty(fileName))
response.Errors.Add(new Error(ErrorName.FileError, Errors.MissingFileName)); response.IsSuccessful = false;
SharepointDocumentDto item = new SharepointDocumentDto();
item.Name = fileName;
//Set FileName item.
IsNewItem = true;
//Flag as true so we know to save it when the asset is saved item.
GeneratedListItemId = Guid.NewGuid().ToString();
MemoryStream ms = new MemoryStream();
byte[] data = new byte[256];
int c = contentStream.Read(data, 0, data.Length);
//Check if it is a valid image
if (!IsImage(data))
response.Errors.Add(new Error(ErrorName.FileError, Errors.InvalidImageUploaded)); response.IsSuccessful = false;
return response;
//Read into buffer until end of file
while (c > 0)


Happy Programming

Latest Developments in the .Net World

Do you want to know about the latest development in the .Net technology? Here is a comprehensive look at the latest developments in the world of Microsoft’s.NET.
If you are committed software developer, you must be aware that ‘web services’ is the latest buzzword to have hit the IT industry. And that this technology trend holds tremendous potential for addressing business problems.
Extensible markup language (XML) is the universal format for data on the web. With XML web services gaining momentum among developers as the next generation of internet-based computing. A platform that made it similar to build these solutions and provide a reliable framework for integration and interoperability was needed. Microsoft’s answer to this much-felt need was .NET—a platform for building, deploying, operating and integrating XML web services.
.NET is the only platform that has been built to support XML services ground up, and Microsoft has been extensively working with the industry to develop standard s like SOAP and UDDI, the XML web services search directory that exits today.
Let’s now take a detailed look at all that Microsoft’s .NET has to offer software developers by the analyzing the latest developments that have taken place in this platform.
ASP.NET is more than the next version of active server pages (APS) ----- it is the unified web development platform that provides the services necessary for developers to build enterprise-class web applications.ASP.NET is a compiled, .NET –based environment; you can author applications in any.NET compatible language, including ASP.NET Visual Basic .NET,C#, and the jscript.NET.Additionally, the entire .NET framework is available to any ASP.NET application.
Developers can choose from one of two features when creating an ASP.NET application, web services, or combine these in any way they see fit.
Web forms to allow you to build powerful forms-based web pages. When building these pages, you can use ASP.NET server controls to create common UI elements, and programs then from common tasks.
These controls to allow you to rapidly build a web form out of reusable built-in or custom components, simplifying the code of a page.
An XML web service provides the means to access server functionality remotely. Using web services, interfaces to their data or business logic, which is turn can be obtained and manipulated by client and server applications. XML web services enable the exchange of data in client-server or server- server scenarios, using standards like HTTP and XML messaging to move data across firewalls.
Each of these models can take full advantage of all ASP.NET framework and.NET framework common language runtime. These features and how you can use them are outlined as follow:
If you have ASP development skills, the new ASP.NET programming model will seem very familiar to you. However, the ASP.NET object model has changed significantly from ASP, making it move structured and object oriented.
Accessing database from ASP.NET application is an often-used technique for displaying data to website visitors. ASP.NET makes it easier then ever to access database for this purpose.
ASP.NET provides a simple model that enables developers to write logic that runs at the application level. Developers can write this code in the global. Asax text files or in a compiled class deployed as an assembly.
ASP.NET provides easy-to-use application and session-state-facilities that are familiar to ASP developers and readily compatible with all other .NET framework APIs.
For advanced developers who wants to use APIs as powerful as the ISPI programming interfaces that were included with previous version of ASP, ASP.NET offer the IHttpHandler interfaces.
ASP.NET takes advantage of performance enhancements found in the .NET framework and common language runtime.
The. NET framework and ASP.NET provide default authorization and authentication schemes for web application.
ASP.NET configuration setting are stored in XML-based files , which are human readable and writable.
Visual basic .NET enable you to create rich application for Microsoft Windows in less time, incorporate data access from a wider range of database scenarios, create components with minimal code, and build web-based application using your exiting skills. Builds powerful windows-based applications in less time and more robust windows-based applications with less code.
1. Web-based applications
Helps to create web solutions in visual basic.NET using the shared web forms designer and HTML designer
2. Flexible, simplified data access
Offers support to tackle any data access scenario easily with Microsoft ADO.NET and Microsoft Active X Data objects (ADO) data access.
3. Improved coding
It brings a multitude of enhancements to the code editor, including enhanced intellisence , smart listing of code for greater readability , squiggles , and a background compiler for realtime notification of syntax .
4. Direct access to the platform
Features quick leverage of registry , eventlog , performance counters , and file system in user’ application and eliminates the need to use declared statements .
5. Full object-oriented constructs
Helps create reusable, enterprise-class code using full object-oriented constructs .Language features include full implementation inheritance, encapsulation ,and polymorphism .
6. XML Web services
The new XML .Web services project templates builds all underlying Web services enable you to call components running on any platform.
7. Mobile applications
These new features give developers a single, mobile Web interface to support a broad range of Web devices, including WWL 1.1 for WAP-enabled cellular phones , compact HTML (cHTML) for i-mode phones ,and HTML for pocket PC handheld devices , and pagers . Reach out to more than 80 different Internet-enabled mobile devices using the Microsoft mobile Internet Toolkit .
8. Com interoperability
This feature enables seamless bi-directional communication between Visual Basic 6.0 and Visual Basic Net applications.
Visual Studio .NET is the comprehensive tool for rapidly building and inter grating XML. Web services and application dramatically increasing developer productivity, and enabling new business opportunities.
1. Enterprise Architect
Visually specify and communicate application architecture: It uses Microsoft Visio-based Modeling Language (UML) modeling to specify and communicate application architecture and functionality.
Gain unparalleled support for database modeling: Full roundtrip engineering, with logical and physical data models, enables communication from the business analyst to the database designer.
Easily shared best practices: Senior developers and architects can customize enterprise template projects to provide application starting points and guidance for less experienced developers.
Use the industry-leading development environment: Leverage the powerful capabilities in Visual Studio.Net for rapidly building XML web services and applications that span devices and platforms.
Define and communicate development policies: developers can immediately view any policy violations and discrepancies in their code in the task list window.
Enterprise Developers:
Fast and easy test of XML web services and applications: VS.Net can quickly create and run tests within the visual studio.Net environment to fine-tune the performance of XML web services and applications and verify functionality.
Maximize developer productivity: It leverages the powerful capabilities in Visual Studio .Net for rapidly building XML web services and applications that span devices and platforms.
Simplify server-side development: This feature helps to visually build server-side components with the server explorer and Visual component Designer.
Build, leverage, and extend scalable XML web services: it creates components that can be accessed on any platform by using XML web services easily publish and component as XML web services, and reuse existing XML web services running on any platform.
Get support for the complete lifecycle: The Visual Studio integration technologies bring a broad array of partners of visual studio .Net developers and enables third party languages, components and tools to integrate tightly with visual studio .Net through various stages of the development in lifecycle.VS .NET Professional :
XML web services : It helps to create components that can be accessed on any platform by using XML web services . Converts existing functions to XML web services and reuses existing XML web services.
High-performance database application with XML : It uses the built-in Microsoft ADO.NET tools to build database applications with Microsoft SQL Server , Oracle ,or any other XML-based data source .
Supports Rapid Application Devlopment (RAD) for the server developed for thin-client devices : Offers developers a single mobile web interface to support a broad range of web devices –including WML .1.1 for WAP cell phones , compact HTML(cHTML) for i-mode , and HTML, for pocket PC, palm-size PCs pagers .
Shared IDE : It uses a single unified integrated development environment (IDE) for all languages with a single toolbox debugger and task window across Visual Basic ,C++ and C# project .
Windows CE .NET
Window CE .NET is the successor to Windows CE 3.0 Designed from the ground up for the embedded marketplace , Window CE .NET aims to deliver a robust realtime operating system for rapidly building the next generation of smart mobile and small footprint devices. With a complete operating system feature set and end-to-end development environment Windows CE-based devices that requires rich networking hard real time, and a small footprint , as well as rich multimedia and Web browsing capabilities. Windows CE .NET offers.
Scalable wireless technologies : Windows CE.NET include scalable wireless technologies that enable mobile devices to flexibly connect into existing infrastructures . Supported wireless technologies include.
Bluetooth : Windows CE .NET allows a devices to use a Bluetooth-enabled cellular phone as a data modem , and to use a Bluetooth-enabled local area network (LAN) access point to provide network connectivity.
802.1x/Zero Configuration – New features in window CE .NET i.e., 802.11 zero configuration, aim to simplify setup of 802.11 network and to enable seamless roaming from one 802.11 network to another. 801.1x and EAP enhance the security of 802.11 by enabling user/password, certificate, or original equipment manufacturer (OEM) specific authentication to log on to the network.
Object Exchange (OBEX) protocol – Windows CE .Net’s support for OBEX works over Bluetooth and infra red data association (IrDA) protocols . Object Exchange (OBEX) is an efficient, compact binary protocol that enables a wide range of devices to exchange data spontaneously in a simple, efficient manner.
Media Sense – This feature improves the roaming experience for mobile devices users by notifying application of network status.
Real time collaboration and communication (RTC/SIP) – Real time communication (RTC) enables messaging, presence, and audio (voice over IP between any two IP-enabled devices.
Realiable core operating system services for demanding embedded designs : Windows CE .ET offers reliable core operating system services that enable the most demanding real time embedded designs across a breadth of devices . New and enhanced operating system features include.
Small footprint: Continuing the effort to minimize the operating system footprint for embedded devices, Windows CE .NET provides granular Kernel componentization. Windows CE .NET supports a minimum configuration platform as small as 200 KB with minimum Kernel functions only.
Enterprise-scale – Network security enhancements include support for the Kerberos Security Protocol.
Wide selection of CPUs- Windows CE .NET provides a high level of processor flexibility with support for the following four families of microprocessors and emulation technologies like ARM, MIPS, SHx, x 86 etc.
Real time – Real time processing support for the most demanding support for the most demanding deterministic applications with 256 priority levels and nested interrupt support.
Net- enabled for creating rich personalized experiences - Windows CE .NET enables you to build smart Microsoft .NET-enabled devices and create rich, personalized experiences.
XML – XML allows developers to easily describe and deliver rich, structured data from any application in a standard consistent way.
Net compact Framework : The .NET Compact Framework supports all processors supported by windows CE .NET . For more information on how to develop application using the .NET Framework, please see .NET on the MSDN site. Look in the .NET Compact Framework Read me’ for specific information about implementation issues in your embedded design.
Microsoft Direct3D API – Provides support for interactive three-dimensional (3-D) graphics applications by allowing device dependent access to 30d video-display hardware in devices-independent manner.
Windows Media 8 compressor/decompressor (codecs) and controls – Supports the latest Microsoft Windows Media 8 codes and controls ,which allows for the latest high-bandwidth encoded multimedia streams.
Easy-to-use end-to-end tool set: Windows CE .NET provides an integrated end-to-end tool set to help developers reduce both operating system and application development time, allowing them to get devices to market faster. These tools include.
Emulation technology - Windows CE .NET include emulation technology to enable developers to build and test their designs on their Windows 2000 or Windows xp professional workstations without additional hardware investments.
The new platform wizard – The new platform wizard provides a foundation for startingDevice designs for:
Cellophanes / Smart phones
Custom devices
Digital imaging devices
Industrial automation devices
Internet/media appliances
Personal digital assistants (PDA)/Mobile handhelds
Residential gateways
Retail point-of-sale
Set-top boxes
Tiny kernels
Web pads Windows thin clients.
CE .Net also provides support for managed and native code – To write applications for Windows CE .NET, Microsoft offers a rich set of languages for creating managed .NET-enabled or unmanaged (native) applications.
NET Compact Framework
Microsoft Corp. Has recently released the beta of the Microsoft .NET Compact Framework, extending the .NET strategy to smart handheld devices. The .NET Compact Framework is Microsoft’s mobile application platform technology that harnesses the power of XML Web services on mobile devices. As a subset of the .NET Framework, the .NET Compact Framework shares same programming model and application development tools, enabling .NET developers to transfer their existing skills to build mobile applications, which is expected to accelerate adoption of mobile solutions. It provides key features for smart devices such as a programming model unified with the .Net framework on desktop and server, integral XML web services support, enterprise-class data access using ADO.Net and XML, and rich class libraries that enable developers to build powerful applications in minimal time. Runtime features such as managed code and just-in-time compilation help ensure reliable, high performance applications for a better user experience.The .Net compact framework is complemented by other technologies such as Microsoft SQL server 2000, windows CE edition version 2.0 and the Microsoft mobile internet toolkit (MMIT), SQL server CE is the compact, relational database for rapidly developing applications that extend enterprise data management capabilities to new smart devices. The SQL server CE is the only mobile database that integrates with the .Net compact framework, allowing data to be locally and securely stored and extracted to interact with back-end applications or web services. The Microsoft mobile internet toolkit offers a wide reach to project applications to any kind of mobile device with a browser. The development experience for these technologies is unified through Microsoft Visual Studio >net, which provides a consistent set of tools and interfaces for building applications using Microsoft’s mobile technologies.

Happy Programming

Mar 14, 2008

Web Farming with the Network Load Balancing Service in Windows Server 2003

When a single Web Server machine isn’t enough to handle the traffic on your Web site it’s time to look into building a Web Farm that uses multiple machines on the network acting as a single server. In this article Rick looks at the Windows Load Balancing Service and the new interface it sports in Windows Server 2003, which makes creating a Web Farm quick and easy and – gasp –even an affordable solution.
With the release of Windows Server 2003 Network Load Balancing has become a much more visible tool as a part of the operating system, providing a very usable and relatively easy to configure interface that makes it easy to build a Web Farm. The Network Load Balancing Service has been around in one incarnation or another since Windows NT SP4, but Windows Server 2003 is the first operating system that brings this service into the forefront as a main component of the OS. A new Network Load Balancing Manager application is now directly available from the Adminstrative Tasks menu and it’s powerful enough to allow to configure the entire cluster from a single console. The service is now available for all products in the Windows Server family including the lower end Web Edition which means that you now have a much more affordable solution to create Web Farms at your disposal. Just add servers please.

In this article I’ll review the basics of a Load Balancing service and then show you how to set up configure a basic installation using two machines.
Web Farms for city folk – do you need it?
A Web Farm is a not so fancy term for a collection of servers that act as a single Web server. The process behind the scenes maps a ‘virtual’ IP address to multiple machines. Software such as the Network Load Balancing Service or hardware like a specialized router or Load Balancer then deals with dishing up requests to the appropriate machine in the server pool.
Web Farms are an obvious choice if you’ve hit the limits of your single machine hardware. But before jumping on the Web Farm band wagon (or is that a tractor?) you should look closely at your hardware and application and be sure that you can’t make it all run on a single machine first. Although the process of creating a Web Farm isn’t difficult, administration of two or more servers and keeping them properly synched is actually a lot more work than administering a single server.

Upgrading your hardware is certainly one option available to you. Today’s hardware is incredibly capable and should be sufficient to handle all but the most demanding Web applications on a single box. Multiprocessor machines with up to 16 processors on Windows make a pretty powerful platform to run Web applications with, even if those high end machines are rather pricey. While the Yahoo’s and Amazon’s won’t run on a single box (or on Windows for that matter), a vast majority of applications are likely to be able to comfortably serve millions of transactional hits a day from a single machine even with a single processor.

But Load Balancing can also provide benefits in the overload scenario. For one, it’s generally cheaper to throw mid-level machines at a load problem rather than buying one top of the line high end machine. Even with server licenses involved multiple low end machines might provide a more cost efficient solution.

Load Balancing also provides something else that has nothing to do with scalability: The ability to have failover support if something goes wrong on one of the servers in the pool. Because a Web Farm are made up of essentially identically configured servers, a failure on a single server will not bring down the entire Web site. Other servers in the pool can continue to process requests and pick up the slack. For many companies this feature of load balancing is often important for peace of mind both in the knowledge that a single point of failure on the Web Server is avoided as well as providing an in place mechanism to grow the application should the need arise at a later point.


Happy Programming

ListView and DataPager in ASP.NET 3.5

New controls in asp.net 3.5
I spent a couple of hours today looking over the ListView and DataPager controls in ASP.NET 3.5. Both controls sound interesting and both provide welcome new features to the ASP.NET control arsenal. Although I'm a little wary of having yet another list control (as if we haven't enough of those already between DataGrid, DataList, Repeater, GridView and now the ListView) the ListView control kind of combines functionality of all of these controls into one. Maybe the most important feature of this control is that like the Repeater control it provides much more control over the rendering process at the cost of more markup code in the page.
The ListView is a sort of hybrid between a DataGrid and Repeater that combines the free form templating of the Repeater with the editing features of the data grid. It looks interesting because it basically allows you much more control over the layout than a DataGrid does while still giving you many of the more advanced features of the data grid. The ListView doesn't support paging natively, so the DataPager serves as an external control to provide paging features. The advantage of a separate control is that it gives you much more control about what the pager looks like and where it can be placed on the page - anywhere basically. The Pager is essentially an extender control that extends the ListView with paging capabilities.
The ListView Control
Using the ListView for basic data display is very similar to using a Repeater. You have the ListView control and a set of templates that you can apply which include:
EmptyDataTemplate (?)
That's a lot of templates . There are a few new ones here like GroupTemplate and InsertItemTemplate. I haven't figured out how GroupTemplate works, but InsertItemTemplate certainly is a nice addition so you can handle both editing and adding in the same space (previously with a DataGrid you had to insertion externally or insert data manually into a DataTable to display the empty row).


Happy Programming

Mar 13, 2008

Lambda expressions in C# 3.0

1. Introduction
It is no secret for anybody that C#, which was initially conceived as a language targeted to subsume such different programming paradigms as procedural (imperative), object-oriented (in line with the standards set by C++ and later Java) and component-based (with two clear referents, Delphi and Visual Basic), has evolved since then in a way that attempts to take into account and integrate into the language the best ideas arisen under another points of view of programming, like dynamic languages (Perl, Python, Ruby), data manipulation languages (SQL, XML) or functional programming (LISP, ML).
Lambda expressions, one of the most important new features to be included in the next 3.0 version of C# [3] and one that offers support needed by the LINQ Project [4], are precisely a feature coming from the world of functional programming. In LISP and its dialects, like Scheme, the lambda construction is a mechanism that allows the programmer to define new functions. For instance, the expression:
(define square (lambda (x) (* x x)))

defines a variable named square, whose value is a function that produces the square of its argument. One of the most prominent characteristics of functional languages, to which the architects of .NET Framework give great importance [2], is that lambda functions can be treated not only as pieces of code that can be invoked, but also as “common and earthly” values that can be manipulated by other code blocks. Using a term I heard the first time more than 20 years ago from my tutor of then, Dr. Luciano Garcia, lambda functions facilitate metaprogramming – the writing of programs capable of manipulating other programs.
This article describes the implementation of lambda expressions in C# 3.0, concentrating mainly on its exploitation as code blocks; issues related to the representation as data and further programmatic manipulation of lambda expressions will be only introduced for the sake of completeness, and a more in-depth discussion of them will be left for a next installment of this column.

2. Lambda expressions as code entities
The natural way of implementing a definition like that of the square lambda function in C# would be through a delegate type and a delegate instance [5]:
delegate T Mapping(T x);
Mapping square = delegate(int x) { return x * x; };

The first line above defines a generic delegate type named Mapping. From this type model, we will be able to create delegate instances for functions that produce a value of type T from another value of the same type T (that is, functions that map – remember the term, which we will be using more frequently in the near future – a value of type T into another value of the same type).
The second line of code defines an instance of the previous delegate type that “points” to a function that returns the square of an integer number. In this sentence we make use of another feature added to C# in version 2.0, anonymous methods, that allow the in-line specification of the block of code that defines the functionality we wish to associate to the delegate instance. In the original version of C# we would have had to define the function explicitly (besides, the delegate couldn’t have been generic):
static int Square(int x)
return x * x;
Mapping square2 = Square;

Although anonymous methods offer a more compact and direct notation, their syntax is still quite verbose and imperative by nature. In particular, when defining an anonymous method it is necessary:
· To explicitly use the keyword delegate.
· To explicitly specify the types of the parameters, without any possibility of compiler inference from the usage context.
· In the relatively frequent case when the body of the function is a simple return sentence followed by an expression that calculates the result (as in the case of our square), the excess in syntax is even more evident.
Lambda expressions can be seen as an extension of anonymous methods that offers a more concise and functional syntax. The syntax of a lambda expression consists of a list of variables-parameters, followed by the implication (function application) sign =>, then followed by the expression or block that implements the desired functionality. For instance, our definition of square could be rewritten using a lambda expression like this:
Mapping square3 = x => x * x;

Shorter - impossible, right? This sentence expresses in quite a succinct and natural way that square3 references a function that, given some x, produces x multiplied by itself. In this case, the compiler automatically infers from the context that the type of the parameter and the result should be int. We could have indicated that explicitly:
Mapping square4 = (int x) => x * x;

If the type of the parameter is specified, or if the expression has more than one parameter (be their type indicated explicitly or not) parenthesis are mandatory. On the other hand, in the right side of the implication we can place a simple expression, as previously, or a block of sentences of any complexity (as long as it produces a result of the correct type):
Mapping square5 = (int x) => { return x * x; };

Until now we have been using our own generic delegate type Mapping, but in practice most of the times we will use the different “overloads” of the predefined generic delegate type Func:
// in System.Query.dll
// namespace System.Query
public delegate T Func();
public delegate T Func(A0 a0);
public delegate T Func(A0 a0, A1 a1);
public delegate T Func(A0 a0, A1 a1, A2 a2);
public delegate T Func(A0 a0, A1 a1, A2 a2, A3 a3);

The Func family of types represents delegate instances that reference functions (with 0, 1, 2 or 3 arguments, respectively) that return T. Using Func, we could define a new version of square like this:
Func square6 = x => x * x;

Below we show some more examples of definition and usage of lambda expressions:
// more examples
static Func hypotenuse =
(x, y) => Math.Sqrt(x * x + y * y);

static Func divisibleBy =
(int a, int b) => a % b == 0;

static Func isPrime =
x => {
for (int i = 2; i <= x / 2; i++) if (divisibleBy(x, i)) return false; return true; }; static void Main(string[] args) { int n = 19; if (isPrime(n)) Console.WriteLine(n + " is prime"); Console.ReadLine(); } 3. Lambda expressions as data entities
Considering what we’ve seen until now, anybody could think that lambda expressions are mere “syntactic sugar” added to the language in order to “sweeten” the consumption of delegates and anonymous methods. But C# 3.0 lambda expressions offer an additional possibility not available to anonymous methods, and one that plays a key role in the implementation of the LINQ (Language Integrated Query) technology, that will also be included in the next version of C# and VB and that constitutes, in the humble opinion of this author, one of the most significant advances in programming languages and systems in recent times.
This additional possibility is that of being compiled as expression trees, data objects that efficiently represent in memory the algorithm of evaluation of lambda expressions. These in-memory trees can later be easily manipulated by software (metaprogramming!), stored, transmitted, etc. Although we’ll defer a more detailed analysis of expression trees until our next installment, let’s see a small example:
static Expression func double, hypotenuseExpr =
(x, y) => Math.Sqrt(x * x + y * y);

static void Main(string[] args)
// prints '(x, y) => Sqrt(Add(Multiply(x, x), Multiply(y, y)))'

hypotenuse = hypotenuseExpr.Compile(); // here ILAsm is generated!
Console.WriteLine("Hypotenuse(3, 4) = " + hypotenuse(3, 4));
// prints 'Hypotenuse(3, 4) = 5'


In the code fragment above, the lambda expression that calculates the hypotenuse of a right triangle is assigned not to a delegate, but to a variable of the predefined generic type Expression:
// in System.Query.dll
// namespace System.Expressions
public class Expression : LambdaExpression { … }

In this case, the compiler does not generate the ILAsm code corresponding to the expression; an object tree that represents the sequence of actions needed for expression’s evaluation is produced instead. You can get an idea of the internal structure of this tree by watching the output produced by the call to its ToString() method.
Note also that the Expression class offers a Compile() method that makes it possible to dynamically generate the executable code corresponding to the expression when needed. That is, this method serves as a “bridge” between both worlds, translating data into code when it becomes necessary to evaluate the expression.


Happy Programming

Lambda Expressions Feature in C# 3.0

C# 2.0 (released in November 2005) introduced a new feature, anonymous methods, that allows you to declare your method code inline instead of with a delegate function. Lambda expressions, a new feature in C# 3.0, have a more concise syntax to achieve the same goal. Take a closer look at anonymous methods before discussing lambda expressions.
Suppose you want to create a button that updates a ListBox on your form when you click it. In C# 1.0 and 1.1, you would do it as follows:public MyForm()
listBox = new ListBox(...);
textBox = new TextBox(...);
addButton = new Button(...);
addButton.Click += new EventHandler(AddClick);
void AddClick(object sender, EventArgs e)
With C# 2.0, you could have it as under:public MyForm()
listBox = new ListBox(...);
textBox = new TextBox(...);
addButton = new Button(...);
addButton.Click += delegate
As you can see, you don't have to explicitly declare a new method to link it with an event. You can use anonymous methods to achieve the same thing in C# 2.0. C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=>" token, followed by an expression or a statement block.

Parameters to Lambda Expressions
The parameters of a lambda expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each expression is explicitly specified. In an implicitly typed parameter list, the types are inferred from the context in which the lambda expression occurs:(int x) => x + 1 // explicitly typed parameter
(y,z) => return y * z; // implicitly typed parameter
Lambda Expressions Demonstration
The following code snippet from
the downloadable source code uses two techniques to print out strings in a list whose length is even. The first technique, implemented in the function AnonMethod, is through anonymous methods. The second technique, implemented in the function LambdaExample, is through a lambda expression:// Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;
namespace LambdaExample
public delegate bool KeyValueFilter(K key, V value);
static class Program
static void Main(string[] args)
List list = new List();
Console.WriteLine("Through Anonymous method");
Console.WriteLine("Through Lambda expression");
Dictionary varClothes= new Dictionary();
varClothes.Add("Jeans", 20);
varClothes.Add("Shirts", 15);
varClothes.Add("Pajamas", 9);
varClothes.Add("Shoes", 9);
var ClothesListShortage = varClothes.FilterBy((string name,
int count) => name == "Shoes" && count <> 0)
Console.WriteLine("We are short of shoes");
static void AnonMethod(List list)
List evenNumbers =
list.FindAll(delegate(string i)
{ return (i.Length % 2) == 0; });
foreach (string evenNumber in evenNumbers)
static void LambdaExample(List list)
var evenNumbers = list.FindAll(i =>
(i.Length % 2) == 0); // example of single parameter
foreach(string i in evenNumbers)
public static class Extensions
public static Dictionary FilterBy
(this Dictionary items, KeyValueFilter filter)
var result = new Dictionary();
foreach(KeyValuePair element in items)
if (filter(element.Key, element.Value))
result.Add(element.Key, element.Value);
return result;

full article on Lambda Expressions Feature in C# 3.0 read: http://www.developer.com/net/csharp/article.php/3598381

Happy Programming