Sunday, May 6, 2012
Windows 8 metro XAML - VariableSizedWrapGrid
VariableSizedWrapGrid for metro apps provides a grid-style layout panel where each tile/cell can be variable size based on content.If your first item is a big item and the subsequent items are small, then you will see that all the subsequent items are shown at the same size. If your first item is small and one/all subsequent items are bigger than the first item, then the subsequent items are clipped to the size of the first item. This is the behaviour of VSWG. You will need to use rowspan and colspan properties to achieve the variable size effect you want. Also you may need to set ItemHeight and ItemWidth properties.
Here is the reason why?
VSWG allows for variable sized items but the item sizes allowed are in multiples of the base cell size. The size of the layout cell is determined by ItemHeight and ItemWidth properties. If these properties are not set, then the item is measured in integral multiplication of the cell size based on RowSpan and ColumnSpan properties.
Features that are not supported yet in VSWG:
1. You can not reorder items in a gridview with a variablesizedwrapgrid. It would be nice if microsoft implements this.
2. You can not change the size of an item once it is set.
Tuesday, February 21, 2012
How to improve Performance of applications
Here is the list of things I have done to improve performance
1. Use Javascript/JQuery when postbacks are not necessary to update portions of page.
2. Use Client Side Validation to save round trips. This way you do not post back the data unless all the controls pass the required validation criteria.
3. Use Page Methods if updating just a small piece of information.
4. Consider Table Partioning if the tables have grown enormously.
5. Consider Indexing on appropriate columns.
6. Return just the necessary data to the application. (Avoid using Select *)
7. If you have large query result, consider paginating data with Sql Server Row_Number() method.
8. Write your stored procedures WITH RECOMPILE option if you are writing a search page that allows its users to search by any of several columns.
9. Enable HTTP Compression.
I am looking forward to try HTTP Compression soon. Here is an article that details how to do this. http://madskristensen.net/post/Performance-tuning-tricks-for-ASPNET-and-IIS-7-part-1.aspx
1. Use Javascript/JQuery when postbacks are not necessary to update portions of page.
2. Use Client Side Validation to save round trips. This way you do not post back the data unless all the controls pass the required validation criteria.
3. Use Page Methods if updating just a small piece of information.
4. Consider Table Partioning if the tables have grown enormously.
5. Consider Indexing on appropriate columns.
6. Return just the necessary data to the application. (Avoid using Select *)
7. If you have large query result, consider paginating data with Sql Server Row_Number() method.
8. Write your stored procedures WITH RECOMPILE option if you are writing a search page that allows its users to search by any of several columns.
9. Enable HTTP Compression.
I am looking forward to try HTTP Compression soon. Here is an article that details how to do this. http://madskristensen.net/post/Performance-tuning-tricks-for-ASPNET-and-IIS-7-part-1.aspx
Tuesday, January 31, 2012
PageRequestManagerParserErrorException when using Ajax UpdatePanel
Sys.WebForms.PageRequestManagerParserErrorException:The message received from the server could not be parsed.
Common causes for this error are when the response is modified by calls to response.Write(), response filters, HttpModules, or server trace is enabled.
Well, why do these cause the exception?
The updatepanel uses asynchronous postbacks. Asynchronous postbacks have the same life cycle and go through the same life cycle events as regular postbacks except for the rendering phase. Only the content that goes in the update panel is captured and sent to the client after combining the content with other pieces of information like page title, hidden form values, form action url and lists of scripts. The content is rendered out using a special format that the JavaScript on the client can understand. If you mess with the format by rendering things outside of the render phase of the page, by using Response.Write(), the client ends up receiving a blob of data that it can't parse, so it gives up and shows you a PageRequestManagerParserErrorException.
How to get around this exception and get the results you need?
If you can avoid writing code, that causes this exception, that is the route to take.
But, sometimes for example you may absolutely have to use Response.Write() because you want to open an active report in PDF format on a button click or you want to download a file. The solution then is to do a regular postback instead of an asynchronous postback.
There are a number of ways of doing this:
The easiest is to simply place the button outside of any UpdatePanels. Unfortunately the layout of your page might not allow for this.
Add a PostBackTrigger to your UpdatePanel that points at the button. This works great if the button is declared statically through markup on the page.
Call ScriptManager.RegisterPostBackControl() and pass in the button in question. This is the best solution for controls that are added dynamically, such as those inside a repeating template or for those control inside a user control.
Here is example code you can add in your page_Load event
ScriptManager sm = (ScriptManager)Page.Master.FindControl("ToolkitScriptManager1");
sm.RegisterPostBackControl(GeneratePDFReportButton);
Common causes for this error are when the response is modified by calls to response.Write(), response filters, HttpModules, or server trace is enabled.
Well, why do these cause the exception?
The updatepanel uses asynchronous postbacks. Asynchronous postbacks have the same life cycle and go through the same life cycle events as regular postbacks except for the rendering phase. Only the content that goes in the update panel is captured and sent to the client after combining the content with other pieces of information like page title, hidden form values, form action url and lists of scripts. The content is rendered out using a special format that the JavaScript on the client can understand. If you mess with the format by rendering things outside of the render phase of the page, by using Response.Write(), the client ends up receiving a blob of data that it can't parse, so it gives up and shows you a PageRequestManagerParserErrorException.
How to get around this exception and get the results you need?
If you can avoid writing code, that causes this exception, that is the route to take.
But, sometimes for example you may absolutely have to use Response.Write() because you want to open an active report in PDF format on a button click or you want to download a file. The solution then is to do a regular postback instead of an asynchronous postback.
There are a number of ways of doing this:
The easiest is to simply place the button outside of any UpdatePanels. Unfortunately the layout of your page might not allow for this.
Add a PostBackTrigger to your UpdatePanel that points at the button. This works great if the button is declared statically through markup on the page.
Call ScriptManager.RegisterPostBackControl() and pass in the button in question. This is the best solution for controls that are added dynamically, such as those inside a repeating template or for those control inside a user control.
Here is example code you can add in your page_Load event
ScriptManager sm = (ScriptManager)Page.Master.FindControl("ToolkitScriptManager1");
sm.RegisterPostBackControl(GeneratePDFReportButton);
Tuesday, January 17, 2012
Exception Handling in ASP.Net
In my experience, I have seen developers use variety of techniques for handling exceptions. Some developers surround each and every block of code with a Try...Catch. Some developers let them bubble up and handle them in the Main method for windows applications or handle them at the application level in the Application_Error method of the Global.asax file or handle them at the page level in the Page_Error method of the .aspx file for Web applications.
My take on Exception handling is that all exceptions should be logged no matter where you catch them. You could log them to the event log, database or file.
There are three general cases when Try...Catch blocks make sense:
1. When there is an opportunity to recover from the application by taking some alternative course of action. For Example: If an SMTP server fails, you may want to connect to a back up SMTP server.
2. When an exception indicates a problem that should not impede the current flow, log the exception and swallow the exception. For Example: If an email notification fails after an order is processed, you may just want to log the error and proceed.
3. When additional information needs to be included with the exception. In this case it is useful to catch the exception and re throw a new exception with the original exception as an inner exception.
There are Error Logging and notification libraries you could use like ELMAH.
Below is the example code on how to handle errors in Application_Error event of Global.asax file:
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
if (ctx == null) return;
Exception exception = ctx.Server.GetLastError();
if (exception.InnerException != null)
{
EventLog MyLog = new EventLog();
MyLog.Source = e.Source;
MyLog.WriteEntry(e.Message + " " + e.StackTrace);
Response.Redirect("error.html");
}
}
My take on Exception handling is that all exceptions should be logged no matter where you catch them. You could log them to the event log, database or file.
There are three general cases when Try...Catch blocks make sense:
1. When there is an opportunity to recover from the application by taking some alternative course of action. For Example: If an SMTP server fails, you may want to connect to a back up SMTP server.
2. When an exception indicates a problem that should not impede the current flow, log the exception and swallow the exception. For Example: If an email notification fails after an order is processed, you may just want to log the error and proceed.
3. When additional information needs to be included with the exception. In this case it is useful to catch the exception and re throw a new exception with the original exception as an inner exception.
There are Error Logging and notification libraries you could use like ELMAH.
Below is the example code on how to handle errors in Application_Error event of Global.asax file:
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
if (ctx == null) return;
Exception exception = ctx.Server.GetLastError();
if (exception.InnerException != null)
{
EventLog MyLog = new EventLog();
MyLog.Source = e.Source;
MyLog.WriteEntry(e.Message + " " + e.StackTrace);
Response.Redirect("error.html");
}
}
Thursday, January 12, 2012
Exporting long strings to Excel format using Active Reports.
When you are pulling a huge text field data from the database, Active Reports breaks the text into multiple rows. Sorting the excel sheet columns will be a problem with the way active report generates the Exel report. Below is the code to change the default behavior of the excel format Active Report. All you will need to do is explicitly set wordwrap on the controls to false. Here, I am looping to find all the controls and setting the word wrap on each control to false.
// To fix excel reports from displaying single cell data in multiple rows
if (IsXls == true)
{
Section Hsec = this.Sections["pageHeader"];
for (int i = 0; i < Hsec.Controls.Count; i++)
{
if ((Hsec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.Label")
{
((Label)(Hsec.Controls[i])).WordWrap = false;
}
}
Section sec = this.Sections["detail"];
for (int i = 0; i < sec.Controls.Count; i++)
{
if ((sec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.TextBox")
{
((TextBox)(sec.Controls[i])).WordWrap = false;
}
}
}
// To fix excel reports from displaying single cell data in multiple rows
if (IsXls == true)
{
Section Hsec = this.Sections["pageHeader"];
for (int i = 0; i < Hsec.Controls.Count; i++)
{
if ((Hsec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.Label")
{
((Label)(Hsec.Controls[i])).WordWrap = false;
}
}
Section sec = this.Sections["detail"];
for (int i = 0; i < sec.Controls.Count; i++)
{
if ((sec.Controls[i].GetType()).ToString() == "DataDynamics.ActiveReports.TextBox")
{
((TextBox)(sec.Controls[i])).WordWrap = false;
}
}
}
Tuesday, January 10, 2012
Java vs CSharp
I started reading a book on Java - 'Java How to Program' to learn and possibly start working with it. As I read, it is so similar to C#. There are just a very few subtle differences.
Static Import: A static import declaration in java enables you to import the static members of a class or interface so you can access them via their unqualified names in your class. The class name and a dot (.) are not required to use an imported static member.
Syntax:
import static packageName.ClassName.staticMemberName; to import a particular static member.
import static packageName.ClassName.*; to import all static members of the specified class
Example:
// Static import of Math class methods.
public class StaticImportTest
{
public static void main( String[] args )
{
System.out.printf( "sqrt( 900.0 ) = %.1f\n", );
System.out.printf( "ceil( -9.8 ) = %.1f\n", );
System.out.printf( "E = %f\n", E );
System.out.printf( "PI = %f\n", PI );
} // end main
}
Final Modifier: Final Modifier in Java is same as readonly in C#. final modifier in Java and readonly modifier in C# can be initialized when they're declared. If they are not, they must be initialized in every constructor of the class. Initializing constants in constructors enables each object of the class to have a different value for constant.
package: package in java is same as namespace in C#.
Import: Import in Java is same as Using in C#.
Java source code file has the following order
1. a package declaration (if any)
2. import declarations (if any), then
3. class declarations
Only one of the class declarations in a particular file can be public.
C# source code file has the following order
1. using declarations (if any)
2. namespace declaration (if any)
3. class declarations
Any number of class declarations in a particular file can be public.
Access modifiers :In Java, if no access modifier (public, protected or private) is specified for a method or variable when it’s declared in a class, the method or variable is considered to have package access. If a class has no access modifier, then it can only be accessed from same package.
In C#, if no access modifier is specified, the default accessibility of class members (including methods) is private. If no access modifier is specified for a class, The default accessibility of a class itself is internal.
Super: To call a base class method in Java, Super followed by dot is used. In C# base followed by dot is used.
Extends:In java to extend from a base class, keyword 'extends' is used. In C# : is used.
Java example:
public class CommissionEmployee extends Object
{
...
}
@Override: To override a super class method in Java, '@Override' is used.
In C# 'override' is used.
Also in .Net, The overridden base method/property must be virtual, abstract, or override. Both the override method/property and the overridden method/property must have the same access level modifier. When a class contains an abstract method, that class must be declared as abstract. classes that derive from that abstract class, must provide an implementation for this abstract method. A class can have a virtual method. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.
Java example:
@Override // indicates that this method overrides a superclass method
public String toString()
{
...
} // end
Class Object:All classes in Java inherit directly or indirectly from the Object class (package java.lang), so its 11 methods (some are overloaded) are inherited by all other classes - clone, equals, finalize, getClass, hashCode, wait, notify, notifyAll, toString.
Inheritence: In C#, To call a base class constructor from the derived class constructor, you should use ": base class name ( args)"
Csharp Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test : supertest
{
public test(int x): base(x){ }
}
In Java, you simply write super(args...); as the first line in the child class constructor to call the base class constructor
Java Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test extends supertest
{
public test(int x) { super(x); }
}
instanceof: Java's "instanceof" keyword equivalent in csharp is "is"
Java example:
if ( currentEmployee instanceof BasePlusCommissionEmployee )
{
}
C# example:
if ( currentEmployee is BasePlusCommissionEmployee )
{
}
Inteface: Interface in C# cannot contain fields.
In Java, Interface can contain fields and are implicitly public, static and final. All methods declared in an interface are implicitly public abstract methods. Interface methods in java are always public abstract, so they do not need to be declared as such. You will not have any compile errors by declaring methods in the interface public abstract.
In C#, you will have compile errors if you declare methods with any modifiers.
Implementing an interface: To implement an interface in java implements keyword is used. In C# ":" is used.
In Java, When a class implements from an interface, the class should override the methods defined in the interface using the keyword @override.
In C#, you do not override the method in the class implementing the interface.
Java example:
public interface Payable
{
double getPaymentAmount(); // You can declare public abstract double getPaymentAmount()
}
public class Invoice implements Payable
{
@Override
public double getPaymentAmount()
{
return getQuantity() * getPricePerItem(); // calculate total cost
} //
}
C# example:
public interface supertest
{
void printhello(string str); // You will have compile errors if you use public abstract void printhello(string str)
}
public class test : supertest
{
public void printhello(string str)
{
Console.WriteLine("hello Dear " + str);
}
}
In Java, when a class implements an interface, it makes a contract with the compiler stating either that the class will implement each of the methods in the interface or that the class will be declared abstract. So if you declare the class abstract, you do not have to implement the methods in the interface.
In C#, if the derived class does not implement the methods in the interface, you will have compile errors. If you want to declare the class that implements the interface abstract, you would have to still declare the methods you do not want to implement abstract inside the class.
Exception Handling: In Java exceptions are two types: 1. checked 2. unchecked. Java compiler enforces a catch-or-declare requirement for checked exceptions. All exception types that are direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in your program’s code. All classes that inherit from class Exception but not class RuntimeException are considered to be checked exceptions. Such exceptions are typically caused by conditions that are not under the control of the program— for example, in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked.
Another feature Java provides is Preconditions and Postconditions - A precondition must be true when a method is invoked. A postcondition is true after the method successfully returns. Typically, a method’s preconditions and postconditions are described as part of its specification. When designing your own methods, you should state the preconditions and
postconditions in a comment before the method declaration.
To catch multiple exceptions in java, operation '|' is used. The code is simple.
Java Example:
catch ( Type1 | Type2 | Type3 e )
A little more code should be written in C# to do the same.
C# Example:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}
(To be Continued...)
Static Import: A static import declaration in java enables you to import the static members of a class or interface so you can access them via their unqualified names in your class. The class name and a dot (.) are not required to use an imported static member.
Syntax:
import static packageName.ClassName.staticMemberName; to import a particular static member.
import static packageName.ClassName.*; to import all static members of the specified class
Example:
// Static import of Math class methods.
public class StaticImportTest
{
public static void main( String[] args )
{
System.out.printf( "sqrt( 900.0 ) = %.1f\n", );
System.out.printf( "ceil( -9.8 ) = %.1f\n", );
System.out.printf( "E = %f\n", E );
System.out.printf( "PI = %f\n", PI );
} // end main
}
Final Modifier: Final Modifier in Java is same as readonly in C#. final modifier in Java and readonly modifier in C# can be initialized when they're declared. If they are not, they must be initialized in every constructor of the class. Initializing constants in constructors enables each object of the class to have a different value for constant.
package: package in java is same as namespace in C#.
Import: Import in Java is same as Using in C#.
Java source code file has the following order
1. a package declaration (if any)
2. import declarations (if any), then
3. class declarations
Only one of the class declarations in a particular file can be public.
C# source code file has the following order
1. using declarations (if any)
2. namespace declaration (if any)
3. class declarations
Any number of class declarations in a particular file can be public.
Access modifiers :In Java, if no access modifier (public, protected or private) is specified for a method or variable when it’s declared in a class, the method or variable is considered to have package access. If a class has no access modifier, then it can only be accessed from same package.
In C#, if no access modifier is specified, the default accessibility of class members (including methods) is private. If no access modifier is specified for a class, The default accessibility of a class itself is internal.
Super: To call a base class method in Java, Super followed by dot is used. In C# base followed by dot is used.
Extends:In java to extend from a base class, keyword 'extends' is used. In C# : is used.
Java example:
public class CommissionEmployee extends Object
{
...
}
@Override: To override a super class method in Java, '@Override' is used.
In C# 'override' is used.
Also in .Net, The overridden base method/property must be virtual, abstract, or override. Both the override method/property and the overridden method/property must have the same access level modifier. When a class contains an abstract method, that class must be declared as abstract. classes that derive from that abstract class, must provide an implementation for this abstract method. A class can have a virtual method. When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.
Java example:
@Override // indicates that this method overrides a superclass method
public String toString()
{
...
} // end
Class Object:All classes in Java inherit directly or indirectly from the Object class (package java.lang), so its 11 methods (some are overloaded) are inherited by all other classes - clone, equals, finalize, getClass, hashCode, wait, notify, notifyAll, toString.
Inheritence: In C#, To call a base class constructor from the derived class constructor, you should use ": base class name ( args)"
Csharp Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test : supertest
{
public test(int x): base(x){ }
}
In Java, you simply write super(args...); as the first line in the child class constructor to call the base class constructor
Java Example:
public abstract class supertest
{
private int x;
public supertest(int x)
{
this.x = x;
}
}
public class test extends supertest
{
public test(int x) { super(x); }
}
instanceof: Java's "instanceof" keyword equivalent in csharp is "is"
Java example:
if ( currentEmployee instanceof BasePlusCommissionEmployee )
{
}
C# example:
if ( currentEmployee is BasePlusCommissionEmployee )
{
}
Inteface: Interface in C# cannot contain fields.
In Java, Interface can contain fields and are implicitly public, static and final. All methods declared in an interface are implicitly public abstract methods. Interface methods in java are always public abstract, so they do not need to be declared as such. You will not have any compile errors by declaring methods in the interface public abstract.
In C#, you will have compile errors if you declare methods with any modifiers.
Implementing an interface: To implement an interface in java implements keyword is used. In C# ":" is used.
In Java, When a class implements from an interface, the class should override the methods defined in the interface using the keyword @override.
In C#, you do not override the method in the class implementing the interface.
Java example:
public interface Payable
{
double getPaymentAmount(); // You can declare public abstract double getPaymentAmount()
}
public class Invoice implements Payable
{
@Override
public double getPaymentAmount()
{
return getQuantity() * getPricePerItem(); // calculate total cost
} //
}
C# example:
public interface supertest
{
void printhello(string str); // You will have compile errors if you use public abstract void printhello(string str)
}
public class test : supertest
{
public void printhello(string str)
{
Console.WriteLine("hello Dear " + str);
}
}
In Java, when a class implements an interface, it makes a contract with the compiler stating either that the class will implement each of the methods in the interface or that the class will be declared abstract. So if you declare the class abstract, you do not have to implement the methods in the interface.
In C#, if the derived class does not implement the methods in the interface, you will have compile errors. If you want to declare the class that implements the interface abstract, you would have to still declare the methods you do not want to implement abstract inside the class.
Exception Handling: In Java exceptions are two types: 1. checked 2. unchecked. Java compiler enforces a catch-or-declare requirement for checked exceptions. All exception types that are direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in your program’s code. All classes that inherit from class Exception but not class RuntimeException are considered to be checked exceptions. Such exceptions are typically caused by conditions that are not under the control of the program— for example, in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked.
Another feature Java provides is Preconditions and Postconditions - A precondition must be true when a method is invoked. A postcondition is true after the method successfully returns. Typically, a method’s preconditions and postconditions are described as part of its specification. When designing your own methods, you should state the preconditions and
postconditions in a comment before the method declaration.
To catch multiple exceptions in java, operation '|' is used. The code is simple.
Java Example:
catch ( Type1 | Type2 | Type3 e )
A little more code should be written in C# to do the same.
C# Example:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}
(To be Continued...)
Wednesday, December 21, 2011
How to call Server Side function from Client Side Code
You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds.
1. Use __doPostBack() and IPostBackEventHandler.
2. Set hidden variables and sumbit the form using form.submit()
3. Use PageMethods in ASP.net AJAX.
PageMethods can possibly save you a large amount of bandwidth which can mean faster response times for visitors on slower connections. Instead of posting all of the form values, we can send only what is needed. Instead of returning a large chunk of data, we can return precisely what we need to display to the user. For performance and bandwidth sensitive situations, they may be the right tool. So use PageMethods where possible instead of UpdatePanel as UpdatePanel posts all of the page's form values when all you might need to pass to the server is very little information. Using PageMethods you can save bandwidth.
Here is a link to learn how to use PageMethods: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109
1. Use __doPostBack() and IPostBackEventHandler.
2. Set hidden variables and sumbit the form using form.submit()
3. Use PageMethods in ASP.net AJAX.
PageMethods can possibly save you a large amount of bandwidth which can mean faster response times for visitors on slower connections. Instead of posting all of the form values, we can send only what is needed. Instead of returning a large chunk of data, we can return precisely what we need to display to the user. For performance and bandwidth sensitive situations, they may be the right tool. So use PageMethods where possible instead of UpdatePanel as UpdatePanel posts all of the page's form values when all you might need to pass to the server is very little information. Using PageMethods you can save bandwidth.
Here is a link to learn how to use PageMethods: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109
Tuesday, December 20, 2011
Disable a button during postback
You may want to disable a button during postback to stop user from clicking the button before the results are returned. You could do this on the client side using the OnClientClick attribute. The problem with disabling a submit button on the client side is that it will cancel the browser's submit, and thus the postback. Hence your server side event (BtnSumbit_Click) will not trigger.
asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
OnClick="BtnSubmit_Click"
Text="Submit Me!"
The trick is to set the UseSubmitBehavior property to false. This tells .Net to inject the necessary client script to fire the postback anyway, instead of relying on the browser's form submission behavior.
asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!"
This property will inject __doPostBack giving us this rendered HTML:
input type="button" name="BtnSubmit"
onclick="this.disabled = true; this.value = 'Submitting...';__doPostBack('BtnSubmit','')"
asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
OnClick="BtnSubmit_Click"
Text="Submit Me!"
The trick is to set the UseSubmitBehavior property to false. This tells .Net to inject the necessary client script to fire the postback anyway, instead of relying on the browser's form submission behavior.
asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!"
This property will inject __doPostBack giving us this rendered HTML:
input type="button" name="BtnSubmit"
onclick="this.disabled = true; this.value = 'Submitting...';__doPostBack('BtnSubmit','')"
Friday, July 1, 2011
How to determine the row size of all tables
A quick google brought me the below SQL and I been using this sql a lot.
SELECT OBJECT_NAME (sc.[id]) tablename
, COUNT (1) nr_columns
, SUM (sc.length) maxrowlength
FROM syscolumns sc
join sysobjects so
on sc.[id] = so.[id]
WHERE so.xtype = 'U'
GROUP BY OBJECT_NAME (sc.[id])
ORDER BY SUM (sc.length) desc
SELECT OBJECT_NAME (sc.[id]) tablename
, COUNT (1) nr_columns
, SUM (sc.length) maxrowlength
FROM syscolumns sc
join sysobjects so
on sc.[id] = so.[id]
WHERE so.xtype = 'U'
GROUP BY OBJECT_NAME (sc.[id])
ORDER BY SUM (sc.length) desc
Wednesday, May 11, 2011
Comparing two database tables for equality
Binary_Checksum can be used to compare two tables for equality.
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) from dbo.[Table1]
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) from dbo.[Table2]
But there are some concerns about the algorithm that it might not always be unique
Example:
select binary_checksum('A') ,binary_checksum('AAAAAAAAAAAAAAAAA')
The out put is 65 and 65
select binary_checksum('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA A') ,binary_checksum('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAA')
The out put is 577 and 577.
So the other way to compare two tables cell by cell would be to write a query like this
SELECT COUNT(*) as cnt, MIN(ViewName) as TableName, col1, col2, ...
FROM
(
SELECT '[DataBase1].dbo.[TableName or ViewName goes here]' as ViewName,
*
FROM [DataBase1].dbo.[TableName or ViewName goes here] A
UNION ALL
SELECT '[DataBase2].dbo.[TableName or ViewName goes here]' as ViewName,
*
FROM [DataBase2].dbo.[TableName or ViewName goes here] B
) tmp
GROUP BY ALL col1, col2, ...
HAVING COUNT(*)%2 <> 0
UNION concatenates two tables
GROUP BY groups the records by comparing cell to cell of all the columns listed and merges all the matching rows as a single row with COUNT(*) displaying the number of matching rows that have been merged.
If there is a row in View1/Table1 that matches the row in View2/Table2, then COUNT returns an even number (after the entire cell by cell comparison is performed by group by).
If there are any rows in View1/Table1 and View2/Table2 that do match each other, then after the merge performed by GROUP BY, COUNT(*) returns an odd number.
COUNT(*) is an even number when all the data cells in view1 match to view2 and when divided by 2 the reminder is 0. If any rows do not match exactly cell by cell, COUNT(*) is an odd number and when divided by 2 has a reminder.
Hence
HAVING COUNT(*)%2 <> 0
Returns all the mismatched rows. The query does not return any results if View1 and View2 match.
To get the list of columns if you are comparing views run this script:
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + c.name FROM sys.columns c, sys.views v
WHERE c.object_id = v.object_id
AND v.name = 'View Name here'
Print @Names
The out put is 577 and 577.
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) from dbo.[Table1]
SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) from dbo.[Table2]
But there are some concerns about the algorithm that it might not always be unique
Example:
select binary_checksum('A') ,binary_checksum('AAAAAAAAAAAAAAAAA')
The out put is 65 and 65
select binary_checksum('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA A') ,binary_checksum('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAA')
The out put is 577 and 577.
So the other way to compare two tables cell by cell would be to write a query like this
SELECT COUNT(*) as cnt, MIN(ViewName) as TableName, col1, col2, ...
FROM
(
SELECT '[DataBase1].dbo.[TableName or ViewName goes here]' as ViewName,
*
FROM [DataBase1].dbo.[TableName or ViewName goes here] A
UNION ALL
SELECT '[DataBase2].dbo.[TableName or ViewName goes here]' as ViewName,
*
FROM [DataBase2].dbo.[TableName or ViewName goes here] B
) tmp
GROUP BY ALL col1, col2, ...
HAVING COUNT(*)%2 <> 0
UNION concatenates two tables
GROUP BY groups the records by comparing cell to cell of all the columns listed and merges all the matching rows as a single row with COUNT(*) displaying the number of matching rows that have been merged.
If there is a row in View1/Table1 that matches the row in View2/Table2, then COUNT returns an even number (after the entire cell by cell comparison is performed by group by).
If there are any rows in View1/Table1 and View2/Table2 that do match each other, then after the merge performed by GROUP BY, COUNT(*) returns an odd number.
COUNT(*) is an even number when all the data cells in view1 match to view2 and when divided by 2 the reminder is 0. If any rows do not match exactly cell by cell, COUNT(*) is an odd number and when divided by 2 has a reminder.
Hence
HAVING COUNT(*)%2 <> 0
Returns all the mismatched rows. The query does not return any results if View1 and View2 match.
To get the list of columns if you are comparing views run this script:
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ', ', '') + c.name FROM sys.columns c, sys.views v
WHERE c.object_id = v.object_id
AND v.name = 'View Name here'
Print @Names
The out put is 577 and 577.
Tuesday, May 10, 2011
Caching using SqlCacheDependency class with command notification
Caching is very simple when caching a table
SqlCacheDependency dep = new SqlCacheDependency("Connection String", "dbo.tablename")
but when caching a sql command I had to struggle and it just did not work until I read this article and changed my query to not have any of these mentioned in the below article. The reason to cache a sql command instead of table was that I had to join more than two tables.
The reasons why cache was not working for me was I was doing two things that I am not supposed to do for the notifications to work.
1. My table names did not have two-part names like in dbo.tablename
It also means that all tables referenced in the statement must be in the same database.
2. I was using 'DISTINCT'. One of the many keywords Query notification does not support.
For full list of requirements for the Query notification to work, read the following article.
http://msdn.microsoft.com/en-us/library/aewzkxxh%28VS.80%29.aspx
Same rules apply if you want to Cache data from a stored procedure. The reason I like to use SqlCacheDependency class is because it uses the notification mechanism instead of polling.
object o = HttpContext.Current.Cache["MITES"];
if (o == null)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand ("GetMites",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
dtMites = new DataTable("dtMites");
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
SqlCacheDependency dep = new SqlCacheDependency(cmd);
da.Fill(dtMites);
// This is just test code to make sure cache is really working
/* DataRow row = dtMites.NewRow();
row[0] = "Retreived from database";
dtMites.Rows.Add(row);
*/
// The data returned has duplicates. dtMites.DefaultView.ToTable(true, "Table1")
// retrieves distinct rows from the datatable
HttpContext.Current.Cache.Add("MITES", dtMites.DefaultView.ToTable(true, "Table1"), dep,
Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1),
CacheItemPriority.Default, null);
return (DataTable)HttpContext.Current.Cache["MITES"];
}
}
}
}
else
{
// This is just test code to make sure cache is really working
/* dtMites = (DataTable)o;
DataRow row = dtMites.NewRow();
row[0] = "Retreived from Cache";
dtMites.Rows.Add(row);
return dtMites;
*/
return (DataTable)o;
}
You need to add some tags to the web.config file for this to work
<system.web>
<caching>
<sqlcachedependency enabled = "true" pollTime = "60000" >
<databases>
<add name="Connection String"
connectionStringName="Connection String"
pollTime="9000000"
/>
</databases>
</sqlCacheDependency>
</caching>
You will also need to add this to Application_Start method in Global.asax.cs file
protected void Application_Start(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings["Connection String"].ConnectionString);
// Code that runs on application startup
}
on the database server run this command
Aspnet_regsql -S ServerName -U username -P Password -d DatabaseName -ed
Using Sql management studio run this script on the database
Run the script
DECLARE @SQL nvarchar(max)
BEGIN TRY
SET @SQL = 'ALTER DATABASE' + DatBaseName + 'SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE '
PRINT @SQL
EXEC sp_executesql @SQL
END TRY
BEGIN CATCH
SET @SQL = 'ALTER DATABASE' + DatBaseName + 'SET NEW_BROKER WITH ROLLBACK IMMEDIATE '
PRINT @SQL
EXEC sp_executesql @SQL
END CATCH
GO
If the script is taking too long to run, restart the Database server instance by opening Control Panel > Administrative Tools > Services >
SqlCacheDependency dep = new SqlCacheDependency("Connection String", "dbo.tablename")
but when caching a sql command I had to struggle and it just did not work until I read this article and changed my query to not have any of these mentioned in the below article. The reason to cache a sql command instead of table was that I had to join more than two tables.
The reasons why cache was not working for me was I was doing two things that I am not supposed to do for the notifications to work.
1. My table names did not have two-part names like in dbo.tablename
It also means that all tables referenced in the statement must be in the same database.
2. I was using 'DISTINCT'. One of the many keywords Query notification does not support.
For full list of requirements for the Query notification to work, read the following article.
http://msdn.microsoft.com/en-us/library/aewzkxxh%28VS.80%29.aspx
Same rules apply if you want to Cache data from a stored procedure. The reason I like to use SqlCacheDependency class is because it uses the notification mechanism instead of polling.
object o = HttpContext.Current.Cache["MITES"];
if (o == null)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand ("GetMites",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
dtMites = new DataTable("dtMites");
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
SqlCacheDependency dep = new SqlCacheDependency(cmd);
da.Fill(dtMites);
// This is just test code to make sure cache is really working
/* DataRow row = dtMites.NewRow();
row[0] = "Retreived from database";
dtMites.Rows.Add(row);
*/
// The data returned has duplicates. dtMites.DefaultView.ToTable(true, "Table1")
// retrieves distinct rows from the datatable
HttpContext.Current.Cache.Add("MITES", dtMites.DefaultView.ToTable(true, "Table1"), dep,
Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1),
CacheItemPriority.Default, null);
return (DataTable)HttpContext.Current.Cache["MITES"];
}
}
}
}
else
{
// This is just test code to make sure cache is really working
/* dtMites = (DataTable)o;
DataRow row = dtMites.NewRow();
row[0] = "Retreived from Cache";
dtMites.Rows.Add(row);
return dtMites;
*/
return (DataTable)o;
}
You need to add some tags to the web.config file for this to work
<system.web>
<caching>
<sqlcachedependency enabled = "true" pollTime = "60000" >
<databases>
<add name="Connection String"
connectionStringName="Connection String"
pollTime="9000000"
/>
</databases>
</sqlCacheDependency>
</caching>
You will also need to add this to Application_Start method in Global.asax.cs file
protected void Application_Start(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Start(System.Configuration.ConfigurationManager.ConnectionStrings["Connection String"].ConnectionString);
// Code that runs on application startup
}
on the database server run this command
Aspnet_regsql -S ServerName -U username -P Password -d DatabaseName -ed
Using Sql management studio run this script on the database
Run the script
DECLARE @SQL nvarchar(max)
BEGIN TRY
SET @SQL = 'ALTER DATABASE' + DatBaseName + 'SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE '
PRINT @SQL
EXEC sp_executesql @SQL
END TRY
BEGIN CATCH
SET @SQL = 'ALTER DATABASE' + DatBaseName + 'SET NEW_BROKER WITH ROLLBACK IMMEDIATE '
PRINT @SQL
EXEC sp_executesql @SQL
END CATCH
GO
If the script is taking too long to run, restart the Database server instance by opening Control Panel > Administrative Tools > Services >
Tuesday, April 12, 2011
Restrict special characters from being entered into the textbox using Javascript
If the input from the textbox is going to be used as a filter criteria to retrieve records from the database, your application will throw exceptions as sql does not like special characters like '%', ', " in 'Where' and 'Like' clauses. You could write some javascript to restrict users from entering these special characters
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event) {
keynum = e.keyCode
}
// For Netscape/Firefox/Opera
else if (e.which) {
keynum = e.which
}
keychar = String.fromCharCode(keynum)
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`" || keychar == "%" || keychar == "\"" {
return false;
}
else {
return true;
}
}
Here is the asp.net tag
<asp:TextBox ID="txtName" runat="server" onkeypress="return check(event)"></asp:TextBox>
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event) {
keynum = e.keyCode
}
// For Netscape/Firefox/Opera
else if (e.which) {
keynum = e.which
}
keychar = String.fromCharCode(keynum)
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`" || keychar == "%" || keychar == "\"" {
return false;
}
else {
return true;
}
}
Here is the asp.net tag
<asp:TextBox ID="txtName" runat="server" onkeypress="return check(event)"></asp:TextBox>
Friday, April 8, 2011
How to pass an array to the stored procedure
If you have a situation where you have to pass multiple selected values from the listbox to a stored procedure and these multiple selected values should be used in a filter criteria "IN", you could do it using dynamic sql. Concatenate the list of selected values with comas. If the search criteria are strings, concatenate quotes to the strings and pass this string to the storedprocedure with dynamic sql in it.
string _selList = "";
int[] indSel = DDL.GetSelectedIndices();
foreach (int i in indSel)
{
_selList += "'" + DDLMfgSite.Items[i].Text + "',";
}
if (_selList.LastIndexOf(",") > 0)
_selList = _selList.Substring(0, _selList.LastIndexOf(","));
string _selList = "";
int[] indSel = DDL.GetSelectedIndices();
foreach (int i in indSel)
{
_selList += "'" + DDLMfgSite.Items[i].Text + "',";
}
if (_selList.LastIndexOf(",") > 0)
_selList = _selList.Substring(0, _selList.LastIndexOf(","));
Populating a Texbox with ListBox multiple selected items using Javascript
function ddlChange() {
var ddl = document.getElementById('<%=DDL.ClientID%>');
var textBox = document.getElementById('<%=txtSelected.ClientID%>');
len = ddl.length;
textBox.value = "";
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
textBox.value += ddl.options[j].text + "\r\n";
}
}
}
<div>Available Items:</div>
<div>
<asp:ListBox ID="DDL" runat="server" SelectionMode="Multiple" onChange="ddlChange()" Height="170px">
</asp:ListBox>
</div>
<div>Selected Items:</div>
<div>
<asp:TextBox ID="txtSelected" runat="server" TextMode="MultiLine"
ReadOnly="true" Height="170px" Width="365px"></asp:TextBox>
</div>
var ddl = document.getElementById('<%=DDL.ClientID%>');
var textBox = document.getElementById('<%=txtSelected.ClientID%>');
len = ddl.length;
textBox.value = "";
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
textBox.value += ddl.options[j].text + "\r\n";
}
}
}
<div>Available Items:</div>
<div>
<asp:ListBox ID="DDL" runat="server" SelectionMode="Multiple" onChange="ddlChange()" Height="170px">
</asp:ListBox>
</div>
<div>Selected Items:</div>
<div>
<asp:TextBox ID="txtSelected" runat="server" TextMode="MultiLine"
ReadOnly="true" Height="170px" Width="365px"></asp:TextBox>
</div>
Thursday, April 7, 2011
Setting Textbox to the dropdownlist's selected item using javascript
<script type="text/javascript"/>
function ddlChange() {
var ddl = document.getElementById('<%=DDL.ClientID%>');
var textBox = document.getElementById('<%=txtSelected.ClientID%>');
textBox.value = ddl.options[ddl.selectedIndex].text;
}
</script>
<asp:DropDownList ID="DDL" runat="server" DataTextField="Site" DataValueField="Site" onChange="ddlChange()">
</asp:DropDownList>
<asp:TextBox ID="txtSelected" runat="server" Width="300px"></asp:TextBox>
function ddlChange() {
var ddl = document.getElementById('<%=DDL.ClientID%>');
var textBox = document.getElementById('<%=txtSelected.ClientID%>');
textBox.value = ddl.options[ddl.selectedIndex].text;
}
</script>
<asp:DropDownList ID="DDL" runat="server" DataTextField="Site" DataValueField="Site" onChange="ddlChange()">
</asp:DropDownList>
<asp:TextBox ID="txtSelected" runat="server" Width="300px"></asp:TextBox>
Setting ListBox scroll position at the Selected Items
If you have a listbox inside your user control and if all of these conditions below apply:
1. Your listbox is inside a user control
2. The user control becomes visible based on other selections on the webform you made.
3. The listbox is bound to the data in the Page_Init and the default SelectedValue is set in the code behind.
In this scenario, when the user control becomes visible, the listbox scroll position is set at the first item in the listbox instead of at the SelectedValue.
If you want the listbox scroll position at the SelectedValue, you have to write javascript.
Write this javascript in your user control:
window.onload = function () {
var ddl = document.getElementById('<%=DDL.ClientID%>');
len = ddl.length;
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
ddl.options[j].selected = false;
ddl.options[j].selected = true;
}
}
}
What you do here is just unselect and reselect the selected items.
1. Your listbox is inside a user control
2. The user control becomes visible based on other selections on the webform you made.
3. The listbox is bound to the data in the Page_Init and the default SelectedValue is set in the code behind.
In this scenario, when the user control becomes visible, the listbox scroll position is set at the first item in the listbox instead of at the SelectedValue.
If you want the listbox scroll position at the SelectedValue, you have to write javascript.
Write this javascript in your user control:
window.onload = function () {
var ddl = document.getElementById('<%=DDL.ClientID%>');
len = ddl.length;
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
ddl.options[j].selected = false;
ddl.options[j].selected = true;
}
}
}
What you do here is just unselect and reselect the selected items.
Monday, March 28, 2011
Static vs Const vs Readonly
Static variables are stored in a special area inside Heap known as High Frequency Heap. Those methods and variables which don't need an instance of a class to be created are defined as being static. Static methods can only call other static methods, or access static properties and fields. Static classes can not inherit from any class and can not be inherited.
Static variables keep their values for the duration of the application domain.
It will survive many browser sessions until you restart the web server (IIS) or until it restarts on its own (when it decides it needs to refresh its used resources).
There is a subtle but important distinction between const and readonly keywords in C#:
Use Const when the value of the variable will stay fixed. const variables are implicitly static and they need to be defined when declared.
Use readonly when the value of the variable changes from user to user but remains constant once initialized at runtime. readonly variables are not implicitly static and can only be initialized once. readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.
For example:
public class MyClass
{
public readonly double PI = 3.14159;
}
or
public class MyClass
{
public readonly double PI;
public MyClass()
{
PI = 3.14159;
}
}
E.g.: You are writing a storage program in which the memory has a fixed size of 104857600 Bytes. You can define a const variable to denote this as:
private const int _memSize = 104857600 ;
Now, you want the user to enter the amount of memory he needs. Since this number would vary from user to user, but would be constant throughout his use, you need to make it readonly. You cannot make it a const as you need to initialize it at runtime. The code would be like:
public class Storage
{
//this is compile time constant
private const int _totalMemory = 104857600 ;
//this value would be determined at runtime, but will
//not change after that till the class's
//instance is removed from memory
private readonly int _memSize ;
public Storage(int memSize)
{}
public AllocateMemory(int memSize)
{
///
///Get the number of cars from the value
///use has entered passed in this constructor
///
_memSize= memSize;
}
}
Static variables keep their values for the duration of the application domain.
It will survive many browser sessions until you restart the web server (IIS) or until it restarts on its own (when it decides it needs to refresh its used resources).
There is a subtle but important distinction between const and readonly keywords in C#:
Use Const when the value of the variable will stay fixed. const variables are implicitly static and they need to be defined when declared.
Use readonly when the value of the variable changes from user to user but remains constant once initialized at runtime. readonly variables are not implicitly static and can only be initialized once. readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.
For example:
public class MyClass
{
public readonly double PI = 3.14159;
}
or
public class MyClass
{
public readonly double PI;
public MyClass()
{
PI = 3.14159;
}
}
E.g.: You are writing a storage program in which the memory has a fixed size of 104857600 Bytes. You can define a const variable to denote this as:
private const int _memSize = 104857600 ;
Now, you want the user to enter the amount of memory he needs. Since this number would vary from user to user, but would be constant throughout his use, you need to make it readonly. You cannot make it a const as you need to initialize it at runtime. The code would be like:
public class Storage
{
//this is compile time constant
private const int _totalMemory = 104857600 ;
//this value would be determined at runtime, but will
//not change after that till the class's
//instance is removed from memory
private readonly int _memSize ;
public Storage(int memSize)
{}
public AllocateMemory(int memSize)
{
///
///Get the number of cars from the value
///use has entered passed in this constructor
///
_memSize= memSize;
}
}
Friday, March 25, 2011
Performance - Using ViewState for dropdownlist and binding the first time vs Turning off viewstate and binding dropdownlist on each postback with a static data table
Static variables are stored in special area inside Heap known as High Frequency Heap.
***Incomplete***
***Incomplete***
Notes on Validation Controls
SetFocusOnError property on a validation control: This property, if set to True, causes the Web control the validation control is operating on to receive focus if the validation control is invalid. This is a nice little usability touch that your users will likely appreciate.
EnableClientScript property on validation control:Leaving the default value (true) of EnableClientScript is a first line of defense, good for 90% of situations. Leaving EnableClientScript as default or setting it to true avoids a postback. If you look at the page source with property setting EnableClientScript="false", you will see some javascript that does the client side validation without posting back. If you look at the page source with property setting EnableClientScript="true", you will see not see any javascript in the source.
You should also check the value of Page.IsVaild in your code behind to handle situations in which the client disabled JavaScript or otherwise circumvented your client-side validation
In Fritz Onion's Essential ASP.NET book:
"As soon as you place a validation control on a page, it is imperative that you check the IsValid flag of the Page class before using any of the data posted by the client. It is a common misconception that if validation fails on a page, the code for that page will not execute. On the contrary, the only thing that happens when server-side validation fails is that the IsValid flag of the Page class is set to false, and each validation control that failed renters itself as a visible span so that the error indicator shows up when the page is redisplayed to the user."
EnableClientScript property on validation control:Leaving the default value (true) of EnableClientScript is a first line of defense, good for 90% of situations. Leaving EnableClientScript as default or setting it to true avoids a postback. If you look at the page source with property setting EnableClientScript="false", you will see some javascript that does the client side validation without posting back. If you look at the page source with property setting EnableClientScript="true", you will see not see any javascript in the source.
You should also check the value of Page.IsVaild in your code behind to handle situations in which the client disabled JavaScript or otherwise circumvented your client-side validation
In Fritz Onion's Essential ASP.NET book:
"As soon as you place a validation control on a page, it is imperative that you check the IsValid flag of the Page class before using any of the data posted by the client. It is a common misconception that if validation fails on a page, the code for that page will not execute. On the contrary, the only thing that happens when server-side validation fails is that the IsValid flag of the Page class is set to false, and each validation control that failed renters itself as a visible span so that the error indicator shows up when the page is redisplayed to the user."
Wednesday, March 23, 2011
Improving performance
1. ScriptManager control has LoadScriptsBeforeUI property which you can set to “False” in order to postpone several script downloads after the content is downloaded. This adds the script references end of the tag. As a result, you see the content first and then the additional scripts, extenders, ACT scripts get downloaded and initialized.
< asp:ScriptManager ID =”ScriptManager1″ runat =”server” EnablePartialRendering =”true” LoadScriptsBeforeUI =”false”> … asp:ScriptManager >
http://omaralzabir.com/fast_page_loading_by_moving_asp_net_ajax_scripts_after_visible_content/
2. Configure Compression (IIS 6.0)
To more efficiently use available bandwidth, it is advisable to enable IIS's HTTP compression feature. HTTP compression provides faster transmission time between compression-enabled browsers and IIS regardless of whether your content is served from local storage or a UNC resource. You can compress static files only, application response files only, or both static files and application response files. Compressing application response files is usually called dynamic compression.
Read this msdn link on how to enable compression
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/92f627a8-4ec3-480c-b0be-59a561091597.mspx?mfr=true
3. Do Not Use the Sp_ Prefix for Custom Stored Procedures
SQL Server always looks in the master database for a stored procedure that begins with the sp_ prefix. SQL Server then uses any supplied qualifiers such as the database name or owner. Therefore, if you use the sp_ prefix for a user-created stored procedure, and you put it in the current database, the master database is still checked first. This occurs even if you qualify the stored procedure with the database name. To avoid this issue, use a custom naming convention, and do not use the sp_ prefix.
4. View state can impact web pages dramatically, not only in page size but also in server side performance. Moreover, pages with large view states can throw unexpected errors. Disable viewstate when there is no need to persist state across postbacks.
consider disabling view state in these cases:
If the controls value is hard-coded.
If the controls value is assigned on every page.
5. Avoid long control names; especially ones that are repeated in a DataGrid or Repeater control. Control names are used to generate unique HTML ID names. A 10-character control name can easily turn into 30 to 40 characters when it is used inside nested controls that are repeated.
6. Something very interesting I came across while reading msdn is to "remove characters such as tabs and spaces that create white space before you send a response to the client. Removing white spaces can dramatically reduce the size of your pages. The following sample table contains white spaces.
// with white space
<table>
<tr>
<td>hello<td>
</td>world</td>
</tr>
</table>
The following sample table does not contain white spaces.
// without white space
<table<<tr><td>hello</td><td\>world</td></tr></table>
Save these two tables in separate text files by using Notepad, and then view the size of each file. The second table saves several bytes simply by removing the white space. If you had a table with 1,000 rows, you could reduce the response time by just removing the white spaces. In intranet scenarios, removing white space may not represent a huge saving. However, in an Internet scenario that involves slow clients, removing white space can increase response times dramatically. You can also consider HTTP compression; however, HTTP compression affects CPU utilization.
You cannot always expect to design your pages in this way. Therefore, the most effective method for removing the white space is to use an Internet Server API (ISAPI) filter or an HttpModule object. An ISAPI filter is faster than an HttpModule; however, the ISAPI filter is more complex to develop and increases CPU utilization. "
Now I need to figure out how to write an ISAPI filter to remove white space.
7. Install Runtime Page Optimizer (RPO). Refer to http://www.iis.net/community/default.aspx?tabid=34&g=6&i=1716. There is a price to it.
Or Write your own optimizer. You can start by reading this blog http://www.darkside.co.za/archive/2008/03/03/web-page-optmisation-using-httpmodule.aspx.
< asp:ScriptManager ID =”ScriptManager1″ runat =”server” EnablePartialRendering =”true” LoadScriptsBeforeUI =”false”> … asp:ScriptManager >
http://omaralzabir.com/fast_page_loading_by_moving_asp_net_ajax_scripts_after_visible_content/
2. Configure Compression (IIS 6.0)
To more efficiently use available bandwidth, it is advisable to enable IIS's HTTP compression feature. HTTP compression provides faster transmission time between compression-enabled browsers and IIS regardless of whether your content is served from local storage or a UNC resource. You can compress static files only, application response files only, or both static files and application response files. Compressing application response files is usually called dynamic compression.
Read this msdn link on how to enable compression
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/92f627a8-4ec3-480c-b0be-59a561091597.mspx?mfr=true
3. Do Not Use the Sp_ Prefix for Custom Stored Procedures
SQL Server always looks in the master database for a stored procedure that begins with the sp_ prefix. SQL Server then uses any supplied qualifiers such as the database name or owner. Therefore, if you use the sp_ prefix for a user-created stored procedure, and you put it in the current database, the master database is still checked first. This occurs even if you qualify the stored procedure with the database name. To avoid this issue, use a custom naming convention, and do not use the sp_ prefix.
4. View state can impact web pages dramatically, not only in page size but also in server side performance. Moreover, pages with large view states can throw unexpected errors. Disable viewstate when there is no need to persist state across postbacks.
consider disabling view state in these cases:
If the controls value is hard-coded.
If the controls value is assigned on every page.
5. Avoid long control names; especially ones that are repeated in a DataGrid or Repeater control. Control names are used to generate unique HTML ID names. A 10-character control name can easily turn into 30 to 40 characters when it is used inside nested controls that are repeated.
6. Something very interesting I came across while reading msdn is to "remove characters such as tabs and spaces that create white space before you send a response to the client. Removing white spaces can dramatically reduce the size of your pages. The following sample table contains white spaces.
// with white space
<table>
<tr>
<td>hello<td>
</td>world</td>
</tr>
</table>
The following sample table does not contain white spaces.
// without white space
<table<<tr><td>hello</td><td\>world</td></tr></table>
Save these two tables in separate text files by using Notepad, and then view the size of each file. The second table saves several bytes simply by removing the white space. If you had a table with 1,000 rows, you could reduce the response time by just removing the white spaces. In intranet scenarios, removing white space may not represent a huge saving. However, in an Internet scenario that involves slow clients, removing white space can increase response times dramatically. You can also consider HTTP compression; however, HTTP compression affects CPU utilization.
You cannot always expect to design your pages in this way. Therefore, the most effective method for removing the white space is to use an Internet Server API (ISAPI) filter or an HttpModule object. An ISAPI filter is faster than an HttpModule; however, the ISAPI filter is more complex to develop and increases CPU utilization. "
Now I need to figure out how to write an ISAPI filter to remove white space.
7. Install Runtime Page Optimizer (RPO). Refer to http://www.iis.net/community/default.aspx?tabid=34&g=6&i=1716. There is a price to it.
Or Write your own optimizer. You can start by reading this blog http://www.darkside.co.za/archive/2008/03/03/web-page-optmisation-using-httpmodule.aspx.
Subscribe to:
Posts (Atom)