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

Thursday, January 6, 2011

Entity Framework vs. LINQ to SQL(edmx vs dbml)

Hi Friends,


This post is regarding the difference between LINQ to SQL vs. Entity Framework.
Both are introduced as latest technologies and at times a bit confusing when to use which. Entity Framework and LINQ to SQL have a lot in common but still different from each other in quite a few ways:

Entity Framework:
1. Enterprise Development
2. Works with Conceptual model of database
3. Works with all data sources
4. ".EDMX" is created while using Entity Framework

LINQ:
1. Rapid Application Development
2. Works with objects in database
3. Mainly woks with SQL Server
4. ".dbml" is created while using LINQ to SQL

Entity Framework is more targeted towards Enterprise Development where the schema is usually optimized for storage considerations like performance consistency and partitioning. Entity Framework is designed around exposing an application-oriented data model that is loosely coupled and may differ from the existing database schema. For example, you can map a single entity (class) to multiple or map multiple entities to the same table. Entity Framework has “.edmx” (ADO.NET Entity Model) file when added in the application.

LINQ to SQL mainly has features to support Rapid Application Development against SQL Server. LINQ to SQL allows you to have a strongly typed view of your existing database schema. You can build LINQ queries over tables and return results as strong typed objects. LINQ to SQL has “.dbml”(LINQ to SQL) file when added in the application. You can use LINQ to SQL by decorating the existing classes with the attributes.

Please review: Entity Framework Basics

Thanks,
Paras Sanghani

Wednesday, December 29, 2010

Entity Framework Best Practices

Dear Friends,


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






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

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

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

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

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


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

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

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

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

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


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

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

 


Thanks,
Paras Sanghani

Wednesday, November 17, 2010

Passing Data in an ASP.NET MVC Application


Hello Friends,

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

Passing Data in an ASP.NET MVC Application

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

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

Kindly, find some important links below:

http://msdn.microsoft.com/en-us/library/dd394711.aspx

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

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


Thanks,

Paras Sanghani


Tuesday, November 16, 2010

ADO .NET Entity Framework

Hello Friends,

For Entity Framework Beginners, please review: Entity Framework Basics

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

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

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

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

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

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




Thanks,
Paras Sanghani