Replacing the ASP.NET Browser Capabilities Functionality in asp.net 4.0

To replace the ASP.NET browser capabilities definition functionality completely, follow these steps:

1. Create a provider class that derives from HttpCapabilitiesProvider and that overrides the GetBrowserCapabilities method, as in the following example:

public class CustomProvider : HttpCapabilitiesProvider

{

public override HttpBrowserCapabilities

GetBrowserCapabilities(HttpRequest request)

{

HttpBrowserCapabilities browserCaps = new HttpBrowserCapabilities();

Hashtable values = new Hashtable(180, StringComparer.OrdinalIgnoreCase);

values[String.Empty] = request.UserAgent;

values["browser"] = "MyCustomBrowser";

browserCaps.Capabilities = values;

return browserCaps;

}

}

The code in this example creates a new HttpBrowserCapabilities object, specifying only the capability named browser and setting that capability to MyCustomBrowser.

2. Register the provider with the application.

In order to use a provider with an application, you must add the provider attribute to the browserCaps section in the Web.config or Machine.config files. (You can also define the provider attributes in a location element for specific directories in application, such as in a folder for a specific mobile device.) The following example shows how to set the provider attribute in a configuration file:

<system.web>

<browserCaps provider="ClassLibrary2.CustomProvider, ClassLibrary2,

Version=1.0.0.0, Culture=neutral" />

</system.web>

Another way to register the new browser capability definition is to use code, as shown in the following example:

void Application_Start(object sender, EventArgs e)

{

HttpCapabilitiesBase.BrowserCapabilitiesProvider =

new ClassLibrary2.CustomProvider();

// ...

}

This code must run in the Application_Start event of the Global.asax file. Any change to the BrowserCapabilitiesProvider class must occur before any code in the application executes, in order to make sure that the cache remains in a valid state for the resolved HttpCapabilitiesBase object.

Caching the HttpBrowserCapabilities Object

The preceding example has one problem, which is that the code would run each time the custom provider is invoked in order to get the HttpBrowserCapabilities object. This can happen multiple times during each request. In the example, the code for the provider does not do much. However, if the code in your custom provider performs significant work in order to get the HttpBrowserCapabilities object, this can result in huge overhead. To prevent this from happening, you can cache the HttpBrowserCapabilities object. Follow these steps:

1. Create a class that derives from HttpCapabilitiesProvider, like the one in the following example:

public class CustomProvider : HttpCapabilitiesProvider

{

public override HttpBrowserCapabilities

GetBrowserCapabilities(HttpRequest request)

{

string cacheKey = BuildCacheKey();

int cacheTime = GetCacheTime();

HttpBrowserCapabilities browserCaps =

HttpContext.Current.Cache[cacheKey] as

HttpBrowserCapabilities;

if (browserCaps == null)

{

HttpBrowserCapabilities browserCaps = new

HttpBrowserCapabilities();

Hashtable values = new Hashtable(180,

StringComparer.OrdinalIgnoreCase);

values[String.Empty] = request.UserAgent;

values["browser"] = "MyCustomBrowser";

browserCaps.Capabilities = values;

HttpContext.Current.Cache.Insert(cacheKey,

browserCaps, null, DateTime.MaxValue,

TimeSpan.FromSeconds(cacheTime));

}

return browserCaps;

}

}

In the example, the code generates a cache key by calling a custom BuildCacheKey method, and it gets the length of time to cache by calling a custom GetCacheTime method. The code then adds the resolved HttpBrowserCapabilities object to the cache. The object can be retrieved from the cache and reused on subsequent requests that need your custom provider.

2. Register the provider with the application as described in the preceding procedure.

Posted in: asp.net | Tags: asp.net asp.net 4.0 replace broser capabilities functionality httpcapabilitiesprovider httpbrowsercapabilities

Routing in ASP.NET 4

ASP.NET 4 adds built-in support for using routing with Web Forms. Routing lets you configure an application to accept request URLs that do not map to physical files. Instead, you can use routing to define URLs that are meaningful to users and that can help with search-engine optimization (SEO) for your application. For example, the URL for a page that displays product categories in an existing application might look like the following example:

http://website/products.aspx?categoryid=12

By using routing, you can configure the application to accept the following URL to render the same information:

http://website/products/software

Routing has been available starting with ASP.NET 3.5 SP1. However, ASP.NET 4 includes some features that make it easier to use routing, including the following:

· The PageRouteHandler class, which is a simple HTTP handler that you use when you define routes. The class passes data to the page that the request is routed to.

· The new properties HttpRequest.RequestContext and Page.RouteData (which is a proxy for the HttpRequest.RequestContext.RouteData object). These properties make it easier to access information that is passed from the route.

· The following new expression builders, which are defined in System.Web.Compilation.RouteUrlExpressionBuilder and System.Web.Compilation.RouteValueExpressionBuilder:

· RouteUrl, which provides a simple way to create a URL that corresponds to a route URL format within an ASP.NET server control.

· RouteValue, which provides a simple way to extract information from the RouteContext object.

· The RouteParameter class, which makes it easier to pass data contained in a RouteContext object to a query for a data source control (similar to FormParameter).

Routing for Web Forms Pages

The following example shows how to define a Web Forms route by using the new MapPageRoute method of the Route class:

public class Global : System.Web.HttpApplication

{

void Application_Start(object sender, EventArgs e)

{

RouteTable.Routes.MapPageRoute("SearchRoute",

"search/{searchterm}", "~/search.aspx");

RouteTable.Routes.MapPageRoute("UserRoute",

"users/{username}", "~/users.aspx");

}

}

ASP.NET 4 Beta 2 introduces the MapPageRoute method. The following example is equivalent to the SearchRoute definition shown in the previous example, but uses the PageRouteHandler class.

RouteTable.Routes.Add("SearchRoute", new Route("search/{searchterm}",

new PageRouteHandler("~/search.aspx")));

The code in the example maps the route to a physical page (in the first route, to ~/search.aspx). The first route definition also specifies that the parameter named searchterm should be extracted from the URL and passed to the page.

The MapPageRoute method supports the following method overloads:

· MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess)

· MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults)

· MapPageRoute(string routeName, string routeUrl, string physicalFile, bool checkPhysicalUrlAccess, RouteValueDictionary defaults, RouteValueDictionary constraints)

The checkPhysicalUrlAccess parameter specifies whether the route should check the security permissions for the physical page being routed to (in this case, search.aspx) and the permissions on the incoming URL (in this case, search/{searchterm}). If the value of checkPhysicalUrlAccess is false, only the permissions of the incoming URL will be checked. These permissions are defined in the Web.config file with settings such as the following:

<configuration>

<location path="search.aspx">

<system.web>

<authorization>

<allow roles="admin"/>

<deny users="*"/>

</authorization>

</system.web>

</location>

<location path="search">

<system.web>

<authorization>

<allow users="*"/>

</authorization>

</system.web>

</location>

</configuration>

In the example configuration, access is denied to the physical page search.aspx for all users except those who are in the admin role. When the checkPhysicalUrlAccess parameter is set to true (which is its default value), only admin users are allowed to access the URL /search/{searchterm}, because the physical page search.aspx is restricted to users in that role. If checkPhysicalUrlAccess is set to false and the site is configured as shown in the previous example, all authenticated users are allowed to access the URL /search/{searchterm}.

Posted in: asp.net | Tags: xml asp.net asp.net 4.0 eventargs routing pageroutehandler httprequest requestcontext routevalueexpressionbuilder web form page authorization location configuration

Reading Routing Information in a Web Forms Page

In the code of the Web Forms physical page, you can access the information that routing has extracted from the URL (or other information that another object has added to the RouteData object) by using two new properties: HttpRequest.RequestContext and Page.RouteData. (Page.RouteData wraps HttpRequest.RequestContext.RouteData.) The following example shows how to use Page.RouteData.

protected void Page_Load(object sender, EventArgs e)

{

string searchterm = Page.RouteData.Values["searchterm"] as string;

label1.Text = searchterm;

}

The code extracts the value that was passed for the searchterm parameter, as defined in the example route earlier. Consider the following request URL:

http://localhost/search/scott/

When this request is made, the word "scott" would be rendered in the search.aspx page.

Accessing Routing Information in Markup

The method described in the previous section shows how to get route data in code in a Web Forms page. You can also use expressions in markup that give you access to the same information. Expression builders have been described as a "hidden gem of ASP.NET" (see the entry Express Yourself With Custom Expression Builders on Phil Haack's blog). It is unfortunate that they are not better known, because expression builders are a powerful and elegant way to work with declarative code.

ASP.NET 4 includes two new expression builders for Web Forms routing. The following example shows how to use them.

<asp:HyperLink ID="HyperLink1" runat="server"

NavigateUrl="<%$RouteUrl:SearchTerm=scott%>">Search for Scott</asp:HyperLink>

In the example, the RouteUrl expression is used to define a URL that is based on a route parameter. This saves you from having to hard-code the complete URL into the markup, and lets you change the URL structure later without requiring any change to this link.

Based on the route defined earlier, this markup generates the following URL:

http://localhost/search/scott

ASP.NET automatically works out the correct route (that is, it generates the correct URL) based on the input parameters. You can also include a route name in the expression, which lets you specify a route to use.

The following example shows how to use the RouteValue expression.

<asp:Label ID="Label1" runat="server" Text="<%$RouteValue:SearchTerm%>" />

When the page that contains this control runs, the value "scott" is displayed in the label.

The RouteValue expression makes it very simple to use route data in markup, and it avoids having to work with the more complex Page.RouteData["x"] syntax in markup.

Posted in: asp.net | Tags: asp.net asp.net 4.0 webform web application routing web form

ASP.NET Interview Questions and answers

his is a list of questions I have gathered and created over a period of time from my experience, many of which I felt where incomplete or simply wrong.  I have finally taken the time to go through each question and correct them to the best of my ability.  However, please feel free to post feedback to challenge, improve, or suggest new questions.  I want to thank those of you that have contributed quality questions and corrections thus far.

There are some questions in this list that I do not consider to be good questions for an interview.  However, they do exist on other lists available on the Internet so I felt compelled to keep them here for easy access.

  1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
    inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.
     
  2. What’s the difference between Response.Write() andResponse.Output.Write()?
    Response.Output.Write() allows you to write formatted output.  
  3. What methods are fired during the page load?
    Init() - when the page is instantiated
    Load() - when the page is loaded into server memory
    PreRender() - the brief moment before the page is displayed to the user as HTML
    Unload() - when page finishes loading.  
  4. When during the page processing cycle is ViewState available?
    After the Init() and before the Page_Load(), or OnLoad() for a control.  
  5. What namespace does the Web page belong in the .NET Framework class hierarchy?
    System.Web.UI.Page  
  6. Where do you store the information about the user’s locale?
    System.Web.UI.Page.Culture  
  7. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?
    CodeBehind is relevant to Visual Studio.NET only.  
  8. What’s a bubbled event?
    When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.  
  9. Suppose you want a certain ASP.NET function executed on MouseOver for a certain button.  Where do you add an event handler?
    Add an OnMouseOver attribute to the button.  Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");  
  10. What data types do the RangeValidator control support?
    Integer, String, and Date.  
  11. Explain the differences between Server-side and Client-side code?
    Server-side code executes on the server.  Client-side code executes in the client's browser.  
  12. What type of code (server or client) is found in a Code-Behind class?
    The answer is server-side code since code-behind is executed on the server.  However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser.  But just to be clear, code-behind executes on the server, thus making it server-side code.  
  13. Should user input data validation occur server-side or client-side?  Why?
    All user input data validation should occur on the server at a minimum.  Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.  
  14. What is the difference between Server.Transfer and Response.Redirect?  Why would I choose one over the other?
    Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser.  This provides a faster response with a little less overhead on the server.  Server.Transfer does not update the clients url history list or current url.  Response.Redirect is used to redirect the user's browser to another page or site.  This performas a trip back to the client where the client's browser is redirected to the new page.  The user's browser history list is updated to reflect the new address.  
  15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
    Valid answers are:
    · 
    A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
    ·  A DataSet is designed to work without any continuing connection to the original data source.
    ·  Data in a DataSet is bulk-loaded, rather than being loaded on demand.
    ·  There's no concept of cursor types in a DataSet.
    ·  DataSets have no current record pointer You can use For Each loops to move through the data.
    ·  You can store many edits in a DataSet, and write them to the original data source in a single operation.
    ·  Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources. 
     
  16. What is the Global.asax used for?
    The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.  
  17. What are the Application_Start and Session_Start subroutines used for?
    This is where you can set the specific variables for the Application and Session objects.  
  18. Can you explain what inheritance is and an example of when you might use it?
    When you want to inherit (use the functionality of) another class.  Example: With a base class named Employee, a Manager class could be derived from the Employee base class.  
  19. Whats an assembly?
    Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN  
  20. Describe the difference between inline and code behind.
    Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.  
  21. Explain what a diffgram is, and a good use for one?
    The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML.  A good use is reading database data to an XML file to be sent to a Web Service.  
  22. Whats MSIL, and why should my developers need an appreciation of it if at all?
    MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.  MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.  
  23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
    The Fill() method.  
  24. Can you edit data in the Repeater control?
    No, it just reads the information from its data source.  
  25. Which template must you provide, in order to display data in a Repeater control?
    ItemTemplate.  
  26. How can you provide an alternating color scheme in a Repeater control?
    Use the AlternatingItemTemplate.  
  27. What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?
    You must set the DataSource property and call the DataBind method.  
  28. What base class do all Web Forms inherit from?
    The Page class.  
  29. Name two properties common in every validation control?
    ControlToValidate property and Text property.  
  30. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
    DataTextField property.  
  31. Which control would you use if you needed to make sure the values in two different controls matched?
    CompareValidator control.  
  32. How many classes can a single .NET DLL contain?
    It can contain many classes. 

Web Service Questions

  1. What is the transport protocol you use to call a Web service?
    SOAP (Simple Object Access Protocol) is the preferred protocol.  
  2. True or False: A Web service can only be written in .NET?
    False 
     
  3. What does WSDL stand for?
    Web Services Description Language.  
  4. Where on the Internet would you look for Web services?
    http://www.uddi.org  
  5. True or False: To test a Web service you must create a Windows application or Web application to consume this service?
    False, the web service comes with a test page and it provides HTTP-GET method to test.
     

State Management Questions

  1. What is ViewState?
    ViewState allows the state of objects (serializable) to be stored in a hidden field on the page.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source.  ViewState is used the retain the state of server-side objects between postabacks.  
  2. What is the lifespan for items stored in ViewState?
    Item stored in ViewState exist for the life of the current page.  This includes postbacks (to the same page).  
  3. What does the "EnableViewState" property do?  Why would I want it on or off?
    It allows the page to save the users input on a form across postbacks.  It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser.  When the page is posted back to the server the server control is recreated with the state stored in viewstate.  
  4. What are the different types of Session state management options available with ASP.NET?
    ASP.NET provides In-Process and Out-of-Process state management.  In-Process stores the session in memory on the web server.  This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server.  Out-of-Process Session state management stores data in an external data source.  The external data source may be either a SQL Server or a State Server service.  Out-of-Process state management requires that all objects stored in session are serializable.
Posted in: Interview Questions | Tags: asp.net aspnet_isapi inherit ado.net wp aspnet pageload init load prerender response dataset universal ado recordset server transfer server-side client-side loop alternatingitem

New Features in ASP.NET AJAX 4

New Features in ASP.NET AJAX 4

Note   The documentation in this section concerns ASP.NET 4 AJAX Preview 4. A more recent preview release might be available at the URL above. If so, it will include updated documentation.

The new functionality in ASP.NET AJAX enables new client data scenarios for page and component developers that enable JSON data from the server to be rendered as HTML in a highly manageable and efficient way. To enable these scenarios, ASP.NET AJAX includes the following major features:

· Client-side template rendering.

· Declarative instantiation of client-side behaviors and controls.

· Live data binding.

· Use of the observer pattern with JavaScript types.

· An AdoNetServiceProxy class for client-side interaction with ADO.NET Data Services.

· A client-side DataView control for data-bound UI in the browser.

· DataContext and AdoNetDataContext classes for interaction with Web services.

· Refactored ASP.NET AJAX framework libraries.

· Support for the DOM Ready event.

· Using JSONP to retrieve cross-domain data.

Client Template Rendering

In client-based development, templates are the most manageable way of creating UI from data. ASP.NET AJAX 4 includes a new template engine for client development that meets the following requirements:

· Performance — The engine must be able to render a typical number of items using a reasonably complex template before users perceive an interruption in their interaction with the application.

· Simplicity — The template syntax must be very readable and must be optimized for the most common scenario, namely one-way/one-time binding.

· Expression language — Templates must support an expression language to go beyond the simplest cases. The expression language should use familiar syntax, ideally JavaScript syntax.

· Interspersed code and markup — It must be possible to perform conditional rendering or to loop over markup by using code that surrounds HTML.

· Components — When using the template syntax, the developer must be able to instantiate client-side controls and behaviors that attach to HTML elements in the page or within templates.

Template Example

The following example shows a typical client template that you can create using ASP.NET AJAX 4.

<ul id="myTemplate" class="sys-template"

sys:attach="dataview"

>

<li>

<h3>{{ Name }}</h3>

<div>{{ Description }}</div>

</li>

</ul>

The class attribute of the outer div element is set to sys-template, which is a convention that is used in order to hide the initial template from the user. You should define this class in your CSS style sheet as {display:none;}.

When the template is rendered, it has a data item as context. Fields or properties of that data item can be included in the template markup by using {{ }} expressions — for example, {{ Name }}, if the data item has a Name field. These expressions can be placed anywhere in text content, or you can use them as the value of an attribute. In addition to fields or properties, the expression blocks can also contain any JavaScript expression that can be evaluated as a string.

You can set up DOM events by using the $addHandler method. The DOM on* attributes of elements (for example, onclick=method) also work from within templates.

Instantiating a Template by Using the DataView Control

The most convenient way to use client templates in ASP.NET AJAX 4 is through the DataView control. The content of a DataView control is used as a template that renders the data item that is provided to the control. If you set the DataView control's data property to an array, the template is rendered once for each item in the array. The DataView control binds to live data, meaning that the control is automatically updated when the data changes, without the need to rebind. This provides a dynamic data-driven UI in the browser. The following example shows the declarative markup for a DataView control that binds to an array named imagesArray.

<body xmlns:sys="javascript:Sys"

xmlns:dataview="javascript:Sys.UI.DataView"

sys:activate="*">

<ul sys:attach="dataview" class="sys-template"

dataview:data="{{ imagesArray }}"

>

<li>

<h3>{{ Name }}</h3>

<div>{{ Description }}</div>

</li>

</ul>

</body>

Instantiating a Template by Using Code

You can also create a compiled template from code by using the Sys.UI.Template class, as shown in the following example:

var t = new Sys.UI.Template($get("myTemplate"));

The constructor takes the parent element of the template as its argument. You can then render a compiled template into the DOM by calling its instantiateIn method and specifying an HTML container element and a data item as context. The following example shows how to do this.

t.instantiateIn(

$get("targetContainer"),

{

Name: "Name",

Description: "Description"

}

);

Using Pseudo-Columns in a Template

In addition to providing access to fields and properties of the data item, the template rendering engine also provides access to pre-defined "pseudo-columns" such as $index and $dataItem. These pseudo-columns give you access to values from the rendering engine at render time. You can use pseudo-columns the way you use any JavaScript variable in the template instance. The first example applies a different CSS class to the div element for alternating items that are rendered by the dataView control. The second examples passes the pseudo-column $dataItem, which represents the data for the current row, to a custom function named nameConvert for processing.

<div class:alternateitem="{{$index%2 == 1}}">

<span>{{nameConvert($dataItem)}}</span>

Incorporating Code into a Template by Using the code:if, code:before, and code:after Attributes

You can add the new code:if, code:before, and code:after declarative attributes to any DOM element within a template in order to render the element conditionally (code:if) or to render arbitrary code before (code:before) or after (code:after) the element. The following example shows how to use the code:If attribute to render an hr element as a separator between items. The code:if attribute uses the value of the $index pseudo-column to ensure that the hr element is rendered only between items, and not before the first one or after the last one.

<ul id="myTemplate" class="sys-template">

<li>

<hr code:if="$index!==0" />

<h3>{{ Name }}</h3>

<div>{{ Description }}</div>

</li>

</ul>

Posted in: asp.net | Tags: asp.net asp.net 4.0 performance feature asp.net ajax ajax dataview adonetdatacontext datacontext rendering simplicity template example