Showing posts with label Paras Sanghani. Show all posts
Showing posts with label Paras Sanghani. Show all posts

Sunday, July 29, 2012

Benefits of Asp.Net MVC development

  When we assist developers with new applications using the .NET framework, there is always a question of what is the best architecture for development? In most cases, we recommend the model-view-controller software architecture. The MVC architecture isolates the domain logic from the user interface, allowing for faster, more controlled development. MVC is under continued enhancements, providing more benefits with each new version.

Model-view-controller has three layers: the model, the view, and the controller. The model can be considered the data used in the program, the controller includes the class files with the business logic, and the view is simply the user interface. By isolating the model, the view, and the controller, development is faster, complexity is easier to manage, and there is more control over the behavior of the application.

1.      Managed Complexity – The separated nature of model-view-controller makes it easier to manage the complexity of large applications and keep it well organized. Developers are able to focus on one aspect of implementation at a time, such as concentrating on the view without depending on the business logic. Some functions and classes of MVC can even be auto-created to save time.

2.      Faster Test-Driven Development – With MVC, it’s easier to test applications than it is to test Forms-based ASP.NET web applications. This is because the separation of application tasks are all defined differently so they add no more complexity. Developers can test very short development cycles by writing a failing automated test case to define a desired improvement or function, then writing the new code.

3.      Rapid, Parallel Development – Because of the loose coupling of the MVC architecture, it’s easier for more than one developer can code at the same time on the application. If one developer is working on the view, another on the controller logic, and the last on the business logic in the model, the application can potentially be completed three times faster. Using other architectures, the three developers are more likely to step on each other’s toes. But with model-view-controller, they code independently and simultaneously.

4.      Full Control Over Behaviour – The MVC framework is ideal for developers who want full control over the behaviour of their application because MVC does not use a view state or server-based forms.

5.      Code Reuse – Since the controller uses different pieces of the model and view to create a request, many of these parts can be reused in other MVC applications. These reusable building blocks are chosen by the controller to handle specific processing (model) and display (view) requirements.

6.      JavaScript Integration – The model-view-controller architecture also integrates with the JavaScript Framework. This means, MVC applications can be made to work with applications outside web pages, such as PDF documents, site-specific browsers, and desktop widgets. It also supports asynchronous calls to such scripts which results to faster loading.

7.      No Viewstate or Postback Events – Rather than using Viewstate or Postback events to store the state of server controls on the page and to manage invocation of server side events, MVC instead uses different view engines to generate the markup that streams back to the browser client. The advantage here is that you can produce more standard markup and have greater control over what will be rendered to the client.

                Please let me in case of any queries.




Thanks,
Paras Sanghani


           

Thursday, July 19, 2012

I am Microsoft Certified Trainer (MCT) 2012

Well......After many days, I am writing blog to thanks all my friends, colleges, blog readers and good wishers that I am now Microsoft Certified Trainer. I am really proud of it. One of the achievement in life which is everlasting. I am now having support of whole community leaders,supporters and trainers. I would really make the people aware about importance of Certification and its influence in their career. I already had blog related to same: Importance and Benefits of Certifications......

I am working on Sharepoint 2010 and ASP.NET MVC and will surely have very interesting blogs series on Sharepoint Development


Thanks & Regards,
Paras Sanghani

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

Tuesday, February 15, 2011

Creating a Custom HTTP Handler

In the previous post about HTTP Handler, we had understanding on HTTP Handler and its importance.

We will look now on creating the Creating a Custom HTTP Handler in Asp.Net Application.An HTTP handler is code that executes when an HTTP request for a specific resource is made to the server. For example, when a user requests an .aspx page from IIS, the ASP.NET page handler is executed. When an .asmx file is accessed, the ASP.NET service handler is called. You can create your own custom HTTP handlers, register them with IIS, and receive notice when a specific request has been made. This allows you to interact with the request and write your own custom output to the browser.

To create a custom Hypertext Transfer Protocol (HTTP) handler, you first create a class that implements the IHttpHandler interface (to create a synchronous handler) or the IHttpAsyncHandler (to create an asynchronous handler). Both handler interfaces require you to implement the IsReusable property and the ProcessRequest method. The IsReusable property specifies whether the IHttpHandlerFactory object (the object that actually calls the appropriate handler) can place your handlers in a pool and reuse them to increase performance or whether it must create new instances every time the handler is needed. The ProcessRequest method is responsible for actually processing the individual HTTP requests. Once it is created, you then register and configure your HTTP handler with IIS.
As an example, consider the processing of image requests in ASP.NET. Each image in an HTML page requires a separate browser request and a separate response from the Web server. By default, IIS does not pass requests for images to ASP.NET. Instead, IIS simply reads the image file from the file system and sends it directly to the Web browser.

Now, imagine you want to handle requests for images in ASP.NET instead of them just being passed back by IIS. You might need to dynamically generate a chart displaying performance information over a period of time or you might want to dynamically create thumbnails in a photo album application. In these circumstances, you either periodically generate the images in advance or you can create a custom HTTP handler to receive the image requests. It is the latter action on which this example focuses. The following outlines how you can configure ASP.NET (and your custom HTTP handler code) to receive requests for images:

1. Write code to dynamically generate the images.
2. Configure IIS to pass requests for the required image types to ASP.NET.
3. Configure ASP.NET to process requests for files with the required file extensions.

Dynamically Generating Images
The following code demonstrates how you can write an HTTP handler for generating images.

//C#
public class ImageHandler : IHttpHandler
{
public ImageHandler()
{ }

public bool IsReusable
{
get { return false; }
}

public void ProcessRequest(HttpContext context)
{

//set the MIME type
context.Response.ContentType = "image/jpeg";
//TODO: Generate the image file using the System.Drawing namespace
// and then use Context.Response to transmit the image
}
}

Configuring IIS to Forward Requests to ASP.NET
For performance reasons, IIS passes only requests for specific file types to ASP.NET. For example, IIS passes requests for .aspx, .axd, .ascx, and .asmx to the Aspnet_Isapi.dll file that performs the ASP.NET processing. For all other file types, including .htm, .jpg, and .gif, ASP.NET simply passes the file from the file system directly to the client browser.

Therefore, to handle image requests using ASP.NET, you must configure an IIS application mapping from the image file extension you need to the Aspnet_Isapi.dll file. The process of configuring this information is different for IIS 6 and IIS 7. The following steps outline the process for configuring with IIS 7:

1. Open IIS Manager.
2. Expand the nodes until you get to your site or Default Web Site. Select the node for your application.
3. Double-click the Handler Mappings icon in the center pane of IIS Manager.
4. In the Actions pane (right side), select Add Managed Handler.
5. In the Add Managed Handler dialog box, shown in Figure 11-1, set the Request path to the file name or extension you wish to map, in this case, .jpg. The Type name is the class name of the HTTP handler. If your HTTP handler is inside the App_Code directory, it will appear in the drop-down list. The Name field is simply a descriptive name.


Configure an application mapping to process image requests in ASP.NET



Once you configure the application extension mapping, all requests for that file type are forwarded to ASP.NET and to your handler. To enable normal image processing in most areas of your Web site, create a separate virtual directory just for dynamically generated images.

Configuring the Handler in Web.config
Alternatively, if you are using IIS 7, you can simply configure the handler for the file extension in your Web.config file. You do not, then, need to use IIS Manager. For each file extension or file name you want to register, create an element in the section of your Web.config file, as the following example demonstrates:




ASP.NET handles requests for files ending in .jpg or .gif by forwarding them to the ImageHandler class. For this to work properly, the ImageHandler assembly must be available in the application’s Bin folder or the source code must be in the App_Code folder.





The HTTP Handler

An HTTP handler is code that executes when an HTTP request for a specific resource is made to the server. For example, when a user requests an .aspx page from IIS, the ASP.NET page handler is executed. When an .asmx file is accessed, the ASP.NET service handler is called.An HTTP handler component is an instance of a class that implements the IHttpHandler interface. This component is a pillar of the ASP.NET runtime architecture. Here’s the defnition of the interface:

//C#
public interface IHttpHandler
{
public void ProcessRequest(HttpContext context) ;
public bool IsReusable;
}

The name of the method ProcessRequest says it all about the intended semantics. It takes the context of the request as the input and ensures that the request is serviced. In the case of synchronous handlers, when ProcessRequest returns, the output is ready for forwarding to the client. (It is not of primary importance here, but HTTP handlers can also work asynchronously according to the methods in the IHttpAsyncHandler interface.)

In Visual Studio, you build an ASP.NET application as a collection of Web Forms pages. Each page consists of two fles: an .aspx markup fle describing the expected HTML template and a C# (or Visual Basic) class file that contains postback handlers and any ancillary methods.

Where’s the HTTP handler, then? Who writes the HTTP handler for each and every ASP.NET request that originates within an application? Is the Web Forms model really centered on the concept of an HTTP handler?

The answer is in the underlying design pattern used to implement the Web Forms model.
Known as Page Controller, the pattern suggests that you arrange the processing of an HTTP request around the concept of the page. Processing the request is a task that goes through a number of steps, such as instantiating the page, initializing the page, restoring the page’s state, updating the page, rendering the page, and unloading the page. In the implementation of the pattern, you start from a base page class and define a strategy to process the request—the page life cycle. In the implementation of the page life cycle,you come up with an interface of virtual methods and events that derived pages will have to override and handle. Derived page classes are known as code-behind classes in ASP.NET jargon.

In ASP.NET, the base page class is System.Web.UI.Page and, guess what, most of what it does is implement the IHttpHandler interface. (See Figure Below Figure)





You can create your own custom HTTP handlers, register them with IIS, and receive notice when a specific request has been made. This allows you to interact with the request and write your own custom output to the browser. Please check Creating Custom HTTP Handlers.


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.

Wednesday, February 2, 2011

Microsoft Community Contritor Award 2011


I would like to take opportunity to thank all readers for making my blogs successful and I have been awarded as Microsoft Community Contributor Award 2011. I thanks Microsoft for providing such honour to me and also thanks all my friends who are marking my posts as Answers and blog readers.......




The begining of year 2011 has been very successful for me. I believe this award as achievement in life and may this year will bring success to all of you. I would like to tell all my friends and readers to start blogging. I have seen quite intelligent IT Professionals and Excepectional Developers are not blogging....I would like to encourage them to start blogging immediately because unless and until you don’t blog community will not know what you are doing.

My Msdn Profile

Thanks,
Have happy blogging and programming

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

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


Sunday, August 8, 2010

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