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
Wednesday, December 21, 2011
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)