In this post I will show how to create a new website dynamically in an already deployed web role on Azure. This is especially interesting for multi tenant scenario. One other way of doing this would be creating a new deploy package and upgrade the running role. But this would mean downtime for the existing sites and will take longer than dynamically creating the site.
I will start with some important things when creating websites dynamically from the web role and then I will show the code that does it.
The web role needs to have elevated privileges. This is done by adding the following element to the WebRole element in the ServiceDefinition.csdef file.
<Runtime executionContext="elevated" />
Only some ports are open in the firewall. When you normally creates new sites, you either run them on the same port as the deployed site does using host header (host name) or on a different port. On Azure using a different port is not an option. Only the ports that are specified for sites (or Remote Desktop Connection) when the package is deployed are open in the firewall. So the only option here is to use host header (host name) for new sites. You can see which ports that are open in the Window Azure Management Portal.
Microsoft.Web.Administration reference. You need to add the assembly Microsoft.Web.Administration to use the ServerManager class. The Microsoft.Web.Administration can be found in %WinDir%\System32\InetSrv directory. You also need to change the property Copy Local to true because it is not in the GAC on the Azure host.
The code! Now lets get to the fun part, the code! Below is the code needed to create a new site. This could be done in OnStart or where you see fit. Though it has to be in the web role to have the privileges to do it. Here is the code:
string newWebsitePath = "SOME PATH!";
using (ServerManager serverManager = new ServerManager())
/* Create the app pool */
ApplicationPool applicationPool =
applicationPool.AutoStart = true;
applicationPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
applicationPool.ManagedRuntimeVersion = "v4.0";
/* Create the web site */
Site site = serverManager.Sites.
Add("MyNewSite", "http", "*:80:www.mynewwebsite.com", newWebsitePath);
site.Applications.First().ApplicationPoolName = "MyApplicationPool";
site.ServerAutoStart = true;
Testing. A easy way to test this, is to edit your hosts file (C:\Windows\System32\drivers\etc\hosts). First you need to find the IP address of your web role. This can be done by either pinging it or by looking in the Window Azure Management Portal. So lets say the IP address is 111.222.333.444 and you have used www.mynewwebsite.com as host name. Then you need to add the following line to your hosts file:
When you have added this line and saved the file you can open www.mynewwebsite.com in your browser and the request will go to your web role.