Sunday, September 29, 2013

Load ASP.NET page routes from XML file using C#

Want to load your ASP.NET page routes from an XML file? Here is a sample file and a short snippet of code to load them. This supports not only basic page routes, but default items and route constraints.

Have fun!
<?xml version="1.0" encoding="utf-8" ?>
<pageRoute routeExisting="true">
   <routes>
      <!-- route with no defaults or constraints -->
      <route name="HomePage">
         <url>home</url>
         <file>~/default.aspx</file>
      </route>
      <!-- route with defaults -->
      <route name="FAQView">
         <url>faqs/{id}</url>
         <file>~/faqs/ViewFAQ.aspx</file>
         <defaults>
            <default key="id" value="1000" />
         </defaults>
      </route>
      <!-- route with constraints -->
      <route name="ProductView">
         <url>products/view/{id}</url>
         <file>~/products/ViewProduct.aspx</file>
         <constraints>
            <constraint key="id" value="\d+" />
         </constraints>
      </route>
   </routes>
</pageRoute>
Code:
private void RegisterRoutes(RouteCollection routes)
{
   routes.Ignore("{resource}.axd/{*pathInfo}"); 

   string path = Path.Combine(
      Server.MapPath("~/App_Data"),
      "PageRoute.xml");
   if (File.Exists(path))
   {
      // load file with all page routes
      XElement xmlPageRoutes = XElement.Load(path);

      // set some defaults
      routes.RouteExistingFiles = (bool)xmlPageRoutes.Attribute("routeExisting");

      // map each individual route
      foreach (XElement xmlRoute in xmlPageRoutes.XPathSelectElements("routes/route"))
      {
         // defaults
         RouteValueDictionary defaults = new RouteValueDictionary();
         foreach (XElement def in xmlRoute.XPathSelectElements("defaults/default"))
         {
            defaults.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
         }

         //constraints
         RouteValueDictionary constraints = new RouteValueDictionary();
         foreach (XElement def in xmlRoute.XPathSelectElements("constraints/constraint"))
         {
            constraints.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
         }

         routes.MapPageRoute(
            (string)xmlRoute.Attribute("name"),
            (string)xmlRoute.Element("url"),
            (string)xmlRoute.Element("file"),
            true,
            defaults,
            constraints);
      }
   }
}

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...