Skip navigation

.browser Files in ASP.NET 2.0

Learn by Example: Create a Browser Profile for the Sony PlayStation Portable (PSP)

It seems that with every new iteration of Microsoft s .NET Framework we get tools that make development and deployment of applications even easier and more powerful. Of course, sometimes these technologies are there, but lightly documented. I found this true of the browser configuration files, hence the reason for this tutorial. For more on web application development with ASP.NET, see "HTML5 for the ASP.NET Developer " and " Create a Single-Page Application in ASP.NET MVC 4 ."

 

What Are Browser Configuration Files?

If you wanted to deploy your Web application to mobile devices in ASP.NET 1.x, you had to: a) try to figure out how the mobile toolkit really worked; b) possibly modify your machine.config and its associated xml (which wasn t well documented), and; c) cross your fingers and hope development doesn t go out of hand with the myriad custom controls you had for all the different devices to which you deploy.

Microsoft has greatly simplified this task with ASP.NET 2.0 with master pages and their associated Browser Definition files. ASP.NET 2.0 can properly render itself on around two-dozen browsers right out of the box. Each of these browsers definitions are defined in fairly straightforward XML files with a .browser file extension. By combining their definitions with master pages, you can tell your Web form to use a different master page based on which browser is being used.

Consider my page header example for a Sony PSP (see Figure 1). The PSP is far from a standard browser. It runs 474x280 pixels, can t load Java applets, and has marginal JavaScript support and limited text-entry capabilities. I need optimized layouts for such a device, with fewer links more readily laid out so visitors on PSPs can quickly find what they want using the navigation capabilities of their device. So I created one master page for full power browsers like Firefox and Internet Explorer, and another master page for PSPs. Because of ASP.NET 2.0 s master pages capability, it s very easy to tell my application which to use when it builds the page. Figure 1 shows the header I used on Home.aspx to define the master page to use for each browser type that requests the page.

<%@ Page Language="VB"

 MasterPageFile="~/HackingPSP_RegularBrowsers.master"

 SonyPSP:MasterPageFile="~/HackingPSP_PSPOptimized.master"

 AutoEventWireup="false" CodeFile="Home.aspx.vb"

 Inherits="Home"

 Title="Hacking the PSP by Auri Rahimzadeh - Home Page" %> 

Figure 1: The master page s header.

Note that I have a standard MasterPageFile for all browsers other than PSP (I really don t care if someone browses the site with a phone; that s not my audience and I won t spend time optimizing for them) and my specific SonyPSP:MasterPageFile designation for users who come to me with a Sony PSP. That s almost all there is to it to get ASP.NET 2.0 to show your device-optimized content (in this case, PSP-optimized) once you re done with this tutorial, of course.

Browser designations aren t limited to selecting master pages. Individual controls in ASP.NET are browser-aware, as well. Consider this Label control:

 

As you can see, you can define control values for specific browsers. Check Microsoft s Web site for more details on which controls are browser-aware. (WARNING: Do not develop this on a production server until you re sure it works! Constantly recompiling the browser cache file may cause IIS to recycle or restart, which is a bad thing in production!)

 

Step 1: Build Your Optimized Master Pages

Obviously you want content to test. In my case, it was my entire Hacking the PSP Web site, which is for my book, Hacking the PSP (go figure). In Figure 2 you can see where I ve built a master page for regular browsers and a master page for PSPs.


Figure 2: A master page for regular browsers and a master page for PSPs (circled in red).

Recall that master pages are meant to separate content from page templates, so you can re-use your content by plugging it into content placeholders in master pages, which are basically template files. This way, you can use that same content on regular browsers and the PSP by keeping the same placeholder names in your content files, and they ll automatically populate in the appropriate places in the templates. There are some great books from Wrox, O Reilly, and others on how all this works, plus tons of online help from Microsoft and third-parties. If you haven t tried ASP.NET 2.0 s master pages capability yet, try it now you ll love it!

NOTE: When you build master page files, make sure the Content Placeholder controls have matching names across master pages that will be used to service different browsers. The mapping of which content goes where is contingent upon knowing where placeholders are; if a placeholder can t be found, an error may be thrown.

Figure 3 shows the master page for regular browsers; Figure 4 shows the PSP version. Because the PSP has limited screen real estate, I needed to limit the navigation to only include items that would be of interest to PSP Web surfers (and not require a lot of scrolling). This meant eliminating my AdRotator control, Google AdSense ads, the Buy the Book link, and other items. I also had to use a slightly different version of my CSS file to accommodate the PSP s unique characteristics. Note that on the PSP master page I call out the fact that it is PSP-optimized, both to inform the reader there is a full version of the site available and to show off a little bit.

<%@ Master Language="VB"

CodeFile="HackingPSP_RegularBrowsers.master.vb"

Inherits="HackingPSP_RegularBrowsers" %>

...removed for brevity...



   

...removed for brevity...


Copyright (c) 2005-2006 Auri Rahimzadeh.



...removed for brevity...

Figure 3: The regular browser master page file.

<%@ Master Language="VB"

CodeFile="HackingPSP_PSPOptimized.master.vb"

Inherits="HackingPSP_PSPOptimized" %>

... removed for brevity ...



 

 Hacking the PSP by Auri Rahimzadeh-PSP Optimized Web Site









...removed for brevity... HACKING THE PSP - OFFICIAL WEB SITE
blog forums psp links homebrew central the book contact
...removed for brevity... ...removed for brevity...

Figure 4: The PSP-optimized master page file.

Figure 5 shows the Web form for my home page, which has the content for use on both the regular browser s master page and the PSP master page (separated by panels). The PSP version of my home page s content doesn t need to include the Flash component, and I may want separate content for PSP users, hence the two panels.

<%@ Page Language="VB"

MasterPageFile="~/HackingPSP_RegularBrowsers.master"

SonyPSP:MasterPageFile="~/HackingPSP_PSPOptimized.master"

AutoEventWireup="false" CodeFile="Home.aspx.vb"

Inherits="Home"

Title="Hacking the PSP by Auri Rahimzadeh - Home Page" %>





...removed for brevity...









...rest of regular browser text removed for brevity...



 



Figure 5: HackingPSP.com s home page Web form.

Figure 6 shows the code used to determine which panel to display. I used the Request.Browser.Browser property to determine the browser type. The Browser property is defined within the .browser file you will be building in this article. You can see the result of the two master pages being applied in Figures 7 and 8.

VB

Protected Sub Page_Load(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Me.Load

      

 ' Local vars.

 Dim dts As New System.Data.DataSet()

 ' Check to see if the RSS feed is in cache.

 If Not (Cache.Item("PSPNews") Is Nothing) Then

   ' If the item is in cache, then use it.

   dts = Cache.Item("PSPNews")

 Else

   ' If it's not in cache, then put it there.

   ' Load the PSP news RSS feed from the Hacking the

   ' PSP Community site.

   dts.ReadXml(AppSettings("BlogRSSURL"))

   ' Put the item in cache for 20 minutes.

   Cache.Insert("PSPNews", dts, Nothing, _

     Now.AddMinutes(20), _

     System.Web.Caching.Cache.NoSlidingExpiration)

 End If

 ' Show the right content based on the browser type.

 If Request.Browser.Browser <> "SonyPSP" Then

   ' Show the panel optimized for non-PSP browsers.

   panNonPSPContent.Visible = True

   ' Populate the news datagrid.

   dgdPSPNews_NonPSPBrowsers.DataSource = dts.Tables("Item")

   dgdPSPNews_NonPSPBrowsers.DataBind()

 Else

   ' Show the panel with PSP browser optimized content.

   panPSPContent.Visible = True

   ' Populate the news datagrid.

   dgdPSPNews_PSPOptimized.DataSource = dts.Tables("Item")

   dgdPSPNews_PSPOptimized.DataBind()

 End If

 ' Clean up.

 dts.Dispose()

End Sub

 

C#

protected void Page_Load(object sender, EventArgs e)

{

 // Local vars.

 System.Data.DataSet dts;

 // Check to see if the RSS feed is in cache.

 if (!(Cache["PSPNews"] == null)) {

   // If the item is in cache, then use it.

   dts = (DataSet)Cache["PSPNews"];

 } else {

   // If it's not in cache, then put it there.

   // Load the PSP news RSS feed from the Hacking the

   // PSP Community site.

   dts.ReadXml(AppSettings["BlogRSSURL"]);

          

   // Put the item in cache for 20 minutes.

   Cache.Insert("PSPNews", dts, null,

   DateTime.Now.AddMinutes(20),

   System.Web.Caching.Cache.NoSlidingExpiration);

 }

 // Show the right content based on the browser type.

 if (Request.Browser.Browser != "SonyPSP") {

   // Show the panel optimized for non-PSP browsers.

   panNonPSPContent.Visible = true;

   // Populate the news datagrid.

   dgdPSPNews_NonPSPBrowsers.DataSource = dts.Tables["Item"];

   dgdPSPNews_NonPSPBrowsers.DataBind();

 } else {

   // Show the panel with PSP browser optimized content.

   panPSPContent.Visible = true;

   // Populate the news datagrid.

   dgdPSPNews_PSPOptimized.DataSource = dts.Tables["Item"];

   dgdPSPNews_PSPOptimized.DataBind();

 }

 // Clean up.

 dts.Dispose();

}

Figure 6: The Page_Load event on the Web form determines which content panel to load.


Figure 7: HackingPSP.com viewed in Firefox.


Figure 8: HackingPSP.com viewed on the PSP.

 

Step 2: Find Your Browser Client Identification String

Finding your browser client string is very easy. If you don t already know what it is, build a test page with a label and populate that label s Text property with the contents of Request.Headers( User-Agent ). You can also look in your IIS log files after hitting the page with your device, but that s really awkward. If you want to go the awkward route, though, for a learning experience, see Figure 9, which shows an IIS log file loaded into Notepad (the browser string is circled in red). The PSP s Web browser string is:

Mozilla/4.0 (PSP (PlayStation Portable); 2.00) 

You are likely not going to need your whole browser string. In my case I simply used PSP because browser configuration files use regular expressions to match the browser type. Because scanning for PSP saves me from writing regular expressions, and it covers every version of PSP browser (as they ll all have PSP regardless of the version), I m happy and content. Your approach may vary depending on the device you use.


Figure 9: An IIS log file loaded into Notepad.

 

Step 3: Build Your Configuration File in VS.NET 2005

OK, now here s the fun part: building the .browser file that tells ASP.NET how to identify your browser. We ll also define the capabilities of the PSP, so your application can test for those capabilities. As I said before, if you re not using a PSP, make sure you write the configuration file for your particular device s specifications. I ll write out the whole file and then go through it, section by section. Microsoft also has a helpful article on the XML schema for browser config files at http://msdn2.microsoft.com/en-us/library/ms228122.aspx.

To create a new browser file for use by your application, right-click your root node in your project listing (where it says C:\...\HackingPSP, as shown in Figure 2) and select Add ASP.NET Folder | App_Browsers. After a few moments a grey folder with that name will appear. Right-click that folder and select Add New Item. When the dialog box comes up, select Browser File and give it a name of sonypsp.browser.

Double-click the file you just created and replace its contents with the XML shown in Figure 10. This is my resulting configuration file for the PSP, sonypsp.browser, in it s entirety (note that the name doesn t seem to matter, but it s important to name your files using human-readable names). Remember the XML file contents are case sensitive!





 

 

 

 

 

 

 

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

   

 

 

 

Figure 10: The contents of the .browser file.

Let s break down what s happening here:

 

This is simply a comments section for fame and glory. Comments begin with . You should put any important details about your file here so you know what you were doing when you get back. In this case I haven t done that, but you should include version information, etc.

Every config file will have a starting and ending tag. You can have both browsers and gateways in your .browser file. The link to Microsoft s schema definition above will explain that. I encourage you to look through the various .browser files Microsoft ships with their framework to get a feel for the layout, as it seems to be almost entirely undocumented outside of Microsoft.

The element is what s used to define the name of your extension to ASP.NET. This is not the browser string that will be returned by getting the value of Request.Browser.Browser we ll get to that in a moment. Looking through other profiles you ll see items like Mozilla , Netscape3 , and Netscape4 . The value of id must be unique, otherwise it won t compile and you ll get an error. In this case, I named it SonyPSP :

 

As future PSP Browser versions come out, I may have to rename it SonyPSPv3 , and so forth (since this runs on the browser that shipped with PSP Firmware 2. xx). The parentID is to which browser class this belongs, such as Mozilla, Netscape, etc. You can use Default to derive from the generic browser class. I used Default because I wasn t sure I wanted to classify this under Mozilla, but feel free to experiment:



    

 

The element is important it defines how ASP.NET will identify your browser. Using the element you can tell it to match a string using regular expressions. You can also tell it not to use this profile for certain browsers, using the nonMatch attribute to match other values not to process for, the opposite of the match attribute. Another option is to use the Header element, which enables you to match a particular header, such as name= User-Agent value= Mozilla/4.0 (PSP (PlayStation Portable); 2.00) . Microsoft s schema definition explains this in further detail.

The section enables you to capture data from the matching strings into variables you can use in your section (see Figure 11):



 

Hence, you can dynamically populate items such as screen height and width and make them available to your application. Because you have no choice when it comes to window sizes on the PSP, I removed that capability from my browser file. Review other profiles to see how they accomplished this. It tends to require some knowledge of regular expressions.



 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 11: Capture data from the matching strings into variables you can use in your section.

The section defines the capabilities of your client s browser. These capabilities are made available via the Request.Browser collection and also help ASP.NET determine how to render pages to the client you re defining. Search through the other profiles to get a sampling of which attributes are available (you can even create your own).

Note that I set the browser attribute SonyPSP . This defines the string that is returned when you retrieve the value of Request.Browser.Browser in your code.

I haven t covered the mobile control redirect capabilities of browser definition files in this tutorial. Reviewing Microsoft s schema definition cited earlier will help you, as will the other profiles in the browsers directory you opened earlier.

 

Step 5: Attempt to Test

Launch the Web browser on your device and see if it works. If it works, great! You re done! Unfortunately, it probably won t work as most browsers are Netscape/Mozilla-based and Microsoft s built-in browser profiles override whatever you ve done so you ll have to work around that ...

I ve not found any documented way to override Microsoft s browser configuration files without modifying them to specifically exclude your browser type (more on this in a moment). Of course, Microsoft may ship framework updates with new browser definition files, or the capability to override their definition files with your own. It would also be helpful if Microsoft published the order in which definition files are processed, such as application browser definition files first, then your own, or vice versa.

 

Step 6: Exclude Your Configuration from Microsoft s Parent Browser Configuration Files

I know Microsoft says to not do this, but until they offer a method of forcing your profile to override their own I see no other way around this. Please Microsoft, document this great capability.

Open %windir%\microsoft.net\framework\v2.x\config\browsers and you ll see a lot of .browser files (see Figure 12).

 


Figure 12: The browsers directory.

 

Now we need to find out which browser configuration file is the culprit that s overriding everything you re doing. This is easy in code, so build a test page in ASP.NET with a label named lblBrowser and add this code to the Page_Load event of that page (remember, put this code in the Web form, not the master page, if you re using master pages with your test page):

VB.NET

lblBrowser.Text = "Browser type: " & Request.Browser.Browser

 

C#

lblBrowser.Text = "Browser type: " + Request.Browser.Browser;

When you load your page, you ll see what type of browser ASP.NET thinks you re using. It will likely be Netscape or Mozilla . It may be something else, of course. But the point here is you now know which .browser file you need to work with (for now). Depending on your device, you may have to come back to this step a few times if you find you need to exclude yourself from more files (more on that next).

In my case, I had to modify two files: Mozilla.browser and Netscape.browser. Because they both handle Mozilla requests, I needed to make sure any requests for Mozilla 4.0 excluded any clients with PSP in their name. This is done using the nonMatch attribute in the section of the XML file. The modifications I made are shown in the snippets in Figure 13 (I edited each file in Notepad, but you can use any text editor, including Visual Studio 2005).

mozilla.browser:



   

       

           

           

      

       

netscape.browser:

   

       

           

           

           

      

        

Figure 13: Exclude any clients with PSP in their name.

 

Step 7: Register the Modified Browser Configuration Files with the ASPNET_REGBROWSERS Tool

Now that you ve modified Microsoft s files, you ll need to manually rebuild the browser configuration cache so ASP.NET knows to use it. Unlike web.config files, the cache is not automatically rebuilt every time you edit browser files.

Launch the Visual Studio 2005 Command Prompt or open a command window and navigate to %windir%\microsoft.net\framework\v2.x\ and run the following command:

aspnet_regbrowsers /i

If you receive an error, you ve made a mistake in your browser files. Go fix it. Remember case sensitivity, and check for malformed tags and missing elements in the XML.

You can copy your SonyPSP.browser file into the browsers directory on a machine and it will apply for all applications using ASP.NET that want to use it. Simply copy it into that directory and run aspnet_regbrowsers /i again. However, for testing purposes I recommend against this it s too much work to keep recompiling after every change. You ll have to run this tool for every version of the .NET Framework 2.x (and possibly higher) that is installed.

 

Step 8: Publish Your Application

Alright, now that everything s registered, publish your application in Visual Studio and load it with your mobile device s Web browser (in this case, PSP s browser). Make sure you test with normal browsers, as well, to ensure everything still works properly for them, too.

The source code accompanying this article is available for download.

 

Auri Rahimzadeh is president of The Auri Group, LLC, an Indiana software development firm. Auri is also author of Hacking the PSP and Geek My Ride, co-author of Hacking Digital Cameras from Wiley s ExtremeTech series, and technical editor of Beginning Access 2007 VBA from Wrox. Contact him at http://www.hackingpsp.com or mailto:[email protected].

 

Requirements

  • Visual Studio 2005, any edition (you can also use the free Express editions, like Visual Basic 2005 Express, C# 2005 Express, and so forth)
  • Web Server (built into 2005)
  • .NET Framework 2.0 (should also be installed if you have the two above)
  • Patience

Additional Resources

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish