Sunday, July 25, 2010

Interview Tips

1. Attend as many interviews and walk-ins as possible and learn from each and every interview. Make a note of all the questions asked in the interview and prepare for upcoming interviews from those questions.

2. Learn aptitude from RS Agarwal and shakuntala devi puzzles.

3. Do certification, like if you know the Java subject do Java certification. If you know Dotnet, do Dotnet certification. This will add value to your resume and improve your subject knowledge also and it will help you fetch job.

4. Register your profile on as many job sites as possible mainly naukri.com and monster.com and keep updating your profile weekly once to get many calls.

5. Tell your friends, Relatives, neighbors that you are in search of Job. Make network of friends so that you get to know about the opportunities.

Wednesday, July 21, 2010

Get the id/name of the ASP.NET server control as rendered on the browser in JQUERY/Javascript

var id = '<%=controlId.ClientID %>' is used to retrieve the id of the ASP.NET control with id=controlId as rendered on the browser.
Var name = '<%=controlId.UniqueID %>' is used to retrieve the name of the ASP.NET control with id=controlId as rendered on the browser.


where controlId is the id of the asp.net web server control.

Sunday, July 18, 2010

Views,Indexes, Joins in SQLServer

This article covers basic information about Views, Indexes and Joins in Sql Server

What are Views?

 A View is a logical table based on a table or another view.Only the Definition of View(Select statement) is stored.

What are the advantages of Views?

1.Views restrict access to the data because the views can display selected columns from the table.

2.View can be used to write simple queries to retrieve the results of complicated queries.

3.A View can be used to retrieve data from several tables.

4. Views provide data independence for adhoc users and applications.

Give an example of a View:


 Create View vuEmp as

SELECT EmpId,EmpName,EmpSalary

FROM Emp

WHERE DeptId=10;
View Created.


What is an Index ?

1.It is used to retrieve data quickly by using a pointer when a query is processed.

2. It provides direct and fast access to rows in a table.

3. It can be created or dropped or dropped at any time and have no effect on the tables or other indexes.

4.When a query is processed which has a where condition on some column then if you do not have an index on the column in the where clause then a full table scan occurs. That is every row in the table has to be processed to execute the query. If the table grows then processing a query becomes slow and expensive.

5. It is used and maintained automatically by SQL Server.

6. An Index stores the column value on which the index is created for each row of the table along with the RowId of that row in either ascending/descending order.

Give an example of index ?

 SELECT EmpId,Name,Sal
FROM Emp
WHERE (Sal > 1000) and (Sal < 5000)

 In this example we have to retrieve employee details whose salary is greater than 1000 and less than 5000.

If the Emp table has 50,000 records then 50,000 records needs to be scanned to get the results of the query but if you have an index on the Sal column then using the index we can retrieve data directly only from those rows which has salary >1000 and less than 5000.


What are the types of index?

There are two types of index.

1. Unique Index: IT is automatically created when you define a column in a table to have a PRIMARY KEY or a UNIQUE KEY constraint.

2. Non-Unique Index: The Index which user creates.


 When should you consider creating index ?

More indexes on a table does not mean faster query processing. For each DML operation committed on a table with indexes, the indexes must be updated. The more indexes associated with a table the more effort the sql server must make to update all the indexes after a DML operation. Therefore Indexed should be created only if

1. The column contains a wide range of values.

2. The column contains a large number of null values.

3. One or more columns are frequently used together in a where clause or join condition.

4. The table is big and most of the queries being processed are expected to retrieve less than 2 to 4 % of the rows.

What is a Composite Index?

Ans: CompositeIndex is an index that you create on multiple columns in a table.

Note:

1. NULL values are not included in the index.

 2.You cannot modify an index . To change an index, you must drop it and then recreate it. Drop index using Drop keyword. Ex: DROP INDEX indexname.

 3.If you drop a table, Index and constraints are automaticallr dropped but views and sequences remain.

When you should not create an index?

1.If the table is small.

2. If the indexed column is not often used as a condition in a query.

3.The table is updated frequently.

4.The indexed columns are referenced as part of an expression.

How to list the indexed associated with a table ?

 EXEC sp_helpindex tablename

  
What are the disadvantages of using Index?

1.As Index is stored on disk. As the size of the table grows. The size of the index also grows.

2.For every insert,update, delete operation the database has to update all of the indexes where data has changed.

What are the applications of indexes?

1.Report generation is optimized using indexes.

2.Index increase search performance.

  Joins

What are Joins?

Ans: To query data from more than one table use joins.

Consider below two tables for below examples:

Emp(EmpId,Name,DeptId,managerId)

Dept(DeptId,DeptName,LocId)

Job(Low_Sal,High_Sal,Grade)

Loc(LocId,City)

What is EquiJoin/SimpleJoin/Inner Join ?

The relationship between Emp,Dept tables is an equijoin. That is, values in the DeptId column on both tables must be equal.

Ex: To find an employee’ss department name you compare the value in the DeptId column in emp table with DeptId value in Dept Table.

SELECT e.EmpId, e.Name, e.DeptId

FROM Emp e, Dept d

WHERE e.DeptId = d.DeptId

  
What is Non-EquiJoin

 It is a join condition containing something other than an equality operator.

Ex:

SELECT e.EmpId, e.Sal,j.Grade

 FROM Emp e, Job j

 WHERE e.Sal BETWEEN j.Low_Sal AND j.High_Sal

  
What is OUTER JOIN

It is used to include rows that do not match JOIN condition. + sign is placed on the side of the join that is deficient in the information.

Ex:

SELECT table1.col, table2.col

FROM table1,table2

WHERE table1.col (+) = table2.col;


What is LEFT OUTER JOIN? Explain.

Below query retrieves all rows in Emp table which is the left table even if there is no match in Dept table.

Ex:

SELECT e.name,e.deptid,d.deptname

FROM Emp e, Dept d

WHERE d.DeptId(+) = e.DeptId

Or

SELECT e.name,e.deptid,d.deptname

FROM Emp e

LEFT OUTER JOIN Dept d

ON e.DeptId = d.DeptId

   
What is RIGHT OUTER JOIN? Explain.

Below query retrieves all rows in Dept table which is the Right table even if there is no match in Emp table i.e., even if DeptId column of Dept table contains null values.

Ex:

SELECT e.name,e.deptid,d.deptname

FROM Emp e, Dept d

WHERE d.DeptId= e.DeptId(+)

Or

SELECT e.name,e.deptid,d.deptname

FROM Emp e

RIGHT OUTER JOIN Dept d

ON e.DeptId = d.DeptId



What is FULL OUTER JOIN?

It retrieves all rows from both the tables including null values.

Ex:

SELECT e.name,e.deptid,d.deptname

FROM Emp e

FULL OUTER JOIN Dept d

ON e.DeptId = d.DeptId


Give an example of CROSS Join(Cartesian Product)?

SELECT name,deptname

FROM EMP,DEPT\

Or

SELECT name,deptname

FROM EMP

CROSS JOIN DEPT

What is NATURAL JOIN?

It is based on all columns in the 2 tables that have the same name and datatypes


NOTE: Using clause can be used to specify only those columns that should be used for an Equii Join.

ON condition is used to specify a join condition. This lets us specify join condition separate from any search / filter condition in where clause.

What is SELF JOIN ?

Joining a table to itself is self join. In the below query, you look into the table twice. the first time you look in the table to find Name in the name column and managerId value in the managerId column. The second time you look in the EmpId column to find the employee with the managerId value got from the first result and the name column to find the name.

Ex:

SELECT Employee.name  ‘Works for ‘ manager.name

FROM emp Employee , emp manager

WHERE Employee.managerId = manager.EmpId


How to join 3 tables using joins?

Joins are always performed from Left to Right. First Join condition can reference column in Emp and Dept tables but cannot reference columns in Loc Table. Second join can reference columns from all the three tables.

Ex:

SELECT EmpId,City,DeptName

FROM Emp e

JOIN Dept d

ON d.DeptId = e.DeptId

JOIN Loc l

ON d.LocId = l.LocId


Or


Select EmpId, City, DeptName

FROM Emp, Dept, Loc

WHERE Emp.DeptId = Dept.DeptId

AND Dept.LocId = Loc.LocId







.

.

.

.

.





XML in Dotnet

This article covers:


1. Basic concepts of XML.

2. Example of adding an XML file in Visual Studio.

3. Different ways of Processing XML

a. XMLReader and XMLWriter

b. XmlDocument

c. XPath.

4. Loading XML data into Dataset.



Basic contepts of XML:

What is XML: XML is a standard by W3C.

XML provides structure to the ordinary text data.

It is used for exchanging information between objects developed in different programming languages. It is used to exchange data between incompatible systems over internet.

Data is stored in plain text format in xml file.

What is a well formed xml document ?

Ans: Every XMLdocument must be well formed

1. It should have only one root element tag.

2. Tags are case-sensitive and hence the opening and closing tag case must match.

3. Every tag must be closed.

4. Tags must not overlap each other.

5. The value of attributes must be enclosed in quotes.

What is XML Schema document?

Ans: It contains declarations of various XML constructs including elements, attributes etc. These declarations define the syntax and the restrictions while using them in an XML document. An XML document is validated using XML schema document and it is optional.





2. Example of adding XML file in a Website.

1. Open Microsoft Visual Studio2008. Go to File ->New ->Website -> Select ASP.NET website under Visual Studio Installed Templates ->Browse for the location where you want to create your website or type the folder name as XMLDemo.

2. Go To View in the MenuBar and select Solution Explorer. Right Click on your Web Application and select Add New Item-> Select XML File under Visual Studio Installed Templates. Give the name for the XMl file as Employee.xml. This will Add Employee.xml file in your application.

3. Open the Employee.xml file (It will be opened as soon as you add it to your application). The instruction below

<?xml version="1.0" encoding="utf-8" ?> implies that this is an xml file version 1.0 and the encoding format is utf-8.

4.Type the below text into the XML file.

<EmployeeInfo>


<Employee id="1">


<Name>xyz</Name>


<Department>IT</Department>


</Employee>


<Employee id="2">


<Name>abc</Name>


<Department>Sales</Department>


</Employee>


<Employee id="3">


<Name>bbb</Name>


<Department>HR</Department>


</Employee>


<Employee id="4">


<Name>aaa</Name>


<Department>IT</Department>


</Employee>


<Employee id="5">


<Name>ccc</Name>


<Department>HR</Department>


</Employee>


</EmployeeInfo>




Loading XML data from an XML document into Dataset

DataSet ds = new DataSet();//Create a new Dataset


ds.ReadXml(MapPath("Employee.xml"));//Read the xml file contents into dataset


StringBuilder sb = new StringBuilder();//using stringbuilder object to display xml file contents from dataset


//displaying the contents of the Table "Employee"


foreach (DataRow dr in ds.Tables["Employee"].Rows)


{


foreach (DataColumn dc in ds.Tables["Employee"].Columns)


{


sb.Append( dr[dc.ColumnName] + " "); //separate each column value separated with space.


}


sb.Append("<br/>");//Go to next line


}


Response.Write(sb);//display the data




write an XML representation of a DataSet to a string .

Below example shows how to obtain the XML representation of the DataSet as a string. We use the GetXml method as shown in the following example.

//Getting xml data from the dataset


string xmlData = ds.GetXml();


Response.Write(xmlData);






//Writing data from the dataset to Employee1.xml file without the schema


ds.WriteXml(MapPath("Employee2.xml"), XmlWriteMode.IgnoreSchema);






///Writing data from the dataset to Employee1.xml file along with the schema


ds.WriteXml(MapPath("Employee1.xml"), XmlWriteMode.WriteSchema );



The XML classes in the System.Xml namespace allow you to work with XML documents and data.

The XML classes support parsing and writing XML, editing XML data in memory, data validation and XSLT transformation.

In the .Net Framework, we have following XML namespaces:

System.Xml, System.Xml.XPath, System.Xml.Xsl, System.Xml.Schema, System.Xml.Linq.

Different ways of XML Processing :

1. Stream based XML processing: The XmlReader and XmlWriter classes provide a non-cached, forward-only means of processing XML data.

2. In-Memory XML processing: XmlDocument class and XPathNavigator class.

Stream based XML Processing :

1. XmlReader provides forward-only, read-only access to a stream of XML data. It is an abstract class.

2. XMLTextReader and XMLTextWriter are stream based parsers:

• XMLTextReader represents a reader that provides fast, non-cached, forward-only access to xml data.

• Used if the XML document needs to be parsed only once.

• Parsing the XML document using stream based parsers is faster when compared to DOM API as the complete document is not loaded into memory at once.

• XMLTextReader is only used for READONLY operations.

• XMLTextWriter can be used only to create a new XML file, but we cannot modify the already existing XML file.

3. Using XMLTextReader to read all the employee id’s from the Employee.xml file

Steps:

a. Initialize a new instance of XmlTextReader class with the specified file Employee.xml.

b. Position the reader for reading from the XML file using Read() method.

c. Check if the NodeType is XmlNodeType.Element and the node name is “Employee”.

d. Get the attribute value from the node and display it.

e. Close the XML Reader.

XmlTextReader xr = new XmlTextReader(MapPath("Employee.xml"));


while (xr.Read())//Reader is advanced using the Read method.


{


//Gets the id of each employee by comparing the nodetype with element and name with "Employee"


//Then retreives the attribute of that element.


if (xr.NodeType == XmlNodeType.Element && xr.Name == "Employee")


{


string attributeValue = xr.GetAttribute("id");


Response.Write(attributeValue + " ");


}


}


xr.Close();//Close the XmlTextReader


4. Read and Display the names of the Employee


//Display the names of the Employee.


XmlTextReader xr = new XmlTextReader(MapPath("Employee.xml"));


while (xr.Read())//Reader is advanced using the Read method.


{






if (xr.NodeType == XmlNodeType.Element && xr.Name == "Name")


{


//First way of reading the data


xr.Read(); //Reads the text node.


Response.Write(xr.ReadContentAsString());






Response.Write("<br/>");//Go to next line






//Second way of reading the data


// Response.Write(xr.ReadString() + " ");






}


}


Xr.Close();

Saturday, July 10, 2010

Exception handling in ASP.NET

This article covers how to handle Application level Errors in ASP.NET

In Web Applications, There are generally four ways of handling the Exceptions.

a. In Try,Catch Block.
b. In Page_Error event.
c. In Application_Error event of Global.asax file.
d. Using Custom Errors in web.config file.

Contents:
1. Four ways of handling the Exceptions.
2. Advantages and Disadvantages of each of the above ways of handling Exceptions.
3. When to use what kind of Exception handling Technique.

Error handling using Try/Catch block :
I am not showing here how to use try catch block rather I am showing you the various ways of handling errors in ASP.NET. We have to use Try/Catch blocks around any code that is subject to errors. Example below takes the numerator and denominator values from the values entered by the user in textbox and performs division. Since the division logic is enclosed in try catch block, If the denominator is 0 the division operation results in Attempted to divide by zero exception and the execution is transferred to catch block where we are handling the exception and displaying the corresponding exception message to the user.
The following code demonstrates this:
try
{
decimal num1 = Decimal.Parse(txtNum1.Text);
decimal num2 = Decimal.Parse(txtNum2.Text);
decimal result = num1 / num2;
Response.Write(result);


}
catch (Exception ex)
{
Response.Write(ex.Message);
}
If possible, you should handle errors in Try/Catch blocks within your code, because a problem is more easily corrected where it occurs. As in the above example, user can understand what is the problem and correct the problem and the page needs to return to the same place.

2. Page Level Error Handler :
When an error occurs in a page if it is not handled in the Try/Catch block. If a Page-level handler handles the error, it returns you to the page, but there is no longer anything on the page because instances of controls are not created. To provide the user any information, you must specifically write it to the page.

You can use a page-level error handler :
1. To log unhandled errors.
2. To take the user to a page that can display helpful information.

This code example shows a handler for the Error event in an ASP.NET Web page. This handler catches the exceptions that are not already handled within Try/Catch blocks in the page.
protected void Page_Error(object sender, EventArgs e)
{
Server.Transfer("~/ErrorHandler.aspx");//Whenever an error occurs in this webpage and if it is not handled in try/catch block. User is redirected to ErrorHandler.aspx page.
}

Handling errors in Global.asax file :
All the errors that are not caught with a Try/Catch block or in a page-level error handler can be caught in error handler in the Global.asax file.
This code example shows how to create an error handler in the Global.asax file that will catch all unhandled ASP.NET errors while processing a request. The Application_Error event handler in Global.asax will process all unhandled errors.
If the Global.asax file is not added to your Website. Go to View Menu ->Select Solution Explorer ->Right Click on the Project ->Select Add New Item -> Under Templates select Global Application Class (Name: Global.asax) ->click on Add. This will add and open Global.asax file in Visual Studio.
The following example provides the ErrorLogUtility file. All the errors which might occur in a Web Application are written to the ErrorLog file. You can also immediately notify system/site administrators of a problem that occurs in a web Application. The following ErrorLogUtility has a static method to log the exception. How this method is implemented in your code depends on the needs of the organization. For this example, you must grant write permissions to the NETWORK SERVICE /ASPNET account for the App_Data folder to enable the application to write to the error log file present in App_Data folder of you application.
In the App_Code folder of your Application. Add a class ErrorLogUtility. Right click on App_Data folder and add a Text File (Name: ErrorLog.txt) to the website.
public class ErrorLogUtility
{
public ErrorLogUtility()
{
//
// TODO: Add constructor logic here
//
}
// Log an Exception
public static void LogError(Exception exc)
{
// Include the logic for logging exceptions
// Get the absolute path to the log file
string logFile = "App_Data/ErrorLog.txt";
logFile = HttpContext.Current.Server.MapPath(logFile);
// Open the log file for append and write the log
StreamWriter sw = new StreamWriter(logFile, true);
sw.Write("----------------------- " + DateTime.Now);
sw.WriteLine(" --------------------");
if (exc.InnerException != null)
{


sw.Write("Inner Exception: ");
sw.WriteLine(exc.InnerException.Message);


if (exc.InnerException.StackTrace != null)
sw.WriteLine("Inner Stack Trace: ");
sw.WriteLine(exc.InnerException.StackTrace);
}


sw.WriteLine("Exception: " + exc.Message);
sw.WriteLine("Stack Trace: ");
if (exc.StackTrace != null)
sw.WriteLine(exc.StackTrace);
sw.WriteLine();
sw.Close();
}


The following code should be written in the Global.asax file to handle the error and log the error.
void Application_Error(object sender, EventArgs e)
{


// Code that runs when an unhandled error occurs
// Give the user error information and log it.
Exception ex = Server.GetLastError();
Response.Write("Global Page Error\n");Global Page Error
\n");
Response.Write(" +ex.Message + "\n");


if (ex.InnerException != null)
Response.Write("Error " +ex.InnerException.Message + "");



Response.Write(@"Go Back");


// Log the exception and notify system operators
ErrorLogUtility.LogError(ex);


// Clear the error from the server
Server.ClearError();


}


Handling the Errors using web.config file:
Uncomment the CustomErrors section found under Authentication section in web.config file. Add three files GenericErrorPage.htm, NoAccess.htm, FileNotFound.htm to your website with error details describing the error.
The section enables configuration of what to do when an unhandled error occurs during the execution of a request. We can configure either html or aspx error pages to be displayed in place of a error stack trace. If the error occurs in your application and the Error Status code is 403 then the user is redirected to NoAccess.htm page similarly if the Error Status code is 404 then the user is redirected to FileNotFound.htm page. You can write any number of error sections under customErrors depending on the requirement. If the error statusCode is neither 403 nor 404 then the user is redirected to GenericErrorPage.htm as specified in the defaultRedirect attribute of customErrors section. When the user is redirected to customErrorPage like NoAccess.htm, the querystringparameter “aspxerrorpath” is appended to the url of the page which actually has the error.




The mode attribute of customErrors section takes any of the following values:
1. RemoteOnly : This configures the application to show detailed errors only to local users (Developer). If the request is from a Remote user, Redirect the user to Custom error page.
2. Off : Both Local and Remote users , It shows detailed errors and does not redirect to custom Error page.
3. On: Both Local and Remote users are redirected to the Error Page.

Important Points:
1. It is better to use Try/Catch blocks around any code that is subject to errors instead of relying on a global error handler.
2. Never set customErrors to Off in your Web.config file if you do not have an Application_Error handler in your Global.asax file. Potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.
3. An error handler that is defined in the Global.asax file will only catch errors that occur during processing of requests by the ASP.NET runtime. For non-ASP.NET errors, you can create a custom handler in Internet Information Services (IIS). The custom handler will also not be called for server-level errors.
4. You cannot directly output error information for requests from the Global.asax file; you must transfer control to another page, typically a Web Forms page. When transferring control to another page, use Transfer method. This preserves the current context so that you can get error information from the GetLastError method.
5. After handling an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class).
6. Include error handling whenever practical and construct your own error messages. In your error handler, you can test to see whether the user is local and react accordingly.
7. Create a global error handler at the page or application level that catches all unhandled exceptions and routes them to a generic error page. That way, even if you did not anticipate a problem, at least users will not see an exception page.

Note: Always Global.asax file settings will take precedence over the web.config file CustomErrors settings.

Keywords:
Global.asax: 1. Every Web Application can contain only one Global.asax file and it must be present in the root directory.
2. When the Web application is started, ASP.NET creates an instance of the Global.asax class that is derived from HttpApplication class and this class is used to represent the application.
Exception: Errors in the program at run time are called exceptions.
Context: Provides access to the entire current context such as user session,Current Http Request. You can use this class to share information between pages.
Custom Errors: Provides information about custom error messages for an ASP.NET application.
Network Service/ASPNET account: By default, ASP.NET pages run with the Windows identity of the service that processes ASP.NET pages on the Web server. On a computer running Windows Server 2003, that identity is by default, the NETWORK SERVICE account. On computers running Windows 2000 and Windows XP Professional, the identity is the local ASPNET account which is created when the .NET Framework is installed.
MapPath: It returns the Physical path that corresponds to the specified virtual path on the Web Server.
InnerException: Gets the Reference to actual Exception raised in the page that caused the current Exception.

Handling Expcetions in ASP.NET

This article covers how to handle Application level Errors in ASP.NET
In Web Applications, There are generally four ways of handling the Exceptions.
a. In Try,Catch Block.
b. In Page_Error event.
c. In Application_Error event of Global.asax file.
d. Using Custom Errors in web.config file.
In this Article we will see
Contents:
1. Four ways of handling the Exceptions.
2. Advantages and Disadvantages of each of the above ways of handling Exceptions.
3. When to use what kind of Exception handling Technique.

Error handling using Try/Catch block :
I am not showing here how to use try catch block rather I am showing you the various ways of handling errors in ASP.NET. We have to use Try/Catch blocks around any code that is subject to errors. Example below takes the numerator and denominator values from the values entered by the user in textbox and performs division. Since the division logic is enclosed in try catch block, If the denominator is 0 the division operation results in Attempted to divide by zero exception and the execution is transferred to catch block where we are handling the exception and displaying the corresponding exception message to the user.
The following code demonstrates this:
try
{
decimal num1 = Decimal.Parse(txtNum1.Text);
decimal num2 = Decimal.Parse(txtNum2.Text);
decimal result = num1 / num2;
Response.Write(result);

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
If possible, you should handle errors in Try/Catch blocks within your code, because a problem is more easily corrected where it occurs. As in the above example, user can understand what is the problem and correct the problem and the page needs to return to the same place.
2. Page Level Error Handler :
When an error occurs in a page if it is not handled in the Try/Catch block. If a Page-level handler handles the error, it returns you to the page, but there is no longer anything on the page because instances of controls are not created. To provide the user any information, you must specifically write it to the page.
You can use a page-level error handler :
1. To log unhandled errors.
2. To take the user to a page that can display helpful information.
This code example shows a handler for the Error event in an ASP.NET Web page. This handler catches the exceptions that are not already handled within Try/Catch blocks in the page.
protected void Page_Error(object sender, EventArgs e)
{
Server.Transfer("~/ErrorHandler.aspx");//Whenever an error occurs in this webpage and if it is not handled in try/catch block. User is redirected to ErrorHandler.aspx page.
}
Handling errors in Global.asax file :
All the errors that are not caught with a Try/Catch block or in a page-level error handler can be caught in error handler in the Global.asax file.
This code example shows how to create an error handler in the Global.asax file that will catch all unhandled ASP.NET errors while processing a request. The Application_Error event handler in Global.asax will process all unhandled errors.
If the Global.asax file is not added to your Website. Go to View Menu ->Select Solution Explorer ->Right Click on the Project ->Select Add New Item -> Under Templates select Global Application Class (Name: Global.asax) ->click on Add. This will add and open Global.asax file in Visual Studio.
The following example provides the ErrorLogUtility file. All the errors which might occur in a Web Application are written to the ErrorLog file. You can also immediately notify system/site administrators of a problem that occurs in a web Application. The following ErrorLogUtility has a static method to log the exception. How this method is implemented in your code depends on the needs of the organization. For this example, you must grant write permissions to the NETWORK SERVICE /ASPNET account for the App_Data folder to enable the application to write to the error log file present in App_Data folder of you application.
In the App_Code folder of your Application. Add a class ErrorLogUtility. Right click on App_Data folder and add a Text File (Name: ErrorLog.txt) to the website.
public class ErrorLogUtility
{
public ErrorLogUtility()
{
//
// TODO: Add constructor logic here
//
}
// Log an Exception
public static void LogError(Exception exc)
{
// Include the logic for logging exceptions
// Get the absolute path to the log file
string logFile = "App_Data/ErrorLog.txt";
logFile = HttpContext.Current.Server.MapPath(logFile);
// Open the log file for append and write the log
StreamWriter sw = new StreamWriter(logFile, true);
sw.Write("----------------------- " + DateTime.Now);
sw.WriteLine(" --------------------");
if (exc.InnerException != null)
{

sw.Write("Inner Exception: ");
sw.WriteLine(exc.InnerException.Message);

if (exc.InnerException.StackTrace != null)
sw.WriteLine("Inner Stack Trace: ");
sw.WriteLine(exc.InnerException.StackTrace);
}

sw.WriteLine("Exception: " + exc.Message);
sw.WriteLine("Stack Trace: ");
if (exc.StackTrace != null)
sw.WriteLine(exc.StackTrace);
sw.WriteLine();
sw.Close();
}


The following code should be written in the Global.asax file to handle the error and log the error.
void Application_Error(object sender, EventArgs e)
{

// Code that runs when an unhandled error occurs
// Give the user error information and log it.
Exception ex = Server.GetLastError();
Response.Write("

Global Page Error

\n");
Response.Write(
"

" + ex.Message + "

\n");
if (ex.InnerException != null)
Response.Write("Error " +ex.InnerException.Message + "

");
Response.Write(@"Go Back");

// Log the exception and notify system operators
ErrorLogUtility.LogError(ex);

// Clear the error from the server
Server.ClearError();

}

Handling the Errors using web.config file:
Uncomment the CustomErrors section found under Authentication section in web.config file. Add three files GenericErrorPage.htm, NoAccess.htm, FileNotFound.htm to your website with error details describing the error.
The section enables configuration of what to do when an unhandled error occurs during the execution of a request. We can configure either html or aspx error pages to be displayed in place of a error stack trace. If the error occurs in your application and the Error Status code is 403 then the user is redirected to NoAccess.htm page similarly if the Error Status code is 404 then the user is redirected to FileNotFound.htm page. You can write any number of error sections under customErrors depending on the requirement. If the error statusCode is neither 403 nor 404 then the user is redirected to GenericErrorPage.htm as specified in the defaultRedirect attribute of customErrors section. When the user is redirected to customErrorPage like NoAccess.htm, the querystringparameter “aspxerrorpath” is appended to the url of the page which actually has the error.




The mode attribute of customErrors section takes any of the following values:
1. RemoteOnly : This configures the application to show detailed errors only to local users (Developer). If the request is from a Remote user, Redirect the user to Custom error page.
2. Off : Both Local and Remote users , It shows detailed errors and does not redirect to custom Error page.
3. On: Both Local and Remote users are redirected to the Error Page.

Important Points:
1. It is better to use Try/Catch blocks around any code that is subject to errors instead of relying on a global error handler.
2. Never set customErrors to Off in your Web.config file if you do not have an Application_Error handler in your Global.asax file. Potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.
3. An error handler that is defined in the Global.asax file will only catch errors that occur during processing of requests by the ASP.NET runtime. For non-ASP.NET errors, you can create a custom handler in Internet Information Services (IIS). The custom handler will also not be called for server-level errors.
4. You cannot directly output error information for requests from the Global.asax file; you must transfer control to another page, typically a Web Forms page. When transferring control to another page, use Transfer method. This preserves the current context so that you can get error information from the GetLastError method.
5. After handling an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class).
6. Include error handling whenever practical and construct your own error messages. In your error handler, you can test to see whether the user is local and react accordingly.
7. Create a global error handler at the page or application level that catches all unhandled exceptions and routes them to a generic error page. That way, even if you did not anticipate a problem, at least users will not see an exception page.






Note: Always Global.asax file settings will take precedence over the web.config file CustomErrors settings.







Keywords:
Global.asax: 1. Every Web Application can contain only one Global.asax file and it must be present in the root directory.
2. When the Web application is started, ASP.NET creates an instance of the Global.asax class that is derived from HttpApplication class and this class is used to represent the application.
Exception: Errors in the program at run time are called exceptions.
Context: Provides access to the entire current context such as user session,Current Http Request. You can use this class to share information between pages.
Custom Errors: Provides information about custom error messages for an ASP.NET application.
Network Service/ASPNET account: By default, ASP.NET pages run with the Windows identity of the service that processes ASP.NET pages on the Web server. On a computer running Windows Server 2003, that identity is by default, the NETWORK SERVICE account. On computers running Windows 2000 and Windows XP Professional, the identity is the local ASPNET account which is created when the .NET Framework is installed.
MapPath: It returns the Physical path that corresponds to the specified virtual path on the Web Server.
InnerException: Gets the Reference to actual Exception raised in the page that caused the current Exception.

Saturday, July 3, 2010

Navigate to previous page in ASP.NET

Requirement: To Get the URL of the previous page from which I was redirected to the New page in the Button click event handler of the New Page so that I can redirect the user to previous page.
In this article we will see how to get the URL of the previous page from which you were redirected to the New page.
We have to use UrlReferrer  property of Request  object to access previous page url. The UrlReferrer property is used to get the information about the URL of the client's previous request that linked to the current URL.
Please follow the below steps for the requirement given above.
Step1: Creating a new Website: PrvsPageDemo
a.     Open Visual Web Developer or VisualStudio 2008.
b.     On the File menu, click New Website, In the Dialog box that appears Under VisualStudioInstalled templates  select ASP.NET Website.
c.     Then Type the location (Foldername) where you want to create your website such as D:\ PrvsPageDemo in the second location box.
d.     Select the language you want to create website in. Let us select C#.
e.     Click ok , This will create a website with the name PrvsPageDemo. This website by default contains a Webpage named Default.aspx.
f.        Add 2 more Webpages namely Management.aspx  and Development.aspx page to the website. (Go to View tab ->click on SolutionExplorer -> In the Solution Explorer window right click on the Project name(PrvsPageDemo) -> Select Add New Item -> In the name Box: type Management.aspx and then click on Add. Similarly add Development.aspx page.)
Step 2: In the Default Page Source view, add the following code under form tag.
<div>
    This is Default Page.<br /><br />
    <asp:Button runat="server" ID="btnBack" Text="Back" onclick="btnBack_Click" />
    </div>
Go to Default.aspx.cs file and add the following code as below:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) //check if the webpage is loaded for the first time.
        {
            ViewState["PreviousPage"] = Request.UrlReferrer;//Saves the Previous page url in ViewState
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        if (ViewState["PreviousPage"] != null)//Check if the ViewState contains Previous page URL
        {
            Response.Redirect(ViewState["PreviousPage"].ToString());//Redirect to Previous page by retrieving the PreviousPage Url from ViewState.
        }
    }

Here, In the Default.aspx page we have added some static text and a Back Button.
In the Default.aspx.cs page, In the PageLoad event , in !IsPostBack section, we are Saving the value of the Request.UrlReferrer in viewState which is the Previous page URL and using the same in the Back Button click event handler.
In the Button click , We are first checking if ViewState contains Previous page url. If the ViewState contains Previous Page URL then we are using the viewstate information to redirect the user back to the previous page.

Step 3: In the Management.aspx page under form tag, add the following code:
<div>
    This is management Page.<br /><br />
        <asp:Button ID="btnDefault" runat="server" Text="Go to Default Page"
            onclick="btnDefault_Click" />
    </div>
In the code-behind file (Management.aspx.cs ) add the below code:
protected void btnDefault_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }
Here, When you click the button, User is redirected to Default.aspx page as written in the btnDefault_click event handler of the button.

Step 4: In the Development.aspx page under form tag, add the following code:
<div>
    This is Development Page.<br /><br />
        <asp:Button ID="btnDefault" runat="server" Text="Go to Default Page"
            onclick="btnDefault_Click" />
    </div>
In the code-behind file (Development.aspx.cs ) add the below code:
protected void btnDefault_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }
Here, When you click the button, User is redirected to Default.aspx page.

Step 5:   Press CTRL + F5 to execute the Default page.
The Webpage (Default.aspx page) appears in the web browser. Click the Back button nothing happens.
Now view the Management.aspx page and then click on the button on this page which will redirect you to Default Page. When you click on Back button on Default.aspx page now. It will redirect you to Management.aspx page. Similarly try accessing Development.aspx page.
Conclusion: Using Request.UrlReferrer we can get the Previous page url of the current request. Previous Page information is available in the Request.UrlReferrer  property only if user is redirected to the current page from some other page and is available in the !Page.IsPostBack of Page Load event of the form.Here we are using ViewState because it can be used if you want to store the values on postback to the same form. ViewState is used for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.



Post back using Javascript


This article shows how to postback the ASP.NET webpage to server using Javascript and raise a server control event.
In this article we will post back the ASP.NET webpage to server and raise the TextChanged Event of TextBox1  textbox control using Javascript.
 Prerequisites.
1.      The AutoPostBack property of Textbox must be set to false.
2.      The TextChanged event of Textbox must be defined in the Code-Behind file.
Below steps shows how to do this. 
Step1: Creating a new Website: Demo1
a.     Open Visual Web Developer or VisualStudio 2008.
b.     On the File menu, click New Website, In the Dialog box that appears Under VisualStudioInstalled templates  select ASP.NET Website.
c.     Then Type the location (Foldername) where you want to create your website such as D:\Demo1 in the second location box.
d.     Select the language you want to create website in. Let us select C#.
e.     Click ok , This will create a website with name Demo1. This website by default contains a Webpage named Default.aspx.
Step 2: Adding Textbox to the Default.aspx form and generating TextChanged event handler.
a.     Go to View Menu -> Select Toolbox -> From the Toolbox window ->Under Standard section Drag and Drop a Textbox control  and a Button control on the Default.aspx page or  You can also copy and paste the below code in form tag.
<div>
        <asp:TextBox ID="TextBox1" AutoPostBack="false" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox><asp:Button
            ID="Button1" OnClientClick="RaiseEvent();" runat="server" Text="Button" />
    </div>
b.     In VisualStudio /Visual WebDeveloper, switch to Design view . Right click the Textbox control  and then click on Properties. This displays the properties window for the Textbox control on right. In this window click on Events tab which is next to properties tab.
c.     In the Event tab, you will find TextChanged event listed above unload event from bottom. Double-click on TextChanged event. This will generate TextChanged event handler for the textbox control in the Code-Behind file as below.
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {

    }
d.     In the above () event handler write the following code to display some text on browser.
e.     Response.Write("You entered " + TextBox1.Text);
protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        Response.Write("You entered " + TextBox1.Text);
    }

Step 3: Writing Javascript code to raise the TextChanged event of the textbox.
a.    Now, Switch to Source view of Default.aspx page, by selecting the source tab at the bottom of the page.
b.    In the head section of the Default.aspx page write the following code.
<script type="text/javascript" language="javascript">
        function RaiseEvent()
        {
            __doPostBack('window.document.forms[0].TextBox1', 'TextChanged');
        }
</script>
This function has a javascript method: __doPostBack (2 underscores doPostBack) which takes 2 parameters. The first parameter (window.document.forms[0].TextBox1) is the id of the control whose event has to be raised on server. The second parameter('TextChanged') is the name of the event to be raised.
c.    For the Button control add the following attribute and the corresponding value which will call the javascript method RaiseEvent when the button is clicked by the user.
<asp:Button ID="Button1" OnClientClick="RaiseEvent();" runat="server" Text="Button" />

Step 4: Press CTRL + F5 to execute the Default page.
The Webpage (Default.aspx page) appears in the webbrowser which shows The Textbox and a Button. Enter some value like test in the textbox and hit the button.  You will see that the form is posted to server and TextChanged event of the Textbox is raised which will display text like: You entered test.
Note: Once the TextChanged event is raised on server. If the value in the TextBox is not changed and when you click on Button again. Though the Webpage is posted to server the TextChanged event of TextBox is not fired as the name value pairs of the TextBox which are posted to server in the previous postback is same as now.  So In order to raise the TextChanged event of the Textbox the value of the Textbox must be different from the previous one.



how to display data in the GridView from the Database Table Emp


This article explains how to display data in the GridView from the Database Table Emp.
Let us first assume that We have a database Table Emp with columns EmpId,EmpName,EmpSal in the database CompanyDB.
Requirement: To display the Employee details from the Emp table in the GridView.
Step1: Creating a new Website: GridViewDemo
a.     Open Visual Web Developer or VisualStudio 2008.
b.     On the File menu, click New Website, In the Dialog box that appears Under VisualStudioInstalled templates  select ASP.NET Website.
c.     Then Type the location (Foldername) where you want to create your website such as D:\GridViewDemo in the second location box.
d.     Select the language you want to create website in. Let us select C#.
e.     Click ok , This will create a website with name GridViewDemo. This website by default contains a Webpage named Default.aspx.
Step2:  Adding GridViewControl to display data.
a.     Open the Default.aspx page. 
b.     Go to View Menu -> Select Toolbox -> From the Toolbox window ->Under Data section Double click on Gridview or Drag and Drop the GridView from the Toolbox onto the Default.aspx page.
c.     In VisualStudio /Visual WebDeveloper, switch to Design view . Right click the GridView control  and then click on ShowSmartTag -> This displays a small button with an arrow (>) on the extreme right-top of the gridivew(SmartTag).
d.     select the smart tag, this will open the gridiview tasks menu, in the choose datasource list click the dropdown and select  New Datasource. The Data Source configuration dialog box appears.
e.     Click Database->This specifies that you want to fetch data from database. In the Specify an ID for the data source textbox, a default data source control name appears (SqlDataSource1).
f.        Click Ok.
g.     The Configure Data Source Wizard appears, which displays a page on which you can choose a connection to the database.
h.      Click New connection . In the Add Connection Window. Change the Data Source to Microsoft SQL Server.
i.         The servername should be database server name. If it is the localsystem on which you are trying to connect to the database. Usually it is .\SQLEXPRESS. Where . (dot)here represents the current machine name. SQLEXPRESS is the database server instance name.
j.         Tip: How to find the Database server Instance name:  (StartMenu->All Programs->Administrative Tools->Service->In the services window search for service with the name SQL  Server. Beside this you will find Database Server instance name in paranthesis(generally it is SQL EXPRESS). This name is the Server name which has to be specified in the above Add connection window after “.\”
k.      Let the Windows authentication be selected for log in and connecting to the database or if required you can type the username and password. Then select the database from which you want to display the data.
l.         The Emp table is present in CompanyDB database so I selected CompanyDB here.

m.    Click Next.
n.      The wizard appears, displaying a page on which you can choose to store the connection string in the configuration file
o.     Click Next again.
p.     Under Specify columns from a table or view, in the Name list, click Emp
q.     Under Columns, select the EmpId,EmpName, EmpSal checkboxes.
r.        This window also displays the SQL statement that you are creating in a box at the bottom of the window.
s.       Click Next and then Click Test Query to make sure that you are fetching the data you want.
t.         Click on finish.
u.      Press CTRL + F5 to execute the Default page.
v.     The Webpage (Default.aspx page) appears in the webbrowser which shows The Gridview displaying all the datarows from the Emp table of CompanyDB database.

Conclusion: In this article we have seen how to fetch selectted data from the SQLSERVER database and display in the GridView.