URL Routing in ASP.Net 4 Web Forms

ASP.Net 4 simplifies the routing experience introduced in ASP.NET 3.5 SP1. Routing allows the use of more meaningful or 'friendly' URLs (which may also benefit search engine ranking).

For example, rather than .../ShowCountryDetails.aspx?country=australia routing could be enabled so the url looked like .../countries/australia

Defining Routes

You can define routes using the MapPageRoute method of the RouteCollection class. The code below is an extract from Global.asax.cs, the method RegisterRoutes is called from application start, and it's here that a route is registered:

protected void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}



void RegisterRoutes(RouteCollection routes)
{
    /*  Create a routing which maps SayHello to ShowGreeting.aspx
        and defines 2 parameters, greeting and name. */
    routes.MapPageRoute("ShowGreetingRoute",
        "SayHello/{greeting}/{name}",
        "~/ShowGreeting.aspx");
}
 

Accessing URL Param Values In Markup

When routing is in use, RouteValue expressions can be used in markup:

<asp:Literal Text="<%$RouteValue:greeting%>" runat="server" />

Accessing URL Param Values In Code

In code we can use Page.RouteData to get the values of any routed URL parameter values; we can either check for a null before calling ToString() or as in the following example use ContainsKey to check first (in practice you wouldn't use 'magic' string literals for "greeting", rather you'd define these as constants, etc.):

string greetingText = "no greeting text specified";
       
if (Page.RouteData.Values.ContainsKey("greeting"))
        greetingText = Page.RouteData.Values["greeting"].ToString();

Creating Routed URLs in Markup

We can create routed URLs in markup by using RouteUrl expressions:

<asp:HyperLink ID="declarativeLinkToRoutedPage"
    NavigateUrl="<%$RouteUrl:greeting=bonjour, name=Bob, routename=ShowGreetingRoute%>"
    Text="Say hello to Bob in French" runat="server" />

Creating Routed URLs in Code

Instead of setting NavigateUrl using RouteUrl in markup, we could set it in code RouteValueDictionary & VirtualPathData:

/// <summary>
/// Example of setting a Hyperlink's NavigateUrl in code
/// </summary>
private void SetHyperlinkNavigateUrlProperty()
{
    RouteValueDictionary routeParamValues = new RouteValueDictionary
    {
        {"greeting", "goodnight"},
        {"name", "Fred"}
    };

    VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, routeParamValues);

    linkSetInCodeToRoutedPage.NavigateUrl = vpd.VirtualPath;
}

Using Routed Values as Parameters in Bound Data Sources

We can define RouteParameter in a data source that is being bound to.

The following markup shows a DetailsView being bound to an ObjectDataSource. The SelectParameters collection defines a RouteParameter which will pass the value of the 'name' URL routed parameter to the GetPersonsAge method of the MockDataBase class.

<asp:ObjectDataSource ID="odsPersonsAge" runat="server"
    SelectMethod="GetPersonsAge" TypeName="ASPNET4Routing.MockDataBase">
    <SelectParameters>
        <asp:RouteParameter Name="name" RouteKey="name" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>
      
<asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="odsPersonsAge"
                AutoGenerateRows="true" /> 

<asp:ObjectDataSource ID="odsPersonsAge" runat="server"
    SelectMethod="GetPersonsAge" TypeName="ASPNET4Routing.MockDataBase">
    <SelectParameters>
        <asp:RouteParameter Name="name" RouteKey="name" Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>

Managing ViewState in ASP.Net 4

ASP.Net 4 allows us to use an opt-in viewstate approach rather than an opt-out approach in previous ASP.Net versions (EnableViewState was available in prior versions, but if you disable viewstate, all children of the page/container also inherited this with no one to override and opt-in).

To use the opt-in approach in ASP.Net 4, the new ViewStateMode property can be used. The following example disables viewstate for the whole page (all children will inherit this disabled value) but Label2 opts in to viewstate. The codebehind sets the values of the labels only on the first page load - not any subsequent postbacks.

<%@ Page Language="C#" AutoEventWireup="true"
 CodeFile="Default.aspx.cs" Inherits="_Default"
 ViewStateMode="Disabled"
 %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p><asp:Label ID="Label1" Text="not set" runat="server" /></p>
        <p><asp:Label ID="Label2" Text="not set" ViewStateMode="Enabled" runat="server" /></p>
        <p><asp:Button Text="do a postback" runat="server" /></p>
    </div>
    </form>
</body>
</html>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Label1.Text = "this text has been set from code behind only on the first load i.e. not set in any following postbacks.";
        Label2.Text = Label1.Text;
    }
}

The first time the page loads, the 2 text boxes show the text as set in the code behind:

 

 



Once a postback happens (in this case by clicking the button), no code is executed in the Page_Load event due to the if (!IsPostBack) check. This means that the Text property of the labels will be set to what's initially declared in the aspx mark-up (i.e. "not set"); however because we have set ViewStateMode="Enabled" on Label2, it's Text will be retained in viewstate between callbacks:

 

Setting Meta Tags in ASP.Net 4

ASP.Net 4 adds 2 new Meta tag related properties to the Page. They can be used to set meta tags for keywords and description.

You can set them in the code behind:

Page.MetaKeywords = "keyword1, keyword2, keyword3";
Page.MetaDescription = "Example of new meta tag support in ASP.Net 4";

You can also set in the @Page directive:

<%@ Page Language="C#" AutoEventWireup="true"
MetaKeywords="keyword1, keyword2, keyword3"
MetaDescription="Example of new meta tag support in ASP.Net 4"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

The ouput of either of these methods renders html similar to the following:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
    ASP.NET 4 Meta Tag Support
</title><meta name="description" content="Example of new meta tag support in ASP.Net 4" /><meta name="keywords" content="keyword1, keyword2, keyword3" /></head>
<body>
 </body>
</html>
 

Session State Compression in ASP.NET 4

ASP.NET 4 introduces the ability to turn on compression of session data.

Compression is disabled by default, to enable it modify the web.config file and set the new compressionEnabled attribute to true:

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="10"
sqlConnectionString="data source=127.0.0.1;Integrated Security=SSPI"
sqlCommandTimeout="30"
customProvider=""
compressionEnabled="true" cookieless="UseCookies" cookieName="ASP.NET_SessionId" timeout="20" allowCustomSqlDatabase="false" regenerateExpiredSessionId="true" partitionResolverType="" useHostingIdentity="true"> <providers> <clear /> </providers> </sessionState> </system.web> </configuration>

The <sessionState> element is not defined in either the root machine or web config, and according to msdn the above (minus the compressionEnabled attribute) is the default.

The choice to enable compression should only be taken if the server is not already CPU bound as compression adds an additional compression/decompression overhead.

Permanently Redirecting a Page in ASP.NET 4

Rather that using Response.Redirect("newpage.aspx"), ASP.NET 4 introduces the RedirectPermanent method.

To signal that the redirect is of a permanent nature (such as a url to a page changing permanently) you can now call:

Response.RedirectPermanent("newpage.aspx");

This will issue a http response HTTP 301 (Moved Permanently) rather than the normal HTTP 302 (Found). This can potentially remove a round trip to the server.

From msdn.com: "Search engines and other user agents that recognize permanent redirects will store the new URL that is associated with the content, which eliminates the unnecessary round trip made by the browser for temporary redirects."

Notification Window "toast" in Silverlight 4

To create "toast" notifications (small popup messages that appear at the bottom right on Windows) the NotificationWindow class can be used.

NotificationWindow will only work in out-of-browser mode, if you try to show a notification when running in-browser a System.InvalidOperationException is thrown.

The default size of the toast is 400 x 100, the size can be altered by setting NotificationWindow's Width & Height, but the max size is 400 x 100;

Example 1 - Creating Some Simple Content

The code below shows a notification that contains a  TextBlock with the text "hello" and show it for 2 seconds:

var toast = new NotificationWindow();

// Create some content to show
var tb = new TextBlock();
tb.Text = "hello";

// Set content of the toast before we show it
toast.Content = tb;

// Show notification for 2 seconds
toast.Show(2000);

Example 2 - Using a UserControl as Content

This example shows how a UserControl defined elsewhere in XAML can be used as the content of the notification:

var toast = new NotificationWindow();

// Create an instance of a UserControl called SampleToast
// that is defined in XAML
var toastContent = new SampleToast();

// Set the content of the notification window to that of the UserControl
toast.Content = toastContent;

// Optionally set size to be different from the
// default of 400 x 100
toast.Width = 200;
toast.Height = 50;

// Show notification for 2 seconds
toast.Show(5000);

MSDN Docs

 

Hosting HTML Content in Silverlight 4

In Silverlight 4 we can present HTML content to the user.

The WebBrowser Control

For example to display the content of DontCodeTired.com we can set the Source property in XAML:

<WebBrowser Name="webBrowser" Source="http://www.dontcodetired.com" />

Or we can use the Navigate method of WebBrowser:

webBrowser.Navigate(new Uri(@"http://www.dontcodetired.com"));

The user can navigate to links, right-click and open in new tab (which opens up tab in a full web browser), view source, etc.

To use the WebBrowser the Silverlight app must be running out of browser (OOB), if you view when embedded in a web page (i.e. not OOB) the control displays a message saying that it can only be used in Out-of-Browser mode.

WebBrowser control running in-browser

WebBrowserBrush

Using the new WebBrowserBrush (previously HtmlBrush in beta 4) we can use the contents of a WebBrowser to fill another element.

For example, to fill an Ellipse with the content of a WebBrowser named "webBrowser" we define a WebBrowserBrush and sets its SourceName:

<Ellipse>
    <Ellipse.Fill>
        <WebBrowserBrush SourceName="webBrowser"  />
    </Ellipse.Fill>
</Ellipse>

The following example creates an ellipse which is filled with a blurred version of the content of a WebBrowser. One thing to note is that we hook into the WebBrowser's LoadCompleted event to ensure the ellipse is updated whenever a page has been loaded into the WebBrowser. When run it looks like the image below: 



XAML:

<UserControl x:Class="SL4HTMLHosting.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
       
        <WebBrowser Name="webBrowser"
                    Source="http://www.dontcodetired.com"
                    Grid.Row="0"
                    LoadCompleted="webBrowser_LoadCompleted">
        </WebBrowser>
       
        <Ellipse HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Grid.Row="1">
            <Ellipse.Effect>
                <BlurEffect Radius="5" />
            </Ellipse.Effect>
            <Ellipse.Fill>
                <WebBrowserBrush x:Name="browserBrush"
                                    SourceName="webBrowser"  />
            </Ellipse.Fill>
        </Ellipse>
          
    </Grid>
</UserControl>

Code Behind:

using System.Windows.Controls;

namespace SL4HTMLHosting
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            browserBrush.Redraw();
        }
    }
}

Interacting With WebBrowser Content

The following example uses WebBrowser.NavigateToString which allows a string of HTML to be rendered rather than a page at some Uri. The example creates a simple html button which uses window.external.notify to pass a message to the WebBroswer control via it's ScriptNotify event.

XAML:

<Grid x:Name="LayoutRoot" Background="White">            
    <WebBrowser Name="webBrowser"
                ScriptNotify="webBrowser_ScriptNotify">                  
    </WebBrowser>          
</Grid>

Code Behind:

using System.Windows.Controls;
using System.Text;
using System.Windows;

namespace SL4HTMLHosting
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
           
            // Create some basic HTML on the fly containing a simple button,
            // that when clicked passes a message to the containing WebBrowser
            var html = new StringBuilder();
            html.Append("<html>");
            html.Append("   <body>");
            html.Append(@"       <input type=""button"" value=""Show Message Box"" onclick=""window.external.notify('button click');"" /> ");
            html.Append("   </body>");
            html.Append("</html>");

            webBrowser.NavigateToString(html.ToString());
        }



        private void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            MessageBox.Show(string.Format("Message from web page: '{0}'.",e.Value));
        }
    }
}
 

Right Click and Context Menu Support in Silverlight 4

Silverlight 4 allows us access to right-click functionality, in earlier versions of Silverlight right-clicking would bring up the standard SL popup menu.

Simple Right Click

To capture a right-click the MouseRightButtonDown event can be subscribed to:

MouseRightButtonDown="btnPopup_MouseRightButtonDown"

To prevent the standard SL popup from appearing, in the event handler we set Handled to true, this stops the right-click event from bubbling up to Silverlight:

private void btnPopup_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{   
    // Prevent the standard Silverlight popup          
    e.Handled = true;

    MessageBox.Show("Right button clicked");
}

Context Menu

The ContextMenu is available in the Silverlight Toolkit.

A popup context menu can easily be added to a control (e.g. a button), when the control is right-clicked the context menu is automatically shown

The XAML below declares a simple popup menu with 2 menu items: Open & Save that when clicked both fire the same event handler.

<Button Name="btnContextMenu"
        Content="ContextMenu Right Click"
        MouseRightButtonDown="btnContextMenu_MouseRightButtonDown">
    <toolkit:ContextMenuService.ContextMenu>
        <toolkit:ContextMenu>
            <toolkit:MenuItem Header="Open" Click="ContextMenuItem_Click"/>
            <toolkit:MenuItem Header="Save" Click="ContextMenuItem_Click"/>
        </toolkit:ContextMenu>                   
    </toolkit:ContextMenuService.ContextMenu>     
</Button>

The namespace (xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit") must be declared - if you drag and drop something from the Toolkit the namespace will be automatically added.

Full listing (simple popup & context menu)

XAML:

<UserControl x:Class="SL4RClickPopup.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" >  
   
    <StackPanel>
       
        <Button Name="btnPopup"
                Content="Simple Right Click"
                MouseRightButtonDown="btnPopup_MouseRightButtonDown" />
       
        <Button Name="btnContextMenu"
                Content="ContextMenu Right Click"
                MouseRightButtonDown="btnContextMenu_MouseRightButtonDown">
           
            <toolkit:ContextMenuService.ContextMenu>
                <toolkit:ContextMenu>
                    <toolkit:MenuItem Header="Open" Click="ContextMenuItem_Click"/>
                    <toolkit:MenuItem Header="Save" Click="ContextMenuItem_Click"/>
                </toolkit:ContextMenu>
            </toolkit:ContextMenuService.ContextMenu>
           
        </Button>
         
    </StackPanel>
   
</UserControl>

Code Behind:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace SL4RClickPopup
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }



        private void btnPopup_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Prevent the standard Silverlight popup          
            e.Handled = true;

            MessageBox.Show("Right button clicked");
        }



        private void btnContextMenu_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Because we have declare a ContextMenu in Xaml we don't
            // need to manually set e.Handled = true;
        }



        private void ContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("ContextMenu item clicked");
        }
    }
}
 

Drag and Drop in Silverlight 4

To enable drag and drop support on a Silverlight UIElement the AllowDrop property needs to be set to True (it is false by default). The Drop event can now be subscribed to, in which the dropped item(s) can be processed.

The example below allows a .jpg file to be dragged (from the desktop, Windows Explorer, etc.) and dropped onto the application. When the user drops a .jpg, the image is loaded and displayed.

<Grid x:Name="LayoutRoot"
        Background="Black"
        AllowDrop="True"
        Drop="LayoutRoot_Drop">
       
    <Image Name="imgPresenter"
            Stretch="UniformToFill"
            IsHitTestVisible="False" />
       
    <TextBlock HorizontalAlignment="Center"
                VerticalAlignment="Center"
                IsHitTestVisible="False"
                Foreground="#FFCBC3C3"
                FontSize="32"
                Opacity="0.33"
                Text="drag photo here"/>       
       
</Grid>

 

Code behind:

private void LayoutRoot_Drop(object sender, DragEventArgs e)
{
    if (e.Data != null)
    {
        // Get a list of the file(s) that the user has dragged & dropped
        FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

        // If there is at least 1 file that has been dropped
        if (droppedFiles != null && droppedFiles.Length > 0)
        {
            LoadImage(droppedFiles.First());
        }               
    }
}



private void LoadImage(FileInfo imageFileInfo)
{
    if (imageFileInfo.Extension.ToUpper() != ".JPG")
    {
        MessageBox.Show("Only .jpg files are supported...");
    }
    else
    {
        // Load the image from disk
        BitmapImage source = new BitmapImage();
        source.SetSource(imageFileInfo.OpenRead());

        // Set the image being displayed to the new dropped one
        imgPresenter.Source = source;
    }
}

Copy and Paste in Silverlight 4

Silverlight 4 added the static Clipboard class with the clearly-named SetText, GetText and ContainsText methods.

If running in-browser or out-of-browser without elevated trust the Clipboard methods can only be called as a result of user actions (such as Click, KeyDown). The first time a method is called, a security prompt is presented to the user asking them to grant the app access to the clipboard.



If the user selects 'No' a SecurityException is thrown.

 

If the app is running out-of-browser with elevated trust, the above dialog is not shown and the Clipboard methods can be called even if not in response to user initiated events such as in your page constructor, in a DispatcherTimer.Tick event, etc.

Example Code

<Button x:Name="btnCopy" Click="btnCopy_Click">Copy</Button>
<Button x:Name="btnPaste" Click="btnPaste_Click">Paste</Button>
<TextBox x:Name="txtBox"></TextBox>

 

private void btnCopy_Click(object sender, RoutedEventArgs e)
{
    // Assumes we want to prevent the user from copy 'nothing' to the clipboard.
    // Without this check, whatever text is currently in the clipboard will be replaced
    // with nothing.
    if (!string.IsNullOrEmpty(txtBox.Text))
    {
        try
        {
            Clipboard.SetText(txtBox.Text);
        }
        catch (SecurityException ex)
        {
            // If the user does not grant access for the app to access the clipboard
            // a SecurityException is thrown
            MessageBox.Show("Clipboard access is required to use this feature.");
        }
    }
}


private void btnPaste_Click(object sender, RoutedEventArgs e)
{
    try
    {
        txtBox.Text = Clipboard.GetText();
    }
    catch (SecurityException ex)
    {
        // If the user does not grant access for the app to access the clipboard
        // a SecurityException is thrown
        MessageBox.Show("Clipboard access is required to use this feature.");
    }
}