Saturday, December 7, 2013

Best Practices for .NET Application





1. Practices for Data Tier

Database plays a very important role in performance improvement.
  • Avoid multiple round trips to database.
  • Always use stored procedures
  • Avoid using dynamic queries and Cursors.
  • Set NoCount ON, unless and until you require the number of rows affected.
  • Avoid querying the same table multiple times in a single session/stored procedure.
  • Choose properly between Table Variables and Temp Tables.
  • Temp Tables are more preferred when the number of records is greater.
  • Avoid putting too many indexes into a table.
  • If a column is not going to repeat its values, then assign a unique key to it (assuming a primary key is already assigned to some other column).
  • Union all is more preferred than Union.
  • Avoid writing co-related sub queries like:

    Select * from TblEmployee where EmployeeId =(Select EmployeeId from TblAttendance where leaves>1 and EmployeeId= TblEmployee.EmployeeId).
    (Try to use a Join instead.)
     
  • If you are sure about the number of rows to be returned by a query, set the Row Count to that number.

    Example : Let's say for instance it's 2, then:

    set RowCount 2
    Select * from TblEmployee where where1=@where1 and where2=@where2
    set RowCount 0
2. Paging

Whenever a list of data is needed to be shown, apply paging and show only some records in every page.

3. Layout

Prefer Div Layout over Table Layout. Tables save HTML development time but create performance overhead since the browser must often wait for the whole table to load before it can begin to layout the content.

4. Caching

Try to cache the things which are more on static or will not be changed frequently.

ASP.NET provides substantial support for caching by means of Page Caching and Fragment Caching.

5. Threading

Using threads in an application improves performance by a great extent.

Let's take an example where we can use Threading in ASP.NET.

Consider there is a form with many input fields to be dumped into the database on submit and after that mail must be sent to admin as a success receipt.

With the mail being sent by a separate thread, it is completely independent of the UI rendering.

Note: A thread can be counter-productive if used excessively; in other words, performance will be affected in a reverse manner when a Thread is used excessively.

6. ViewState

It's one of the biggest culprits for performance issues in ASP.NET.

Always disable the ViewState when it's not necessary, like in the case that we have a form filled only with textboxes, the ViewState is not required because, textboxes maintain their values from the postback data regardless of ViewState.
(Please go through the ASP.NET life cycle first.)

Complex controls like a GridView maintains a very large amount of ViewState, better disable it and rebind it when it's required.

7. SessionState
  • Do not overuse Session State for user data storage.
  • Choose proper session state (InProc, OutProc).
  • Avoid storing complex objects into sessions because such things involve serialization and deserialization internally which results in a big performance penalty.
  • If a session variable is no longer required then clear it.

    Note:
     
  • ViewState is used to store Page-specific data whereas Session is used to store user-specific (in other words, stored in server memory).
  • More things in ViewState means slow page, more things in session means slow website.
  • The above statement doesn't mean we should go with ViewState always, it's up to the environment and condition.

    For example consider we have to store a huge amount of data but the website is not going to be accessed by many users; there might be one to three users that will access it simultaneously. In this case the session will be worthwhile.
    If you try ViewState for such huge objects pages then it can get extremely heavy and might not even load.
8. Set retail="true" in your machine.config
<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>
  • It will force the "debug" flag in the web.config to be false.
  • It will disable page output tracing.
  • It will force the custom error page to be shown to remote users rather than the actual exception or error message.
9. Use HTML controls whenever possible

ASP.NET server controls renders them according to the browser capabilities and if required write some JavaScript also, so use HTML controls whenever possible.

One scenario is if there are some controls which are never going to be accessed from the server side then it is better to make them HTML controls.

10. Postback

Avoid unnecessary postback to the server whenever possible.

One scenario is, a postback is not required for just validating empty text, we can do that even using JavaScript.

11. Page.IsPostBack

Use Page.IsPostBack to avoid performing unnecessary processing on a postback.

12. Exception handling

Try to avoid Try...Catch block , instead try to avoid exceptions using If…else.

Example

Try
{
//Read A
//Read B
//Return A/B
}
Catch(DevidebyZeroException e)
{
//B is zero please provide something else
}

Can be replaced with

//Read A
//Read B
//If (B==0){Please provide some other value}.
//else return A/B

13. ListView instead of GridView

As automation increases, performance decreases, becuase sometimes we use many things that are not required.
GridView provides automatic structure in a table format whereas a ListView can be used to create our own structure in a productive manner.

StringBuilder

Choose wisely between string and StringBuilder.

Only if a string will be manipulated more than twice use a StringBuilder or else string is preferred.

14. Server.Transfer

If navigation to a page is necessary in the same application then use Server.Transfer instead of Response.Redirect.

15. Remove Unnecessary modules


ASP.NET has many default Http Modules in its request pipeline, each for doing a specific task.

Example: SessionStateModule intercepts each request, parses the session cookie and then loads the proper session in the context.

There are many modules like FormAuthentication, WindowsAuthentication, Membership And Profile provider and even SessionStateModule which are usually not required. (For instance, if we are not using Windows Authentication then the corresponding module is also not required).

These modules are just sitting in the pipeline, executing some unnecessary code for each and every request.

Now to remove these default modules from your Web application, simply add <remove> nodes in your site's Web.Config.
<httpmodules>
  <remove name=""WindowsAuthentication"" />
  <remove name=""PassportAuthentication"" />
  <remove name=""AnonymousIdentification"" />
  <remove name=""UrlAuthorization"" />
  <remove name=""FileAuthorization"" />
</httpmodules>

16. Ajax

Using Ajax in our applications dramatically increases the performance, as it gets the data without making a complete postback.

There are various mechanisms for performing Ajax calls in ASP.NET like PageMethods, using jqury $.ajax or even ASP.NET update Panel.

PageMethods and $.ajax works faster than UpdatePanel, but you won't be able to access control values when working with those.

17. Clean up resources

Always clean up your resources once it completes its purpose.
(Use proper use of IDisposable interface in you custom business classes.)


18. Choose Generics instead of collections and arrays
  • Arrays - Fixed Size and Type Safe.
  • ArrayList - Dynamic Size but not Type Safe.
  • Generic List - Dynamic Size and Type Safe.
Generics improve performance over Collections as implicit boxing and explicit unboxing are not needed.

19. CSS and JS

Never use inline or internal CSS, use external.

The same applies to JS.

(When we include external CSS/JS in the page it is cached and so won't download on every request. Two birds in a single shot Performance and Management.)

20. Use HTTP Compression

HTTP compression is a feature of IIS and what it means is that you can compress data sent to the client using compression techniques like GZIP and Deflate. On the other side the browser decompresses the data and shows the response to the client. Most modern browsers are capable of handling compressed data. You will certainly get a huge performance boost if your page size is large.

 
Hope you enjoyed reading this article,

I want you guys to share some more tips and thoughts related to performance.

If we share then only we can learn, I really appreciate to see some more good comments.

Sunday, September 16, 2012

How to use the MVC Application?

Use MVC Applciation?


Introduction

This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.

MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.

Inside MVC Architecture

The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?

  1. MVC model is basically a C# or VB.NET class
  2. A model is accessible by both controller and view
  3. A model can be used to pass data from Controller to view
  4. A view can use model to display data in page.

What is a View?

  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method
What is a Controller?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. Controller uses ViewData to pass any data to view

MVC File Structure & File Naming Standards

MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
  • Root [directory]
    • Controller [directory]
      • Controller CS files
    • Models [directory]
      • Model CS files
    • Views [directory]
      • View aspx/ascx files
    • Global.asax
    • Web.config

ASP.NET MVC Execution Life Cycle

Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:

Browser Request (Step 1)

Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/

Job of Global.asax – MVC routing (Step 2)

The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [xyz.com]/home/index/:
  • Controller = home
  • Action = index()
  • ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string

Controller and Action methods (Step 3)

MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.

Call to View (Step 4)

Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.
This is it, the whole process ends here. So this is how MVC architecture works..

All the Best....

Saturday, September 15, 2012

Free Online Tools for Web Design

Free online Tools for Web Designing!!!!

Find the Attachment Link...Enjoy ....

Dot Net Interview!!!!

.Net Interview Prepration????

Give an example of using querystrings to send data from one page to another?
Query strings are a very simple and popular technique to pass data from one Web page to the next. You send data as part of the URL. In the below example FName and LName are sent as part of the URL. In the page load of QueryStrings2.aspx we use Request.QueryString to read the values. As we are sending more than one query string we use the & symbol to seperate query strings.
//Code to send query strings FName and LName as part of the URLQueryStrings2.aspx?FName=David&LName=Boon protected void Page_Load(object sender, EventArgs e)
{
//Code to read Query String values
string FirstName = Request.QueryString["FName"];
string LastName = Request.QueryString["LName"];
Response.Write("Data from QueryStrings1.aspx : " + FirstName + ", " + LastName);



Give an example to send Query Strings from code? 
You can send query strings from server side code using the Response.Redirect() method as shown below.
Response.Redirect("QueryStrings2.aspx?FName=David&LName=Boon");

What are the advantages of using Query Strings?
1.
 Query strings are easy to implement.
2. Browser support for passing values in a query string is nearly universal.
3. Query strings are contained in the HTTP request for a specific URL and do not require server resources.
What are the disadvantages of using querystrings to send data from one page to another?
1.
 Query strings are insecure because the information in the query string is directly visible to the user on the address line in the browser.
2. Many browsers impose a 255 URL character limit which can limit their flexibility.