Wednesday, June 20, 2012

How to bind data to a DDL present inside a GridView from Database and retain the selection


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
  DropDownList ddlDropDownList = (DropDownList)e.Row.FindControl("ddlDropDownList");
  if (ddlDropDownList != null)
  {
     ddlDropDownList.FindByValue(Convert.ToString(ViewState["selectedvalue"])).Selected = true;    
  }
  }
}

How to retrieve value from stored procedure using out parameter?


SP

CREATE PROCEDURE GetPasswordOP
    (
   
      @UserName  varchar(50)= '' ,
      @Password varchar(50)= '' ,
      @RtnValue INT OUT
    )
AS
BEGIN
   IF EXISTS (SELECT * FROM tblUserPasswordDetail WHERE UserName = @UserName )
    BEGIN
        SET  @RtnValue = 1;
    END
    ELSE
    BEGIN

        insert into tblUserPasswordDetail(UserName,Password) values(@UserName,@Password)
        set  @RtnValue = SCOPE_IDENTITY()
    END  
END
-------------------------------------------------------------------------------

C# Page

  string Constr = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
        SqlConnection con = new SqlConnection(Constr);
        SqlCommand cmd = new SqlCommand("GetPasswordOP", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter parm = new SqlParameter("@UserName", SqlDbType.VarChar, 50);
        parm.Value = "abc";
        cmd.Parameters.Add(parm);

        SqlParameter parm2 = new SqlParameter("@Password", SqlDbType.VarChar, 50);
        parm.Value = "abc";
        cmd.Parameters.Add(parm2);



        SqlParameter parm3 = new SqlParameter("@RtnValue", SqlDbType.Int);
        parm3.Direction = ParameterDirection.Output; // This is important!
        cmd.Parameters.Add(parm3);

        con.Open();
        cmd.ExecuteNonQuery();
       


        // Print the output value
        string rtnvalue = cmd.Parameters["@RtnValue"].Value.ToString();
        con.Close();



Page.IsValid and Validate


Page.IsValid and Validate

ASP.net ships with a couple of validator controls that allow you to determine whether the value of the input controls they are validating is valid.
Here is a simple example of a TextBox control with a RequiredFieldValidator attached and a Button control.
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyValidationGroup">asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
 ErrorMessage="This field is required!" ValidationGroup="MyValidationGroup">asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" ValidationGroup="MyValidationGroup" />
 

Note that all controls belong to the same ValidationGroup  - a new feature of ASP.net 2.0. With JavaScript turned on, when a user clicks the button, they will see an error message displayed next to the control being validated if they fail to fill in the TextBox. (One could also use a ValidationSummary control)
With JavaScript turned off, what may not be known is that, on the server side, even though the validators fire, it is left to the developer on how to use that information. 

You may think you have built a secure application but a hacker could disable JavaScript and bypass *all* your validators! This is where the Page.Validate method and more importantly, the Page.IsValid property come in.
The Validate method is fired automatically by controls that have the CausesValidationproperty set to true. Note that the Button control's CausesValidation property is true by default. The Validate method iterates through all enabled validation controls on the page and validates them. This event occurs after the Load event in the page lifecycle.
If the control that raised the event has a ValidationGroup specified, then only enabled validator controls that belong to the same ValidationGroup are validated by calling the Page.Validate(ValidationGroup) overload method. As mentioned previously, this is done automatically for controls that have the CausesValidation property set to true.
The Page.IsValid property tells you whether the validation succeeded or not. It can be called only after the Page.Validiate method is called. By using this property, you can add logic to your page to determine whether to proceed with the PostBack event or not.So, in addition to relying on client side validation, it is also important that you call Page.IsValid when handling the postback event. Here is what the code behind will look like:
protected void Button1_Click(object sender, EventArgs e) {
 
//Not required since the CausesValidation property of the Button control is true by default.
//Page.Validate("MyValidationGroup");
 
//Proceed only if the vaidation is successfull
if (!Page.IsValid) {
 return;
}
 
//Insert data into SQL
 
}
 
With the ASP.net declarative programming approach, the Page.IsValid method is something easy to forget.

Since you have reached this point, here is a simple quiz ;-) In the code below, what happens when Button2 is clicked?
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyValidationGroup">asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="This 
field is required!" ValidationGroup="MyValidationGroup">asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" 
ValidationGroup="MyValidationGroup" CausesValidation="true" />
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server" ValidationGroup="AnotherValidationGroup">asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
ErrorMessage="This 
field is required!" ValidationGroup="AnotherValidationGroup">asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="AnotherValidationGroup" 
OnClick="Button2_Click" /> 
 
protected void Button2_Click(object sender, EventArgs e) {
 
    Page.Validate("MyValidationGroup");
 
    if (!Page.IsValid) {
         return;
    }
 
    Response.Write("Button was clicked at " + DateTime.Now.ToShortTimeString());
} 

Sorting in Gridview


protected void grdWorkOrder_SortCommand(object sender, GridSortCommandEventArgs e)
    {
        GridSortExpression sortExpr = new GridSortExpression();
        switch (e.OldSortOrder)
        {
            case GridSortOrder.None:
                sortExpr.FieldName = e.SortExpression;
                sortExpr.SortOrder = GridSortOrder.Descending;

                e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                break;
            case GridSortOrder.Ascending:
                sortExpr.FieldName = e.SortExpression;
                sortExpr.SortOrder = grdWorkOrder.MasterTableView.AllowNaturalSort ? GridSortOrder.None : GridSortOrder.Descending;
                e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                break;
            case GridSortOrder.Descending:
                sortExpr.FieldName = e.SortExpression;
                sortExpr.SortOrder = GridSortOrder.Ascending;
                e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                break;
        }

        e.Canceled = true;
    }

Saturday, June 16, 2012

Sorting in Gridview


 protected void grdSpecialIndent_SortCommand(object sender, GridSortCommandEventArgs e)
    {
        GridSortExpression sortExpr = new GridSortExpression();
        switch (e.OldSortOrder)
        {
            case GridSortOrder.None:
                sortExpr.FieldName = e.SortExpression;
                sortExpr.SortOrder = GridSortOrder.Descending;

                e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                break;

            case GridSortOrder.Ascending:
                sortExpr.FieldName = e.SortExpression;
                sortExpr.SortOrder = grdSpecialIndent.MasterTableView.AllowNaturalSort ? GridSortOrder.None : GridSortOrder.Descending;
                e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                break;
            case GridSortOrder.Descending:
                sortExpr.FieldName = e.SortExpression;
                sortExpr.SortOrder = GridSortOrder.Ascending;

                e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                break;
        }

        e.Canceled = true;

Saturday, May 19, 2012

How to get client ip from web site.


protected void Button1_Click(object sender, EventArgs e)
        {
            string strHostName = System.Net.Dns.GetHostName();
            string clientip = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

            Label1.Text = clientip;
        }

Thursday, May 17, 2012

MVC Interview Questions/Answers

 MVC Interview Questions/Answers
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.

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-allparameter.
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.

What is the use of action filters in an MVC application?
Action Filters allow us to add pre-action and post-action behavior to controller action methods.

If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

What are the different types of filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

Give an example for Authorization filters in an asp.net mvc application?
1. RequireHttpsAttribute
2. AuthorizeAttribute

Which filter executes first in an asp.net mvc application?
Authorization filter


What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method
2. Controller
3. Application
[b]Is it possible to create a custom filter?[/b]
Yes

What filters are executed in the end?
Exception Filters

Is it possible to cancel filter execution?
Yes

What type of filter does OutputCacheAttribute class represents?
Result Filter

What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx

What symbol would you use to denote, the start of a code block in razor views?
@

What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

What are sections?
Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

What are the file extensions for razor views?
1. .cshtml - If the programming lanugaue is C#
2. .vbhtml - If the programming lanugaue is VB

How do you specify comments using razor syntax?
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below.
@* This is a Comment *@