Thursday, December 29, 2011

Asp.net 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:

<system.net>
     <mailSettings>
        <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\" />
        </smtp>
    </mailSettings>
</system.net>


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 <httpHandlers> 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).

<compilation optimizeCompilations="true">

Retail mode at the machine.config level:

<configuration>
  <system.web>
    <deployment retail="true"/>
  </system.web>
</configuration>

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<string> GetFruitBeginingWith(string letter)
{
        List<string> products = new List<string>() 
        { 
                "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:

<form id="form1" runat="server">
        <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
                <input type="button" value="Get Fruit" onclick="GetFruit('B')" />
        </div>
</form>
And call your server side method via JavaScript using:

    <script type="text/javascript">
        function GetFruit(l)
        {
                PageMethods.GetFruitBeginingWith(l, OnGetFruitComplete);
        }

        function OnGetFruitComplete(result)
        {
                alert("You got fruit: " + result);
         }
</script>


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:

<pages>
<tagMapping>
   <clear />
   <add tagType="System.Web.UI.WebControls.DropDownList"
         mappedTagType="SmartDropDown"/>
  </tagMapping>
</pages>


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.

<%--
    <div>
        <asp:Button runat="server" id="btnOne"/>
     </div>
--%>

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:

<system.web>    
    <compilation debug="true">
        <expressionBuilders>
            <add expressionPrefix="Code" type="CodeExpressionBuilder" />
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.

Run 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:

<system.web>
    <pages pageBaseType="MyBasePageClass" />
</system.web>
 

No comments: