Wednesday, December 29, 2010

Entity Framework Best Practices

Dear Friends,

This post is regarding some of points to be considered while writing the LINQ Queries which may affect the performance alot.

For Beginners in Entity Framework, Please review: Entity Framework Basics

Kindly, find all the below points which can increase the performance:

Compiled queries
When you have an application that executes structurally similar queries many times in the Entity Framework, you can frequently increase performance by compiling the query one time and executing it several times with different parameters. For example, an application might have to retrieve all the customers in a particular city; the city is specified at runtime by the user in a form. LINQ to Entities supports using compiled queries for this purpose.

use Compiled queries to amortize the overhead inherent in SQL generation.
The CompiledQuery class provides compilation and caching of queries for reuse.
For Example:
// Compiled Query
public static Func> _statesByCountry =
CompiledQuery.Compile((Entities db, int CountryID) => db.States.Where(s => s.CountryID == CountryID));

//Using Compiled Query
public virtual IEnumerable GetStatesByCountryID(int countryID)
return _ statesByCountry (Context, countryID).ToList();

Select N+1
Select N + 1 is a data access anti-pattern where the database is accessed in a suboptimal way. Suppose that want to show all Sites Information from all schools. The native implementation would be something like:
var productQuery = from product in _ctx. Product
select Product;

foreach (Product product in productQuery)
         //lazy loading of comments list causes:
        // SELECT * FROM Sites where SchoolId = @SchoolId
       foreach (ProdutDetail productDetail in product.ProductDetails)
       //print comment...

In this example, we can see that we are loading a list of Product (the first select) and then traversing the object graph. However, we access the collection in a lazy fashion, causing Entity Framework to go to the database and bring the results back one row at a time. This is incredibly inefficient.
The solution for this example is simple. Force an eager load of the collection using the Include method to specify what pieces of the object model we want to include in the initial query.
// SELECT * FROM Product JOIN ProductDetail ..
var productQuery = (from product in _ctx.Product.Include("ProductDetail")
                               select product);

foreach (Product product in productQuery)
             // no lazy loading of comments list causes
            foreach (ProdutDetail productDetail in product.ProductDetails)
             //print comment...
In this case, we will get a join and only a single query to the database.
Note: this is the classical appearance of the problem. It can also surface in other scenarios, such as calling the database in a loop, or more complex object graph traversals. In those cases, it is generally much harder to see what is causing the issue.

Avoid too many joins
Queries with too many joins might be a performance problem.
Each join requires the database to perform additional work, and the complexity and cost of the query grows rapidly with each additional join. While relational database are optimized for handling joins, it is often more efficient to perform several separate queries instead of a single query with several joins in it.
For OLTP systems, you should consider simplifying your queries or simplifying the data model. While we do not recommend avoiding joins completely, we strongly discourage queries with large numbers of joins. Another issue to pay attention to is possible Cartesian products in queries contains joins, it is very easy to create such a thing and not notice it during development.

Avoid Too Many Database Calls Per Session
One of the most expensive operations that we can do in our applications is to make a remote call. Going beyond our own process is an extremely expensive operation. Going beyond the local machine is more expensive still.
Calling the database, whether to query or to write, is a remote call, and we want to reduce the number of remote calls as much as possible.
There are several reasons why this can be:

  1. A large number of queries as a result of a Select N + 1
  2. Calling the database in a loop
  3. Updating (or inserting / deleting) a large number of entities
  4. A large number of (different) queries that we execute to perform our task
For the first reason, you can see the suggestions for Select N + 1.
Calling the database in a loop is generally a bug, and should be avoided. Usually you can restructure the code in such a way that you are not required to call the database in that way. All of the above points must taken into consideration while writing the Complex LINQ Queries. 


Paras Sanghani

Wednesday, November 17, 2010

Passing Data in an ASP.NET MVC Application

Hello Friends,

We will look into how to pass Data from Controller to View in Asp.Net MVC.

Passing Data in an ASP.NET MVC Application

The ASP.NET MVC framework provides page-level containers that can pass data between controllers and views. This topic explains how to pass both weakly typed and strongly typed data in an MVC application. It also explains how to pass temporary state data between action methods.
Passing Data between a Controller and a View
• To render a view, you call the View method of the controller.
• To pass data to the view, you use the ViewData property of the ViewPage class.
If you can pass data from the controller object's ViewData property is passed to the view that has the same name as the action method. Like,
public class HomeController : Controller
{ Add Video
public ActionResult Index()
ViewData["Message"] = "Welcome to ASP.NET MVC!";

return View();
In the view, you can access the ViewData property to obtain data that was passed to the view. The ViewData property is a dictionary that supports an indexer that accepts dictionary keys.

Kindly, find some important links below:

Also, Asp.Net MVC support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

Also, Asp.Net MVC Supports Web Farm Session Management....
1. By default, the TempDataProvider use Session. You can store the session on database and/or use TEmpDataCookieProvider- based on cookies.
2. MVC does NOT support storing session in URL


Paras Sanghani

Tuesday, November 16, 2010

ADO .NET Entity Framework

Hello Friends,

For Entity Framework Beginners, please review: Entity Framework Basics

We will have brief introduction on the Entity Framework in .Net Framework 4.0.
Let start with
Entity Framework Over View:
The Entity Framework is the new concept introduced by Microsoft in .Net Framework which allows developers to create the DataAccess applications by programming against a conceptual application model which is logical model instead of programming directly against a relational storage schema or Database. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Basically ADO .NET Entity Framework divides the database model into three sub-models viz:
1. Conceptual Schema Definition Language(CSDL)
2. Store Schema Definition Language(SSDL)
3. Mapping Specification Language(MSL)
Before discussing further about the three sub models lets discuss why Entity Framework is a better option than the traditional approach.

Entity Framework Vs Traditional ADO .NET:One can write code against the Entity Framework and the system will automatically produce objects as well as track changes on those objects and simplify the process of updating the database. The EF can therefore replace a large chunk of code a developer would otherwise have to write and maintain. Further, because the mapping between the objects and the database is specified declaratively instead of in code, if there is a need to change the database schema, a developer can minimize the impact on the code he has to modify in the applications--so the system provides a level of abstraction which helps isolate the application from the database. Finally, the queries and other operations written into the code are specified in a syntax that is not specific to any particular database vendor--in ADO.NET prior to the EF, ADO.NET provided a common syntax for creating connections, executing queries and processing results, but there was no common language for the queries themselves; just passed a string from the program down to the provider without manipulating that string at all, and if there was a need to move an app from Oracle to SQL Server, one would have to change a number of queries. So the developers must become SQL experts to build advanced queries. With the EF, the queries are written in LINQ or Entity SQL and then translated at runtime by the providers to the particular back-end query syntax for that database.
Together with LINQ to SQL (L2S), LINQ to Entities (L2E) and EF are currently the best data access API that Microsoft offers. They are way better than 'traditional' ADO.NET for most scenarios.

Now let’s discuss the three sub-models:
CSDL is the Entity Framework's implementation of the Entity Data Model. It is an XML based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application.

CSDL Specification:Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or ADO.NET Data Services. The metadata that is described with CSDL is used by the Entity Framework to map entities and relationships that are defined in a conceptual model to a data source. CSDL is the Entity Framework's implementation of the Entity Data Model.
In an Entity Framework application, conceptual model metadata is loaded from a .csdl file (written in CSDL) into an instance of the System.Data.Metadata.Edm.EdmItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses conceptual model metadata to translate queries against the conceptual model to data source-specific commands. In the .edmx file, under the following tag one can view the CSDL contents:

SSDL :It is a XML based language that describes the storage model of an Entity Framework application. The Entity Framework uses storage model metadata to translate queries against the conceptual model to store-specific commands. For more information on SSDL visit the link:
SSDL Specification :Store schema definition language (SSDL) is an XML-based language that describes the storage model of an Entity Framework application.
In an Entity Framework application, storage model metadata is loaded from a .ssdl file (written in SSDL) into an instance of the System.Data.Metadata.Edm.StoreItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses storage model metadata to translate queries against the conceptual model to store-specific commands.

MSL :It is an XML-based language that describes the mapping between the conceptual model and storage model of an Entity Framework application.
MSL Specification :Mapping specification language (MSL) is an XML-based language that describes the mapping between the conceptual model and storage model of an Entity Framework application.
In an Entity Framework application, mapping metadata is loaded from an .msl file (written in MSL) at build time. The Entity Framework uses mapping metadata at runtime to translate queries against the conceptual model to store-specific commands.

Paras Sanghani

Wednesday, August 11, 2010

Importance and Benefits of Certifications......

Hello Friends,

We are all in the IT Industry. And we all very well know that technology is upgrading and new technology are emerging, Certification helps you to learn the new technology and outline next-generation skills. Moreover, it gives Confidence, knowledge to the developer. Label of Microsoft Certification which is valid throughout the world. Being certified means one can properly function on a certain job. This means, companies will easily hire a person with certification especially when certifications come from a reliable learning institution.

You might want to look for the Microsoft Certification courses that can open a lot of job opportunities for you. Learning new skills and enhancing your current skill-sets can take you way higher in your career. There are plenty of Microsoft training programs offered by many centers in India and in other countries. As a matter of fact there are many IT training companies that offer Microsoft certified training programs for the corporate employees.

There are many different types of courses offered by Microsoft. These courses mainly include:
Microsoft Certified Systems Engineer

Microsoft Certified Application Developer

Microsoft Certified Database Administrator

Microsoft Certified System Administrator

Microsoft Certified Professional Developer

Microsoft Certified Professional Developer - Enterprise Application

There are many other Microsoft Certification Courses available with various recognized institutions. It is important to identify the course which will enhance your skills and prove to be advantageous for your career.

Kindly, find the below links for your reference:

Benefits of Certification
Certification Over View

In Short, If you are an expert, a certification is proof. If you are not yet an expert, the path you must take to become certified will provide you with the tools to become one.

Paras Sanghani

Regular Expression in C#.NET......

Hello Friends,

In our day to day life, developers need to frequently process data and text. The clients and endusers input the data and we need to validate that input data according to our business rules.

A regular expression is a set of characters that can be compared to a string to determine whether the string meets specified format requirements. You can also use regular expressions to extract portions of the text or to replace text. To make decisions based on text, you can create regular expressions that match strings consisting entirely of integers, strings that contain only lowercase letters, or strings that match hexadecimal input. You can also extract key portions of a block of text, which you could use to extract the state from a user's address or image links from an HTML page. Finally, you can update text using regular expressions to change the format of text or remove invalid characters.

How to use Regular Expressions for Pattern Matching?
To enable yourself to test regular expressions, create a console application named TestRegExp that accepts two strings as input and determines whether the first string (a regular expression) matches the second string. The following console application, which uses the System.Text.RegularExpressions namespace, performs this check using the static System.Text.RegularExpressions.Regex.IsMatch method and displays the results to the console:

// C#
using System.Text.RegularExpressions;

namespace TestRegExp
class Class1
static void Main(string[] args)
if (Regex.IsMatch(args[1], args[0]))
Console.WriteLine("Input matches regular expression.");
Console.WriteLine("Input DOES NOT match regular expression.");

Next, run the application by determining whether the regular expression "^\d{5}$" matches the string "12345" or "1234". The regular expression won't make sense now, but it will by the end of the lesson. Your output should resemble the following:

C:\>TestRegExp ^\d{5}$ 1234
Input DOES NOT match regular expression.

C:\>TestRegExp ^\d{5}$ 12345
Input matches regular expression.

As this code demonstrates, the Regex.IsMatch method compares a regular expression to a string and returns true if the string matches the regular expression. In this example, "^\d{5}$" means that the string must be exactly five numeric digits. As shown in Figure 3-1, the carat ("^") represents the start of the string, "\d" means numeric digits, "{5}" indicates five sequential numeric digits, and "$" represents the end of the string.

If you remove the first character from the regular expression, you drastically change the meaning of the pattern. The regular expression "\d{5}$" will still match valid five-digit numbers, such as "12345". However, it will also match the input string "abcd12345" or "drop table customers - 12345". In fact, the modified regular expression will match any input string that ends in any five-digit number.

Also, Kindly find few of randomly used Randomly used Regular Expressions below:
1. Regular Expression for allowing only Integer values:

Allows Negative and Positive Values:
Regex.IsMatch(base.Text, @"^-[0-9]+$|^[0-9]+$");

Allow Only Positive Values:
Regex.IsMatch(base.Text, @"^\d+$");

2. Regular Expression for Float Values:

Allows Negative and Positive Values:
Regex.IsMatch(base.Text, @"^[-]?\d+(?:\.\d{0,2})?$");

Allow Only Positive Values:
Regex.IsMatch(base.Text, @"^\d+(?:\.\d{0,2})?$");

3. Regular Expression for valid Email:

Regex.IsMatch(base.Text, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");

4. Regular Expression for valid Internet Address:

Regex.IsMatch(base.Text, @"([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");

5. Regular Expression for valid AlphaNumeric:

Regex.IsMatch(base.Text, @"[a-zA-Z0-9]");

Paras Sanghani

Tuesday, August 10, 2010

Encrypting and Decrypting Data in C#.NET.....

Hello Friends,

The security of the Data is most important in Softwares and our job is to protect it from the attackers. You can use cryptography to protect the privacy and integrity of the data that your application stores or transfers. Fortunately, .NET Framework provides classes for several different types of cryptography, including symmetric and asymmetric encryption, hashing, and digital signatures.

Encrypting and Decrypting Data with Symmetric Keys
Many people are introduced to encryption at an early age. Children protect even the most mundane communications from imaginary spies with a secret decoder ring—a toy with two rings that translates encrypted characters to unencrypted characters. The rings on a decoder ring rotate, and a message can be decrypted only when the two rings are lined up correctly. To exchange an encrypted message, the children must first agree on how the rings will line up. After they have exchanged this secret piece of information, they can freely pass encrypted messages without worrying that someone will be able to decrypt them. Even if an imaginary spy had a decoder ring, the spy would need to know how to position the rings to decrypt the message.

Because both the sender and the recipient of the message must know the same secret to encrypt and decrypt a message, secret decoder rings are an example of symmetric key encryption. Symmetric key encryption is a game for children, but it is also the foundation for most encrypted communications today. As children know, encryption is a fun topic. You should enjoy building it into your application, and you'll greatly reduce the chance of private data being compromised.

What Is Symmetric Key Encryption?
Symmetric key encryption, also known as secret-key encryption, is a cryptography technique that uses a single secret key to both encrypt and decrypt data. Symmetric encryption algorithms (also called ciphers) process plain text with the secret encryption key to create encrypted data called cipher text. The cipher text cannot easily be decrypted into the plain text without possession of the secret key.

Symmetric Algorithm Classes in the .NET Framework
Most of the .NET Framework's cryptography functionality is built into the System.Security.Cryptography namespace, including the four implementations of symmetric encryption algorithms. Table 12-2 shows symmetric encryption algorithm classes.

Key Length: 128 through 256 bits, in 32-bit increments
Description: The .NET Framework implementation of the Rijndael symmetric encryption algorithm. As a government encryption standard, this algorithm is also known as Advanced Encryption Standard, or AES.RijndaelManaged is the only .NET Framework symmetric encryption class that is fully managed. All other encryption classes call unmanaged code. Because of this, RijndaelManaged is the preferred choice when your application will be running in a partially trusted environment.

Key Length: Variable
Description: An encryption standard designed to replace DES that uses variable key sizes.

Key Length: 56 bits
Description: The Data Encryption Standard (DES) is a symmetric encryption algorithm that uses relatively short key lengths that are vulnerable to cracking attacks. As a result, it should be avoided. However, it remains commonly used because it is compatible with a wide range of legacy platforms.

Key Length: 156 bits, of which only 112 bits are effectively used for encryption
Description: The .NET Framework implementation of the Triple DES (3DES) symmetric encryption algorithm, it essentially applies the DES algorithm three times.

How to Encrypt and Decrypt Messages Using Symmetric KeysAfter both the encryptor and decryptor have the same key, they can begin exchanging encrypted messages. The .NET Framework makes this process easy. In fact, using encryption is similar to reading and writing to standard files and streams, and it requires only a few additional lines of code. To encrypt or decrypt messages in your application, perform the following tasks:

1. Create a Stream object to interface with the memory or file that you will be reading from or writing to.

2. Create a SymmetricAlgorithm object.

3. Specify the algorithm's key, the IV, or both.

4. Call SymmetricAlgorithm.CreateEncryptor() or SymmetricAlgorithm.CreateDecryptor() to create a ICryptoTransform object.

5. Create a CryptoStream object using the Stream object and the ICryptoTransform object.

6. Read from or write to the CryptoStream object just like any other Stream object.

The following console application demonstrates these steps by reading an unencrypted file (the C:\Boot.ini file), encrypting it with the Rijndael algorithm, and saving the encrypted results as a new file. The application requires the System.IO and System.Security.Cryptography namespaces.
// C#
string inFileName = @"C:\Boot.ini";
string outFileName = @"C:\Boot.ini.enc";

// Step 1: Create the Stream objects
FileStream inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
FileStream outFile = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);

// Step 2: Create the SymmetricAlgorithm object
SymmetricAlgorithm myAlg = new RijndaelManaged();

// Step 3: Specify a key (optional)

// Read the unencrypted file into fileData
byte[] fileData = new byte[inFile.Length];
inFile.Read(fileData, 0, (int)inFile.Length);

// Step 4: Create the ICryptoTransform object
ICryptoTransform encryptor = myAlg.CreateEncryptor();

// Step 5: Create the CryptoStream object
CryptoStream encryptStream = new CryptoStream(outFile, encryptor, CryptoStreamMode.Write);

// Step 6: Write the contents to the CryptoStream
encryptStream.Write(fileData, 0, fileData.Length);

// Close the file handles

Because the key is randomly generated, running the application repeatedly generates different results each time. Because the key is not stored, the file can never be decrypted. The key is simply an array of bytes and can be stored by using the BinaryWriter object or by transferring the key across a network.

The code for decrypting a file is almost identical to the code for encrypting a file, except that it must read the encryption key that was used to encrypt the data rather than randomly generate it, and it must call decryption methods instead of encryption methods. To reverse the process to decrypt a file, simply make the following changes to an application:

Change the code for step 3 to read the key and IV that was used to encrypt the data.

Change the code for step 4 to use the CreateDecryptor method instead of CreateEncryptor.

Change the code for step 5 to use the CryptoStreamMode.Read enumeration instead of CryptoStreamMode.Write.

Change the code for step 6 to read from the CryptoStream object.

How to Encrypt and Decrypt Messages Using Asymmetric Encryption
To encrypt and decrypt messages using asymmetric encryption, call the RSACryptoServiceProvider.Encrypt and RSACryptoServiceProvider.Decrypt methods. Both take two parameters:

byte[] rgb An array of bytes containing the message to be encrypted or decrypted.

bool fOAEP A Boolean value. When set to true, encryption and encryption will use OAEP data padding, which is supported only on Windows XP and later operating systems. When set to false, PKCS#1 v1.5 data padding will be used. Both the encryption and decryption methods must use the same data padding.

The most challenging aspect of encryption is converting data into the byte array format. To convert strings to byte arrays, use the System.Text.Encoding.Unicode.GetBytes and System.Text.Encoding.Unicode.GetString methods. For example, the following console application encrypts a string using PKCS#1 v1.5 data padding, and then immediately decrypts and displays the string:

// C#
string messageString = "Hello, World!";
RSACryptoServiceProvider myRsa = new RSACryptoServiceProvider();

byte[] messageBytes = Encoding.Unicode.GetBytes(messageString);
byte[] encryptedMessage = myRsa.Encrypt(messageBytes, false);

byte[] decryptedBytes = myRsa.Decrypt(encryptedMessage, false);

Whichever encoding method you use to convert the data into a byte array, be sure you use a matching decoding method after decrypting the data.

Paras Sanghani

Selecting application types in WPF?

Hello Friends,
As we know WPF - Windows Presentation Foundation is the latest technology introduced by Microsoft in .Net Framework 3.5 and later version.
Let first have a brief look at what is WPF?
Windows Presentation Foundation is the Successor of Windows Forms for desktop application development. Wpf Application differs from traditional Windows Forms Application in several ways. The most notable is that code for the user interface is separated from the code for application functionality. Although the code for project can be done in ,, etc but the user interface of a WPF project is typically defined using a relatively new declarative syntax called Extensible Application Mark Up Language(XAML).
Wpf development support three kinds of application:

  1. Windows Application
  2. Navigation Application
  3. XAML Browser Application(XBAPs)

Each of the above application has its own benefits and drawbacks and let us check when and where to select which type of application.

1. Windows Application

Windows Application are most similar to Windows Forms applications. Windows applications are Microsoft Windows-driven and provide user experience that is familiar to Windows users and developers alike. Multiple windows can be open at any given time, and there is no built-in sense of navigation or history. We can have the full access of user machine such as Registry, File System. It uses the Windows as their Top-level user interface (UI) element. Window derives from Content Control.

When to use Windows Application?

  • For a user experience that most closely resembles a traditional Windows Form application
  • Menu driven, multiwindow application that combines the rich functionality of a desktop with the rich UI that WPF provides.

2. Navigation Application

This application provides a page-based user experience, similar to the experience of using Web Site. Typically, only a single page can be open at any given time, and the journal functionality keeps records of pages visited and allows back-and-forth navigation. Unlike a Website, however, a navigation application is a compiled application that runs on your desktop computer and, like a Windows application , has full access to the resource of your computer.It uses the Page as their Top-level user interface (UI) element providing similar look and feel as website.

When to user Navigation Application?

  • For user experience that more closely resembles a Web site, you should choose a page-based application. Navigation applications and XBAP applications provide built in navigation functionality that allows you to structure the application paralleling a task, such as in an Internet shopping application or wizard.
  • If application require to access System Resources that fall outside the Internet Security Zone, then XBAP is not a good choice, a better choice would be a Windows application or Navigation application

3. XBAPs Application?

XBAPs application are similar to Navigation Applications, but they are designed to run in Windows Internet Explorer. These applications can be deployed to a server or to a Website and are downloaded when instantiated. Applications of this type do not have full access to a computer's resources. XBAPs run under a partial-trust environment, and resources such as the file system and registry are inaccessible by XBAPS. It uses the Pages as their Top-level user interface (UI) element. XBAP application is not installed on the User machine and thus they have default rights of Internet zones. Howeover, it is technically possible to run XBAP under full trust but it is not recommended because doing so gives full access of your system resources to an application from an untrusted location, thus creating security risks. XBAP are allowed to access isolated storage.

When to use XBAP Application?

  • When you want to deploy the application to a WebServer and have users start if from the hyperlink, thus making it easily accesible to a large-scale audience.
  • If your application does not require access to system resources, XBAP might be good choice.


Paras Sanghani


Paras Sanghani

Sunday, August 8, 2010

What is Globalization?

Hello Friends,
We often came across the problems related to the geographical scope of applications. The costs of not knowing who will be using the applications are increasing as well. Dealing with issues as an afterthought is always more costly than designing for them, and building applications for different locales is no different in this respect. The .NET Framework provides the System.Globalization namespace to help developers address such concerns.

CultureInfo Class
One of the core tools for manipulating and retrieving information about the cultural context an application is running in is the CultureInfo class. This class provides culture-specific information such as the format of numbers and dates, and casing conventions. More broadly, it represents the name of a culture, the culture's writing system, the culture's calendar, the culture's language and sublanguages if applicable, and the country and region of the culture, and it provides methods to manipulate all these aspects. The basic uses of the CultureInfo class are shown in the following list:

Control how string comparisons are performed.

Control how number comparisons and formats are performed.

Control how date comparisons and formats are performed.

Control how resources are retrieved and used.

As a rule, a culture will be grouped into one of three categories: an invariant culture, a neutral culture, or a specific culture. The distinctions between these categories are detailed in the following list:

Invariant Culture This culture category is culture-insensitive. The category is to be used as essentially a default culture when consistency is desired. One situation where this category might be desirable to use is creating a trial application with a hard-coded expiration date. Using an invariant will allow you to check for a specific date, regardless of the culture's format, which will greatly simplify the task of comparing these dates. The invariant culture is not based on the English language per se, but it is associated with it and bears more similarities to it than to any other identifiable culture. Although it might be tempting to use the invariant culture for every possible comparison and just ignore specific cultural comparisons, doing so is a great mistake. Without intending to do so, you can overuse an invariant culture and end up with language that is syntactically incorrect or inappropriate.

Neutral Culture English (en), French (fr), and Spanish (sp) are all neutral cultures. A neutral culture is associated with a language but has no relationship to countries or regions. For instance, the English spoken in England is different from that spoken in the United States. The same holds true for Spanish spoken in Mexico versus that spoken in Spain. As mentioned earlier, the neutral culture will be designated by the first two characters in the CultureInfo class. If only two letters are specified, they will be the Neutral class. Although neutral cultures, like the invariant culture, might be tempting to use, they should be avoided as well, if possible, for the same reasons that invariants should be avoided. The language spoken in different countries that are covered by a neutral culture will almost certainly be different in at least a few respects. In reality, the differences will be many. Therefore, overuse of neutral cultures can result in incorrect or inappropriate language.

Specific Culture This is the most precise of the three categories and is represented by a neutral culture, a hyphen, and then a specific culture abbreviation. For instance, in the designations "fr-FR" and "en-US", fr and en represent the neutral culture (French and English, respectively), and FR and US represent the specific culture (France and the United States, respectively). Specific cultures should be used if at all possible.

To detect a user's current culture information, use the CurrentCulture property of the executing thread's CurrentThread property, as shown in the following code sample:

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;
MessageBox.Show("The current culture of this application is : " + UsersCulture.Name);
MessageBox.Show("The Display Name of this application is : "
+ UsersCulture.DisplayName);
MessageBox.Show("The Native Name of this application is : "
+ UsersCulture.NativeName);
MessageBox.Show("The ISO Abbreviation of this application is : "
+ UsersCulture.TwoLetterISOLanguageName);

Setting the current culture is similar to retrieving it. CurrentCulture is a property of the CurrentThread property of the Thread class; therefore, all that's needed to change or set this property is to specify a different value for it, as shown in the following code:

// C#
CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;
MessageBox.Show("The current culture of this application is : "
+ UsersCulture.Name);
//Change this to Spanish/Venezuela
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-VE");
MessageBox.Show("The current culture of this application is : "
+ Thread.CurrentThread.CurrentCulture);

Paras Sanghani

What are Generics?

Hello Friends,

Generics are part of the .NET Framework's type system that allows you to define a type while leaving some details unspecified. Instead of specifying the types of parameters or member classes, you can allow code that uses your type to specify it. This allows consumer code to tailor your type to its own specific needs.

The .NET Framework version 2.0 includes several generic classes in the System.Collections.Generic namespace, including Dictionary, Queue, SortedDictionary, and SortedList. These classes work similarly to their nongeneric counterparts in System.Collections, but they offer improved performance and type safety.

Why Use Generics?
Versions 1.0 and 1.1 of the .NET Framework did not support generics. Instead, developers used the Object class for parameters and members and would cast other classes to and from the Object class. Generics offer two significant advantages over using the Object class:

Reduced run-time errors:
The compiler cannot detect type errors when you cast to and from the Object class. For example, if you cast a string to an Object class and then attempt to cast that Object to an integer, the compiler will not catch the error. Instead, the runtime will throw an exception. Using generics allows the compiler to catch this type of bug before your program runs. Additionally, you can specify constraints to limit the classes used in a generic, enabling the compiler to detect an incompatible type.

Improved performance
Casting requires boxing and which steals processor time and slows performance. Using generics doesn't require casting or boxing, which improves run-time performance.

How to Create a Generic Type
First, examine the following classes. Classes Obj and Gen perform exactly the same tasks, but Obj uses the Object class to enable any type to be passed, while Gen uses generics:

// C#
class Obj
public Object t;
public Object u;

public Obj(Object _t, Object _u)
t = _t;
u = _u;

class Gen
public T t;
public U u;

public Gen(T _t, U _u)
t = _t;
u = _u;

As you can see, the Obj class has two members of type Object. The Gen class has two members of type T and U. The consuming code will determine the types for T and U. Depending on how the consuming code uses the Gen class, T and U could be a string, an int, a custom class, or any combination thereof.

There is a significant limitation to creating a generic class: generic code is valid only if it will compile for every possible constructed instance of the generic, whether an Int, a string, or any other class. Essentially, you are limited to the capabilities of the base Object class when writing generic code. Therefore, you could call the ToString or GetHashCode method within your class, but you could not use the + or > operator. These same restrictions do not apply to the consuming code because the consuming code has declared a type for the generic.

How to Use Constraints
Generics would be extremely limited if you could only write code that would compile for any class, because you would be limited to the capabilities of the base Object class. To overcome this limitation, use constraints to place requirements on the types that consuming code can substitute for your generic.

Generics support four types of constraints:

Interface Allow only types that implement specific interfaces to use your generic.

Base class Allow only types that match or inherit from a specific base class to use your generic.

Constructor Require types that use your generic to implement a parameterless constructor.

Reference or value type Require types that use your generic to be either a reference or value type.

Use the As clause in Visual Basic or the where clause in C# to apply a constraint to a generic. For example, the following generic class could be used only by types that implement the IComparable interface:

// C#
class CompGen where T : IComparable
public T t1;
public T t2;

public CompGen(T _t1, T _t2)
t1 = _t1;
t2 = _t2;

public T Max()
if (t2.CompareTo(t1) < 0)
return t1;
return t2;

The preceding class will compile correctly. However, if you remove the where clause, the compiler will return an error indicating that generic type T does not contain a definition for CompareTo. By constraining the generic to classes that implement IComparable, you guarantee that the CompareTo method will always be available.

Paras Sanghani

Friday, August 6, 2010

LINQ --- An interesting Technology...

Hello Friends,
Linq is very interesting Technology introduced in .Net Framework 3.5.
LINQ stands for Language Integrated Query.
Over View Of LINQ:
  • LINQ provides query functionality directly in C# programming languages as we do in Sql Server
  • LINQ queries are language constructs which are similar to any other defined code block, such as methods and class definations.
  • We can run LINQ queries against any .NET Framework collection that implements IEnumerable, IEnumerable(T), or any collection that implements an interface that inherits from IEnumerable(T), blocks of XML and XML Documents, SQL Server databases, and ADO.NET datasets.
LINQ Providers:
There are mainly four types of LINQ Providers available:
  1. LINQ to Objects
  2. LINQ to XML
  3. LINQ to SQL
  4. LINQ to DataSets
Besides the above four, Other Providers is also supported.
LINQ Queries:
The LINQ query by itself defi nes only the shape and structure of the data returned by the
query, not the actual data. The data is available after executing the query. The process of
targeting a data source with a LINQ query and accessing the data has three stages:
1. The data source
2. Query creation
3. Query execution
The Data SourceThe data source is any .NET Framework collection that implements IEnumerable,
IEnumerable(T), or any collection that implements an interface that inherits from
IEnumerable(T), Blocks of XML and XML Documents, SQL Server databases, and ADO.NET
Query CreationQuery creation is the LINQ query that determines the data to retrieve from the data source.
In addition to the actual data to return, LINQ queries can also specify additional information,
such as sort order, and grouping of the returned data.
The following code shows a LINQ query that returns all buttons on a form:
var buttonsQuery =
from Control buttons in this.Controls
where (buttons is Button)
orderby buttons.Text
select buttons;
The variable that will contain the results of the query is called the range variable. In the
above example, the variable is named buttonsQuery.
Query ExecutionQuery execution is typically deferred until the query is iterated over with a foreach loop. In
the case of aggregate functions, such as Sum, Count, and Average, these queries execute
immediately and do not need to be iterated over.
To force immediate execution of a query, call the ToList or ToArray methods of the query’s
range variable, as shown in the following example.
var buttonsQuery =
from Control buttons in this.Controls
where (buttons is Button)
orderby buttons.Text
select buttons.ToList();
In the example LINQ query shown above, you force the query to execute immediately by
calling buttons.ToList().

Paras Sanghani

How to Bind Enums to windows Combobox?

Hello Friends,
Sometime our ComboBox lookup value are fixed and we don’t have any database table. In such situation we mostly make enum of our look up value. But most of the time we are used to bind datasource of tables or list to combbox. So we might be wonder how to bind our enum to combobox.

Here is the simple way to bind combobox. Say for example you have RoleTypes Enum.

public enum RoleTypes
Owner = 1,
Manager = 2,
AssitManager = 3,
Employee = 4
Now, to bind this enum to our combo box.

this.cmbUserRole.DataSource = Enum.GetValues(typeof(RoleTypes));

Set value to combobox.

this.cmbUserRole.SelectedItem = (RoleTypes)1;
To get value from combobox.

Convert.ToInt32((RoleTypes) this.cmbUserRole.SelectedItem);

Moreover, kindly have a look at the enum and how to create the same :

Enumerations are related symbols that have fixed values. Use enumerations to provide a list of choices for developers using your class. Moreover, it is way to avoid the hardcode values in the applicaiton. For example, the following enumeration contains a set of titles:

// C#
enum Titles : int { Mr, Ms, Mrs, Dr };

If you create an instance of the Titles type, Visual Studio displays a list of the available values when you assign a value to the variable. Although the value of the variable is an integer, it is easy to output the name of the symbol rather than its value, as shown here:

// C#
Titles t = Titles.Dr;
Console.WriteLine("{0}.", t); // Displays "Dr."

The purpose of enumerations is to simplify coding and improve code readability by enabling you to use meaningful symbols instead of simple numeric values. Use enumerations when developers consuming your types must choose from a limited set of choices for a value.


Paras Sanghani

Wednesday, August 4, 2010

Difference between Setup Project and Click Once Deployment?

Hello Friends,
In our day to day life, we often need to deploy our latest build to our client in C#.Net.
Microsoft .Net provides mainly two types of deployment processes:
1. Setup Project
2. Click Once Deployment Project

Now, developers need to identify when and where we should use one of the above deployment technology according to deployment requirement.
So, kindly find below mention points for our understanding:
When To Use Click Once Deployment:
ClickOnce is a new deployment technology that Microsoft developed to address several problems with deployment namely

  1. Difficulty in providing regular updates
  2. The inability of nonadministrative users to install applications
  3. The dependence of multiple programs on shared components
  4. Installation folder will be isolated storage

ClickOnce deals with all of these problems and allows you to create a deployment strategy that is easily updateable, isolated from other applications, and installable by nonadministrative users.

When to use the Setup Project:

Although ClickOnce provides simple and easy deployment for a variety of applications, you
might need a more configurable environment for complex programs. Setup projects allow you to create highly confi gurable deployment plans.

  1. Allows you to create the directories on the target computers
  2. Windows Service installation
  3. Registry Modifications during installation
  4. Execute Custom Actions during installation
  5. Copy files to target machine


Paras Sanghani

Tuesday, August 3, 2010

Asynchronous Programming Techniques

You will often have to create applications that perform time-consuming operations, such as fi le downloads or complex calculations. These operations can cause the user interface (UI) to lock up and become unresponsive, leading to an unpleasant user experience. By using asynchronous programming techniques, you can enable time-consuming operations to be run asynchronously, thus keeping the UI responsive while the operations are run.

You are frequently required to perform tasks that consume fairly large amounts of time, such as file downloads. The BackgroundWorker component provides an easy way to run timeconsuming processes in the background, thereby leaving the UI responsive and available for user input.

The BackgroundWorker component is designed to allow you to execute time-consuming
operations on a separate, dedicated thread. This allows you to run operations that take a lot of time, such as fi le downloads and database transactions, asynchronously and allow the UI to remain responsive.
The key method of the BackgroundWorker component is the RunWorkerAsync method.
When this method is called, the BackgroundWorker component raises the DoWork event. The code in the DoWork event handler is executed on a separate, dedicated thread, allowing the UI to remain responsive. Important members of the BackgroundWorker component are shown below:
1. CancellationPending Property - Indicates whether the application has requested cancellation of a background operation.
2. IsBusy Property - Indicates whether the BackgroundWorker is currently
running an asynchronous operation.
3. WorkerReportsProgress Property - Indicates whether the BackgroundWorker component can report progress updates.
4. WorkerSupportsCancellation Property - Indicates whether the BackgroundWorker component supports asynchronous cancellation.
5. CancelAsync Method - Requests cancellation of a pending background operation.
6. ReportProgress Method - Raises the ProgressChanged event.
7. RunWorkerAsync Method - Starts the execution of a background operation by
raising the DoWork event.
8. DoWork Event - Occurs when the RunWorkerAsync method is called. Code in the DoWork event handler is run on a separate and dedicated thread.
9. ProgressChanged Event - Occurs when ReportProgress is called.
10. RunWorkerCompleted Event - Occurs when the background operation has been completed or cancelled or has raised an exception.

Running a Background Process :
The RunWorkerAsync method of the BackgroundWorker component starts the execution of
the background process by raising the DoWork event. The code in the DoWork event handler
is executed on a separate thread. The following procedure explains how to create a background
1. From the Toolbox, drag a BackgroundWorker component onto the form.

2. In the component tray, double-click the BackgroundWorker component to create the
default event handler for the DoWork event. Add the code that you want to run on the
separate thread. An example is shown below.
// C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
// Insert time-consuming operation here
3. Elsewhere in your code, start the time-consuming operation on a separate thread by
calling the RunWorkerAsync method, as shown:
// C#

Providing Parameters to the Background Process:
Sometimes you will want to run a background process that requires a parameter. For example,you might want to provide the address of a fi le for download. You can provide a parameter in the RunWorkerAsync method. This parameter will be available as the Argument property of the instance of DoWorkEventArgs in the DoWork event handler.

1. Include the parameter in the RunWorkerAsync call, as shown below:
// C#
2. Retrieve the parameter from the DoWorkEventArgs.Argument property and cast it
appropriately to use it in the background process. An example is shown below:
// C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
string myPath;
myPath = (string)e.Argument;
// Use the argument in the process

Announcing the Completion of a Background Process :
When the background process terminates, whether because the process is completed or
the process is cancelled, the RunWorkerCompleted event is raised. You can alert the user to the completion of a background process by handling the RunWorkerCompleted event. An example is shown below:

// C#
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
System. Windows.Forms.MessageBox.Show("Background process completed");

You can ascertain if the background process was cancelled by reading the e.Cancelled
property, as shown below:
// C#
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
if (e.Cancelled)
System. Windows.Forms.MessageBox.Show ("Process was cancelled!");
System. Windows.Forms.MessageBox.Show("Process completed");

You might want to return a value from a background process. For example, if your process
is a complex calculation, you would want to return the end result. You can return a value by
setting the Result property of the DoWorkEventArgs in the DoWorkEventHandler. This value
will then be available in the RunWorkerCompleted event handler as the Result property of the
RunWorkerCompletedEventArgs parameter, as shown in the following example:
// C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
// Assigns the return value of a method named ComplexCalculation to
// e.Result
e.Result = ComplexCalculation();
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
System. Windows.Forms.MessageBox.Show("The result is " +

Cancelling a Background Process :
You might want to implement the ability to cancel a background process. Background-
Worker supports the ability to cancel a background process, but you must implement most of the cancellation code yourself. The WorkerSupportsCancellation property of the Background Worker component indicates whether the component supports cancellation. You can call the CancelAsync method to attempt to cancel the operation; doing so sets the CancellationPending property of the BackgroundWorker component to True. By polling the CancellationPending property of the BackgroundWorker component, you can determine whether or not to cancel the operation.

1. In the Properties window, set the WorkerSupportsCancellation property to True to
enable the BackgroundWorker component to support cancellation.
2. Create a method that is called to cancel the background operation. The following
example demonstrates how to cancel a background operation in a Button.Click event
// C#
private void btnCancel_Click(object sender, EventArgs e)
3. In the BackgroundWorker.DoWork event handler, poll the BackgroundWorker.CancellationPending
property and implement code to cancel the operation if it is True. You
should also set the e.Cancel property to True, as shown in the following example:
// C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
for (int i = 0; i <>

if (backgroundWorker1.CancellationPending)


e.Cancel = true; return;




Reporting Progress of a Background Process with BackgroundWorker:
For particularly time-consuming operations, you might want to report progress back to the primary thread. You can report progress of the background process by calling the Report- Progress method. This method raises the BackgroundWorker.ProgressChanged event and allows you to pass a parameter that indicates the percentage of progress that has been completed to the methods that handle that event. The following example demonstrates how to call the ReportProgress method from within the BackgroundWorker.DoWork event handler and then to update a ProgressBar control in the BackgroundWorker.ProgressChanged event handler:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
for (int i = 1;i <>

{ RunTimeConsumingProcess();

// Calls the Report Progress method, indicating the percentage

// complete




private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)


progressBar1.Value = e.ProgressPercentage;


Note that in order to report progress with the BackgroundWorker component you must set the WorkerReportsProgress property to True.


Paras Sanghani

How to Create Setup Project in vs 2008?

Setup Projects:
You can add a setup project to a solution to create a Windows Installer application for your solution. Setup projects are highly configurable and allow you to create directories on the target computer, copy files, modify the registry, and execute custom actions during installation. When compiled, a setup project produces an .msi file, which incorporates a setup wizard for the application. The .msi file can be distributed by disk, download, or file share. When it is clicked, the .msi file launches the application setup wizard and installs the application.

1. From the File menu, choose Add and then New Project to open the Add New Project
dialog box.

2. In the Project Types pane, expand Other Project Types, and then click Setup And
3. In the Templates pane, click Setup Project, and then click OK.

Setup Project Editors :
Each setup project includes six editors that allow you to configure the contents and the
behavior of the setup project. These editors are:
􀁑 File System Editor:
Allows you to configure the installation of your application to the file system of the target computer.
􀁑 Registry Editor:
Allows you to write entries to the registry upon installation.
􀁑 File Types Editor:
Allows you to set associations between applications and file types.
􀁑 User Interface Editor:
Allows you to edit the user interface seen during installation for both regular installation and administrative installation.
􀁑 Custom Actions Editor:
Allows you to def ne custom actions to be performed during installation.
􀁑 Launch Conditions Editor:
Allows you to set conditions for launching the installation of your setup project.

You can open any of these editors by selecting the deployment project in Solution Explorer
and then selecting the appropriate editor from the View menu.

1. Right-click Application Folder in the left-hand pane of the File System Editor, choose
Add, and then choose Project Output. The Add Project Output Group dialog box opens.
2. Choose the project outputs that you want to add to your setup project. All .exe and .dll
files created by the project are contained in Primary Output. You can also add other
project files to your setup project, such as localized resources, content files, or documentation
files, or, less frequently, debug symbols, source files, or Extensible Markup
Language (XML) serialization assemblies. Once you have selected the output to be
added to the folder, click OK.


1. In the right-hand pane of the File System Editor, right-click the file for which you want
to create a shortcut and choose Create Shortcut. A shortcut to the file is created and
added to the pane.
2. Drag the shortcut from the right-hand pane to the appropriate folder in the left-hand

How to Select Prerequisties in Setup Project?

  • Right Click your project in your Solution Explorer
  • Select Properties
  • Select Prerequisties checkboxes what ever applicable
  • Press OK

Kindly find the following link containing the Screen cast for creating Setup Project: