ASP.NET some little used tips and tricks

*While testing*, you can have emails sent to a folder on your computer
instead of an SMTP server. Put this in your web.config:










*HttpContext.Current* always gives you access to the current context's
Request/Response/etc., even when you don't have access to the Page's
properties (e.g., from a loosely-coupled helper class).

*You can continue* executing code on the same page after redirecting the
user to another one by calling Response.Redirect(url, false )

*You don't need .ASPX files* if all you want is a compiled Page (or any
IHttpHandler). Just set the path and HTTP methods to point to the class in
the element in the web.config file.

*A Page object can be retrieved *from an .ASPX file programmatically by
calling PageParser.GetCompiledPageInstance(virtualPath,aspxFileName,Context)


*Add this* to your web.config for much faster compilation (post 3.5SP1).



*Retail mode* at the machine.config level:







This overrides the web.config settings to enforce debug to false, turns
custom errors on and disables tracing. No more forgetting to change
attributes before publishing - just leave them all configured for
development or test environments and update the production retail
setting. Of course, you still want to build in Release mode.

*You can use:*

Request.Params[Control.UniqueId]
To get the value of a control before viewstate is initialized (Control.Text
etc will be empty at this point). This is useful for code in Init.


*You can use ASP.NET AJAX callbacks* to web methods placed in ASPX pages.
You can decorate a static method with the [WebMethod()] and
[ScriptMethod()] attributes. For example:

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List GetFruitBeginingWith(string letter)
{
List products = new List()
{
"Apple", "Banana", "Blackberry", "Blueberries", "Orange",
"Mango", "Melon", "Peach"
};

return products.Where(p => p.StartsWith(letter)).ToList();
}

Now, in your ASPX page you can do this:



EnablePageMethods="true" />
/>


And call your server side method via JavaScript using:




*Check to see if the client is still connected*, before starting a
long-running task:

if (this.Response.IsClientConnected)
{
// long-running task
}


*Tag Mapping:*
Tag mapping allows you to swap compatible controls at compile time on every
page in your web application. A useful example is if you have a stock
ASP.NET control, such as a DropDownList, and you want to replace it with a
customized control that is derived from DropDownList. This could be a
control that has been customized to provide more optimized caching of
lookup data. Instead of editing every web form and replacing the built in
DropDownLists with your custom version, you can have ASP.NET in effect do
it for you by modifying web.config:




mappedTagType="SmartDropDown"/>




*You can use ASP.NET Comments* within an .aspx page to comment out full
parts of a page including server controls. And the contents that is
commented out will never be sent to the client.

<%--



--%>

*The Code Expression Builder*
Sample markup:

Text = '<%$ Code: GetText() %>'
Text = '<%$ Code: MyStaticClass.MyStaticProperty %>'
Text = '<%$ Code: DateTime.Now.ToShortDateString() %>'
MaxLenth = '<%$ Code: 30 + 40 %>'
The real beauty of the code expression builder is that you can use
databinding like expressions in non-databinding situations. You can also
create other Expression Builders that perform other functions.

web.config:





The cs class that makes it all happen:

[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(
BoundPropertyEntry entry,
object parsedData,
ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}



*IsDebuggingEnabled:*

HttpContext.Current.IsDebuggingEnabled

This is great for determining which scripts to output (min or full
versions) or anything else you might want in dev, but not in production.


*MaintainScrollPositionOnPostBack:*

MaintainScrollPositionOnPostback attribute in the @Page directive. It is
used to maintain scroll position of an aspx page across postbacks.

*R**un ASP.Net outside of IIS or Visual Studio**:*

The whole runtime is packaged up and ready to be hosted in any process that
wants to give it a try. Using ApplicationHost, HttpRuntime and
HttpApplication classes, you too can grind up those .aspx pages and get
shiny HTML output from them.

HostingClass host =
ApplicationHost.CreateApplicationHost(typeof(HostingClass),
"/virtualpath", "physicalPath");
host.ProcessPage(urlToAspxFile);
And your hosting class:

public class HostingClass : MarshalByRefObject
{
public void ProcessPage(string url)
{
using (StreamWriter sw = new StreamWriter("C:\temp.html"))
{
SimpleWorkerRequest worker = new SimpleWorkerRequest(url, null,
sw);
HttpRuntime.ProcessRequest(worker);
}

}
}



*Request.IsLocal Property:*

It indicates whether current request is coming from Local Computer or not.

if( Request.IsLocal )
{
LoadLocalAdminMailSettings();
}
else
{
LoadServerAdminMailSettings();
}


*By default web form page inherits from System.Web.UI.Page class*. There is
a way to constraint any page to inherit from a base class. Simply add a new
line on your web.config:




 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.