Sunday, June 3, 2012

MVC Interview Questions on Routing

What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5
Controller Name = Customer
Action Method Name = Details
Parameter Id = 5

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.

What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
 
What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

Basic MVC Interview Questions

What are the 3 main components of an ASP.NET MVC application?
1. M - Model
2. V - View
3. C - Controller

In which assembly is the MVC framework defined?
System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC

What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

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;
}
}
}
}