Sunday, June 3, 2012

Interview Questions on ASP.NET Exception Handling

What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.


What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation.
                try
                catch
                finally
2. Use error events to deal with exceptions within the scope of an object.
                Page_Error
                Global_Error
                Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.


Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.


Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.


What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.


How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the catch statement.

Will the following code block compile?
try
{
     throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
     Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
     Response.Write(FNFE.Message);
}


No, the following compile time error is reported.
A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').



Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample, FileNotFoundException should be placed before the general Exception catch block.


What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception classes based on the ApplicationException class.

For example, the following code defines a class for the UserLoggedOnException:


public class UserLoggedOnException : System.ApplicationException
{
     // Exception constructor (overloaded).
     public UserLoggedOnException()
     : this("The user is already logged on to the server", null)
     {
     }
     public UserLoggedOnException(string message)
     : this(message, null)
     {
     }
     public UserLoggedOnException(string message, Exception inner)
     : base(message, inner)
     {
     }
}
The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception class provides only its own constructor to set the default message to display. This is a standard practice.


What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application, ASP.NET fires the error events shown below.


Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.


Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the following ways:


As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exception-handling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception in a log as part of an ongoing effort to improve your application.


Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the ClearError method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
     // Get the error.
     Exception ex = Server.GetLastError();
     // Store the message in a session object.
     Session["Error"] = ex.Message;
     // Clear the error message.
     Server.ClearError();
     // Redisplay this page.
     Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:


Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
     // Display error. if any.
     if (Session["Error"] != null)
     {
     litError.Text = "The following error occurred:
     " +
     Session["Error"].ToString();
     // Clear the Session state variable.
     Session["Error"] = null;
     }
}


Can you have a try block without a catch or a finally block?
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either a catch block or a finally block or both.


Is the following code legal?
try
{
     Response.Write("Try block executed");
}
finally
{
     Response.Write("Finally block executed");
}


Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.


What is wrong with using the following type of exception handler?
catch(Exception E)
{
     //Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.




Will the second catch block handle the exception thrown by the first catch block?
try
{
     throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
     Response.Write(FNFE.Message);
     throw new Exception();
}
catch(Exception E)
{
     Response.Write(E.Message);
}


No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.


What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
     throw new Exception();
     try
     {
          Response.Write("Hello");
     }
     catch (Exception E)
     {
          Response.Write(E.Message);
     }
}

The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block.

Sunday, February 26, 2012

Combine multiple rows in a single column, Concatenate records without UDF


CREATE TABLE test
(
id INT, Categoryid INT, Category VARCHAR(50), Status VARCHAR(50)
)

------------------------------
INSERT INTO test(id,categoryid,category,[Status])
SELECT 34676 ,02 ,'CLOTHING' ,'ACTIVE'
UNION
SELECT 34676 ,02 ,'CLOTHING' ,'DANCE'
UNION
SELECT 34676 ,02 ,'CLOTHING' ,'LWR'
----------------------------------

There is two ways to implement this
1.
SELECT DISTINCT id,categoryid,category ,dbo.fnMurliTest(categoryid) As NewColumn From test

Alter function fnTest(@int int)
Returns varchar(8000) As
Begin
DECLARE @strOutput VARCHAR(8000)
SET @strOutput = ''
SELECT @strOutput = @strOutput + ',' + [Status] FROM test
WHERE [CategoryID] = @int ORDER BY [Status]
RETURN STUFF(@strOutput, 1, 1, '')
--RETURN SubString(@strOutput, 2, 8000)
End

2.
SELECT DISTINCT id,categoryid,category,
(
SELECT ',' + status as 'data()'
FROM test
FOR XML PATH('')
) As NewColumn
FROM test

Thursday, February 23, 2012

jQuery Function

jQuery substring

jQuery('#textArea').keypress(function() {
var text = jQuery('#textArea').val();
if
(text.length > 400) {
text = text.substring(0, 400);
jQuery('#textArea').val(text); }
}
);

jQuery refresh page
jQuery('#refresh-link').click(function() {     
location.reload();
}
);

jQuery message box

#darkbg {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;

opacity: .5;
filter: alpha(opacity=50);
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
}
#message_box {
width: 300px;
height: 150px;
background: #fff;

border: 4px solid #f0f0f0;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;

position: absolute;
top: 100px;
left: 50%;
margin-left: -150px;

text-align: center;
z-index: 1000;
display: none;
}
#message_box input[type=button] {
float: right;
margin-right: 10px;
}

var message_box = function() {
var button = '<input type="button" onclick="message_box.close_message();" value="Okay!" />';
return {
show_message: function(title, body) {
if(jQuery('#message_box').html() === null) {
var message = '<div id="message_box"><h1>' + title + '</h1>' + body + '<br/>' + button + '</div>';
jQuery(document.body).append( message );
jQuery(document.body).append( '<div id="darkbg"></div>' );
jQuery('#darkbg').show();
jQuery('#darkbg').css('height', jQuery('html, body').height());
jQuery('#message_box').css('top', jQuery('html, body').scrollTop() + 150);
jQuery('#message_box').show('slow');
} else {
var message = '<h1>' + title + '</h1>' + body + '<br/>' + button;
jQuery('#darkbg').show();
jQuery('#darkbg').css('height', jQuery('html, body').height());
jQuery('#message_box').css('top', jQuery('html, body').scrollTop() + 150);
jQuery('#message_box').show('slow');
jQuery('#message_box').html( message );
}
},
close_message: function() {
jQuery('#message_box').hide('fast');
jQuery('#darkbg').hide();
}
}
}();

----------
message_box.show_message('Hi!', 'Whatup?!');
-------------

jQuery('#some_link').onclick(function() { message_box.show_message('Hi!', 'Whatup?!'); });

Javascript to count selected items in CheckBoxList

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
CheckBoxList1.Attributes.Add("onclick", "javascript:CopyNumItemsToTextBox();")
End Sub

--------------------------------

function CopyNumItemsToTextBox() {
//This function updates TextBox1 with the number of items checked when an item is checked/unchecked
//Get the checkbox object
var textBox = document.getElementById("TextBox1");
//Get the checkboxlist object
var checkBoxList = document.getElementById("CheckBoxList1");
//Get the number of checkboxes in the checkboxlist
var numCheckBoxItems = checkBoxList.cells.length;
var numItemsChecked = 0;

for(i=0; i<numCheckBoxItems; i++)
{
//Get the checkboxlist item
var checkBox = document.getElementById(checkBoxList.id + '_' + [i]);
//Check if the checkboxlist item exists, and if it is checked
if(checkBox!=null && checkBox.checked){ numItemsChecked = numItemsChecked + 1; }
}
//Set the text box to the number of items checked in the checkboxlist
textBox
.value = numItemsChecked;
}

Tuesday, February 21, 2012

Copy values from one object to another

public static void CopyPropertyValues(object source, object destination)
{
var destProperties = destination.GetType().GetProperties();

foreach (var sourceProperty in source.GetType().GetProperties())
{
foreach (var destProperty in destProperties)
{
if (destProperty.Name == sourceProperty.Name &&
destProperty
.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
destProperty
.SetValue(destination, sourceProperty.GetValue(
source
, new object[] { }), new object[] { });

break;
}
}
}
}

Friday, February 3, 2012

What are the difference between DDL, DML and DCL commands?

DDL


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

DML


Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

DCL


Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

TCL


Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Thursday, January 19, 2012

Genereate Serial Number in Sql Server 2000 or 2005 query

In Sql Server 2005 and above version you can generate serial number as:

select row_number() over(order by empid) as serial_Number, empid,empname from emp

In Sql server 2000, you can generate serial number as:

select (select sum(1) from emp a where a.empid<=obj.empid) as serial_number,* from emp obj