Where are my Menu Items coming from? - asp.net

I've taken over this website with no documentation (Yay!). Maybe this will help others to understand the SiteMap functionality. I have an idea how the SiteMenu is being built, but want to check with my buddies here at SO to be sure.
I have a Main.Master which calls for a SiteMenuHorizontal User Control.
<%# Register Src="uc2Menu.ascx" TagPrefix="uc2" TagName="smHorizontal" %>
...
<uc2:smHorizontal id="uc2Menu" runat="server" />
The User Control is pretty simple:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="uc2Menu.ascx.vb" Inherits="uc2Menu" %>
<asp:Menu id="siteMenu" runat="server" DataSourceID="menuSiteMapDataSource" Orientation="Horizontal" />
<asp:SiteMapDataSource ID="menuSiteMapDataSource" runat="server" ShowStartingNode="false" />
No help from the control's codebehind:
Public Partial Class uc2Menu
Inherits System.Web.UI.UserControl
Protected Sub siteMenu_MenuItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles siteMenu.MenuItemDataBound
e.Item.Target = CType(e.Item.DataItem, SiteMapNode)("Target")
End Sub
End Class
The Web.Config DOES specify a SiteMap:
<siteMap enabled="true" defaultProvider="objSiteMap">
<providers>
<clear/>
<add name="objSiteMap" type="LOC.DLL.objSiteMap" securityTrimmingEnabled="true" expirationInterval="1"/>
</providers>
</siteMap>
LOC.DLL.objSiteMap inherits SiteMapProvider and has overloads/overrides etc. The methods grab a table from a DB and build a SiteMapNode, or SiteMapNodeCollection.
My confusion is: How is this class populating my web page? There are no visible calls to the SiteMap.
My assumption is this:
When the site (or page) is built (or compiled?), my User Control calls its Datasource, Global.System.Web.UI.WebControls.SiteMapDataSource. Somehow, that control references the Web.Config for a reference to LOC.DLL.objSiteMap, and runs the Override/Overload methods to retrieve a SiteMapNode(/Collection), and return it back to my control?
I have a feeling I've got it down, but wanted to get a confirmation and/or clarification, and hopefully help others in the future who take over projects with dynamic site menus.

How is this class populating my web page? There are no visible calls
to the SiteMap.
SiteMapProvider is based on ASP.Net's Provider model, similar to Membership and Role providers.
My assumption is this: When the site (or page) is built (or
compiled?), my User Control calls its Datasource,
Global.System.Web.UI.WebControls. SiteMapDataSource. Somehow, that
control references the Web.Config for a reference to
LOC.DLL.objSiteMap, and runs the Override/Overload methods to retrieve
a SiteMapNode(/Collection), and return it back to my control?
Yes, your assumption is correct.
Your user control calls the default site map provider objSiteMap, and the sitemap is created on every page request dynamically.
FYI: Since you have set objSiteMap as the defaultprovider, you do not need to do anything. However, if you want a provider other than the default, you'll need to set a provider name explicitly.
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server"
SiteMapProvider="AnotherProvider" />

You're pretty much right on the money with your analysis.
The main connection here that I think you're missing is that the web.config value defaultProvider="objSiteMap" is what causes the SiteMapDataSource in your UserControl to connect to the "objSiteMap" provider in your web.config.
Since it is set as the "default provider", any SiteMap's in your project will be populated using that LOC.DLL.objSiteMap provider (unless you specifically override the default in the code).

Related

Where is the code that runs when a button is clicked in ASP.NET

I'm trying to learn basic aspects of ASP.NET by analyzing the default Web Site project with Visual Studio 2010.
In the Register.aspx page there are fields for user registration and this button:
<asp:Button ID="CreateUserButton" runat="server" CommandName="MoveNext"
Text="Create User" ValidationGroup="RegisterUserValidationGroup"/>
The button does register an user, but I can't find the piece of code that is run and even less how code was associated to that button. I've tried searching the solution for all the identifier keywords and found nothing relevant. Searching on the web mentions a Button.OnClick method that I also can't find.
Any info on the basic aspects of ASP.NET will help me; thanks in advance.
Edit: hierarchically, the button is inside:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser">
<WizardSteps>
<asp:CreateUserWizardStep ID="RegisterUserWizardStep" runat="server">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
There is a RegisterUser_CreatedUser method on the code behind and it does:
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);
string continueUrl = RegisterUser.ContinueDestinationPageUrl;
if (String.IsNullOrEmpty(continueUrl))
{
continueUrl = "~/";
}
Response.Redirect(continueUrl);
}
I was expecting some kind of inserting of user data on a database. I wonder, is this all that the button does?
The button you are looking it should be in CreateUserWizardStep control. I don't know much about this control but probably control looks for a child button having CommandName = "MoveNext", then it hooks for its click event.
Try changing the CommandName to something else like "test", it should NOT hit the breakpoint on RegisterUser_CreatedUser event.
Also note that CreatedUser <- event is telling that user is created, now the rest of the code is just authenticating the same user. Behind that, the user is already been created and saved in database.
If you also look in the web.config you will find this ConnectionString
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
Since you are using the Visual Studio's Default Web Application project, these all things are already done by Visual Studio for you.
An aspx page will also have a "code behind" file with the same name but a different extension (the letters after the dot) which depends on the language it's written in. Visual basic files have a .vb extension while C# files have a .cs extension.
Try looking for Register.vb or Register.cs and see if that's more fruitful.
If you're using a development environment like Visual Studio, you'll probably find that in the Solution Explorer you can click to expand the aspx file and see its code behind file underneath. If you're not, you might want to pick up a copy of the free express edition:
http://www.visualstudio.com/en-US/products/visual-studio-express-vs
When you find the code-behind, look for method called "MoveNext" - that's the code that'll run when you click the button, as specified by the CommandName attribute of the asp: Tag.
You've complicated a couple of things and you are completely not at fault but partly the project templates which comes with VS 2010 IDE. Let me try to help you one by one:
Learning basics of ASP.Net : For this you should be using "ASP.NET Empty Web Application" project template present in Visual Studio 2010. You've started with "ASP.NET Web Application" project template which has complicated things for
you. To start afresh "ASP.NET Web Application" looks the obvious choice for anyone though but it comes with a precooked boiler-plate code meant for ASP.NET membership forms authentication and its associated controls which is the root cause of all your confusion. To get started with the basics take the "ASP.NET Empty Web Application" project template I've suggested above and then add a new "Web Form" and then add various basic server web controls like button or text box to get started with concepts like event handling and code behind stuff.
Your other problem -
"The button does register an user, but I can't find the piece of code
that is run and even less how code was associated to that button"
That is because the button that you are seeing on Register.aspx page is
NOT an individual server web control but it is part of a composite control asp:CreateUserWizard instead. All the events of various controls be it a button, label or text box which are part of the asp:CreateUserWizard composite control is handled by the parent composite control asp:CreateUserWizard. You will NOT find all that code in your code behind file as this is present in System.Web.dll which is referenced in your project.
Since all the control events present on the composite control are handled by a common function written inside the code of composite control it has to distinguish exactly which control was clicked by the user (to take an appropriate action) which caused the current page post back for which CommandName property comes into picture. There is a switch case statement inside that common function for parent composite control which uses the CommandName property.
So essentially what happened is when you tried to start understanding basics of ASP.Net server web controls and event handling you actually got into the path of understanding ASP.Net Membership & role web server controls & providers which might be comparatively tough to understand and grasp initially. Hope this helps you to get started and further your understanding on ASP.Net world.

Change UserControl template at runtime

Is it possible to change the ascx file used by a usercontrol at runtime?
For example in my page i have
<ctl:SampleControl runat="server" />
in the web.config I have
<controls>
<add tagPrefix="ctl" tagName="SampleControl" src="~/UserControls/SampleControl.ascx" />
</controls>
At runtime I would like to be able to change the ascx to another path, it would still be inheriting from the same usercontrol codebehind, it would just be a different template.
Probably the best thing to do here is to not encode the filename of the "default" .ascx file in your web.config. It will make your life harder. Always do that determination at runtime, like this for instance:
In your .aspx file:
<asp:PlaceHolder runat="server" ID="samplePH" />
In the code-behind:
string file = "~/UserControls/SampleControl.ascx";
if (condition)
file = "~/UserControls/OtherControl.ascx";
UserControl uc = (UserControl)LoadControl(file); // from System.Web.UI.TemplateControl.
samplePH.Controls.Clear();
samplePH.Controls.Add(uc);
But, be aware that in order for post-backs to work correctly, you need to instantiate the same control that was loaded on the last request, early in the page lifecycle -- typically the Init stage. This will ensure that viewstate is correctly parsed. Then, further down in your event handler, PreRender, etc. lifecycle steps, you can use the above code to load the UserControl for the current request.
If you really do need to encode a default page setting in a configuration file (for cases where end-users may want to change it), consider doing it in an app.config rather than buried away in a <controls> section of a web.config.
Documentation for the TemplateControl.LoadControl(string) method:
http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.loadcontrol.aspx

One Hyperlink In Many Different Locations

I'd like to implement a hyperlink in many locations on my website, however I just want to have it defined once not several times over. What is the best way to achieve this?
I started down the road of listing it in the node of web.config but I was only able to get that to list as a literal and wasn't successful in having it end up as a hyperlink.
I don't know much about master pages, but what I do know about them seems to me that they aren't the answer for this task because they wouldn't allow for that hyperlink to be located on some pages and not others and in different locations on some pages than others.
Help please! :)
I'm working in ASP.net VB.net
Put a HyperLink control on each page where you want it.
e.g. <asp:HyperLink runat="server" id="LogInLink">Login</asp:HyperLink>
Then either set the NavigateUrl property on the hyperlink in code-behind, e.g. this.LogInLink.NavigateUrl = Global.MySpecialUrl; or use <%=Global.MySpecialUrl%> notation to reference the value you want from your code in the NavigateUrl in the markup.
[Sorry, that's C# code]
You can create a custom control that inherits from HyperLink. This method will not require to use code-behind on individual pages but you will need to create a new class and modify your web.config file. Alter the namespaces as needed.
SpecialLink.vb
Namespace YourWebSite.Controls
Public Class SpecialLink
Inherits HyperLink
Public Sub New()
NavigateUrl = "~/SpecialLinkUri.aspx"
Text = "Special Link Text"
End Sub
End Class
End Namespace
web.config (add this to the system.web node)
This allows you to use this control on any page/master page/user control throughout your site
<pages>
<controls>
<add namespace="YourWebSite.Controls" tagPrefix="YourWebSite"/>
</controls>
</pages>
Using it on your page
<p>This is some text, here's the link: <YourWebSite:SpecialLink></YourWebSite:SpecialLink></p>
<p>This is some text, <YourWebSite:SpecialLink>here's the link</YourWebSite:SpecialLink>.</p>

Cannot see new asp.net user controls

I am feeling like an idiot right now, but I cannot for the life of me figure out why I cannot seem to call user controls from within my asp.net webpage. I'm still learning asp.net but I can't find any information from searching on google.
I'm trying to load a specific control on the page when the user presses a linkbutton. So I created an empty user control via the right click menu:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
In other words, I have not touched any part of the created user control. Yet attempting to create this web control and add it to the form seems to not work, as it claims that the WebUserControl class does not exist (I have no other controls in my project):
UserControl blah = new WebUserControls();
produces a "The type or namespace is invalid". Why can none of my asp.net webform pages get the control into scope?
The new control must be added to the site's Web.config file.
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="my"
tagName="WebUserControl"
src="~/WebUserControl.ascx"/>
</controls>
</pages>
</system.web>
</configuration>
Use this to place the new control in an .aspx page.
<my:WebUserControl runat="server" ID="MyWebUserControl" />
In addition to registering them one-by-one in web.config, you can also use a <%# Register %> directive in the source of the markup files that reference the control.
Or, you can move your controls into a DLL and include them all by referencing the assembly from your web.config (takes some extra work, though).

Hidden Features of ASP.NET [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
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?
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>
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.
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
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:
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)
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.
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
HttpContext.Items as a request-level caching tool
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.
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.
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>
Check to see if the client is still connected, before starting a long-running task:
if (this.Response.IsClientConnected)
{
// long-running task
}
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>
HttpModules. The architecture is crazy elegant. Maybe not a hidden feature, but cool none the less.
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);
}
}
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; }
}
}
}
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.
System.Web.VirtualPathUtility
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.
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.
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
DefaultButton property in Panels.
It sets default button for a particular panel.
ScottGu has a bunch of tricks at http://weblogs.asp.net/scottgu/archive/2006/04/03/441787.aspx
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
MaintainScrollPositionOnPostback attribute in Page directive. It is used to maintain scroll position of aspx page across postbacks.
HttpContext.IsCustomErrorEnabled is a cool feature.I've found it useful more than once. Here is a short post about it.
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>
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.
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.

Resources