tags:

views:

1570

answers:

2

My asp.net site allows users to pick the theme they want from a list generated from the app_themes folder. From time to time, themes are renamed or removed. Any user who has selected a deleted theme name (it is stored in a cookie) will get the exception:

Theme 'XXX' cannot be found in the application or global theme directories
Stack Trace: 
[HttpException (0x80004005): Theme 'test' cannot be found in the application or global theme directories.]
   System.Web.Compilation.ThemeDirectoryCompiler.GetThemeBuildResultType(String themeName) +920
   System.Web.Compilation.ThemeDirectoryCompiler.GetThemeBuildResultType(HttpContext context, String themeName) +73
   System.Web.UI.Page.InitializeThemes() +8699455
   System.Web.UI.Page.PerformPreInit() +38
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +282

Where is the best place to trap and handle this exception?

A: 

You have to make sure that you change users' theme preference if they use your theme to be renamed/deleted. If renamed, then rename accordingly, if deleted, change to default theme.As you store theme preference inside cookies you'll have to check them and make the change on user access.

Robert Koritnik
Are you saying its impossible to catch this exception?
simon831
no of course not. You could always handle it as late as in Application_OnError within Global.asax.
Robert Koritnik
+1  A: 

In the Page_PreInit method where you assign themes, there's a couple of ways to deal with it. What I do is check to make sure that the directory exists. If it does, then that's the theme I want. If it doesn't, then use a default theme where I know the directory exists.

void Page_PreInit(object sender, EventArgs e)
{
    if (ViewState["PageTheme"] == null)
    {
        if (!Directory.Exists("~/App_Themes/THEMENAME_TO_LOOK_FOR"))
        {
            Theme = "DEFAULT_THEME"
        } 
        else 
        {
            Theme = "THEMENAME_TO_LOOK_FOR";
        }
        ViewState["PageTheme"] = Theme;
    } 
    else 
    {
        Theme = ViewState["PageTheme"].ToString();
    }
}

I usually store in the viewstate so I don't have to recheck every time but if you're changing themes on-the-fly, then you'll probably need to not do that.

James Thomas
I can see that this would work but it seems quite an overhead for every page request. Presumably Directory.Exists takes a relatively long time.It should be very rare that this happens, and thats why I wanted to catch the Exception, I just wan't sure what the exception type was or where to put the try catch.
simon831
I agree - which was why I noted that we store the result in the viewstate, which modifies the function above.
James Thomas