OdeToCode IC Logo

Strong Typing and Nested Master Pages

Friday, November 11, 2005 by scott

Here is a little tip for getting a strongly typed Master property when using nested master pages in ASP.NET 2.0.

Let’s say you start with the following, top level master page:

<%@ Master Language="C#" %>

 

<script runat="server">

 

    public string BigFooterText

    {

        get { return BigFooter.Text; }

        set { BigFooter.Text = value; }

    }

 

</script>

 

<html>

<head runat="server"/>

 

<body>

    <form id="form1" runat="server">

    <div>

        <asp:contentplaceholder id="BigContent" runat="server"/>

        <asp:Label ID="BigFooter" runat="server"/>

    </div>

    </form>

</body>

</html>

A second, nested master page provides the content for the top level master.

<%@ Master Language="C#" MasterPageFile="~/BigMaster.master"  %>

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

 

<script runat="server">

 

    public string LittleFooterText

    {

        get { return LittleFooter.Text; }

        set { LittleFooter.Text = value; }

    }

 

</script>

 

<asp:Content ContentPlaceHolderID="BigContent" runat="server">

 

  <asp:ContentPlaceHolder ID="LittleContent" runat="server"/>

  <asp:Label ID="LittleFooter" runat="server"/>

 

</asp:Content>

Now finally, an ASPX content page using the nested master as it’s master page. Notice the web form can reach the BigFooterText property of the top level master page without casting.

<%@ Page Language="C#" MasterPageFile="~/LittleMaster.master" Title="Untitled Page" %>

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

<%@ Reference VirtualPath="~/BigMaster.master" %>

 

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)

    {

        Master.LittleFooterText = "hello";

        Master.Master.BigFooterText = "world";

    }

</script>

 

<asp:Content ID="Content1" ContentPlaceHolderID="LittleContent" Runat="Server">

This is some content

</asp:Content>

Comments:

Typically, the Master property of a form is of type MasterPage. The @ MasterType directive instructs ASP.NET to generate the code for a strongly typed MasterPage property, and to ensure the assembly is properly referenced in scenarios where the master page and the content page end up in different assemblies. The web form needs both an @ MasterType directive (for the nested master) and an @ Reference directive (to the top level master page) for the compiler to see both types.

This setup feels fragile to me. I think a better approach would be to remove the @Reference directive from the aspx file, and add a public member to the nested master page that can forward data to the top level master. This approach reduces coupling and results in less breakage when the inevitable round of changes come to the top level master.

A Look At The Stars

Thursday, November 3, 2005 by scott

The news in science this week is that NASA researchers think they are looking at infrared glows from the first stars of the universe.

I wonder … just how far back we will be able to go?



Dr. Mandleblot sat in front of the hooded display as a cat owner sits in front of his cat. He watched the device intently, while the device summarily ignored him.

“Only 10 more seconds, Scott, and I will be looking at the very beginning of the universe”, the doctor said, unassumingly.

My pulse spiked at the thought. I couldn’t believe how calm Dr. Mandleblot seemed to be. The good doctor would the first human to see the beginning of time itself. I glanced at the hooded display, and the small black curtain that surrounded it. The curtain allowed a viewer to block out all light, and concentrate solely on the incoming video. I imagined myself inside the curtain, and wondered just what I’d see.

A green light flashed. The satellite signal arrived at last.

“It’s time!”, Dr. Mandleblot said with a smile. He reverently lifted the curtain and leaned into the display.

I watched Dr. Mandleblot’s lower body for a long time. I wanted to ask him what he could see, but I knew if I was inside the curtain - I wouldn’t want to be disturbed. Suddenly, I could see the doctor’s legs twitch. Beneath the black cloth that draped his shoulders, I could see his muscles tighten. An alarm went off in my head. From my years of training as a secret service agent, I could see the tell tale signs of a person in danger.

“Doctor?”, I whispered, filled with fright. What could he see? What could be wrong? I began to worry about the doctor’s heart. I shifted into a position behind him, when suddenly…

“Good heavens!”, the doctor ejaculated.

“What is it?”, I shouted. “What do you see?”.

Dr. Mandleblot’s head flew out of the curtain. His eyes were squinting at the sudden change in the light level, but his mouth was wide open. “We’ve gone too far!”, he cried, and jumped to his feet.

“What?”, I shouted.

The doctor began to make his way across the room, clutching at chairs on the way to the door. He turned and looked at me again – a melancholy stare in his eyes. “We’ve gone too far”, he whispered, and shook his head.

“Doctor”, I said firmly. “What … did … you …. see?”.

“Read the fine print”, he said, and walked out the door. I turned back to face the device, looking around the curtain. I was looking for a sign - some writing. Fine print? What was the doctor trying to say? Finally, I gathered my strength, and put my head under the cloth.

My eyes adjusted to the darkness, and I could see the stars. At least I thought they were stars - but they started to move  rapidly, and then suddenly froze. The spots of light seemed to form symmetric blocks. Before I could begin to analyze the patterns, the lights started to swirl again .... then froze.

I gasped.

The lights looked like Chinese logographic writing. Unfortunately, I skipped Chinese studies during my secret service training. Then the lights were swirling again … and they stopped one more time.

My jaw dropped.

I could see letters of the English alphabet. My mind was so stunned by the appearance of these letters, I almost didn’t see the message.

Yes. A message.

There is a message at the beginning of the universe.

The message reads like this:

“The unauthorized reproduction or distribution of this copyrighted universe is illegal. Reverse engineering of this universe without the express consent of the copyright holder is also illegal. Development of a new universe built upon this universe (a derivative universe) is expressly prohibited. Violators will not only be prosecuted – they will be atomized”.

Health Monitoring in ASP.NET 2.0

Wednesday, November 2, 2005 by scott

ASP.NET 2.0 includes a nifty new feature known as Health Monitoring. The name might be a bit misleading, as the feature is really an extensible and general-purpose framework for producing and capturing events during the life of an ASP.NET application. Health monitoring can be useful in a number of scenarios, for instance, health monitoring is useful to administrators who need to monitor an application and be notified when a critical error occurs, or to developers who need to add instrumentation to a mis-behaving application.

The runtime includes a number of classes to represent events. There is a class to represent authentication failures, a class to represent request errors, and more. You can find out the reason for an application restart, and find out when a compilation occurs. You can even derive a class from System.Web.Management.WebBaseEvent to encapsulate your own custom events. If you just want to raise a simple event, instantiate an existing event class and invoke the Raise method.

You capture events using one of the built in event providers. There is a provider to capture events and send email notifications, a provider to log events to SQL Server, a provider to expose events via WMI, and a provider to drop events into an event log. As the name implies, Microsoft built event providers using the pervasive provider model. You can also build a custom event provider and plug into the health monitoring system.

Three providers come pre-configured: the event log provider, the WMI provider, and the SQL Server provider. The default SQL Server provider will log events into a SQL Express aspnetdb database in the special App_Data folder. To log events to a different instance of SQL Server, even a remote instance, you simply need to provide a bit o’ configuration love in web.config:

 

 

 

   

     

       

            connectionStringName="RemoteServerCS"

            maxEventDetailsLength="1073741823"

            buffer="false"

            bufferMode="Notification"

            name="MySqlWebEventProvider"

            type="[SqlWebEventProvider strong name]" />                               

     

     

       

            eventName="All Events"

            provider="MySqlWebEventProvider"/>           

                 

   

 

    ...

 

ScottGu has all the details on switching the default database configuration in his post: “Configuring ASP.NET 2.0 Application Services to use SQL Server 2000 or SQL Server 2005”.

In the above web.config is the rules section. The rules section controls which events the ASP.NET runtime will deliver to a provider. In the config snippet above, we are asking for “All Events” to come to our database via the MySqlWebEventProvider. ASP.NET 2.0 groups events into categories such as “All Events”, “Heartbeats”, “All Audits”, “Failure Audits”, “All Errors” and more using an eventMapping section in the machine’s web.config file (in the CONFIG directory of the .NET framework installation, typically \Windows\Microsoft.Net\Framework\v2.x\Config). Take a look at the file to see the default categories. You can also define your own event categories using an eventMapping section in your application’s web.config file.

One question that comes up with health monitoring is when to use health monitoring and when to use a tool like the Logging and Instrumentation block in Enterprise Library. If you have to provide logging and instrumentation outside of an ASP.NET web application or web service, obviously the block is the solution. Inside of ASP.NET, health monitoring is certainly easy to use and extend, so I wouldn’t see a need to pull in enterprise library for the sole purpose of adding logging functionality.

Scary Software

Tuesday, November 1, 2005 by scott

In honor of Halloween, I was trying to think of the scariest software I’ve ever met.

A long time ago, I worked on an embedded project building one of those blood pressure kiosks like you'll find in a drugstore. The brain of the machine was a little 8 bit CPU. Every so often, I’d volunteer my own arm in the machine and measure my blood pressure as a test.

You know when you are getting your blood pressure measured in the doctor’s office …
… and the rubber bladder is starting to feel extra snug around your arm ...
… and you are wondering if the person who is pumping air into the bladder will stop soon?

Now imagine – instead of a person pumping air, there is a machine filling the bladder …
… using software written in C …
… where it only takes one NULL pointer to really make for a spectacular crash.

Scary thoughts were often in my head when my arm was in the machine. I hated it, although nothing bad ever happened.

Eventually, the FBI came, and I retired from embedded work.

Medium Trust ASP.NET Applications

Saturday, October 29, 2005 by scott

If you are an ISP offering shared hosting, or you are a developer deploying your app in a shared hosting environment, then there is no doubt you want to avoid running ASP.NET applications with full trust. Full trust is the default trust level for ASP.NET.

What is full trust? The runtime defines several trust levels we can use to constrain what an application can do. These trust level range from minimal trust, which is a highly restrictive level, to full trust, which has no restrictions at all. The recommended trust level for an ASP.NET application is right in the middle: medium trust (see the ASP.NET 2.0 Hosting Deployment Guide).

What is wrong with full trust? For starters, the AppDomain hosting the application is no longer a security boundary. Full trust allows native code to execute, and native code can poke around a process that is hosting multiple AppDomains to find or corrupt data from other applications. Full trust also leaves resource protection up to the operating system, which is a bad idea when all the applications are running with the same identity, and thus have equal access to files and registry keys.

For instance…

    1 string parentPath = Server.MapPath("~") + @"\..\";

    2 

    3 string[] webDirectories;

    4 webDirectories = Directory.GetDirectories(parentPath);

    5 

    6 foreach (string directory in webDirectories)

    7 {           

    8     string appDataPath = directory + @"\App_Data\";

    9 

   10     string[] appDataFiles;

   11     appDataFiles = Directory.GetFiles(appDataPath);

   12 

   13     foreach (string file in appDataFiles)

   14     {

   15         try

   16         {

   17             // goodbye, data

   18             File.Delete(file);

   19         }

   20         catch(Exception)

   21         {

   22             // eat it and go on

   23         }

   24     }           

   25 }

The above code tries to walk through the web sites on a server and destroy any files in the well known App_Data directories. Perhaps a database file will be in use and the runtime will throw an exception – that’s ok, we can try again later. The real problem here is that the code can even successfully retrieve a listing of files and directories outside of the root where the code executes.

Medium trust will place a number of restrictions on an application, including limiting an application’s file access to within the virtual directory where the application lives. If we run the above code under medium trust (see How To: Use Medium Trust in ASP.NET 2.0), the runtime will throw a System.Security.SecurityException exception on line 4. Line 4 is the where the code tries to get a list of directories one level above the application’s home directory.

In ASP.NET 2.0, Microsoft has made changes to make life easier for ISPs and developers who want to run code with the medium trust level. You can read more in the PAG document: Security Guidelines for ASP.NET 2.0.

New Microsoft Certifications

Wednesday, October 26, 2005 by scott

The curtain is rising on a new set of Microsoft certifications. I’m particularly interested to see how the new exams fare, as I’ve contributed some blood, some sweat, and quite a few tears in contributing content to these exams, as have many others.

The value of a certification is a hotly debated topic. I think you have to examine the subject from two perspectives.

From a personal perspective, I believe the value of a certification is what you make of it. When I studied for my MCSD years ago, I spent time looking at the objectives, then reading books, looking at examples, and most importantly: writing code. When my certificate arrived, I felt I had truly earned something of significance.

Contrast this experience with people I know who work for large consulting firms. Big consulting firms like developers with certifications because they can bill the dev out at a higher hourly rate. The firms will happily send a dev to a one week crash course with a Friday afternoon exam. If the dev already has the skills, you could say this might not be a bad idea, but I’m sure for many people in that scenario, all they earn are pieces of paper with colored ink.

Then there is the other side of the coin. What value do you apply to a certification when you are looking at job candidates? I’d never hire a person just because they have a cert, and I’d never give a thumbs down to someone because they didn’t have a cert. The trick in small companies is to hire people who are passionate about their chosen profession, certification or not.

In any case, software certifications need to continually evolve, improve, and refine themselves, just as software development does. I hope the industry perceives this set of exams as raising the bar – I’ll feel proud.

Debugging With Visual Studio

Sunday, October 16, 2005 by scott

A basic introduction of the debugger features for those new to the F5 key.

The debugger in Visual Studio 2005 is an amazing piece of software. You can debug C# and C++, Visual Basic and VBScript. Step over managed code, native code, mobile code, and T-SQL code. You can debug locally, or you can debug remotely. You can debug assemblies hosted by SQL Server, and JavaScript hosted by Internet Explorer. There is just-in-time debugging and Just My Code debugging. You can step into XML web services and into XSL transformations. The debugger has data tips, and data visualizers, breakpoints and tracepoints. You can inspect threads, modules, memory, and call stacks; you can view both local and global variables.

If you have a bug you can’t track down with Visual Studio, you’ve got yourself a real sticky problem.

Read more...