Wednesday, August 13, 2008

Asp.net Directvies Previouspagetype

As Name suggest PreviousPageType directive is used to access previous page in currently executing page.PreviousPageType is a new directive makes excellence in asp.net 2.0 pages. The concept of cross-page posting between Asp.Net pages is achieved by this directive.

it has 2 Attributes

TagName: Sets the name of the derived class from which the postback will occur.

And

VirutalPath: sets the location of the posting page from which the postback will occur.

Monday, August 11, 2008

Asp.net Directive :Page

Page Directive defines Page specific attributes, which help to get command over customization of .aspx page.

Main Attributes are

Async

Makes page enable for asynchronous handler. Default value is false.

AsyncTimeOut

It defines the time-out (in seconds) used for asynchronous processes. The default time out is 45 seconds.Value must be in integer.

AspCompat

A the page to be executed on a single-threaded apartment (STA) thread. This allows the page to call STA components, such as a component developed with Microsoft Visual Basic 6.0. Setting this attribute to true also allows the page to call COM+ version 1.0 components that require access to unmanaged Active Server Pages (ASP) built-in objects. default is false.

AutoEventWireup

Indicates whether the page's events are autowired. true if event autowiring is enabled; otherwise, false.

ClassName

A string that specifies the name of the page class that will be dynamically compiled when the page is requested.

CodeFile


S
pecifies a path to the referenced code-behind file for the page.

Culture

Indicates the culture setting for the page. The value of this attribute must be a valid culture ID.

Debug
Indicates whether the page should be compiled with debug symbols.

EnableEventValidation

Validate events in postback and callback scenarios. true if events are being validated; otherwise, false. The default is true.

It reduces the risk of unauthorized postback requests and callbacks. When the enableEventValidation property is set to true, ASP.NET allows only the events that can be raised on the control during a postback request or callback.

EnableSessionState

Defines session-state requirements for the page. true if session state is enabled; ReadOnly if session state can be read but not changed; otherwise, false. The default is true.
EnableTheming
Indicates whether themes are used on the page. true if themes are used; otherwise, false. The default is true.

EnableViewState

Indicates whether view state is maintained across page requests. true if view state is maintained; otherwise, false. The default is true.

EnableViewStateMac

Indicates that ASP.NET should run a machine authentication check (MAC) on the page's view state when the page is posted back from the client. true if view state should be MAC checked; otherwise, false. The default is true.
A view-state MAC is an encrypted version of the hidden variable that a page's view state is persisted to when sent to the browser. When you set this attribute to true, the encrypted view state is checked to verify that it has not been tampered with on the client. Note that setting this attribute to true affects performance, because the variable value must be decrypted and encrypted for each round trip of the page.
ErrorPage

Defines a target URL for redirection if an unhandled page exception occurs.

MaintainScrollPositionOnPostback

Maintain user at same position in the client browser after postback. true if users should be returned to the same position; otherwise, false.

SmartNavigation
Indicates whether the page supports the smart navigation feature of Internet Explorer 5.5 or later. true if smart navigation is enabled; otherwise, false. The default is false.
Theme

Specifies a valid theme identifier to use on the page. When the Theme attribute is set without using the StyleSheetTheme attribute, it overrides individual style settings on controls, enabling you to create a unified and consistent look on a page.
Title
Specifies a title for the page which will rendered as a html title tags in the response. The title can also be accessed programmatically as a property of the page.
Transaction

Tells that transactions are supported on the page. Probable values are Disabled, NotSupported, Supported, Required, and RequiresNew. The default is Disabled.

ValidateRequest

This attributes determines request validation should occur. If true, request validation ensure all input data against a hard-coded list of malicious values If a match occurs, an HttpRequestValidationException exception is thrown.
The default is true.
This feature is enabled in the machine configuration file (Machine.config). You can disable it in your application configuration file (Web.config) or on the page by setting this attribute to false.


I hope this will help you.

Source :MSDN,dotnetspider,Forums.asp.net.

Saturday, August 9, 2008

Asp.net Directive :OutputCache

OutputCache as name suggest use to handle caching concept.

It handles/control caching policies for asp.net pages or controls,
users can handle caching programmatically also.

Attributes are

Duration
The time, in seconds, that the page or user control is cached. Setting this attribute on a page or user control establishes an expiration policy for HTTP responses from the object and will automatically cache the page or user control output.
Location:

To specify the location to store the output cache.
To store the output cache on the browser client where the request originated set the value as ‘Client’.
To store the output cache on any HTTP 1.1 cache-capable devices including the proxy servers and the client that made request, specify the Location as Downstream.
To store the output cache on the Web server, mention the location as Server.

VaryByControl: List of strings used to vary the output cache of a user Control, separated with semi-colon.
A semicolon-separated list of strings used to vary a user control's output cache. These strings represent the ID property values of ASP.NET server controls declared in the user control.

VaryByParam: List of strings used to vary the output cache, separated with semi-colon.

A semicolon-separated list of strings used to vary the output cache. By default, these strings correspond to a query string value sent with GET method attributes, or a parameter sent using the POST method. When this attribute is set to multiple parameters, the output cache contains a different version of the requested document for each specified parameter. Possible values include none, *, and any valid query string or POST parameter name.

VaryByCustom:
String of values, specifies the custom output caching requirements.

VaryByHeader: List of HTTP headers used to vary the output cache, separated with semi-colon.
A semicolon-separated list of HTTP headers used to vary the output cache. When this attribute is set to multiple headers, the output cache contains a different version of the requested document for each specified header.

Friday, August 8, 2008

Directives -Master

@Master directive belongs to Master Pages that is .master files.
Master pages are use to mitigate redundant coding & programming.So, Master pages are use to create for integrating common code in all pages such as header footer,navigation , banners which are most common features in any web applications.

This directive
Defines master page–specific (.master file) attributes that are used by the ASP.NET page parser and compiler.

Its Attributes are

AutoEventWireup

To hook up event with control explicitly if it set false else event auto-wiring is enabled; The default is true.

ClassName

Specifies the class name for the class that is automatically generated from the markup and compiled when the master page is processed. This value can be any valid class name and can include a namespace.

CodeFile

Specifies the name of a separate file that contains a partial class with the event handlers and other master page–specific code.

CompilationMode

Specifies whether to compile an ASP.NET master page at run time. Options are Always to always compile the page; Auto, if ASP.NET is to avoid compiling the page, if possible; and Never, to never compile the page or control. The default is Always.

CompilerOptions
Provides a string containing compiler options to use to compile the page. In C# and Microsoft Visual Basic, this is a sequence of compiler command-line switches.

Debug

Indicates whether to compile the master page with debug symbols. true, to compile with debug symbols; otherwise, false.

Description

Provides a text description of the master page. This value is ignored by the ASP.NET parser.

EnableTheming

Indicates whether the appearance of the master page and of controls on the master page can be modified, if a theme is applied. true if a theme can be applied; otherwise, false. The default is true. Setting the EnableTheming attribute is primarily useful when a page theme is defined in the Web.config file and applies to all pages, by default.

EnableViewState

Indicates whether view state is maintained across page requests. true to maintain view state; otherwise, false. The default is true.

Explicit

Determines whether the page is compiled using the Visual Basic Option Explicit mode. true indicates that the Visual Basic explicit compile option is enabled and that all variables must be declared using a Dim, Private, Public, or ReDim statement; otherwise, false. The default is false.

Inherits

Specifies a code-behind class for the page to inherit. This can be any class derived from the MasterPage class.

Language

Specifies the language used when compiling all inline rendering (<% %> and <%= %>) and code declaration blocks within the page. Values can represent any language that is supported by the .NET Framework, including VB (Visual Basic), C#, and JScript.

LinePragmas

Determines whether the runtime should generate pragmas in the generated code.

MasterPageFile

Specifies the .master file that acts as a master page for a master page. The MasterPageFile attribute is used in a master page when defining a child master page in a nested master-page scenario.

Src

Specifies the source file name of the code-behind class to dynamically compile when the page is requested. You can choose to include programming logic for your page either in a code-behind class or in a Code Declaration Blocks in the .aspx file.

Strict

Specifies whether to compile the page using the Visual Basic Option Strict mode. true if Option Strict is enabled; otherwise, false. The default is false.
The Strict attribute is ignored by languages other than Visual Basic.

WarningLevel

It Specifies the compiler warning level at which you want the compiler to abort compilation for the page. Its Possible values are from 0 through 4.

Thursday, July 10, 2008

Assembly Directive

Hi,
Assembly Directive used to link assembly in to our application.
To Make our ASP.NET page aware of external components.
It has following attibutes/property.

a. Name: Enables you specify the name of an assembly you want to attach to the page.
Here you should mention the filename without the extension.
b. Src: represents the name of a source code file
<%@ Assembly Name="YourAssemblyName" %>



Thursday, July 3, 2008

Asp.net Directives

Directives are those things which handles the behavior of Asp.net pages.
We have eleven directives to enrich and nurture our asp.net pages or user control.


Directives are opened <%@ and close with %>
Developers have tendacy to decalre it on top of the page, It does not matter if you declare them at any part of the page.
List of directives in alphabatical order.

Assembly :- Used to link assembly.Control :- For User Control.Implements:- For implement .Net interface.Import:- For Importing Namespace in to page or user control.
Master :- For Using Master page , .Master Page required.MasterType:-Associate a class name to get strongly typed refrences within the specfied master page.
OutputCache:-Controls the Caching Mechanism.
Page:- Allow users to specify a page level attributes,Only can be used with Asp.net Page.
PreviousPageType:-Enables in asp.net Page to handles few things about previous page.
Reference:-Links page or user control to the current page or user control.
Register:-Associate aliase with namespaces and class name for notation in the custom server control.

I will try to explain each useful directive one by one on my forthcoming

posts.......

Saturday, June 28, 2008

Web Hosting and Domain

Hi,
Let me share few information regarding Web hosting and DNS.

Web Host -Means Server where our website resides.This always up and connected to internet to make our web site active.

Shared Hosting:- Most of the host provides Shared Hosting , as it is meaningless to use whole server for small website which does not have very heavy traffic or not a big application.
At that time on a on server more then one website is hosted and manged.shared hosting is widely used , it is very cost effective too.Shared hosting may not provide full access to server(it is depends upon service provider also).

Dedicated Server:- Dedicated Server means only one particuler website or particular user owns a server.Where Owner(Person who purchase Dedicated server from host ,yes your own pc also can be a dedicated server).Owner have full access of server ,freedom of installing new s/w ,uninstall s/w.

DNS:-Domain Name Server
As we all knows on back side web request is made through IPs.
DNS :- Map the IP(where our website hosted) and Domain Name (like www.google.com).
As defination you can say
DNS is the service which translates between Internet names and Internet addresses.
If you are working on a Windows machine, you can view your current IP address with the command WINIPCFG.EXE (IPCONFIG.EXE for Windows 2000/XP). On a UNIX machine, type nslookup along with a machine name (such as "nslookup www.howstuffworks.com") to display the IP address of the machine (use the command hostname to learn the name of your machine).

DNS is such a big thing so it can not be explained in a single post I will add more information about it.


Monday, June 23, 2008

Create Error log in Asp.net2.0

Here I am simplfying error log implementaiton.
To maintain error log its good to have log for each day for a better review .
so here we will create log file everyday , and when file already exist will append error entry in to it.
For that create one class and write following method....
C#
public static void WriteError(string errorMessage)
{
try
{

//Specify path where log file to be created
string logfilePath = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(logfilePath)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(logfilePath)).Close();
}
using (StreamWriter wrtr = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(logfilePath)))
{
wrtr.WriteLine("\r\nLog Entry : ");
wrtr.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + errorMessage;
wrtr.WriteLine(err);
wrtr.WriteLine("__________________________");
wrtr.Flush();
wrtr.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}

Wednesday, June 18, 2008

Caching Concept

Here is the different kind of caching that you can use in your web applications:
· Output Caching
· Fragment Caching
· Data Caching
· Cache Configuration


Output Caching

Performance is improved in an ASP.NET application by caching the rendered markup and serving the cached version of the markup until the cache expires. For example, if you have a page that displays user information from a database, caching will help improve performance by serving the page from memory instead of making a connection to the database on each page request.
You can cache a page by using the OutputCache API or simply by using the @outputcache
directive. <%@ Page Language=”C#” %><%@ OutputCache Duration=”15” VaryByParam=”none” %>
The above cache directive will cache the page for 15 minutes.
So output caching is great for when you want to cache an entire page.

Fragment Caching
In many situations caching the entire page just isn’t going to cut it, for some reason or another you require specific sections of the page to display live information. One way to improve performance is to analyze your page and identify objects that require a substantial overhead to run. You can build a list of these objects that are expensive to run, and then cache them for a period of time using fragment caching.
For example, say your page default.aspx consists of three user controls. After looking over the code, you identified that you can cache one of them. You can simply add the caching directive to the top of the user control: <%@ Control %><%@ OutputCache Duration=”5” VaryByParam=”none” %>
Now keep in mind that the actual page that contains the control is not cached, only the user control. This means that the default.aspx page will be rendered each and every page request, but the user control is only ‘run’ every 15 minutes.


Data Caching
So we know that we can cache an entire page, or a fragment of a page by caching down to the user control level. Wouldn’t it be great if we could cache down to the object level? The good news is you can with ASP.NET Data caching.
The cache consists of a dictionary collection that is private to each application in memory. To insert items in the cache simply provide the collection with a unique name: Cache[“someKey”] = myObject;
Retrieving the object form the cache: myObject = (MyObject)Cache[“someKey”];
It is a good time to point out that you should always remember to check for null, and be sure to caste to your datatype.


Cache Configuration
If you are familiar with how caching worked in ASP.NET 1.0, you realize that managing all the cache directions for all your pages could potentially get out of hand. ASP.NET 2.0 introduces Cache Profiles that helps you centrally manage your cache. Cache settings can be inherited by your pages, and overridden if required by using the OutputCache directive.
The page directive looks pretty much the same, expect this time it references a cache profile that you defined in your web.config file.

So each and every page that references the ‘myCacheProfile1’ can be centrally managed in the web.config, this means that any changes to the cache settings in the web.config file will be automatically changed on all your referenced pages.

Disable auto id’s when copying ASP.NET controls

Don’t you hate it when you copy an ASP.NET server control without an ID, only to have it add one when you paste it?

For example, look at this code:
I took the first line, copied it and pasted it, and got the second line. It’s rare that I need to reference a validator in my CodeBehind.
Here is the option to disable this functionality in the Visual Studio options
(Tools->Options):


Simply uncheck the “Auto ID elements on paste in Source view” option.



Tuesday, June 17, 2008

Date/Time Conversions Using SQL Server

1

select convert(varchar, getdate(), 1)

01/07/08

2

select convert(varchar, getdate(), 2)

08.01.07

3

select convert(varchar, getdate(), 3)

07/01/08

4

select convert(varchar, getdate(), 4)

07.01.08

5

select convert(varchar, getdate(), 5)

07-01-08

6

select convert(varchar, getdate(), 6)

07 Jan 08

7

select convert(varchar, getdate(), 7)

Jan 07, 08

10

select convert(varchar, getdate(), 10)

01-07-08

11

select convert(varchar, getdate(), 11)

08/01/07

101

select convert(varchar, getdate(), 101)

01/07/2008

102

select convert(varchar, getdate(), 102)

2008.01.07

103

select convert(varchar, getdate(), 103)

07/01/2008

104

select convert(varchar, getdate(), 104)

07.01.2008

105

select convert(varchar, getdate(), 105)

07-01-2008

106

select convert(varchar, getdate(), 106)

07 Jan 2008

107

select convert(varchar, getdate(), 107)

Jan 07, 2008

110

select convert(varchar, getdate(), 110)

01-07-2008

111

select convert(varchar, getdate(), 111)

2008/01/07




TIME FORMATS

8 or 108

select convert(varchar, getdate(), 8)

18:12:39

9 or 109

select convert(varchar, getdate(), 9)

Jan 7 2008 6:13:02:140PM

14 or 114

select convert(varchar, getdate(), 14)

18:13:21:093

You can also format the date or time without dividing characters, as well as concatenate the

date and time string:

Sample statement

Output

select replace(convert(varchar, getdate(),101),'/','')

01072008

select replace(convert(varchar, getdate(),101),'/','') + replace(convert(varchar, getdate(),108),':','')

01072008181409

some sql commands

1. Executing a script file from SQLCMD...

i. Create a script file by typing in the following line and save it as Message.sql
print 'Welcome today''s date is: ' + (convert(varchar, getdate()))

ii. Now goto command prompt and type: SQLCMD -i Message.sql
here, -i is the switch to specify the input file name.

2. Executing series of script files (sample)

Lets create couple of .sql files and then see how to execute them in order from command prompt. Please note that i am just showing an example here :) there are better methods of doing the same which I would explain later in the series!

i) Copy paste the below script and name it as 01TableCreation.sql

Create table tblTest
(
Sno int identity,
FName varchar(20)
)
Go

ii) Copy paste the below script and name it as 02InsertRecords.sql
Insert into tblTest (Fname) values ('a')

iii) Copy paste the below two lines and name it as test.bat

sqlcmd -U sa -P hotmail -S VADIVEL -d testbed -i "C:\Vadivel\SQL Related\Scripts\sqlcmd\01TableCreation.sql"
sqlcmd -U sa -P hotmail -S VADIVEL -d testbed -i "C:\Vadivel\SQL Related\Scripts\sqlcmd\02InsertRecords.sql"

here,
-U is SQL User name
-P is SQL Password
-S is the SQL Server name
-d is the SQL database name
-i is the input file to execute

iv) Execute the batch file

Now goto command prompt (Start >> Run >> cmd) and execute this batch file. The batch file would have created a table and inserted a record into it. If you want to deploy some DB scripts on a remote box for which you don't have access from Mgmt Studio you can follow this batch file route. So that the ppl who are having access to that SQL box can just run this batch file (after changing the values of the different switches, if need be)

Setting your default editor:

From my previous posts one can understand that it is possible to write SQL queries directly in command prompt with the help of SQLCMD utility.

Now let's assume we have typed a 'big' query and there is a typo there! Instead of going back and forth to edit it in command prompt won't it be easy if we are able to open the query in an editor and make the corrections there?

Yes its possible in SQLCMD. All we need to do is type ed and it will open up the last command/query in a text editor. FYI the default editor is Edit (the command line editor of MS DOS).

Step 1: Open up SQLCMD and connect to your SQLServer
Step 2: type any query of your choice
Step 3: type ed
Step 4: The query would have opened in the 'EDIT' utility of DOS. Once you are done with the change, save and exit from that.
Step 5: type go and press enter

Can I make 'ed' to open up notepad or any editor of my choice?
Yes it's possible.

Step 1: Open DOS prompt
Step 2: Type set sqlcmdeditor=notepad
Step 3: Open up SQLCMD and connect to your SQLServer
Step 4: type any query of your choice
Step 5: type ed
Step 6: The query would get opened in notepad. Once you are done with the change, save and exit from that.
Step 5: type go and press enter

Persist the Property Values in User Controls after postbacks.

private String strName

public String Name
{
get{return strName;}
set{strName= value;}
}

This
is wrong approach,It will lose your property values. whenever
you want to get the value of Name Property it will never get in
postbacks and you will always get the Null Exception.


Right Way

public String Name
{
get
{
Object obj = ViewState["Name"];
if(obj == null)
{
return null;
}
else
{
return (String)obj;
}
}
set
{
ViewState["Name"] = value;
}
}
You will retain property value of user control during postback too.

.NET Application performance Tips and Tricks

1.Set debug=false under compilation as follows:-

When you create the application, by default this attribute is set to "true" which is very useful while developing. However,when you are deploying your application, always set it to "false"

Setting it to "true" requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.

2. Turn off Tracing unless until required.

Tracing is one of the wonderful features which enable us to track the application's trace and the sequences. However, again it is useful only for developers and you can set this to "false" unless you require to monitor the trace logging.

Before you deploy your application, disable tracing and debugging. Tracing and debugging may cause performance issues. Tracing and debugging are not recommended while your application is running in production. You can disable tracing and debugging in the Machine.config and Web.config.


3. Turn off Session State, if not required.

ASP.NET Manages session state automatically. However, in case you dont require Sessions, disabling it will help in improving the performance.

You may not require seesion state when ur pages r static or whn u dont need to store infor captured in the page.

For doing it in Page wise

<%@ Page EnableSessionState="false" %>

Changes ha to be Done when building .NET Application
----------------------------------------

4. Select the Release mode before making the final Build for your application.

This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

There are several things happening when you Build/Re-Build applications in the Debug Mode. First of all, it creates an additional PDB File under your BIN directory. This holds all the Debug information.

Secondly, the Timeout is very high since you require higher time out frequency while debugging such that your process hangs on until you get to the exact break point where error is there.

So, selecting Release Mode will greatly improve the performance of the application when u deploy.


General Methods to improve the Performance of Web Application
-------------------------------------------------------------

5. Disable ViewState when not required.

6. Avoid Frequent round trips to the Database.
Calls made to Database can be quite expensive in terms of response time as well as resources and it can be avoided by using Batch Processing.

Make calls to Database as mininal as possible and make them last even lesser time. Use of DataAdapter wherever applicable is very useful since, it automatically opens and closes Connection whenever required and doesnt require user to explicitly open the connection.

A number of connections opened and not closed adequately can directly influence in performance slow down.

7. Avoid Throwing Exceptions. It is very expensive.

8. Use Caching to improve the performance of your application.

9. Use appropriate Authentication Mechanism.

The Authentication Mechanism you choose determines the cost associated with it and hence select the appropriate mechanism. An informal but useful order is as follows:-

Authentication Modes
1. None
2. Windows
3. Forms
4. Passport

10. Validate all Input received from the Users.

Use Client Side Validations as much as possible. However, do a check at the Server side too to avoid the infamous
Javascript disabled scenarios.

11. Use Finally Method to kill resources.
In your Try..Catch.. Block, always use the Finally method to close Open connections, Open DataReaders, Files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.

12. The String and Stringbuilder Usage.

If you are initially creating a string say s = "Hello". Then you are appending to it as s = s + " World"; You are actually creating two instances of string in memory. Both the original as well as the new string will be stored in the memory. For that matter, all the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible.

Use StringBuilder which is very useful in these kind of scenarios. For the example above, using a StringBuilder as
s.Append(" World"); which only stores the value in the original string and no additional reference is created.
Eg:

String Action
--------------
string str="";
DateTime startTime = DateTime.Now;
Response.Write(("
Start time:" + startTime.ToString()));
int i;

for(i=0;i<20000;i++)
{
str += i.ToString()+ "
";
}

DateTime EndTime= DateTime.Now;
Response.Write(("
End time:" + EndTime.ToString()));

Out Put:

Start time:9/22/2007 10:23:44 AM
End time:9/22/2007 10:25:08 AM

The above code took 1 minutes and 24 Seconds to complete its operation

String Builder Action
---------------------
StringBuilder strbuilder = new StringBuilder();
DateTime startTime1 = DateTime.Now;
Response.Write(("
Start time:" + startTime1.ToString()));
int i1;

for (i1 = 0; i1 < 20000; i1++)
{
strbuilder.Append(i1 + "
");
}

DateTime EndTime1 = DateTime.Now;
Response.Write(("
End time:" + EndTime1.ToString()));

Out Put:
Start time:9/22/2007 10:25:08 AM
End time:9/22/2007 10:25:09 AM

The above code took 1 Seconds to complete its operation

13. Avoid Recursive Functions / Nested Loops

14. Enable Option Strict and Option Explicit for your pages.

15. Use early binding in Visual Basic or JScript code.

16. Use Response.Write for String concatenation:

Use the HttpResponse.Write method in your pages or user controls for string concatenation.
This method offers buffering and concatenation services that are very efficient. If you are performing
extensive concatenation, however, the technique in the following example, using multiple calls
to Response.Write, is faster than concatenating a string with a single call to the Response.Write method.

Response.Write("a");
Response.Write(myString);
Response.Write("b");
Response.Write(myObj.ToString());
Response.Write("c");
Response.Write(myString2);
Response.Write("d");

17. Avoid unnecessary round trips to the server:
Use Page.IsPostback to avoid extra work on a round trip.

• Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed. I think Scott's article gave great information on how to implement Ajax Atlas and control.

• Use Client Side Scripts. Client site validation can help reduce round trips that are required to process user’s request. In ASP.NET you can also use client side controls to validate user input.
• Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page first time loaded and not in response to client postbacks.

If Not IsPostBack Then
LoadJScripts()
End If
• In some situations performing postback event handling are unnecessary. You can use client callbacks to read data from the server instead of performing a full round trip.


18. Keep IO Buffer Size Between 4KB and 8KB
For nearly every application, a buffer between 4KB and 8KB will give you the maximum performance. For very specific instances, you may be able to get an improvement from a larger buffer (loading large images of a predictable size, for example), but in 99.99% of cases it will only waste memory. All buffers derived from BufferedStream allow you to set the size to anything you want, but in most cases 4 and 8 will give you the best performance

19. Minimize the Use of Format()
When you can, use toString() instead of format(). In most cases, it will provide you with the functionality you need, with much less overhead.

20. Optimize Assignments

Use exp += val instead of exp = exp + val. Since exp can be arbitrarily complex, this can result in lots of unnecessary work. This forces the JIT to evaluate both copies of exp, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the exp twice.

21. Include Return Statements with in the Function

22. Use For Loops for String Iteration

23. Explicitly Dispose or Close all the resources:

Try
_con.Open()
Catch ex As Exception
Throw ex
Finally
If Not _con Is Nothing Then
_con.Close()
End If
End Try

24. Precompiling pages and disabling AutoEventWireup:

By precompiled pages, users do not have to experience the batch compile of your ASP.NET files; it will increase the performance that your users will experience.

Also setting the AutoEventWireup attribute to false in the Machine.config file means that the page will not match method names to events and hook them up (for example, Page_Load). If page developers want to use these events, they will need to override the methods in the base class (for example, they will need to override Page.OnLoad for the page load event instead of using a Page_Load method). If you disable AutoEventWireup, your pages will get a slight performance boost by leaving the event wiring to the page author instead of performing it automatically.

Database
--------
1.Use the Optimal Managed Provider

2.Use Stored Procedures Whenever Possible

3.Use SqlDataReader Instead of Dataset wherevr it is possible

3.Turn Off Features You Don't Use

Turn off automatic transaction enlistment if it's not needed. For the SQL Managed Provider, it's done via the connection string:

SqlConnection conn = new SqlConnection("Server=mysrv01;Integrated Security=true;Enlist=false");

When filling a dataset with the data adapter, don't get primary key information if you don't have to (e.g. don't set MissingSchemaAction.Add with key):

public DataSet SelectSqlSrvRows(DataSet dataset,string connection,string query){
SqlConnection conn = new SqlConnection(connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(dataset);
return dataset;
}

4.Keep Your Datasets Lean
Only put the records you need into the dataset. Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire.

5.Use Connection Pooling and Object Pooling


source: code project

Simple ASP.NET 2.0 Tips and Tricks that You May (or may not) have Heard About

ASP.NET 2.0 is an awesome framework for developing Web applications. If you've worked with it for awhile then that's no secret. It offers some great new features that you can implement with a minimal amount of code. I wanted to start a list of some of the most simple (yet cool) things you could do with it that required little or no C#/VB.NET code. If you have other suggestions add a comment and I'll update the list if the suggestion is a simple task that can be applied easily.

1. Maintain the position of the scrollbar on postbacks: In ASP.NET 1.1 it was a pain to maintain the position of the scrollbar when doing a postback operation. This was especially true when you had a grid on the page and went to edit a specific row. Instead of staying on the desired row, the page would reload and you'd be placed back at the top and have to scroll down. In ASP.NET 2.0 you can simply add the MaintainScrollPostionOnPostBack attribute to the Page directive:

<%@ Page Language="C#" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="..." Inherits="..." %>

2. Set the default focus to a control when the page loads: This is another extremely simple thing that can be done without resorting to writing JavaScript. If you only have a single textbox (or two) on a page why should the user have to click in the textbox to start typing? Shouldn't the cursor already be blinking in the textbox so they can type away? Using the DefaultFocus property of the HtmlForm control you can easily do this.

<form id="frm" DefaultFocus="txtUserName" runat="server">
...
form>

3. Set the default button that is triggered when the user hits the enter key: This was a major pain point in ASP.NET 1.1 and required some JavaScript to be written to ensure that when the user hit the enter key that the appropriate button on the form triggered a "click" event on the server-side. Fortunately, you can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter. This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page.

<form id="frm" DefaultButton="btnSubmit" runat="server">
...
form>

4. Locate nested controls easily: Finding controls within a Page's control hierarchy can be painful but if you know how the controls are nested you can use the lesser known "$" shortcut to find controls without having to write recursive code. If you're looking for a great way to recursively find a control (in cases where you don't know the exact control nesting) check out my good buddy Michael Palermo's blog entry. The following example shows how to use the DefaultFocus property to set the focus on a textbox that is nested inside of a FormView control. Notice that the "$" is used to delimit the nesting:

<form id="form1" runat="server" DefaultFocus="formVw$txtName">
<
div>
<
asp:FormView ID="formVw" runat="server">
<
ItemTemplate>
Name:
<asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />
ItemTemplate>
asp:FormView>
div>
form>

This little trick can also be used on the server-side when calling FindControl(). I blogged about this awhile back if you'd like more details. Here's an example:

TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox;
if
(tb != null)
{
//Access TextBox control
}

5. Strongly-typed access to cross-page postback controls: This one is a little more involved than the others, but quite useful. ASP.NET 2.0 introduced the concept of cross-page postbacks where one page could postback information to a page other than itself. This is done by setting the PostBackUrl property of a button to the name of the page that the button should postback data to. Normally, the posted data can be accessed by doing something like PreviousPage.FindControl("ControlID"). However, this requires a cast if you need to access properties of the target control in the previous page (which you normally need to do). If you add a public property into the code-behind page that initiates the postback operation, you can access the property in a strongly-typed manner by adding the PreviousPageType directive into the target page of the postback. That may sound a little confusing if you haven't done it so let me explain a little more.

If you have a page called Default.aspx that exposes a public property that returns a Textbox that is defined in the page, the page that data is posted to (lets call it SearchResults.aspx) can access that property in a strongly-typed manner (no FindControl() call is necessary) by adding the PreviousPageType directive into the top of the page:

<%@ PreviousPageType VirtualPath="Default.aspx" %>

By adding this directive, the code in SearchResults.aspx can access the TextBox defined in Default.aspx in a strongly-typed manner. The following example assumes the property defined in Default.aspx is named SearchTextBox.

TextBox tb = PreviousPage.SearchTextBox;

This code obviously only works if the previous page is Default.aspx. PreviousPageType also has a TypeName property as well where you could define a base type that one or more pages derive from to make this technique work with multiple pages. You can learn more about PreviousPageType here.

6. Strongly-typed access to Master Pages controls: The PreviousPageType directive isn't the only one that provides strongly-typed access to controls. If you have public properties defined in a Master Page that you'd like to access in a strongly-typed manner you can add the MasterType directive into a page as shown next (note that the MasterType directive also allows a TypeName to be defined as with the PreviousPageType directive):

<%@ MasterType VirtualPath="MasterPage.master" %>

You can then access properties in the target master page from a content page by writing code like the following:

this.Master.HeaderText = "Label updated using MasterType directive with VirtualPath attribute.";

You can find several other tips and tricks related to working with master pages including sharing master pages across IIS virtual directories at a previous blog post I wrote.

7. Validation groups: You may have a page that has multiple controls and multiple buttons. When one of the buttons is clicked you want specific validator controls to be evaluated rather than all of the validators defined on the page. With ASP.NET 1.1 there wasn't a great way to handle this without resorting to some hack code. ASP.NET 2.0 adds a ValidationGroup property to all validator controls and buttons (Button, LinkButton, etc.) that easily solves the problem. If you have a TextBox at the top of a page that has a RequiredFieldValidator next to it and a Button control, you can fire that one validator when the button is clicked by setting the ValidationGroup property on the button and on the RequiredFieldValidator to the same value. Any other validators not in the defined ValidationGroup will be ignored when the button is clicked. Here's an example:

<form id="form1" runat="server">

Search Text:
<asp:TextBox ID="txtSearch" runat="server" />

<
asp:RequiredFieldValidator ID="valSearch" runat="Server"
ControlToValidate
="txtSearch" ValidationGroup="SearchGroup" />

<
asp:Button ID="btnSearch" runat="server" Text="Search"
ValidationGroup
="SearchGroup" />
....
Other controls with validators and buttons defined here
form>

8. Finding control/variable names while typing code: This tip is a bit more related to VS.NET than to ASP.NET directly, but it's definitely helpful for those of you who remember the first few characters of control variable name (or any variable for that matter) but can't remember the complete name. It also gives me the chance to mention two great downloads from Microsoft. First the tip though. After typing the first few characters of a control/variable name, hit CTRL + SPACEBAR and VS.NET will bring up a short list of matching items. Definitely a lot easier than searching for the control/variable definition. Thanks to Darryl for the tip. For those who are interested, Microsoft made all of the VS.NET keyboard shortcuts available in a nice downloadable and printable guide.

That's all for now. There are a lot of other things that could be mentioned and I'll try to keep this post updated. Have a great (simple) ASP.NET 2.0 tip or trick? Post the details in the comments and I'll add it if the content is appropriate for the list. Make sure to list your name so I can give proper credit.