Azure and creating website dynamically

by ingvar 28. april 2011 21:21

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 =
           serverManager.ApplicationPools.Add("MyApplicationPool");
    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;
    serverManager.CommitChanges();
}

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:

111.222.333.444    www.mynewwebsite.com

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.

Tags:

.NET | Azure | C#

Azure Shared Access Signature and pitfalls

by ingvar 26. april 2011 21:03

To start with, I did not think I would write a blog post about Azure Shared Access Signatures (SAS). But after having worked with them for some time I had stumbled into some things I think is worth sharing. The things I found is shown bellow the code. Thanks to @Danielovich for pointing me in the right direction.

I'll start by showing how to create a SAS. You need to have access to the Primary Access Key (or the Secondary Access Key) for the blob storage that you wish to use. These keys can be obtained through the Windows Azure Platform Portal. The code below shows how to create a SAS, use it and what you can/can not do with it. 

/* Here is how to create the SAS */
StorageCredentialsAccountAndKey masterCredentials = 
     new StorageCredentialsAccountAndKey("[Name]", "[AccessKey]");
CloudStorageAccount account = new CloudStorageAccount(masterCredentials, false);
CloudBlobClient client = account.CreateCloudBlobClient();
CloudBlobContainer container = client.GetContainerReference("mytestcontainer");
container.CreateIfNotExist();

SharedAccessPolicy sharedAccessPolicy = new SharedAccessPolicy();
sharedAccessPolicy.Permissions = 
     SharedAccessPermissions.Delete |
     SharedAccessPermissions.List |
     SharedAccessPermissions.Read |
     haredAccessPermissions.Write;
sharedAccessPolicy.SharedAccessStartTime = DateTime.UtcNow;
sharedAccessPolicy.SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1);

string sharedAccessSignature = container.GetSharedAccessSignature(sharedAccessPolicy);

/* Here is how to use the sharedAccessSignature */
StorageCredentialsSharedAccessSignature sasCredentials = 
    new StorageCredentialsSharedAccessSignature(sharedAccessSignature);
CloudBlobClient sasClient = new CloudBlobClient(account.BlobEndpoint, sasCredentials);

CloudBlobContainer sasContainer = sasClient.GetContainerReference("mytestcontainer");
CloudBlob sasBlob = sasContainer.GetBlobReference("myblob.txt");

/* This will work if SharedAccessPermissions.Write is used */
sasBlob.UploadText("Hello!");

/* This will work if SharedAccessPermissions.Read is used */
sasBlob.DownloadText();

/* This will work if SharedAccessPermissions.Delete is used */
sasBlob.Delete();

/* This will work if SharedAccessPermissions.List is used */
sasContainer.ListBlobs();

/* This will always fail */
sasContainer.FetchAttributes();

/* This will always fail */
sasClient.ListContainers(); 

Here are some points that I think is worth noting when working with SAS. It might even save you some time:

  • Remember to use Utc methods on DateTime. If you use anything else, the time window where the SAS is valid, might not be the same as you think.
  • The FetchAttributes method does not work on the container/blob that the SAS was generated for. This is interesting because the FetchAttributes method is very often used to determine if the container/blob exists or not. But it will work for blobs inside a container if the SAS was generated for that container. 
  • A StorageClientException with the message: The specified resource does not exist, is thrown if the SAS does not grand enough access. So Azure hides the container/blob if the client does not have the right access level. 
  • DeleteIfExists will never fail if SharedAccessPermissions.Delete is not specified. As mentioned above, Azure hides containers/blobs if access rights are missing. 

Tags:

.NET | Azure | C#

Azure and multi website packages created with cspack.exe

by ingvar 19. april 2011 07:49

Introduction

Iwanted to create Azure deploy packages through the command line. Well I wanted to create them outside Visual Studio. I started out with a with two websites in the same role with different binding endpoints. And the setup worked when i deployed from VS. In my setup, the WebRole copied files from the blob to the each website. So the initial websites were empty and the WebRole created them in the OnStart method.

I discovered one very important thing when creating packages with cspack.exe. And I want to share this with other developers, because it took me a great deal of time to find this small, but very important detail: The argument /RolePropertiesFile.

Result

First let me show what I found out was needed to create a working package:

Here is the command:

cspack.exe WindowsAzureProject\ServiceDefinition.csdef 
           /role:MyWebRole;MyWebRole  
           /rolePropertiesFile:MyWebRole;MyWebRole\RoleProperties.txt

 

Here WindowsAzureProject is the folder containing the Azure project and MyWebRole is the folder containing the web role added to the Azure project.

And here is the content of the file RoleProperties.txt

EntryPoint=WebRole.dll
TargetFrameWorkVersion=v4.0

Process

Here is the things i went through to get to the working result above.

I started out with the command, that could be found many places through some simple searching:

cspack.exe WindowsAzureProject\ServiceDefinition.csdef 
           /role:MyWebRole;MyWebRole  

This resulted in this IIS error message: Parser Error Message: Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive.

Then I did some more, well a lot more, searching and found this blog post. I added the argument /RolePropertiesFile:RolePropertoes.txt to the command and tried it out. But no luck, it did not work. The result site just gave me a new error: 403 as if no files existed on the website. The strange part was that it seemed that the WebRole did not run. In the WebRole.OnStart I had added some some remote logging. When I deployed the command line package, there were no logging, but if i deployed through VS it did do the logging. So the package was deployed, but the WebRole did not run, or excepted very early. Almost all the code was inside a try-catch-block and the exception was remote logged. But no log lines. So I’m pretty sure it did not run. Which also was the case after some more digging.

Then I tried adding the /copyOnly argument to the command. This generated a folder containing files that the emulator can use when running the WebRole. I started comparing files in this folder against the folder generated by VS and found a very interesting file: RoleModel.xml. Both files contained Properties element with a series of Property elements. The command line version of this file only had one Property element, namely TargetFrameWorkVersion that i added in the RoleProperties.txt file. The VS version of the RoleModel.xml file contained a lot more Property elements. So I added all of them to the RoleProperties.txt file, ran the command, redeployed and it worked!!

Then I started removing properties one by one, redeploying in between until i found the single property that was needed for the command line generated package to work (Yup, it took a long time to do this). And here is the result RoleProperties.txt file:

EntryPoint=WebRole.dll
TargetFrameWorkVersion=v4.0

I retried the whole setup, but this time with only one website in the web role. And for some strange and unknown reason to me, it worked without the extra parameter in the RoleProperties.txt file. 

So the lesson here is that using the /copyOnly argument and comparing the directory generated by the cspack.exe against VS could be very helpful. 

Tags:

Azure | C# | C1

Microsoft.WindowsAzure.* assemblies not in GAC on Azure sites

by ingvar 16. april 2011 16:34

I discovered something ord with Azure deployments. 99% of developers and Azure deployments will probably never encounter. To put it short if discovered that if the website you deploy to Azure does not have a reference to the assembly Microsoft.WindowsAzure.StorageClient.dll, the assembly can not be used by the website at all. In other words, this assembly is not in the GAC. Many will probably find this scenario strange. But I encountered this issue when I was working with the CMS Composite C1. C1 is deployed to Azure buy the WebRole.OnStart method that downloads a zip file and unzipping it to the website. Why? Well, there are many reasons, but one of them is that this allows developers deploying existing C1 sites to Azure with the same Azure deployment package (no need to rebuild the package). They just zips the site and points to it from the ServiceConfiguration.cscfg file. 

I wanted to share this, so I have found an easy way to reproduce it. Here is the steps to reproduce it (A zipped version can be downloaded Here):

  1. Create new windows azure project.
  2. Add a ASP.NET WebRole (Clean the site so only WebRole.cs and web.config are left).
  3. Add Empty ASP.NET website.
  4. Add the physicalDirectory=”../Website” to the Site element in the ServiceDefinition.csdef file.
  5. Add a Default.aspx to the website (Not the WebRole) with the code below.
  6. Deploy to Azure.
  7. Note that the CloudBlob type is not found!
  8. Add a Default.aspx with the same code to the WebRole project.
  9. Change the physicalDirectory to “../WebRole” in the ServiceDefinition.csdef file.
  10. Deploy to Azure.
  11. Now the types can be found! (WebRole having a reference to the needed assembly)

Here is ths code I added to the Default.aspx.cs files:

protected void Page_Load(object sender, EventArgs e)
{
    Type cloudBlobType = Type.GetType("Microsoft.WindowsAzure.StorageClient.CloudBlob, "
      "Microsoft.WindowsAzure.StorageClient");
    if (cloudBlobType != null)
    {
        PlaceHolder.Controls.Add(new LiteralControl("Type found! <br />"));
    }
    else
    {
        PlaceHolder.Controls.Add(new LiteralControl("Type NOT found! <br />"));
    }
}

I used Type.GetType here only to do the reproduction. This could also happen, as it did with C1, if an assembly is added to the website from the WebRole.OnStart, that have a reference to Microsoft.WindowsAzure.StorageClient.dll and used in the code. In this case the site is totaly dead.  

The fix is easy, just add needed references to the website. The reason that the WebRole in this reproduction works is that it has a reference to the needed assembly and this results in that the assembly is in the bin folder. 



Tags:

.NET | Azure | C#

Paths for each site on a Azure deployment

by ingvar 15. april 2011 22:49

If you need to do any file related work in your WebRole on the deployed files or if you want to add files from the WebRole. This post presents one way to get the physical paths and names of each website on a Azure deployment. This works for both single and multiple site setups.

First we need to get the role model, which is created by Azure from the ServiceDefinition.xml. So some of the aspects of this role model file is recognisable. The root directory of the role can be found in the environment variables. Like this:

string roleRootPath = Environment.GetEnvironmentVariable("RdRoleRoot");

The file name of the role model is ‘RoleModel.xml’, so the full path of the role model can be constructed and loaded like this:

string roleModelPath = Path.Combine(roleRootPath, "RoleModel.xml")
 

We need one more thing before we start parsing the RoleModel.xml file. We need the current application directory. We need this because the paths in RoleModel.xml are relative, so to get the full path we need application directory. We can get it like this:

string currentAppRootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

The web sites construct in this file is very similar as in ServiceDefinition.xml. So finding the web sites names and physical paths could be done like this:

XNamespace roleModelNS = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition";
XDocument roleModel = XDocument.Load(roleModelPath);
var siteElements = roleModel.Root.Element(roleModelNS + "Sites").
                                   Elements(roleModelNS + "Site");

var results = 
    from siteElement in siteElements
    where siteElement.Attribute("name") != null &&
          siteElement.Attribute("physicalDirectory") != null
    select new {
        Path = Path.Combine(appRootDir, siteElement.Attribute("physicalDirectory").Value),
        Name = siteElement.Attribute("name").Value };

Tags:

.NET | Azure | C#

Azure and the REST API

by ingvar 13. april 2011 21:09

Introduction

In this post I’ll write about the interesting things i discovered when doing REST to Azure. And I’ll also post the code needed to; create a hosted server, created a new deplyment and upgrade an existing deployment.

The three most important findings for me was how to get meaningfull error messages when the web request failed. The right way to use Uri for some REST operations and the right way to encode service configuration files in the body of the request.

Documentation for the Azure REST API can be found here: http://msdn.microsoft.com/en-us/library/ee460799.aspx

Certificate

You need a certificate to identify you REST commands to Auzre.

You can create a new certificate by issuing this command:

makecert -r -pe -a sha1 -n CN=AzureMgmt -ss My “AzureMgmt.cer"

The file 'AzureMgmt.ce' that was created by this command should be added to your Azure subscribtion. You can do this through the Azure Management Portal.

Generic setup

Here is a generic setup for issuing REST operations. 

Edit (2011-04-13): Setting the request method to "POST" should only be done if there is a body to send, thanks to Christian Horsdal for pointing this out.

string requestUrl = "";
string certificatePath = "";
string headerVersion = "";
string requestBody = "";

HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(requestUrl, true));
httpWebRequest.ClientCertificates.Add(new X509Certificate2(certificatePath));
httpWebRequest.Headers.Add("x-ms-version", headerVersion);
httpWebRequest.ContentType = "application/xml";

if (!string.IsNullOrEmpty(requestBody))
{
   httpWebRequest.Method = "POST";
   byte[] requestBytes = Encoding.UTF8.GetBytes(requestBody);
   httpWebRequest.ContentLength = requestBytes.Length;

   using (Stream stream = httpWebRequest.GetRequestStream())
   {
      stream.Write(requestBytes, 0, requestBytes.Length);
   }
}

try
{
   using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
   {
      Console.WriteLine("Response status code: " + httpWebResponse.StatusCode);       WriteRespone(httpWebResponse);
   }
}
catch (WebException ex)
{
   Console.WriteLine("Response status code: " + ex.Status);
   WriteRespone(ex.Response);
}

Here is the code for the WriteRepsonse method:

static void WriteRespone(WebResponse webResponse)
{
   using (Stream responseStream = webResponse.GetResponseStream())
   {
      if (responseStream == null) return;

      using (StreamReader reader = new StreamReader(responseStream))
      {
         Console.WriteLine("Response output:");
         Console.WriteLine(reader.ReadToEnd());
      }
   }
}

The three variables; requestUrl, headerVersion and requestBody) are the only things you need to change to do any REST operation. 

The certificatePath variable is the same for all operations, it just need to be the path to your certificate file. 

The requestUrl variable is constructed to match the specific REST operation. See the the documentation for the different REST operations here [http://msdn.microsoft.com/en-us/library/ee460799.aspx].

The headerVersion varies from operation to operation. Some operations has the same version. You can find the correct version in the documentation.

The requestBody is a small XML document. Not all operations needs a body and this is handled by the generic code above. See the documentation [http://msdn.microsoft.com/en-us/library/ee460799.aspx] if the body is needed and if it is, how its constructed.

 

Important findings

Here is a short list of the problems I ran into when doing REST operations and the solutions to them:

  • WebException.Response.GetResponseStream() is your friend! When a operation fails with an exception and the error code 400, reading the WebExceptions response stream can help you finding the reason why.
  • The Uri constructor should have dontEscape=false for the request URL. If this is not the case, REST operations like Upgrade Deployment fails.
  • The ordering of the elements in the body matters, it is XML, so not so supprising.
  • If a Azure deployment package is needed, this should be located in a blob store. This is also documented in the documentation.
  • If an Azure service configuration is needed, this should be read as a string and base64 encoded like i did in the code. My first try i read the file as byte (File.ReadBytes) but this made the operation fail.

 

Create Hosted Service Example

Here is the value of the needed three variables:

string requestUrl = "https://management.core.windows.net/<subscription-id>/services/hostedservices";
string headerVersion = "2010-10-28";
string requestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<CreateHostedService xmlns=\"http://schemas.microsoft.com/windowsazure\">" +
      "<ServiceName>myservicename</ServiceName>" +
      "<Label>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("myservicename")) + "</Label>" +
      "<Location>North Central US</Location>" +
   "</CreateHostedService>";

Create Deployment Example

Here is the value of the needed three variables:

string requestUrl = "https://management.core.windows.net/<subscription-id>/services/hostedservices/myservicename/deploymentslots/staging";
string headerVersion = "2009-10-01";
string requestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<CreateDeployment xmlns=\"http://schemas.microsoft.com/windowsazure\">" +
      "<Name>mydeployment</Name>" +
      "<PackageUrl>http://myblob.blob.core.windows.net/MyPackage.cspkg</PackageUrl>" +
      "<Label>" +
      Convert.ToBase64String(Encoding.UTF8.GetBytes("mydeployment")) +
      "</Label>" +
      "<Configuration>" +
      Convert.ToBase64String(Encoding.UTF8.GetBytes(
         File.ReadAllText(@"C:\MyServiceConfiguration.cscfg"))) +
      "</Configuration>" +
      "<StartDeployment>true</StartDeployment>" +
   "</CreateDeployment>";

Upgrade Deployment Example

Here is the value of the needed three variables:

string requestUrl = "https://management.core.windows.net/<subscription-id>/services/hostedservices/myservicename/deploymentslots/staging/?comp=upgrade";
string headerVersion = "2009-10-01";
string requestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<UpgradeDeployment xmlns=\"http://schemas.microsoft.com/windowsazure\">" +
      "<PackageUrl>http://myblob.blob.core.windows.net/MyPackage.cspkg</PackageUrl>" +
      "<Configuration>" +
      Convert.ToBase64String(Encoding.UTF8.GetBytes(
            File.ReadAllText(@"C:\MyServiceConfiguration.cscfg"))) +
      "</Configuration>" + "<Mode>auto</Mode>" +
      "<Label>"
      Convert.ToBase64String(Encoding.UTF8.GetBytes("mydeployment")) + 
      "</Label>" +
   "</UpgradeDeployment>";

Tags:

.NET | Azure | C#

About the author

Martin Ingvar Kofoed Jensen

Architect and Senior Developer at Composite on the open source project Composite C1 - C#/4.0, LINQ, Azure, Parallel and much more!

Follow me on Twitter

Read more about me here.

Read press and buzz about my work and me here.

Stack Overflow

Month List