292

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here.

More info: https://stackoverflow.com/faq


There are always features that would be useful in fringe scenarios, but for that very reason most people don't know them. I am asking for features that are not typically taught by the text books.

What are the ones that you know?

Community
  • 1
  • 1
Vaibhav
  • 11,310
  • 11
  • 51
  • 70
  • Good question, I wish could vote multiple times! – Gavin Miller Jan 30 '09 at 23:12
  • 1
    Agreed. I love threads like this. There's so much depth to the framework, that you're sometimes amazed at things you never knew were there. – Deane Apr 14 '09 at 21:05
  • I am learning so many cool new tricks from the responses in this thread - thanks! :) – Maxim Zaslavsky Jul 03 '09 at 08:50
  • 16
    Rather than "Hidden features of.. " shouldn't these things be named "Little Known features of.." because most every answer is well documented in MSDN or elsewhere, just not commonly known or used. – John K Jan 26 '10 at 09:04
  • See http://meta.stackexchange.com/questions/56669/should-hidden-features-of-x-be-removed-closed-locked, http://meta.stackexchange.com/questions/57226/should-we-have-a-list-of-x-close-reason, and related Meta posts for discussion on appropriateness and closing. –  Jul 18 '10 at 07:44

53 Answers53

334

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>
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • 6
    Really? I was about to install a fake SMTP Server, like Dumbster. I hidden gem. – Eduardo Molteni Sep 18 '08 at 11:15
  • 2
    Does anyone know if you can you specify a UNC share for the directory location? – Mark Sherretta May 26 '09 at 17:12
  • 32
    Better yet, put this on your dev box machine.config, so you don't have to change the web.config on every app you create. – Max Toro Oct 24 '09 at 21:22
  • Can you set it so it only does this on local host? That way you don't have to change it every time? – chobo2 Dec 07 '09 at 19:40
  • There's no setting for that. You'll have to manage the config differences using other methods (Web Deployment Projects, Build tasks, etc) – John Sheehan Dec 07 '09 at 20:23
  • @Max Toro that's the real gem :) ... Note that you can already does that in Code (if you were exploring the SmtpClient properties by any means) – chakrit Mar 23 '10 at 13:35
  • I thought you could do something like this through IIS. I must be mistaken, I just remember the emails going to a folder. – kirk.burleson Jun 24 '10 at 00:50
  • I think you can configure the SMTP server itself to drop everything in a folder as well, but it's server-wide so it would affect other applications. – John Sheehan Jun 24 '10 at 01:05
  • That's really helpful. We use to use real smtp server and jam it while testing. – Nayana Setty Oct 05 '11 at 06:04
210

If you place a file named app_offline.htm in the root of a web application directory, ASP.NET 2.0+ will shut-down the application and stop normal processing any new incoming requests for that application, showing only the contents of the app_offline.htm file for all new requests.

This is the quickest and easiest way to display your "Site Temporarily Unavailable" notice while re-deploying (or rolling back) changes to a Production server.

Also, as pointed out by marxidad, make sure you have at least 512 bytes of content within the file so IE6 will render it correctly.

Community
  • 1
  • 1
Troy DeMonbreun
  • 3,860
  • 3
  • 25
  • 35
  • 10
    Don't forget the workaround for IE's "friendly" messages: http://tinyurl.com/app-offline-friendly – Mark Cidade Sep 10 '08 at 21:01
  • 1
    Ouch! Be careful when using this with MOSS 2007. It will only work for pages that have been accessed since the last IIS restart. So, if you add this page to your wss virtual root, then try to open a page that hadn't been accessed previously, you will get a 404. – Marc Jun 10 '09 at 20:34
  • 1
    @Marc - Got this tip from Scott Guthrie, if you are feeling generous, you would be helping a lot of SharePoint devs avoid this scenario if you commented on the Gu's article: http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx – Troy DeMonbreun Jun 10 '09 at 20:57
  • Plus, this will also trigger a recycle of the App Domain and close any open database connections, after all requests have finished. – Bart Verkoeijen Jun 22 '11 at 03:58
  • There's a caveat to this one: IIS returns the app_offline.htm content with an HTTP Status Code of 404. Should a search engine wander along and attempt to index your site while you're in this offline mode, you might not appreciate the results. But it works great for my private corporate web app! – Larry Silverman Jul 06 '11 at 19:33
119
throw new HttpException(404, "Article not found");

This will be caught by ASP.NET which will return the customErrors page. Learned about this one in a recent .NET Tip of the Day Post

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • Some developers could argue that it's better to wrap things up manually in HttpContext.Response rather than throwing an exception which is quite expensive operation in .NET books. – lubos hasko Sep 14 '08 at 04:46
  • Isn't this bad form? You're showing the 404 error, whereas you want to display an error/exception. – Donnie Thomas Oct 14 '08 at 05:49
  • 1
    One case I can think of is if someone is maliciously messing with parameters and puts something invalid in, you probably want a generic 404 not a specific error. – John Sheehan Oct 15 '08 at 03:44
  • 3
    Upvoted purely because I'm now aware of the .NET Tip of the Day site. – Kon Dec 23 '08 at 14:07
  • it works only when you throw it in httpModule or httpHandler – Khaled Musaied Jun 12 '09 at 20:46
75

Here's the best one. Add this to your web.config for MUCH faster compilation. This is post 3.5SP1 via this QFE.

<compilation optimizeCompilations="true">

Quick summary: we are introducing a new optimizeCompilations switch in ASP.NET that can greatly improve the compilation speed in some scenarios. There are some catches, so read on for more details. This switch is currently available as a QFE for 3.5SP1, and will be part of VS 2010.

The ASP.NET compilation system takes a very conservative approach which causes it to wipe out any previous work that it has done any time a ‘top level’ file changes. ‘Top level’ files include anything in bin and App_Code, as well as global.asax. While this works fine for small apps, it becomes nearly unusable for very large apps. E.g. a customer was running into a case where it was taking 10 minutes to refresh a page after making any change to a ‘bin’ assembly.

To ease the pain, we added an ‘optimized’ compilation mode which takes a much less conservative approach to recompilation.

Via here:

Scott Hanselman
  • 17,712
  • 6
  • 74
  • 89
73
  • HttpContext.Current will always give 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)

Marek Grzenkowicz
  • 17,024
  • 9
  • 81
  • 111
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • About Response.Redirect(url, false) - That is so much what I hoped for quite a long time.. I dont know how I missed that but thanxxx – Subliminal Hash Jan 23 '09 at 20:17
  • 1
    Can someone explain what you would do with this? I know it has some value, but I can't figure out why... – Deane Apr 14 '09 at 20:47
  • 5
    If you want to redirect the user to a different address but still have some back-end processing to do (e.g., a report generation request that redirects to the report's generation status page while it continues to generate the report in the background) – Mark Cidade Apr 15 '09 at 18:58
  • Can someone explain a useful situation for PageParser.GetCompiledPageInstance(..)? The docs say for it's for infrastructure use - it returns an IHttpHandler type so I don't see how it can be practically used. – John K Apr 23 '10 at 19:55
  • @jdk: I've used it in the past when overriding the default handler for *.aspx requests so I can use dynamic in-memory IHttpHandler objects but also use GetCompiledPageInstance() for physical *.aspx files. – Mark Cidade May 02 '10 at 21:18
  • @Mark Cidade: Thanks for the info. I'm still unclear on one point: did you cast it into a different data type to use effectively it, or did you continue to reference it through the IHttpHandler data type? – John K May 02 '10 at 22:05
  • @jdk: I just call the ProcessRequest() method on the IHttpHandler interface. – Mark Cidade May 06 '10 at 05:41
70

Retail mode at the machine.config level:

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

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.

Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
Troy Hunt
  • 20,345
  • 13
  • 96
  • 151
  • 1
    I sometimes forget to change compilation debug to false before publishing, which negatively affects performance. No problem any more! – Roy Tinker Sep 07 '10 at 18:22
59

Enabling intellisense for MasterPages in the content pages
I am sure this is a very little known hack

Most of the time you have to use the findcontrol method and cast the controls in master page from the content pages when you want to use them, the MasterType directive will enable intellisense in visual studio once you to this

just add one more directive to the page

<%@ MasterType VirtualPath="~/Masters/MyMainMasterPage.master" %>

If you do not want to use the Virtual Path and use the class name instead then

<%@ MasterType TypeName="MyMainMasterPage" %>

Get the full article here

Nathan DeWitt
  • 6,511
  • 8
  • 46
  • 66
Binoj Antony
  • 15,886
  • 25
  • 88
  • 96
  • Using the FindControl can sometimes be hectic, thanks for this great tip! – Alexandre Brisebois Sep 22 '09 at 23:53
  • 4
    Using this might result in unexpected behaviour. See http://stackoverflow.com/questions/1998931/how-to-fix-namespace-problem-with-autogenerated-master-property-if-mastertype-is – citronas Jan 07 '10 at 20:33
  • Personally I think feature should be left unknown to people, it couples the page to the masterpage. If you end up using properties/methods of the masterpage and then change the masterpage you end up with a maintenance nightmare. – Phill Dec 27 '10 at 04:05
  • @Phil: Sometimes it is needed and having a statically typed access to a masterpage is much better than the FindControl approach. At least you get the compiler message and can quickly fix it. – Durden81 Oct 24 '11 at 14:41
58

HttpContext.Items as a request-level caching tool

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
  • 2
    This was going to be my point as well, i use this in nested controlls to pass/receive request level information. Ii also use this in MVC to store a list of js files to append, based in partial views. – Tracker1 May 23 '09 at 03:30
  • 1
    I use this when I use the asp.net routing to pass the parameters fetched from the urls to my pages. (not with MVC) great for url rewriting and is quite flexible. – Alexandre Brisebois Sep 22 '09 at 23:57
  • Hmmmm, just thought of somewhere where I could have used this instead of Session - ta! – Mike Kingscott Dec 18 '09 at 17:00
52

Two things stand out in my head:

1) You can turn Trace on and off from the code:

#ifdef DEBUG 
   if (Context.Request.QueryString["DoTrace"] == "true")
                {
                    Trace.IsEnabled = true;
                    Trace.Write("Application:TraceStarted");
                }
#endif

2) You can build multiple .aspx pages using only one shared "code-behind" file.

Build one class .cs file :

public class Class1:System.Web.UI.Page
    {
        public TextBox tbLogin;

        protected void Page_Load(object sender, EventArgs e)
        {

          if (tbLogin!=null)
            tbLogin.Text = "Hello World";
        }
    }

and then you can have any number of .aspx pages (after you delete .designer.cs and .cs code-behind that VS has generated) :

  <%@ Page Language="C#"  AutoEventWireup="true"  Inherits="Namespace.Class1" %>
     <form id="form1" runat="server">
     <div>
     <asp:TextBox  ID="tbLogin" runat="server"></asp: TextBox  >
     </div>
     </form>

You can have controls in the ASPX that do not appear in Class1, and vice-versa, but you need to remeber to check your controls for nulls.

Radu094
  • 28,068
  • 16
  • 63
  • 80
  • I would have voted this up, but ran out of votes. I am going to try and remember to come back to vote this up. I didn't know that we could have the same Code Behind file for multiple pages. Not sure, how that would work. – Vaibhav Sep 10 '08 at 19:43
  • 5
    Does anyone else think its a security risk to allow you to activate a trace from a url? (#1) I'm not going to downvote this question, but its important to understand the risk there. – Kevin Goff Sep 10 '08 at 21:16
  • 5
    Absolutelly, you should really put that code in a #ifdef DEBUG #endif block – Radu094 Sep 11 '08 at 08:59
  • Great comments, pointing out the security aspect. – Vaibhav Sep 12 '08 at 07:04
  • 2
    Why it's a security risk to activate a trace from url? How it can be used to harm me? – Kamarey Jul 05 '10 at 18:57
48

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.

FlySwat
  • 172,459
  • 74
  • 246
  • 311
  • Viewstate initialization doesnt treat with Request.Params. Use it BEFORE raising of the method LoadPostData of control implemented IPostBackDataHandler. – chapluck Dec 16 '10 at 21:04
46

WebMethods.

You can using 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>
Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
45

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

if (this.Response.IsClientConnected)
{
  // long-running task
}
RickNZ
  • 18,448
  • 3
  • 51
  • 66
44

One little known and rarely used feature of ASP.NET is:

Tag Mapping

It's rarely used because there's only a specific situation where you'd need it, but when you need it, it's so handy.

Some articles about this little know feature:

Tag Mapping in ASP.NET
Using Tag Mapping in ASP.NET 2.0

and from that last article:

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>
CraigTP
  • 44,143
  • 8
  • 72
  • 99
  • This would be very confusing for other developers in your team – Aykut Akıncı Oct 14 '11 at 12:51
  • 1
    @Aykut - Indeed it could be, which is why I state that its usefulness is rather narrow, however, when required it's _very_ handy. Also, I would make sure that any usage of Tag Mapping was very clearly documented to avoid any confusion and ambiguity. – CraigTP Oct 14 '11 at 14:04
43

HttpModules. The architecture is crazy elegant. Maybe not a hidden feature, but cool none the less.

John K
  • 28,441
  • 31
  • 139
  • 229
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238
  • 3
    HttpModules is something that is advanced, but I wouldn't call it rare or less used (or call me naive). But yes, I love the architecture. – Vaibhav Sep 10 '08 at 18:25
  • +1 because a lot of seasoned developers may know about HttpModules but don't fully understand their relationship with requests. (Same thing with HttpHandlers) – John B Jun 06 '11 at 19:53
34

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>
--%>
Chris Pietschmann
  • 29,502
  • 35
  • 121
  • 166
34

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);
    }
} 
andleer
  • 22,388
  • 8
  • 62
  • 82
33

Usage of the ASHX file type:
If you want to just output some basic html or xml without going through the page event handlers then you can implement the HttpModule in a simple fashion

Name the page as SomeHandlerPage.ashx and just put the below code (just one line) in it

<%@ webhandler language="C#" class="MyNamespace.MyHandler" %>

Then the code file

using System;
using System.IO;
using System.Web;

namespace MyNamespace
{
    public class MyHandler: IHttpHandler
    {
        public void ProcessRequest (HttpContext context)
        {   
            context.Response.ContentType = "text/xml";
            string myString = SomeLibrary.SomeClass.SomeMethod();
            context.Response.Write(myString);
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}
Binoj Antony
  • 15,886
  • 25
  • 88
  • 96
  • 5
    It's worth noting that you should add IRequiresSessionState or IReadOnlySessionState if you need it, otherwise it won't be there. – Tracker1 May 23 '09 at 03:34
  • 3
    It's also worth noting that you can specify the setup of the handler in the web.config so you don't need to have a physical ashx file laying around. Or you can register the handler programatically in your application start in the global asax. – Phill Dec 27 '10 at 04:17
27

Setting Server Control Properties Based on Target Browser and more.

<asp:Label runat="server" ID="labelText" 
    ie:Text="This is IE text" 
    mozilla:Text="This is Firefox text" 
    Text="This is general text" 
/>

That one kinda took me by surprise.

Omer van Kloeten
  • 11,800
  • 9
  • 42
  • 53
  • 1
    +1. Can you post a short code sample inline. I think it will generate more attention and upvotes. I want this one to go up. – John K Jan 26 '10 at 08:47
26

System.Web.VirtualPathUtility

Chris Pietschmann
  • 29,502
  • 35
  • 121
  • 166
26

I worked on a asp.net application which went through a security audit by a leading security company and I learned this easy trick to preventing a lesser known but important security vulnerability.

The below explanation is from: http://www.guidanceshare.com/wiki/ASP.NET_2.0_Security_Guidelines_-_Parameter_Manipulation#Consider_Using_Page.ViewStateUserKey_to_Counter_One-Click_Attacks

Consider using Page.ViewStateUserKey to counter one-click attacks. If you authenticate your callers and use ViewState, set the Page.ViewStateUserKey property in the Page_Init event handler to prevent one-click attacks.

void Page_Init (object sender, EventArgs e) {
  ViewStateUserKey = Session.SessionID;
}

Set the property to a value you know is unique to each user, such as a session ID, user name, or user identifier.

A one-click attack occurs when an attacker creates a Web page (.htm or .aspx) that contains a hidden form field named __VIEWSTATE that is already filled with ViewState data. The ViewState can be generated from a page that the attacker had previously created, such as a shopping cart page with 100 items. The attacker lures an unsuspecting user into browsing to the page, and then the attacker causes the page to be sent to the server where the ViewState is valid. The server has no way of knowing that the ViewState originated from the attacker. ViewState validation and HMACs do not counter this attack because the ViewState is valid and the page is executed under the security context of the user.

By setting the ViewStateUserKey property, when the attacker browses to a page to create the ViewState, the property is initialized to his or her name. When the legitimate user submits the page to the server, it is initialized with the attacker's name. As a result, the ViewState HMAC check fails and an exception is generated.

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
Craig McKeachie
  • 1,704
  • 1
  • 21
  • 25
  • 2
    Also remember to leave base.OnInit(e); for the Page_Init() function to do its job. – Druid Sep 13 '09 at 15:59
  • I think that this trick can fail if a real user did not accept cookies, or if sessionid has timeout. – Aristos Apr 22 '10 at 10:18
  • 1
    You don't need `base.OnInit(e);` if you are using `AutoEventWireup="true"` for the page. – Adam Nofsinger May 08 '10 at 21:06
  • 1
    Druid: He's not overriding OnInit (in which case, base.OnInit(e) would be necessary). – crdx Feb 15 '11 at 09:25
  • Using the session ID for the ViewStateUserKey only works after a session has actually started. It also means that these pages can timeout after the session expires. In cases where those issues are a concern, you might consider using something more durable, such as the user's IP address. – RickNZ Dec 02 '11 at 05:44
  • There are circumstances where this doesn't fully prevent CSRF attacks. "It doesn't work for non post-backs (I.e. GET requests), and it doesn't work if the ViewState MAC is turned off." See http://www.cgisecurity.com/2008/09/viewstateuserke.html, so be aware of the assumptions and limitations if you are using this as your anti-CSRF strategy. – Nathan Dec 12 '11 at 18:49
25

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 live.

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
20

DefaultButton property in Panels.

It sets default button for a particular panel.

MRG
  • 3,219
  • 1
  • 26
  • 35
20

Included in ASP.NET 3.5 SP1:

  • customErrors now supports "redirectMode" attribute with a value of "ResponseRewrite". Shows error page without changing URL.
  • The form tag now recognizes the action attribute. Great for when you're using URL rewriting
John Sheehan
  • 77,456
  • 30
  • 160
  • 194
19

Using configSource to split configuration files.

You can use the configSource attribute in a web.config file to push configuration elements to other .config files, for example, instead of:

    <appSettings>
        <add key="webServiceURL" value="https://some/ws.url" />
        <!-- some more keys -->
    </appSettings>

...you can have the entire appSettings section stored in another configuration file. Here's the new web.config :

    <appSettings configSource="myAppSettings.config" />

The myAppSettings.config file :

    <appSettings>        
        <add key="webServiceURL" value="https://some/ws.url" />
        <!-- some more keys -->
    </appSettings>

This is quite useful for scenarios where you deploy an application to a customer and you don't want them interfering with the web.config file itself and just want them to be able to change just a few settings.

ref: http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx

Ryan Shripat
  • 5,574
  • 6
  • 49
  • 77
19

ScottGu has a bunch of tricks at http://weblogs.asp.net/scottgu/archive/2006/04/03/441787.aspx

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
17

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

MRG
  • 3,219
  • 1
  • 26
  • 35
16

HttpContext.IsCustomErrorEnabled is a cool feature.I've found it useful more than once. Here is a short post about it.

Kilhoffer
  • 32,375
  • 22
  • 97
  • 124
16

By default, any content between tags for a custom control is added as a child control. This can be intercepted in an AddParsedSubObject() override for filtering or additional parsing (e.g., of text content in LiteralControls):

    protected override void AddParsedSubObject(object obj)
     { var literal = obj as LiteralControl;
       if (literal != null) Controls.Add(parseControl(literal.Text));
       else base.AddParsedSubObject(obj);
     }

...

   <uc:MyControl runat='server'>
     ...this text is parsed as a LiteralControl...
  </uc:MyControl>
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
13

If you have ASP.NET generating an RSS feed, it will sometimes put an extra line at the top of the page. This won't validate with common RSS validators. You can work around it by putting the page directive <@Page> at the bottom of the page.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kevin Goff
  • 1,331
  • 1
  • 13
  • 18
  • 7
    Wouldn't you do better using an .ASHX handler for generating RSS feeds? – Dan Diplo Jul 21 '09 at 21:08
  • I guess that depends on the complexity of the project. Not every one has the ability or skills to create and compile handlers. In page asp.net works reasonably well for this – Kevin Goff Jul 31 '09 at 00:27
  • 1
    And you can use something like to generate RSS items and do other tricks (such as using the LogInView to remove some items) which is much better than writing strings from ASHX IMO – chakrit Mar 23 '10 at 13:50
  • LinqToXml + ASHX is the way to go! – Carlos Muñoz Aug 18 '10 at 05:52
  • This is useful for much more than RSS feed generation. IIRC, HTML5 must have the tag on the first line at the top to validate correctly. – Roy Tinker Sep 07 '10 at 18:01
12

My team uses this a lot as a hack:

WebRequest myRequest = WebRequest.Create("http://www.google.com");
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream());

// here's page's response loaded into a string for further use

String thisReturn = sr.ReadToEnd().Trim();

It loads a webpage's response as a string. You can send in post parameters too.

We use it in the place of ASCX/AJAX/WebServices when we need something cheap and fast. Basically, its a quick way to access web-available content across servers. In fact, we just dubbed it the "Redneck Web Service" yesterday.

Karim
  • 6,113
  • 18
  • 58
  • 83
Graham
  • 3,217
  • 1
  • 27
  • 29
12

Before ASP.NET v3.5 added routes you could create your own friendly URLs simply by writing an HTTPModule to and rewrite the request early in the page pipeline (like the BeginRequest event).

Urls like http://servername/page/Param1/SomeParams1/Param2/SomeParams2 would get mapped to another page like below (often using regular expressions).

HttpContext.RewritePath("PageHandler.aspx?Param1=SomeParms1&Param2=SomeParams2");

DotNetNuke has a really good HttpModule that does this for their friendly urls. Is still useful for machines where you can't deploy .NET v3.5.

Tyler
  • 3,220
  • 1
  • 30
  • 44
11

Did you know it's possible to 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);
        }
                    // Ta-dah!  C:\temp.html has some html for you.
    }
}
womp
  • 115,835
  • 26
  • 236
  • 269
10

CompilationMode="Never" is a feature which can be crucial in certain ASP.NET sites.

If you have an ASP.NET application where ASPX pages are frequently generated and updated via a CMS or other publishing system, it is important to use CompilationMode="Never".

Without this setting, the ASPX file changes will trigger recompilations which will quickly make your appdomain restart. This can wipe out session state and httpruntime cache, not to mention lag caused by recompilation.

(To prevent recompilation you could increase the numRecompilesBeforeAppRestart setting, but that is not ideal as it consumes more memory.)

One caveat to this feature is that the ASPX pages cannot contain any code blocks. To get around this, one may place code in custom controls and/or base classes.

This feature is mostly irrelevant in cases where ASPX pages don't change often.

frankadelic
  • 20,543
  • 37
  • 111
  • 164
9

Valid syntax that VS chokes on:

<input type="checkbox" name="roles" value='<%# Eval("Name") %>' 
  <%# ((bool) Eval("InRole")) ? "checked" : "" %> 
  <%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> />
leppie
  • 115,091
  • 17
  • 196
  • 297
9

System.Web.Hosting.HostingEnvironment.MapPath

John
  • 5,381
  • 4
  • 30
  • 26
9

one feature came to my mind, sometimes you will need to hide some part of your page from the crowlers. you can do it with javascript or using this simple code:

if (Request.Browser.Crawler){
        HideArticleComments();
Khaled Musaied
  • 2,513
  • 3
  • 25
  • 38
8

Similarly to the optimizeCompilations=”true” solution, here another one to speed up the time you spend waiting in between builds (very good especially if you are working with a large project): create a ram-based drive (i.e. using RamDisk) and change your default “Temporary ASP.NET Files” to this memory-based drive.

The full details on how to do this is on my blog: http://www.wagnerdanda.me/2009/11/speeding-up-build-times-in-asp-net-with-ramdisk/

Basically you first and configure a RamDisk (again, in my blog there a link to a free ramdisk) and then you change your web.config according to this:

 <system.web>
 ....
     <compilation debug="true" tempDirectory="R:\ASP_NET_TempFiles\">
     ....
     </compilation>
 ....
 </system.web>

It greatly increase my development time, you just need invest in memory for you computer :)

Happy Programming!

Wagner Danda

7

Request.IsLocal Property :

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

if( Request.IsLocal )
{
   LoadLocalAdminMailSettings();
}
else
{
   LoadServerAdminMailSettings();
}
MRG
  • 3,219
  • 1
  • 26
  • 35
  • 4
    Please also check the following discussion on asp.net forums about security concerns while using Request.IsLocal property http://forums.asp.net/t/1065813.aspx – MRG Aug 31 '09 at 12:34
  • Yes better avoid that and use - if DEBUG – Aristos Apr 22 '10 at 10:25
7

I thought it was neat when I dumped a xmlDocument() into a label and it displayed using it's xsl transforms.

Paulj
  • 3,096
  • 3
  • 25
  • 30
6

By default any web form page inherits from System.Web.UI.Page class. What if you want your pages to inherit from a custom base class, which inherits from System.Web.UI.Page?

There is a way to constraint any page to inherit from your own base class. Simply add a new line on your web.config:

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

Caution: this is only valid if your class is a stand-alone one. I mean a class that has no code-behind, which looks like <%@ Page Language="C#" AutoEventWireup="true" %>

roland
  • 7,695
  • 6
  • 46
  • 61
5

EnsureChildControls Method : It checks the child controls if they're initiated. If the child controls are not initiated it calls CreateChildControls method.

Canavar
  • 47,715
  • 17
  • 91
  • 122
5

Attach a class located in your App_Code folder to your Global Application Class file.

ASP.NET 2.0 - Global.asax - Code Behind file.

This works in Visual Studio 2008 as well.

cllpse
  • 21,396
  • 37
  • 131
  • 170
4

You can find any control by using its UniqueID property:

Label label = (Label)Page.FindControl("UserControl1$Label1");
Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93
4

Lots of people mentioned how to optimize your code when recompiling. Recently I discovered I can do most of my development (code-behind stuff) in the aspx page and skipping completely the build step. Just save the file and refresh your page. All you have to do is wrap your code in the following tag:

<script runat="server">

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     Response.Write("Look Ma', I didn't even had to build!")
   End Sub

</script>

Once you are done, Just move all to the code-behind, build, test everything works and voila!

-D

Diego C.
  • 2,271
  • 2
  • 20
  • 21
  • 1
    If you use Web site project instead of web application you can write code in code behind and asp.net will compile it for you behind the scene. You'll not need to compile the project yourself. – Branislav Abadjimarinov Jun 09 '10 at 08:13
  • 7
    Most of the time there are lots of good reasons _not_ to do this. – Joel Coehoorn Jun 09 '10 at 13:08
  • @Branislav, Yes, but for those using Web Application projects, this is a workaround. @Joel, What reasons? just to be clear, I take this approach only in development and only when working on pieces of code that might result in several trials. – Diego C. Jun 09 '10 at 18:07
2

If you use web services instead WCF services, you can still use standard .Net membership to enforce authentication and login session behaviour on a set web services similarly to a how you would secure web site with membership forms authentication & without the need for a special session and/or soap headers implementations by simply calling System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false) [after calling Membership.ValidateUser(userName, password) of course] to create cookie in the response as if the user has logged in via a web form. Then you can retrieve this authentication cookie with Response.Cookies[].Value and return it as a string to the user which can be used to authenticate the user in subsequent calls by re-creating the cookie in the Application_BeginRequest by extracting the
cookie method call param from the Request.InputStream and re-creating the auth cookie before the membership authenticates the request this way the membership provider gets tricked and will know the request is authenticated and enforce all its rules.

Sample web method signature to return this cookie to the user would be: string Login(userName,password)

Sample subsequent web method call would be: string DoSomething(string authcookie,string methodParam1,int methodParam2 etc,etc) where you need to extract authcookie(which is value obtained from Login method) param from the Request.InputStreamis

This also simulates a login session and calling FormsAuthentication.SignOut in a web method like this Logout(authcookie) would make the user need to sign in again.

Ivo S
  • 1
  • 1
2

'file' attribute on appsettings element in web.config.

Specifies a relative path to an external file that contains custom application configuration settings.

If you have few app settings out of many that need to modified on different environments (prod), this is excellent choice.

Because any changes to the Web.config file cause the application to restart, using a separate file allows users to modify values that are in the appSettings section without causing the application to restart. The contents of the separate file are merged with the appSettings section in the Web.config file.

chandmk
  • 3,496
  • 3
  • 21
  • 26
2

ClientScript property on Page object.

Canavar
  • 47,715
  • 17
  • 91
  • 122
1

Application variables can be used with web application for communicating across the whole application. It is initialized in Global.asax file and used over the pages in that web application by all the user independent of the session they create.

TRIVER
  • 11
  • 2
0

It's possible to package ASPX pages into a Library (.dll), and serve them with the ASP.NET engine.

You will need to implement your own VirtualPathProvider, which will load via Relfection specific DLL's, or you could include the DLL name in your pathname. It's up to you.

The magic happens when overriding the VirtualFile.Open method, where you return the ASPX file as a resource from the Assembly class: Assembly.GetManifestResourceStream. The ASP.NET engine will process the resource since it is served via the VirtualPathProvider.

This allows to plug-in pages, or like I did, use it to include a HttpHandler with a control.

Bart Verkoeijen
  • 16,545
  • 7
  • 52
  • 56
0

Templated user controls. Once you know how they work you will see all sorts of possibilities. Here's the simplest implementation:

TemplatedControl.ascx

The great thing here is using the easy and familiar user control building block and being able to layout the different parts of your UI using HTML and some placeholders.

<%@ Control Language="C#" CodeFile="TemplatedControl.ascx.cs" Inherits="TemplatedControl" %>

<div class="header">
    <asp:PlaceHolder ID="HeaderPlaceHolder" runat="server" />
</div>
<div class="body">
    <asp:PlaceHolder ID="BodyPlaceHolder" runat="server" />
</div>

TemplatedControl.ascx.cs

The 'secret' here is using public properties of type ITemplate and knowing about the [ParseChildren] and [PersistenceMode] attributes.

using System.Web.UI;

[ParseChildren(true)]
public partial class TemplatedControl : System.Web.UI.UserControl
{
    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate Header { get; set; }

    [PersistenceMode(PersistenceMode.InnerProperty)]
    public ITemplate Body { get; set; }

    void Page_Init()
    {
        if (Header != null)
            Header.InstantiateIn(HeaderPlaceHolder);

        if (Body != null)
            Body.InstantiateIn(BodyPlaceHolder);
    }
}

Default.aspx

<%@ Register TagPrefix="uc" TagName="TemplatedControl" Src="TemplatedControl.ascx" %>

<uc:TemplatedControl runat="server">
    <Header>Lorem ipsum</Header>
    <Body>
        // You can add literal text, HTML and server controls to the templates
        <p>Hello <asp:Label runat="server" Text="world" />!</p>
    </Body>
</uc:TemplatedControl>

You will even get IntelliSense for the inner template properties. So if you work in a team you can quickly create reusable UI to achieve the same composability that your team already enjoys from the built-in ASP.NET server controls.

The MSDN example (same link as the beginning) adds some extra controls and a naming container, but that only becomes necessary if you want to support 'repeater-type' controls.

Michiel van Oosterhout
  • 22,839
  • 15
  • 90
  • 132
-3

One of the things I use that work with multiple versions of VB, VBScript and VB.NET is to convert the recordset values to string to eliminate muliple tests for NULL or blank. i.e. Trim(rsData("FieldName").Value & " ")
In the case of a whole number value this would be: CLng("0" & Trim(rsData("FieldName").Value & " "))

Dave
  • 1,234
  • 13
  • 24
-6

After the website was published and deployed in the production server, If we need to do some changes on the server side button click event. We can override the existing click event by using the newkeyword in the aspx page itself.

Example

Code Behind Method

 Protected void button_click(sender object, e System.EventArgs) 
  {
     Response.Write("Look Ma', I Am code behind code!")  
  }

OverRided Method:

<script runat="server">   
   Protected void new button_click(sender object, e System.EventArgs) 
  {
     Response.Write("Look Ma', I am overrided method!")  
  }

</script

In this way we can easily fix the production server errors without redeployment.

Ramesh
  • 1,692
  • 2
  • 18
  • 37
  • 4
    Doesn't that get archaic after a while? Why is it not better to manage the build and deployment process properly? My initial reaction is this isn't a "hidden" feature but rather bad use of the well known `new` keyword. – John K Jul 02 '10 at 07:28
  • 1
    We have deployment procedures and checks to avoid anything remotely like this as well as pre-compiling any asp.net anythings... – davidsleeps Jul 02 '10 at 12:13
  • 1
    It's not hidden feature, that's for sure! And what's the point in using code-behind if it's going to get overrided in the aspx page? Just to avoid redeploying? It defeats the whole 'code-behind' concept : Separate the code from the presentation layer. – Philippe Jul 05 '10 at 18:40
  • 1
    What's the big deal about redeployment? – kirk.burleson Jul 31 '10 at 05:14
  • this is great if a temp fix needs to be made – Vaibhav Garg Jan 21 '11 at 12:29
  • Development on production server... – Nitin Sawant Jun 20 '11 at 09:34
-6

This seems like a huge, vague question... But I will throw in Reflection, as it has allowed me to do some incredibly powerful things like pluggable DALs and such.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
  • Reflection is of course not an asp.net hidden feature... and yes, the question is meant to be all encompassing... – Vaibhav Sep 10 '08 at 18:25
  • I am not sure what you would define by a 'hidden feature' then. You might think of adding an example of what you consider a hidden feature. – GEOCHET Sep 10 '08 at 18:29
  • 3
    I meant, reflection is not specific to asp.net. It is something that you can use even outside of asp.net (for example, in a win forms application) – Vaibhav Sep 10 '08 at 18:59