Saturday, January 7, 2012

Common errors and solutions of ASP.net

1.When you debug an ASP.NET application in Visual Studio .NET, you may receive the following error message:

Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.
Possible Solution: To do this goto IIS management console and then go to your virtual directory in IIS.Right click and go to properties of virtual directory/website. Then goto Directory Security tab and then click Edit button under anonymous control and authentication control and then make sure to check the last checkbox which states Integrated windows security.

2.Object reference not set to an instance of an object
Possible solution
This is basically a runtime eror and is caused by your code trying to reference an object that is not available, or set to null.Foreg: Connectionobject you have opened and sed and later on you closed it and set it to null and in the later part of code you try to use the connection again.Then you will encounter this error message.
This error may also occur when improperly call an object without the "new" keyword.

3. Cannot implicitly convert type 'object' to 'string'
Possible solution
The solution here is to append ".ToString() which will represents the object as a string.

4.'name' is a type and cannot be used as an expression
Possible solution
This can happen usually when you forget to use the new keyword when instantiating an object or invoking a constructor.

5. Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Possible solution
a.If you call an object that requires parentheses() after the command, you will get this error. Ex. Conn.Open() not Conn.Open
b.Using an assignment operator as opposes to an equality operator

6. The name 'whatever' does not exist in the class or namespace / The type or namespace name 'whatever' could not be found (are you missing a using directive or an assembly reference?)
Possible solution
This occur when you have not declared a variable globally and or it is missing altogether or is improperly declared.

7. 'method name': not all code paths return a value
Possible solution
This will happen when you are trying to make a function method behave like a subroutine or vice-versa.Use the proper method keyword to remedy this. Void is for methods that do not return a value, although you could response write the output. Whereas, applying a keyword value like string, int, works alongside a return value at the end of the method.

8. System.Data.SqlClient.SqlException: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
The three most common problems are:
1. Sql Server not configured for remote connections.
2. Firewall blocking sql server connections.
3. Wrong data source in connection string.

Wednesday, February 9, 2011

Tips on improving performance in Asp.Net

Improve Perfomance in ASP.net

1. Use Foreach loop instead of For loop for String Iteration.

2. Check “Page.IsPostBack”. To avoid repetition code execution.

3. GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)

4. Turn off Session State, if not required.


5. Select the Release mode before making the final Build for your application.
This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

6. Disable ViewState when not required.
EnableViewState="false"

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

8. Use StringBuilder instead of String class.Strings occupy different memory location in every time of amended where stringbuilder use single memory location

9. Avoid Exceptions: Use If condition (if it is check proper condition)

10. Code optimization: Avoid using code like x = x +1; it is always better to use x+=1.

11. Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

12. Use Repeater control instead of DataGrid , DataList as it is efficient, customizable, and programmable.

13. Use single css file instead of multiple css file.

14. Don't make the member variables public or proteted. try to keep private and use public/protected as properties.

15. Use strString=string.Empty instead of strString=""

16. Use Server.Transfer instead of Response.Redirect.


More to come soon..........

Manually sorting gridview

private DataSet GetData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}

GridView HTML Code:
The columns are generated automatically for the GridView control which are bound to the data source. Take a look at the HTML generated by the GridView control to have a clear picture.




public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}

private void SortGridView(string sortExpression,string direction)
{
//Cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}

Monday, November 22, 2010

Multiple Rows to column.

create table #Test (
ProdID varchar(5),
ProdDesc varchar(256)
)

insert into #Test (
ProdID,
ProdDesc
)
select 'Prod1', 'Description 1' union all
select 'Prod1', 'Description 2' union all
select 'Prod2', 'Description 1' union all
select 'Prod3', 'Description 1' union all
select 'Prod3', 'Description 2' union all
select 'Prod3', 'Description 3' union all
select 'Prod3', 'Description 4'


select distinct
a.ProdID,
stuff((select
',' + b.ProdDesc
from
#Test b
where
b.ProdID = a.ProdID
for xml path('')),1,1,'') as ProdDesc
from
#Test a

Thursday, October 28, 2010

Autocomplete feature of textbox

write the below code in aspx page inside the javascript tag:

$(document).ready(function(){ $("#<%=fname.ClientID%>").autocomplete("TestHandler.ashx"); });

where fname is your textbox name .



In TestHandler.ashx write the below code:
using System;
using System.Web;
using System.Data;

public class TestHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string Dealercode = context.Request.QueryString["q"];
DataSet objds = new DataSet();
//get the dataset from your class.Here dataprocessor is a class having
//runspreturndataset method which will return the dataset.
objds = DataProcessor.RunSpReturnDataset("get_dealer_details", Dealercode);
string[] items = new string[objds.Tables[0].Rows.Count];
foreach (DataRow dr in objds.Tables[0].Rows)
{
//items.SetValue(dr["dealercode"].ToString(), Convert.ToInt32(dr["tmsw_dealer_id"].ToString()));
context.Response.Write(dr["dealer_code"].ToString().TrimEnd() +"-"+ dr["dealership_name"].ToString().Trim() + Environment.NewLine);
}


}

public bool IsReusable
{
get
{
return false;
}
}

}

Sort dropdown in ascending order.

private void SortDDL(ref DropDownList myddl)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();


foreach (ListItem li in myddl.Items)
{
textList.Add(li.Text);
}

textList.Sort();
textList.Reverse();


foreach (object item in textList)
{
string value = myddl.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
myddl.Items.Clear();

for (int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
myddl.Items.Add(objItem);
}
}

Saturday, May 1, 2010

Disable back button on browser



Call this in body tag of html :

onload="disableBackButton()"