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 *@

Caching


What is Caching?
Caching is a feature that stores data in local memory, allowing incoming requests to be served from memory directly.
Benefits of Caching
The following are the benefits of using Caching
·         Faster page rendering
·         Minimization of database hits
·         Minimization of the consumption of server resources
Types of Caching
Caching in ASP.NET can be of the following types
·         Page Output Caching
·         Page Fragment Caching
·         Data Caching
Page Output Caching
This is a concept by virtue of which the output of pages is cached using an Output Cache engine and all subsequent requests are served from the cache. Whenever a new request comes, this engine would check if there is a corresponding cache entry for this page. If there is a cache hit, i.e., if the engine finds a corresponding cache entry for this page, the page is rendered from the cache, else, the page being requested is rendered dynamically.
This is particularly useful for pages that are static and thus do not change for a considerable period of time.
Page output caching can be implemented in either of the following two ways:
·         At design time using the OutputCache directive
·         At runtime using the HttpPolicy class
The following is the complete syntax of page output caching directive
<%@ OutputCache Duration="no of seconds"
Location="Any | Client | Downstream | Server | None"
VaryByControl="control" 
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter" %>
The following statement is used to implement output caching in an aspx page at design time.  The directive is placed at the top of the .aspx page.
<%@OutputCache Duration="30"
VaryByParam="none" %>
The duration parameter specifies for how long the page would be in cache and the VaryByParam parameter is used to cache different views of the page. In the code example above, the cache duration is 30 seconds. Cache duration is a required field, and must be set to an integer greater than zero.  The VaryByParam parameter, which is also required, specifies whether the cached page would differ in versions based on any parameter. A value of * in the same parameter indicates that the page would be cached based on all the Get/Post parameters. We can also specify one or more Get/Post parameter(s). Hence, the same statement shown above can have the following variations. The VaryByParam parameter is particularly useful in situations where we require caching a page based on certain criteria. As an example, we might require to cache a specific page based on the EmployeeID.
<%@OutputCache Duration="30"
VaryByParam="*" Location = "Any"%>   
<%@OutputCache Duration="30"
VaryByParam="EmployeeID" Location = "Client" %>   
<%@OutputCache Duration="30"
VaryByParam="EmployeeID;Basic" %> 
The VaryByParam parameter can also have multiple parameters as shown in the example above.
The location parameter is used to specify the cache location, either the server of the client.
To set a page's cacheability programmatically we have to use the method Response.Cache.SetCacheability. This method accepts the following parameters
·         NoCache
·         Private
·         Public
·         Server
The code snippet below shows how to set a page’s cacheability programmatically:
Response.Cache.SetCacheability(HttpCacheability.Server);
Additionally we can set other properties which map to the same fields available when using the OutputCache directive on the page:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["EmployeeID"]= true; 

Page Fragment Caching
This allows specific portions of the page to be cached rather than caching the whole page. This is useful in situations where we can have a page that contains both static and dynamic content. The following code depicts how this can be accomplished.
<%@ OutputCache Duration="15"
VaryByControl="EmpID;DeptID" VaryByParam="*"%>   
This directive is placed at the top of any User Control (.axcx file).

Data Caching
The following code is an implementation of On-Demand caching. The method GetUserInfo checks to see if the data exists in the cache. If it is present, it is returned from the cache, else, the GetUserInfoFromDatabase method fills the DataSet from the database and then populates the Cache.
public DataSet GetUserInfo() 
{   
  string cacheKey = "UserInfo";   
  DataSet ds = Cache[cacheKey] as DataSet;   
  if (ds == null)   
 {     
   ds = GetUserInfoFromDatabase();     
   Cache.Insert(cacheKey, ds, null, NoAbsoluteExpiration,       
   TimeSpan.FromHours(15),CacheItemPriority.High, null);   
}      
return ds; 
}   

DataSet GetUserInfoFromDatabase() { 
// Usual code to populate a data set from thedatabase. This data set 
// object is then returned. 
}
Cache Expirations
Cache expirations can be of the following types
·         Time Based Expiration
·         Dependency Based Expiration
Time Based Expiration
This is used to specify a specific period of time for which the page would remain in the cache. The following statement specifies such expiration for a page in the code behind of a file using C#.
Response.Cache.SetExpires(DateTime.Now.AddSeconds(120));
This can also be accomplished by stating the same in the output cache directive as shown here.
<%@OutputCache Duration="60"
VaryByParam="None" %>
Cache Expiration
Cache expiration strategies can be implemented in either of the following two ways:
·         Time Based
·         File Based
·         Key Based
Time Based Expiration
This is implemented by specifying a specific duration for which the item would remain in the cache. When the time elapses, the item is removed from the cache and subsequent requests to retrieve the item returns a null. Time based expiration strategies can be of the following two types:
·         Absolute
·         Sliding
Absolute
Cache.Insert("UserInfo", dsUserInfo, null,
DateTime.Now.AddMinutes(1), NoSlidingExpiration); 
Sliding
Cache.Insert("UserInfo", dsUserInfo, null,
NoAbsoluteExpiration, 
TimeSpan.FromSeconds(60));
Note that you cannot use both Absolute and Sliding expirations at the same time.
File Based Expiration
This is implemented by using a file as a dependency. Whenever the contents of the dependency file are changed, the cached is invalidated. Please refer to the code below.
CacheDependency cacheDependency = newCacheDependency("userinfo.xml");
Cache.Insert("UserInfo", xmldocObject,cacheDependency); 
In addition to files, entire folders can be monitored for changes using the CacheDependency class.
Key Based Expiration
The third type of dependency is the key dependency.  With it, a cache entry can be made to depend on another, existing dependency.  When the depended-upon entry changes or expires, the dependent entry will also be expired.  An array of keys can be specified as a single CacheDependency.
string[] keys = new string[] {"key"};
CacheDependency cacheDependency = newCacheDependency(null,keys);
Cache.Insert("UserInfo", xmldocObject,cacheDependency);

Using Callbacks
The delegate CacheItemRemovedCallback event handler is used to respond to the event that is raised when an item is deleted from cache. This handler contains the code to populate / re-populate the cache. Please refer to the code snippet below.
public void onRemoveCallBack(string str, objectobj, CacheItemRemovedReason reason) 
{   
   DataSet dataset = GetUserInfoFromDatabase();   
   Cache["userInfo"= dataset; 
} 
1.      First declare a class variable onRemove as shown below.
private static CacheItemRemovedCallback onRemove = null
2.      This delegate is invoked as shown below.
onRemove = newCacheItemRemovedCallback(this.onRemoveCallBack);
3.      The following code snippet shows how this handler is specified when items are added to the Cache.
 
Cache.Insert("userInfo", ds, null, DateTime.Now.AddMinutes(2), 
NoSlidingExpiration, CacheItemPriority.High,
CacheItemPriorityDecay.Slow, onRemove);
The Cache Class
The Add/Insert method of the Cache class is used to add/insert an item into the cache. The Remove method removes a specified item from the cache. The Cache class contains the following properties and methods.
Properties
·         Count
·         Item
Methods
·         Add
·         Equals
·         Get
·         GetEnumerator
·         GetHashCode
·         GetType
·         Insert
·         Remove (Overloaded)
·         ToString
Conclusion
Judicious use of the right type of caching can dramatically improve the performance of web applications.  For more information about caching, please visit the ASPAlliance Caching Reference.



Wednesday, May 16, 2012

Difference between 3 tier and mvc

the three tiers may seem similar to the model-view-controller (MVC) concept; however, topologically they are different. A fundamental rule in a three tier architecture is the client tier never communicates directly with the data tier; in a three-tier model all communication must pass through the middle tier. Conceptually the three-tier architecture is linear. However, the MVC architecture is triangular: the view sends updates to the controller, the controller updates the model, and the view gets updated directly from the model.
From a historical perspective the three-tier architecture concept emerged in the 1990s from observations of distributed systems (e.g., web applications) where the client, middle ware and data tiers ran on physically separate platforms. Whereas MVC comes from the previous decade (by work at Xerox PARC in the late 1970s and early 1980s) and is based on observations of applications that ran on a single graphical workstation; MVC was applied to distributed applications later in its history (see Model 2).

Tuesday, May 15, 2012

date differance in Javascript


  function ValidateDate() {
           var SDate = document.getElementById("ctl00_ContentPlaceHolder1_FromDate").value;
           var EDate = document.getElementById("ctl00_ContentPlaceHolder1_ToDate").value;


           var alertReason1 = 'To Date must be greater than or equal to From Date.'
           var alertReason2 = 'End Date can not be less than Current Date.';

           var endDate = new Date(EDate);
           var startDate = new Date(SDate);

           if (SDate != '' && EDate != '' && startDate > endDate) {
               alert(alertReason1);
               //document.getElementById(CtrlEDate).value = "";
               return false;
           }
           else if (SDate == '') {
               alert("Please enter Start Date");
               return false;
           }
           else if (EDate == '') {
               alert("Please enter End Date");
               return false;
           }
       }

web grid for Razor mvc3


@{
    var grid = new WebGrid(source: Model,
                                           defaultSort: "Title",
                                           rowsPerPage: 10, fieldNamePrefix: "wg_",
                                           canPage: true, canSort: true,
                                           pageFieldName: "pg", sortFieldName: "srt"
                                           );
}
@grid.GetHtml(tableStyle: "listing-border", headerStyle: "gridhead", footerStyle: "paging", rowStyle: "td-dark", alternatingRowStyle: "td-light",
                            columns:
                                grid.Columns(
                                                      grid.Column("SHIFT_CD", "Shift Code", style: "colFirstName"),
                                                      grid.Column("SHIFT_DESC", "Shift Description", style: "colFirstName"),
                                                      grid.Column("SHORT_NM", "Short Name", style: "colFirstName"),
                                                      grid.Column("SHIFT_SEQ", "Sequence No", style: "colFirstName"),
                                                      grid.Column("SHIFT_FM", "Start Time", style: "colFirstName"),
                                                      grid.Column("SHIFT_TO", "End Time", style: "colFirstName"),
                                                 
      grid.Column(header: "Edit", format: @
                        Edit Record, style: "colOperation"),
                                    grid.Column(header: "Delete", format: @
                                        src="../../Content/images/delete.ico" alt="Delete Record" width="20px" height="20px"
                                        style="border: none;" />, style: "colOperation")
                                ),  mode: WebGridPagerModes.Numeric)
       

Monday, May 14, 2012

Date Differance in Javascript


function ValidateDate() {
           var SDate = document.getElementById("ctl00_ContentPlaceHolder1_FromDate").value;
           var EDate = document.getElementById("ctl00_ContentPlaceHolder1_ToDate").value;


           var alertReason1 = 'To Date must be greater than or equal to From Date.'
           var alertReason2 = 'End Date can not be less than Current Date.';

           var endDate = new Date(EDate);
           var startDate = new Date(SDate);

           if (SDate != '' && EDate != '' && startDate > endDate) {
               alert(alertReason1);
               //document.getElementById(CtrlEDate).value = "";
               return false;
           }
           else if (SDate == '') {
               alert("Please enter Start Date");
               return false;
           }
           else if (EDate == '') {
               alert("Please enter End Date");
               return false;
           }
       }

Thursday, May 3, 2012

How to get combobox column in telerik grid in mvc3:

Step 1:columns.Bound(c => c.PRODUCT_CD).Title("Product Code").EditorTemplateName("DropDown");
Step 2: add a Editor Template  folder in shared folder
Step 3: Right click on it add a view like this
@model String

@(Html.Telerik().ComboBox()
    .Name("ComboBox1")
        .BindTo(ViewData["data"] as SelectList)
     .ClientEvents(events => events
            .OnChange("onChange"))
    )

    @Html.TextBoxFor((model => model), new { id = "textbox1", style = "display:none;" })

Step 4: Add  this Script file in ur view(create/Index/Edit)