Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically setting themes in ASP.NET

Tags:

asp.net

themes

Ive got an application that different domains are connected to, instead of copying and modifying each application i use same physical location on hard drive but separate application pools and websites on IIS.

Basically i want to change a theme based on hostname. ie. user comes to "websome.com" gets "websome" theme and user comes to "jamessome.com" gets "jamessome" theme.

I set the theme in web.config "pages" attribute which applies the theme globally to whole website. Is there any way i can modify that setting on fly based on domain use entered from? It is probably possible but what are downsizes and what do you suggest to do with little code in order to simplify solution. As i understand if i edit web.config each time user comes in it will take lots of time which is not that elegant... So any ASP.NET gurus out there can write two lines of code so magic will happen ?

There are few solutions for these problem on the website but this will require me to add code to Page_Init event of every page on the site which is unrealistic.

like image 496
eugeneK Avatar asked Feb 28 '23 04:02

eugeneK


1 Answers

Actually, it must be set in Page_PreInit, it won't work if you try to change the theme in Page_Init.

The most common solution is to use a parent class for all your pages. This is a one-time only change and places the logic in the parent class. Instead of inheriting from Page you then inherit from, say, ThemedPage. Inside the class ThemedPage, which inherits from Page itself of course, you can override the Page.OnPreInit method.

You asked for "two lines", it's actually one if you remove the clutter. This is VB:

Public Class ThemedPage
    Inherits Page

    Protected Overrides Sub OnPreInit(ByVal e As System.EventArgs)
        Me.Theme = HttpContext.Current.Request.Url.Host.Replace(".com", "")
        MyBase.OnPreInit(e)
    End Sub
End Class

And instead of this:

Partial Class _Default
    Inherits System.Web.UI.Page

you now write this:

Partial Class _Default
    Inherits ThemedPage

That's all! A one-time search/replace and you're done. For completeness sake, here's the same (only the class) for C#:

// C# version
using System.Web;
using System.Web.UI;

public class ThemedPage : Page
{

    protected override void OnPreInit(System.EventArgs e)
    {
        this.Theme = HttpContext.Current.Request.Url.Host.Replace(".com", "");
        base.OnPreInit(e);
    }
}

Update: added VB code sample
Update: added C# code sample

Note: the theme must exist, otherwise you get an exception: Theme 'ThemeName' cannot be found in the application or global theme directories.. If you want a default theme or no theme if the theme isn't there, wrap it around a try/catch block and use the catch block for setting the default theme.

like image 135
Abel Avatar answered Mar 06 '23 20:03

Abel