My Development Notes

By Haemoglobin
3/10/2010 (revision 1)

ASP.NET Programmability

Error Handling

//Page Level
private void Page_Error(object sender, EventArgs e) {
    Server.GetLastError().Message; 
    Server.ClearError(); 
}

//Application level (asax)
private void Application_Error(object sender, EventArgs e) {
    Server.GetLastError().Message; 
    Server.ClearError(); 
}

Programming Web.config

    AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection("system.web/authentication");
    section.Mode.ToString(); 

    WebConfigurationManager.AppSettings["MyAppSetting"];

    WebConfigurationManager.ConnectionStrings("MyConnString").ConnectionString;

    Configuration config = WebConfigurationManager.OpenWebConfiguration("/MyApp");
    TraceSection section = (TraceSection)config.GetSection("system.web/trace"); 
    section.Enabled = true; 
    config.Save(); 
    config.SaveAs(fileLocation, ConfigSaveMode.Full|Minimal|Modified, true);

Asyncrhonous web page processing

May increase the performance of the web application by freeing up a connection in the connection pool while running a long running process during page load (has overheads though so use wisely).

<%@ Page Language="C#" Async="true" AutoEventWireup="true" %> 
IAsyncResult BeginGetAsyncData(object src, EventArgs args, AsyncCallback cb, object state) {}
void EndGetAsyncData(IAsyncResult) {}

BeginEventHandler bh = new BeginEventHandler(BeginGetAsyncData);
EndEventHandler eh = new EndEventHandler(EndGetAsyncData);
base.AddOnPreRenderCompleteAsync(bh, eh); 

Custom HTTP Handler

ASP.NET page handler processes .aspx requests, ASP.NET service handler processes .asmx requests. Can define own for other types, like images by default are processed by IIS and not sent to ASP.NET.

public class ImageHandler : IHttpHandler
{
    public bool IsReusable  { get { return false; } } //reuse this in a pool of http handlers

    public void ProcessRequest(HttpContenxt context) 
    {
        content.Response.ContenType = "image/jpeg"; 
        //Do optional processing.
    }
}

Then need to configure IIS to forward requests to ASP.NET for .jpg file types and type in ImageHandler, or if you are using IIS7 it can simply exist in the web.config

configuration
    system.web
        httpHandlers
            add verb="*" path="*.jpg" type="ImageHandler"

Modifying headers

Sylte bodyStyle = new Style(); 
bodyStyle.ForeColor = System.Drawing.Color.Blue; 
Page.Header.StyleSheet.CreateStyleRule(bodyStle, null, "body"); 

Comments

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin