Expect the unexpected to happen while using SPSecurity.RunWithElevatedPrivileges method

While building small feature that takes advantage of new accelerator feature in Internet Explorer 8, I've encountered a weird side effect of using SPSecurity.RunWithElevatedPrivileges method.

I used this method to be able to write IE8 OpenService Accelerator XML file inside LAYOUTS/Feature_Name folder. The code was using user's current context to determine the Url of SPWeb object for which to create the XML file.

In my code I misplaced the scope at which I obtained the web's Url and got unexpected results on the production server. Below is the snippet from my actual code:

//here is where I moved offending url variable initialization
string webPreviewUrl = w.Url;  
Guid siteId = w.Site.ID;  
Guid webId = w.ID;  
SPSecurity.RunWithElevatedPrivileges(delegate  
{
    using (SPSite site = new SPSite(siteId))
    {
        using (SPWeb web = site.OpenWeb(webId))
        {
            //this is where I had my webUrl initialy
            //string webPreviewUrl = web.Url;
            ...
        }
    }
    ...
});

When the buggy version of code was generating the XML file webPreviewUrl contained not the public address, but internal address of the web front-end. This is because the instance of SPWeb object is not equivalent and its properties differ for different users. When we obtain instance of SPWeb for account with Full Access rights, the instance is being set up like we are sitting in the server room and using the console to access the web server, hence the SPWeb.Url property contains local URL address in it.

PS: Please note the Guids outside the using statements. These Guids are there not by an accident! :)