Thursday, January 10, 2008

Did you use proper ConnectionPooling in ASP.NET

http://www.codeproject.com/useritems/ADONET_ConnectionPooling.asp
Read & ponder over Min. Pool Size:

Min Pool Size is 0 (by default) The minimum number of connections allowed in the pool. Means we are not allowing connection to swim in the pool

Final Note : Min Pool Size should be set to a optimal number. Microsoft says 5-12 is a good number.

Encrypt and Decrypt of ConnectionString in app.config and/or web.config!

Encrypt and Decrypt of ConnectionString in app.config and/or web.config!

http://www.codeproject.com/useritems/Configuration_File.asp

Don't use Databinder.Eval, improve performance

Use explicit cast instead of using Eval


Eval uses reflection to evaluate argument passed.Reflection is the ability to read metadata at runtime

<%# DataBinder.Eval(Container.DataItem,"myfield") %>

But explicit casting can reduce the cost of reflection. Imagine if there is 30 rows and each row has 6 Eval calls. So there will be calls to Eval 180 times. And we should take this pretty seriously.So you must be thinking what to do. Hey we can simply do something like this and improve significant performance.


Option1=============

<%# ((DataRowView)Container.DataItem)["myfield"] %>

Option2 for DataReader=====================

<%# ((DbDataRecord)Container.DataItem).GetString(0) %>


Option3 use of ItemDataBound Event====================

protected void Repeater_ItemDataBound(Object sender, RepeaterItemEventArgs e){ DataRowView data = (DataRowView)e.Item.DataItem; Response.Write(string.Format("

{0}
",data["myfield"]));}
And if we are using Collection Objects as DataSource we can do something like this List customers = GetCustomers();Repeater1.DataSource = customers;Repeater1.DataBind();....
protected void Repeater_ItemDataBound(Object sender, RepeaterItemEventArgs e){ Customer customer = (Customer)e.Item.DataItem; Response.Write(string.Format("
{0}
",customer.FirstName));

Fetching user's credential from other site: Hacking

Any subscriber/member may get hacked in following way:

1. Open site
2. Become a member
3. Add blogs with title “”Administrator Announcement”
content may be following

Dear User,



This blog is shown to randomly accessed users. If you have got it, means you are lucky. is offering a date with Anjelina Jolie. If interested. you may enroll for the contest here.




  1. User Name










Note: This contest closes on 15th Oct. 2007



Regards,


Administrator




4.Now when other member logsin, he may visit above posted blog.
5.When he may get fool if he enters is username/password & submits
6.his details/session id/cookie info. /username/password will be submitted to http://www.URLofHackerSite.com/coll.aspx
7.coll.aspx will get his details
8.he will be hacked

Developers: How to Save bytes, ASP.NET


For Software Developers: "Save Bytes", Little Thing, Big Effect....e.g.




Here default name has been used. i.e. ContentPlaceHolder1. Web server has to transfer 25 bytes for this particular name.On client side it becomes something like ctl00$ContentPlaceHolder1.... , which again become too long.

Take A Scenario: If above name has 50 occurrences in a webpage & if 1000000 users are using same page then Web server has to transfer 1000000 X 25 X 50 = 125000000 bytes.If Name "ContentPlaceHolder1" is changed to "CPHold", Web Server will transfer 1000000 X 12 X 50= 60000000 bytes, i.e. Saving of 65000000 bytes
Note: This will be one way saving. Finally saying, use short id/names, don't use default/long id/names.

Character Count for Textarea, Remaining Character

Count and Limit Character Input in Text Boxes:


Put this in between the and tags:
Please view in source code

<script language="JavaScript">
function twdCount(field,cntfield,maxlimit)
{
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
else
cntfield.value = maxlimit - field.value.length;
}
</script>


Here is the form code:


characters left


characters left

change Background Color of onfocus of HTML control


Change Background Color of HTML control:onfocus of any control bgcolor of the control should change & onblur it should again become white.this is the code


<script type="text/javascript" language="javascript">
function set()
{

for (i=0; i {

if (document.forms[0].elements[i].type=="text" || document.forms[0].elements[i].type=="password" || document.forms[0].elements[i].type=="textarea")
{
document.forms[0].elements[i].onfocus=function() {this.style.backgroundColor='#E3E0DB';};
document.forms[0].elements[i].onblur=function() {this.style.backgroundColor='#ffffff';};
}


if (document.forms[0].elements[i].type=="text" || document.forms[0].elements[i].type=="password" || document.forms[0].elements[i].type=="textarea")
{
if(document.forms[0].elements[i].value="")
document.forms[0].elements[i].focus();
}

}
}

</script>

Wednesday, January 9, 2008

General practices

MAXLENGTH:The maxlength of each control should be 1 minus the length set in the corresponding column length in databasee.g. fname = 256 in DB
front end- First Name = 255 should be set (even smaller than this is good)
Be careful while setting the column length: Please set minimum required length e.g. for first name 100 characters are to much. If we set 255 for this, that would be a wastage. Specially for char datatype
for username/password/security answer fields: maxlength should not be too large.

FOCUS:Cursor Focus should come at very first control of the form on the page. e.g. first name is the first control on the page, so cursor should focus in this automatically on page load
VALIDATORS:When validation fails, form should not submit i.e. no postback. on enter keypress form should not be submitted till validation messages appearPlease set SetFocusOnError="True" ValidationGroup="name"for all validators.all validators should fire on client side first.

BLANK FORM VALUES:if after submission of any form , if same page appears again, then all textbox/contols should get cleared.
INVALID CHARACTERS:Invalid characters should not be allowed in inputs.Proactive Strategy: e.g. phone textbox, if 0-9 & hypen is allowed in it.Then other characters should not be typed in this textbox.If somebody types invalid character, message should appear

Time taken by a webpage for execution : Page Cost

Following code will help us finding the Time taken by a page for execution i.e. Page CostWe need to use this for testing environment.This will create a log file.
The code calculates the time by calculating the interval between the Application_BeginRequest and Application_EndRequest events.
<%@ import namespace="System.IO" %>
<script runat="server">
//static members for the writing syncronization
private static StreamWriter _writer;
private static object _lock = new object();
//change this to a directory that the aspnet account has read\write //permissions to
private static string _fileName = string.Format(@"c:\temp\log_{0}.txt",DateTime.Now.ToFileTime());
//member variables for tracking start/end times
private DateTime _startTime;
private DateTime _endTime;
public static StreamWriter GetStaticWriter()
{
//make sure we're thread safe here...
if(_writer==null){
lock(_lock){
if(_writer==null){
_writer = new StreamWriter(_fileName,false);
_writer.WriteLine("IP ADDRESS \tSTART TIME \tEND TIME \tDIFF \tURL");
_writer.WriteLine("===============\t============\t============\t================\t=========================");
_writer.Flush();
}
}
}
return _writer;
}
public static void LogText(string str){
GetStaticWriter().WriteLine(str);
GetStaticWriter().Flush();
}
protected void Application_BeginRequest(Object sender, EventArgs e){
_startTime = DateTime.Now;
}
protected void Application_EndRequest(Object sender, EventArgs e){
_endTime = DateTime.Now;
LogText(string.Format("{0,-12}\t{1:hh:mm:ss.fff}\t{2:hh:mm:ss.fff}\t{3}\t{4}",Request.ServerVariables["REMOTE_ADDRESS"].ToString(),_startTime,_endTime,_endTime-_startTime,Request.Url));
}
protected void Application_End(Object sender, EventArgs e){
//release the writer
// Even if this doesn't execute, when the appdomain gets shutdown //it will be released anyways
if(_writer!=null)
_writer.Close();
}
</script>

know your IP & country

<a href="http://pingme.info/">http://pingme.info/
which will tell you your I.P. & country
You can use the following piece of ASP code to get country details. Sending AJAX CALL

<%strXml=""set XmlHttp=Server.CreateObject("Microsoft.XMLHTTP")XmlHttp.open "POST","http://pingme.info/pingme.asp",falseXmlHttp.send(strXml)
strCountryShort=XmlHttp.responsexml.documentElement.getElementsByTagName("countryshort").Item(0).TextstrCountryLong=XmlHttp.responsexml.documentElement.getElementsByTagName("countrylong").Item(0).TextstrCountry=XmlHttp.responsexml.documentElement.getElementsByTagName("countryname").Item(0).TextResponse.Write("Country Short:"&strCountryShort&"
")Response.Write("Country Long:"&strCountryLong&"
")Response.Write("Country Name:"&strCountry&"
")%>