Saturday, July 5, 2008

Asp.Net Set 2

What platforms does ASP.NET run on?
Currently, it's supported on Windows 2000 and Windows XP. ASP.NET integrates with Internet Information Server (IIS) and thus requires that IIS be installed. It runs on server and non-server editions of Windows 2000 and XP as long as IIS is installed. Microsoft originally planned to support ASP.NET on Windows NT 4.0, but had to reconsider due to time and technical constraints.

Can two different programming languages be mixed in a single ASPX file?
No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived Page classes, and a given parser understands only one language.

Why can't I put <%@ Page Language="C++" %> at the top of an ASPX file and write my server-side scripts in C++?
Because the parsers ASP.NET uses to extract code from ASPX files only understand C#, Visual Basic.NET, and JScript.NET. However, if you use code-behind to get your code out of the ASPX file and into a separately compiled source code file. You can write server-side scripts in any language supported by a .NET compiler.

Can I use code-behind with Global.asax files?
Yes. Here's a simple Global.asax file that doesn't use code-behind:

<%@ Import Namespace="System.Data" %>

Here's the equivalent file written to use code-behind:

<%@ Application Inherits="MyApp" %>
And here's the MyApp class that it references:

using System.Web;
using System.Data;

public class MyApp : HttpApplication
public void Application_Start ()
DataSet ds = new DataSet ();
ds.ReadXml ("GlobalData.xml");
Application["GlobalData"] = ds;

So that ASP.NET can find the MyApp class, compile it into a DLL (csc /t:library filename.cs) and place it in the application root's bin subdirectory.

Can you override method="post" in a
tag by writing ?

Can an ASPX file contain more than one form marked runat="server"?

Is it possible to see the code that ASP.NET generates from an ASPX file?
Yes. Enable debugging by including a <%@ Page Debug="true" %> directive in the ASPX file or a statement in Web.config. Then look for the generated CS or VB file in a subdirectory underneath \%SystemRoot%\Microsoft.NET\Framework\v1.0.nnnn\Temporary ASP.NET Files.

Does ASP.NET support server-side includes?
Yes. Server-side includes work the same in ASP.NET as they do in ASP.

Does ASP.NET support server-side object tags?
Yes. The following tag creates an instance of a custom type named ShoppingCart and assigns it session scope (that is, it creates a unique ShoppingCart instance for each and every session created on the server):

Managed types created this way are identified by class name. Unmanaged types (COM classes) are identified by CLSID or ProgID.

How do I comment out statements in ASPX files?



Can I use custom .NET data types in a Web form?
Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced.

How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use code-behind?
Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list, check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to build debug executables by placing a

<%@ Page Debug="true" %>

statement at the top of an ASPX file or a

statement in a Web.config file.

What event handlers can I include in Global.asax?
Application start and end event handlers
 Application_Start
 Application_End
Session start and end event handlers
 Session_Start
 Session_End
Per-request event handlers (listed in the order in which they're called)
 Application_BeginRequest
 Application_AuthenticateRequest
 Application_AuthorizeRequest
 Application_ResolveRequestCache
 Application_AcquireRequestState
 Application_PreRequestHandlerExecute
 Application_PostRequestHandlerExecute
 Application_ReleaseRequestState
 Application_UpdateRequestCache
 Application_EndRequest
Non-deterministic event handlers
 Application_Error
 Application_Disposed
Global.asax can also include handlers for events fired by custom HTTP modules. The event handlers listed above are intrinsic to ASP.NET.

Is it possible to protect view state from tampering when it's passed over an unencrypted channel?
Yes. Simply include an @ Page directive with an EnableViewStateMac="true" attribute in each ASPX file you wish to protect, or include the following statement in Web.config:

This configuration directive appends a hash (officially called the message authentication code, or MAC) to view state values round-tripped to the client and enables ASP.NET to detect altered view state. If ASP.NET determines that view state has been altered when a page posts back to the server, it throws an exception.
The hash is generated by appending a secret key (the validationKey value attached to the element in Machine.config) to the view state and hashing the result. An attacker can't modify view state and fix up the hash without knowing the secret key, too.

Is it possible to encrypt view state when it's passed over an unencrypted channel?
Yes. Set EnableViewStateMac to true and either modify the element in Machine.config to look like this:

Or add the following statement to Web.config:

Can a user browsing my Web site read my Web.config or Global.asax files?
No. The section of Machine.config, which holds the master configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. Here are the relevant statements in Machine.config:

Do Web controls support Cascading Style Sheets?
Yes. All Web controls inherit a property named CssClass from the base class System.Web.UI.WebControls.WebControl. The following example defines a CSS class named Input and uses it to modify a TextBox control to display text in red 10-point Verdana type:

Are ASP.NET server controls compatible with Netscape Navigator?
Most are. Some controls, such as Label, emit simple HTML tags that are compatible with virtually all browsers. Others, such as Calendar, emit a mix of HTML and client-side JavaScript. Fortunately, that JavaScript is simple enough to work with any browser that supports client-side scripting. The exception is the validation controls, which emit complex JavaScript that integrates intimately with the browser's DHTML Document Object Model (DOM). Because the DOMs used by Navigator and IE are so different, the ASP.NET validation controls don't work with Navigator. They can still validate input on the server, but they don't even attempt to validate on the client in Navigator.

What namespaces are imported by default in ASPX files?
The following namespaces are imported by default. Other namespaces must be imported manually using @ Import directives.
 System
 System.Collections
 System.Collections.Specialized
 System.Configuration
 System.Text
 System.Text.RegularExpressions
 System.Web
 System.Web.Caching
 System.Web.Security
 System.Web.SessionState
 System.Web.UI
 System.Web.UI.HtmlControls
 System.Web.UI.WebControls

What assemblies can I reference in an ASPX file without using @ Assembly directives?
ASP.NET links to the following assemblies by default:
 Mscorlib.dll
 System.dll
 System.Data.dll
 System.Drawing.dll
 System.Web.dll
 System.Web.Services.dll
 System.Xml.dll
This list of "default" assemblies is defined in the section of Machine.config. You can modify it by editing Machine.config or including an section in a local Web.config file.

How does setting a Web control's AutoPostBack property to true cause a page to post back to the server?
With a sprinkle of JavaScript and a dash of Dynamic HTML (DHTML). Enter this into a Web form:

And the control returns this:


The tag includes an onchange attribute that activates a JavaScript function named __doPostBack on the client when the control loses the input focus following a text change. __doPostBack programmatically posts the page back to the server by calling the Submit method of the DHTML object that represents the form (theform).

I sometimes see ASP.NET apps that include ASHX files. What are ASHX files?
ASHX files contain HTTP handlers-software modules that handle raw HTTP requests received by ASP.NET. The following code institutes a simple HTTP handler:

<%@ WebHandler Language="C#" Class="Hello"%>

using System.Web;

public class Hello : IHttpHandler
public void ProcessRequest (HttpContext context)
string name = context.Request["Name"];
context.Response.Write ("Hello, " + name);

public bool IsReusable
get { return true; }

If this code is placed in an ASHX file named Hello.ashx and requested using the URL http://.../hello.ashx?Name=Jeff, it returns "Hello, Jeff" in the HTTP response. ASHX files provide developers with a convenient way to deploy HTTP handlers without customizing CONFIG files or modifying the IIS metabase.

Can I create ASP.NET server controls of my own?
Yes. You can modify existing server controls by deriving from the corresponding control classes or create server controls from scratch by deriving from System.Web.UI.Control. Although a full treatment of custom controls is beyond the scope of this FAQ, here's a simple custom control that writes "Hello, world" to a Web page:

using System;
using System.Web;
using System.Web.UI;

namespace Wintellect
public class HelloControl : Control
protected override void Render (HtmlTextWriter writer)
writer.Write ("Hello, World!");

A custom control emits HTML by overriding the virtual Render method it inherits from Control and using the provided HtmlTextWriter to write its output.

What does the System.Web.UI.Page.RegisterClientScriptBlock method do, and do I need it when I write custom ASP.NET server controls?
RegisterClientScriptBlock enables a custom control to register a block of client-side script that the control returns to a browser. Why does it exist? So the same script block doesn't get returned multiple times if the page contains multiple instances of a control that emits client-side script. Here's the source code for a custom control called AlertButton that renders itself an as tag with an onclick attribute that displays a message using a JavaScript alert:

using System;
using System.Web;
using System.Web.UI;
using System.Text;

namespace Wintellect
public class AlertButton : Control
protected string _Text;
protected string _Message;

public string Text
get { return _Text; }
set { _Text = value; }

public string Message
get { return _Message; }
set { _Message = value; }

protected override void OnPreRender (EventArgs e)
Page.RegisterClientScriptBlock (

protected override void Render (HtmlTextWriter writer)
StringBuilder builder = new StringBuilder ();

builder.Append (" builder.Append (_Text);
builder.Append ("\" onclick=\"javascript:__doAlert (\'");
builder.Append (Message);
builder.Append ("\');\" />");

writer.Write (builder.ToString ());

If the control's register tag prefix is win, then the following statement declares an AlertButton control that, when clicked, displays "Hello, world" in a message box:

The control uses RegisterClientScriptBlock to register the client-side script block that it returns. That script block contains the __doAlert function referenced by the tag's onclick attribute. It's returned only once no matter AlertButtons a page contains. RegisterClientScriptBlock should always be called from the control's OnPreRender method so ASP.NET can control the script's position in the output.

What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?
RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs.

Can a calendar control be customized so that it limits users to selecting certain days of the week, and only dates that fall on or after today's date?
Yes. The secret is to customize the control by processing DayRender events, which are fired as the calendar renders each and every cell. Here's an example that limits selections to future Fridays and Saturdays:

void OnDayRender (Object sender, DayRenderEventArgs e)
e.Day.IsSelectable =
(e.Day.Date.DayOfWeek == DayOfWeek.Friday ||
e.Day.Date.DayOfWeek == DayOfWeek.Saturday) &&
e.Day.Date >= DateTime.Now;

The DayRenderEventArgs passed to a DayRender event handler has a property named Day that identifies the day being rendered. This example sets Day's IsSelectable property to true or false depending on whether the day currently being rendered represents a legitimate selection. Setting IsSelectable to false prevents the control from placing a hyperlink in the corresponding cell, effectively making that cell unselectable.

Is it necessary to lock application state before accessing it?
Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example:

Application.Lock ();
Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
Application.UnLock ();

By locking application state before updating it and unlocking it afterwards, you ensure that another request being processed on another thread doesn't read application state at exactly the wrong time and see an inconsistent view of it.

The ASP.NET application cache doesn't have Lock and UnLock methods as application state does. Does this mean I never need to lock it?
No. It means you have to come up with your own mechanism for locking. System.Threading.ReaderWriterLock is the perfect tool for the job. Assuming rwlock is an instance of ReaderWriterLock, here's how you'd lock the application cache during an update:

rwlock.AcquireWriterLock (Timeout.Infinite);
Cache["ItemsSold"] = (int) Cache ["ItemsSold"] + 1;
Cache["ItemsLeft"] = (int) Cache ["ItemsLeft"] - 1;
rwlock.ReleaseWriterLock ();

And here's how you'd read "ItemsSold" and "ItemsLeft" values from the cache:

rwlock.AcquireReaderLock (Timeout.Infinite);
int sold = (int) Cache["ItemsSold"];
int left = (int) Cache ["ItemsLeft"];
rwlock.ReleaseReaderLock ();

As with application state, locking the application cache is only necessary when performing multistep updates that are to be treated as atomic operations.

If I update session state, should I lock it, too? Are concurrent accesses by multiple requests executing on multiple threads a concern with session state?
Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely that two requests from the same user will overlap. Two, if they do overlap, ASP.NET locks down session state during request processing so that two threads can't touch it at once. Session state is locked down when the HttpApplication instance that's processing the request fires an AcquireRequestState event and unlocked when it fires a ReleaseRequestState event.

ASP.NET's application cache supports expiration policies and cache removal callbacks. Expiration policies are based on time dependencies and file dependencies. Are database dependencies supported, too? In other words, can I have an item automatically removed from the cache in response to a database update?
In ASP.NET version 1.x, no. However, you can forge a link between databases and the ASP.NET application cache by combining file dependencies with database triggers. For details, and for working sample code, see Jeff Prosise's Wicked Code column in the April 2003 issue of MSDN Magazine.

No comments: