Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts

Wednesday, February 16, 2011

Inheritance in Entity Framework - 1

Types of inheritance in Entity Framework

For beginners, please review: Entity Framework Basics
In this blog, I will explore on how to use inheritance in Entity Framework as a part of Advanced Data Models. Basically there are 2 models of Inheritance in Entity Framework and they both actually depend on the database design:

Table-per-Hierarchy Inheritance:
One table in storage schema to maintain data for all the types in an inheritance hierarchy. So, basically there is only one table in database, but different types in Entity model that inherits from a base class and all mapped to that table.

Table-per-Type Inheritance:
Separate table in storage schema to maintain data for each type in the inheritance hierarchy. That means there might have several tables with one-to-one relationships. Each table is mapped to single Entity in the model. But there is a base Entity that is mapped to the very base table.

We will look into Table-per-Hierarchy Inheritance in this blog with example. Generally, Table-per-Hierarchy is type inheritance which is having one table in Database but in Conceptual model of Entity Framework, the Entities are inherited from base Entity. For ex.: Consider real life development scenario, we often have a single table in Database having all the master data in the application ex.: Country, State, City, etc.
Consider below table which will hold all the master data:



In the above table, we are going to have all the Master Table Data along with parent child relationship among them. But through EF - Table-Per-Hierarchy, we will expose all the Entities to the users providing a level of abstraction. Please refer below figure in Entity Framework:


For one table in Database, we will expose Country, State, City as separate Entities referring to same table. So, let see how to achieve the same in Entity Framework:
1. First Add New Model in your Project
a. Add New Item by Right Clicking Project,
b. Select Add
c. Add New Item and ADO.NET Entity Data Model



2. Entity Data Model Wizard will open. Select Generate from Database



3. Configuration your model and DB:



4. Select the Enums Table and Press Finish:




5. You will get the below Entity in Entity Model:



6. Now in Enum Table in Database, we have three Master Category naming Country, State and City having
a. EnumCategoryID = 1 represents Country
b. EnumCategoryID = 2 represents State
c. EnumCategoryID = 3 represents City
So, first add the Country Entity as shown in below figure:





Do same for State and City Entities:





Once all the Entities are added, the model will look like:



7. Defining Columns in derived Entities.
Now, ParentEnumID is key relating the related records in Enum Table. For ex.: Enum table will contain records of Countries, States and Cities. So, for relationship between Country, State and City, ParentEnumID will be used which will be CountryID in State Entity and StateID in City Entity. So, Add Scalar Property CountryID in State and StateID in City Entity.
In order to add new Scalar Property,
a. Select “State” Entity, right click
b. Click Add --> Scalar Property.
Please note that Scalar Property should have the same data type as that in Base Table.
In our ex.: ParentEnumID is int, so Country ID and State ID will be int only.
Once your columns are added the model should look like:



8. Define Table Mappings:
Earlier I mentioned that EnumCategoryID is used to identity each Entity namely Country, State and City. For example EnumCategoryID= 1 represents that Entity is Country. Moreover, we need to map CountryID in State entity and StateID in City entity to ParentEnumID in Enum entity. So, let us now add Table mapping.
For adding Table Mapping, select Entity, Right click and select Table mapping as shown in figure:



Then, for Country, add Condition EnumCategoryID = 1, as there would be no ParentEnumID for Country, we will leave it blank.



For State, add Condition EnumCategoryID =2, in ColumMappings map ParentEnumID to CountryID



For City, add Condition EnumCategoryID =3, in ColumMappings map ParentEnumID to StateID



Once you are done, please don’t forget to delete the ParentEnumID and EnumCategoryID property from Enum Entity as it is not needed anymore.

9. Define An Abstract Class:
As I mentioned earlier, for demonstration I need to set Enum Entity as Abstract. However you can still define a mapping for it instead of making it abstract. You should set an Base Entity as Abstract only if you know there will be no direct instantiation from that Entity. For the case here, I would be having only Country, State and City entities. There is no simple Enum.
To set an Entity as Abstract:
1. Right Click on the Enum Entity, select Properties form context menu.
2. From Properties window and Under Code Generation group, set Abstract property to True. Click Ok on the confirmation message that appears.

Conclusion:
Let see what is exacting happing in the Model by exploring Conceptul Model, Storage Model and Mapping Model:
a. Storage Model



b. Conceptual Model




c. Mapping Model:



Find the sample code. And in few days, I will publish post on using the Table per Hierarchy in the Application with CRUD operations and Table-Per-Type example and explanation.

Thanks,
Paras Sanghani


TablePerHierarchy

Monday, February 14, 2011

Application Domain and its configuration (Part-1)

In .net all application assembly run under an application domain that is created by default for each application, we don’t need to create it. Common Language Runtime does it for application.

Developers often need to run an external assembly. However, running an external
assembly can lead to inefficient resource usage and security vulnerabilities. The best way to manage these risks is to create an application domain and call the assembly from within the protected environment.

Application domain is logical unit to run different application in a single process. IIS is the very good example of it, in IIS more than one website or application are hosted, still they run independent with out interfering to any other application, hosted on same IIS.

Application domain creates a separate layer for application; .net run time is responsible for the various application runtime, while operating system manage process. In a process, we can run more than one application domain and each application domain has one or more assembly, application running. Each of these application domains can’t access resource or memory used by another application domain.

To create an application domain is as simple as we create an object of a class. The benefit of application domain is that when we don’t require or our work has been completed we can unload resource occupied by application runtime.

System.AppDomain class provides many methods and property to manipulate application domain.

1. Create an application domain

AppDomain ad = new AppDomain(“myAppDomain”);

We can run our assembly under this newly created Application domain.

ad.ExecuteAssembly(“myAssembly.exe”);

We can either call ExecuteAssemblyByName method to run assembly, in that case we need to pass name of assembly.

ad.ExecuteAssembly(“myAssembly.exe”);

There are so many properties and methods provide by AppDomain which gives ability to specify ID to process, friendlyname etc. Methods like Load, ApplyPolicy,CreateIntance etc.

If you notice in above code, we don’t have any constructor to create application domain, we are using static method of AppDomain class.

We can access current domains by ..

AppDomain myCurrentDomain = AppDomain.CurrentDomain;

To unload application domain, call Unload method of AppDomain

AppDomain.Unload(ad);

Threading Part - 2


This post is in continuation with Threading Part - 1....

In first post, we have seen the basic understanding on the Threading and its usage.
Now, let us consider comparatively complex scenarios....

Using Thread.Join
More often than not, you will need your application to wait for a thread to complete
execution. To accomplish this, the Thread class supports the Join method:

// C#
theThread.Join();

The Join method tells the system to make your application wait until the thread has
completed. Of course, in this simple case you do not really need a second thread
because you are just waiting for it to complete anyway. A better example is for us to
have five threads that all do some work and to wait for them. When we are working
with multiple threads, our programming task is a bit more complicated, as we need to
wait for all our threads. We can do this by keeping a reference to all our threads and calling Join on each of the threads to wait for the threads to complete, one at a time,as demonstrated in the following code:

// C#
ThreadStart operation = new ThreadStart(SomeWork);
Thread[] theThreads = new Thread[5];
for (i nt x = 0; x < 5; ++x)
{
// Creates, but does not start, a new thread
theThreads[x] = new Thread(operation);
// Starts the work on a new thread
theThreads[x].Start() ;
}
// Wai t for each thread to complete
foreach (Thread t in theThreads)
{
t.Join();
}
By storing the threads in an array, we can wait for each of the Threads one at a time. As each thread completes, the Join method will return and we can continue.

Thread Priority
The Thread class supports the setting or getting of the priority of a thread using the ThreadPriority enumeration.

  1. Highest - The highest priority
  2. AboveNormal - Higher priority than Normal
  3. Normal - The default priority
  4. BelowNormal - Lower than Normal
  5. Lowest - The lowest priority



Threads are scheduled based on this enumeration. In most cases, you will want to use
the default (Normal). Deciding to use threads that have lower thread priority can
cause the operation system to starve a thread more than you might expect, or if you
use higher priorities (especially Highest), you can starve the system. Although it is necessary to use non-Normal thread priorities at times, make this decision with much caution. Increasing the performance of a system simply by increasing thread priority is not likely to help in the long term, as other starved threads tend to back up and cause unexpected consequences.

Passing Data to Threads
In each of the earlier examples, we were using the ThreadStart delegate, which takes
no parameters. In most real-world use of threading, you will need to pass information
to individual threads. To do this, you need to use a new delegate called ParameterizedThreadStart. This delegate specifies a method signature with a single parameter of type Object and returns nothing. The following code snippet provides an example:

// C#
static void WorkWithParameter(object o)
{
string i nfo = (string) o;
for (int x = 0; x < 10; ++x)
{
Console. WriteLine("{0}: {1}", i nfo,
Thread.CurrentThread.ManagedThreadId);
// Slow down thread and let other threads work
Thread. Sleep(10);
}
}

This is a method that takes a single Object parameter (and therefore can be a reference to any object). To use this as the starting point of a thread call, you can create a ParameterizedThreadStart delegate to point at this new method and use the Thread.Start method’s overload that takes a single object parameter. The following code snippet provides an example:

// C#
ParameterizedThreadStart operation = new ParameterizedThreadStart(WorkWithParameter);
// Creates, but does not start, a new thread
Thread theThread = new Thread(operation);
// Starts the work on a new thread
theThread.Start("Hel l o");
// A Second Thread wi th a different parameter
Thread newThread = new Thread(operation);
newThread.Start("Goodbye");

Be aware that because the WorkWithParameter method takes an object, Thread. Start
could be called with any object instead of the string it expects. Being careful in choosing your starting method for a thread to deal with unknown types is crucial to good threading code. Instead of blindly casting the method parameter into our string, it is a better practice to test the type of the object, as shown in the following example:
// C#
string i nfo = o as string;
if (info == null )
{
throw Invali dProgramException("Parameter for thread must be a string");
}

Threading Part - 1


Most of the time developer chooses to develop program in linear way. In this mechanism user would need to wait sometime in some situation like application is going to download page from server, application is going to print document, applications is going to access remote database. Those cases are time consuming, user needs to wait till main thread completes work, sometime user get frustrated by response time, and application does not response to user till task has been completed.
To overcome, .net has provided threading mechanism. Our main thread executes as and in background we can execute process. So user will not feel that application is not responding, in background thread method executes and once result will be available, it would be shown to user.

Threading means in a single process execute more than one task among different processors. Now days most of computers are more than one core, we can use another core when main core is busy to complete task. We can distribute work task among different processors.

Though multithreading seems to be very complex, .net has provided a simple way to implement in programming. At a time there can be more than 250 threads run in back ground. We can even change it to more if required.

To work with thread we need to add System.Threading namespace to our application.

Creating a Thread
To create and start a new thread, follow these steps:
1. Create a method that takes no arguments and does not return any data (for example, use the void return type for C#). This method should look something like this:

// C#
static void SimpleWork()
{
Console. WriteLine("Thread: {0}", Thread. CurrentThread. ManagedThreadId);
}
2. Create a new ThreadStart delegate, and specify the method created in step 1.
3. Create a new Thread object, specifying the ThreadStart obj ect created in step 2.
4. Call Thread.Start to begin execution of the new thread.
Your code will end up looking something like this:

// C#
ThreadStart operation = new ThreadStart(SimpleWork);
// Creates, but does not start, a new thread
Thread theThread = new Thread(operation);
// Starts the work on a new thread
theThread.Start();

When the Start method is called, the SomeWork method is called on a new thread and
the thread executes until the method completes. In this example, our SimpleWork
method writes the phrase “In Thread” and shows the ManagedThreadId property. This
property is a numeric number assigned to every thread.

Using Multiple Threads
A more likely scenario than this simple case is one in which you’ll want to create
multiple threads to do work. For example, we can change the example just shown to
create multiple threads and start them all on the same work:
// C#
ThreadStart operation = new ThreadStart(SimpleWork);
for (i nt x = 1; x <= 5; ++x)
{
// Creates, but does not start, a new thread
Thread theThread = new Thread(operation);
// Starts the work on a new thread
theThread.Start();
}

This executes the work on five separate threads, as concurrently as your particular
machine is capable of doing. If we implement this change, we should get five separate
threads all writing out their own thread ID to the console window:
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7

We see consecutive thread numbers because the work we are doing in SimpleWork is
very quick. Let’s change our work to something a little more lengthy so that we can
see the threads working concurrently:

// C#
static void Simpl eWork()
{
for (int x = 1; x <= 10; ++x)
{
Console. WriteLine("Thread: {0}",
Thread.CurrentThread.ManagedThreadId);
// Sl ow down thread and let other threads work
Thread.Sl eep(10);
}
}

In this new version of SimpleWork, we are writing out our thread identifier 10 times.
In addition, we are using Thread.Sleep to slow down our execution. The Thread.Sleep
method allows us to specify a time in milliseconds to let other threads perform work.
On every thread, we are allowing 10 milliseconds for the other threads to write their
own data to the console. To see how this works, we can change our SimpleWork method to write out the iteration it is working on:

Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7

Doing this allows us to perform operations as concurrently as our hardware will
allow. As our work increases and the time it takes to complete each thread becomes longer, we will need to determine how to make our main thread (the one that the thread creation code exists on) wait until all the work is complete. This is where the Thread.Join method comes in.


Thread which runs first is called Forground and other called background.

static void ThreadProc(object msg)
{
string threadMsg = (string)msg;
if (Thread.CurrentThread.IsBackground)
{
Console.WriteLine(“Background Thread”);
Console.WriteLine(“My Threading method with:” + threadMsg);
}
else
{
Console.WriteLine(“Forground Thread”);
Console.WriteLine(“My Threading method with:” + threadMsg);
}
}
We can check weather thread is background or not with Thread.CurrentThread.IsBackGround property.
Some time threading also overheads on processors, so need to take care while implementing threading as it distribute loads to different processor, more memory is required to manage resource.
Wise use of threading may improve application’s performance. It depends on requirement and application problem to use of Threading.

Tuesday, February 1, 2011

Sending Emails in C#.Net


Hi Friends,
This post is regarding "Sending email", its configuration and samples.

How to Send a Message using C#.NET?
Once you create a message, you need to send it through an SMTP (Simple Message Transfer Protocol) server, which in turn will forward it to the recipient. In the .NET Framework, the SmtpClient class represents the SMTP server. Most of the time, sending a message is as simple as this sample code (where "smtp.contoso.com" is the name of the local SMTP server):
' VB
Dim m As MailMessage = New MailMessage _
("jane@contoso.com", _
"ben@contoso.com", _
"Quarterly data report.", _
"See the attached spreadsheet.")
Dim client As SmtpClient = New SmtpClient("smtp.contoso.com")
client.Send(m)
// C#
MailMessage m = new MailMessage
("jane@northrup.org",
"ben@northrup.org",
"Quarterly data report.",
"See the attached spreadsheet.");
SmtpClient client = new SmtpClient("smtp.contoso.com");
client.Send(m);

How to Configure Credentials
Next is to configure the Credentials. i.e.: UserName, Password, SMTP Settings.
To reduce spam, all SMTP servers should reject messages from unauthorized users when the message recipients are not hosted by the SMTP server. SMTP servers provided by ISPs typically determine whether a user is authorized based on the user's IP address; if you are part of the ISP's network, you are allowed to use the SMTP server.
Other SMTP servers (and some ISP SMTP servers) require users to provide a valid username and password. To use the default network credentials, set SmtpClient.UseDefaultCredentials to True. Alternatively, you can set SmtpClient.Credentials to CredentialCache.DefaultNetworkCredentials (in the System.Net namespace), as the following code demonstrates:
' VB
Dim client As SmtpClient = New SmtpClient("smtp.contoso.com")
client.Credentials = CredentialCache.DefaultNetworkCredentials
// C#
SmtpClient client = new SmtpClient("smtp.contoso.com");
client.Credentials = CredentialCache.DefaultNetworkCredentials;
To specify the username and password, create an instance of the System.Net.NetworkCredential class and use it to define SmtpClient.Credentials. The following example shows hard-coded credentials; however, you should always prompt the user for credentials:
' VB
Dim client As SmtpClient = New SmtpClient("smtp.contoso.com")
client.Credentials = New NetworkCredential("user", "password")
// C#
SmtpClient client = new SmtpClient("smtp.contoso.com");
client.Credentials = new NetworkCredential("user", "password");

Settings the Port No:
You might need to set the port no,

How to attach files?

To attach a file, add it to the MailMessage.Attachments AttachmentCollection by calling the MailMessage.Attachments.Add method. The simplest way to add a file is to specify the file name:
MailMessage m = new MailMessage();
m.Attachments.Add(new Attachment(@”C”\Tes.jpg”));
You can also specify MIME(Multipurpose Internet Mail Extensions) content type using the System.Net.Mime.MediaTypeNames enumeration. There are special MIME types for text and images, but you will typically specify MediaTypeNames.Application.Octet. The following code sample(which requires System.IO and System.Net.Mime in addition to System.Net.Mail) demonstrates how to use a Stream as a file attachment and how to specify the MIME type:
MailMessage m = new MailMessage();
Stream sr = new FileStream(@”C:\Test.txt”, FileMode.Open, FileAccess.Read);
m.Attachments.Add(new Attachment(sr, “testimage.txt”, MediaTypeNames.Application.Octet )

How to Create HTML E-mails?
To created an HTML e-mail message, supply HTML-tagged content for MailMessage.Body and set the MailMessage.IsBodyHtml attribute to True

Code Sample:

MailMessage m = new MailMessage();
m.From = new MailAddress("lance@contoso.com","Lance Trucker");
m.To.Add(new MailAddress("burke@contoso.com", "Burke Fewel"));
m.Subject = "Testing HTML";

//Specify an HTML message Body
m.Body = "HTML Tags...";
m.IsBodyHtml = true;

//send the message
SmtpClient client = new SmtpClient("smtp.contoso.com");
client.Send(m);

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.

Thanks,
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
{
[STAThread]
static void Main(string[] args)
{
if (Regex.IsMatch(args[1], args[0]))
Console.WriteLine("Input matches regular expression.");
else
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]");



Thanks,
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.

RijndaelManaged
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.

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

DES
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.

TripleDES
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)
myAlg.GenerateKey();

// 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
encryptStream.Close();
inFile.Close();
outFile.Close();

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);
Console.WriteLine(Encoding.Unicode.GetString(decryptedBytes));

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.



Thanks,
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 C#.net , vb.net, 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.

Thanks,

Paras Sanghani

Thanks,

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);


Thanks,
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;
else
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.

Thanks,
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
DataSets.
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().


Thanks,
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.

Thanks,

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
process.
TO CREATE A BACKGROUND PROCESS WITH THE BACKGROUNDWORKER COMPONENT :
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#
backgroundWorker1.RunWorkerAsync();


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.

TO PROVIDE A PARAMETER TO A BACKGROUND PROCESS :
1. Include the parameter in the RunWorkerAsync call, as shown below:
// C#
backgroundWorker1.RunWorkerAsync("C:\\myfile.txt");
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
RunTimeConsumingProcess();
}

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!");
}
else
{
System. Windows.Forms.MessageBox.Show("Process completed");
}
}

RETURNING A VALUE FROM A BACKGROUND PROCESS :
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 " +
e.Result.ToString());
}

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.

TO IMPLEMENT CANCELLATION FOR A BACKGROUND PROCESS :
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
handler:
// C#
private void btnCancel_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
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

backgroundWorker1.ReportProgress(i*10);

}

}

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.

Thanks,

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.

TO ADD A SETUP PROJECT TO YOUR SOLUTION:
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
Deployment.
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.



TO ADD OUTPUT FROM A PROJECT TO A DEPLOYMENT PROJECT :
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.








TO CREATE A SHORTCUT AND ADD IT TO THE TARGET COMPUTER:

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
pane.

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:
http://www.screencast.com/t/MmZhYzI5