Staging or Production Instance?

Is there anywhere in the service runtime that would tell me if I'm currently running on 'Staging' or 'Production'? Manually modifying the config to and from production seems a bit cumbersome.


You should really not change your configurations when you're based upon if you're in Prod or Staging. Staging area is not designed to be a "QA" environment but only a holding-area before production is deployed.

When you upload a new deployment, current deployment slot where you upload your package to is destroyed and is down for 10-15minutes while upload and start of VM's is happening. If you upload straight into production, that's 15 minutes of production downtime. Thus, Staging area was invented: you upload to staging, test the stuff, and click "Swap" button and your Staging environment magically becomes Production (virtual IP swap). Thus, your staging should really be 100% the same as your production.

What I think you're looking for is QA/testing environment? You should open up a new service for Testing environment with its own Prod/Staging. In this case, you will want to maintain multiple configuration file sets, one set per deployment environment (Production, Testing, etc.)

There are many ways to manage configuration-hell that occurs, especially with Azure that has on top of .config files, its own *.cscfg files. The way I prefer to do it with Azure project is as follows: Setup a small Config project, create folders there that match Deployment types. Inside each folder setup sets of *.config & *.cscfg files that match to particular deployment environment: Debug, Test, Release... these are setup in Visual Studio as well , as build target types. I have a small xcopy command that occurs during every compile of the Config project that copies all the files from Build Target folder of Config project into root folder of the Config project.

Then every other project in the solution, LINKS to the .config or .cscfg file from the root folder of the Config project.

Voila, my configs magically adapt to every build configuration automatically. I also use .config transformations to manage debugging information for Release vs. non-Release build targets.

If you've read all this and still want to get at the Production vs. Staging status at runtime, then: Get deploymentId from RoleEnvironment.DeploymentId Then use Management API with a proper X509 certificate to get at the Azure structure of your Service and call the GetDeployments method (it's rest api but there is an abstraction library).

Hope this helps

Edit: blog post as requested about the setup of configuration strings and switching between environments @ http://blog.paraleap.com/blog/post/Managing-environments-in-a-distributed-Azure-or-other-cloud-based-NET-solution


Sometimes I wish people would just answer the question.. not explain ethics or best practices...

Microsoft has posted a code sample doing exactly this here: https://code.msdn.microsoft.com/windowsazure/CSAzureDeploymentSlot-1ce0e3b5

image showing Staging instance

image showing Production instance

protected void Page_Load(object sender, EventArgs e) 
{ 
    // You basic information of the Deployment of Azure application. 
    string deploymentId = RoleEnvironment.DeploymentId; 
    string subscriptionID = "<Your subscription ID>"; 
    string thrumbnail = "<Your certificate thumbnail print>"; 
    string hostedServiceName = "<Your hosted service name>"; 
    string productionString = string.Format(
        "https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}",
        subscriptionID, hostedServiceName, "Production"); 
    Uri requestUri = new Uri(productionString); 

    // Add client certificate. 
    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); 
    store.Open(OpenFlags.OpenExistingOnly); 
    X509Certificate2Collection collection = store.Certificates.Find(
        X509FindType.FindByThumbprint, thrumbnail, false); 
    store.Close(); 

    if (collection.Count != 0) 
    { 
        X509Certificate2 certificate = collection[0]; 
        HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(requestUri); 
        httpRequest.ClientCertificates.Add(certificate); 
        httpRequest.Headers.Add("x-ms-version", "2011-10-01"); 
        httpRequest.KeepAlive = false; 
        HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;

        // Get response stream from Management API. 
        Stream stream = httpResponse.GetResponseStream(); 
        string result = string.Empty; 
        using (StreamReader reader = new StreamReader(stream)) 
        { 
            result = reader.ReadToEnd();
        } 
        if (result == null || result.Trim() == string.Empty) 
        {
            return;
        }
        XDocument document = XDocument.Parse(result); 
        string serverID = string.Empty; 
        var list = from item
                   in document.Descendants(XName.Get("PrivateID",
                       "http://schemas.microsoft.com/windowsazure")) 
                   select item; 

        serverID = list.First().Value; 
        Response.Write("Check Production: "); 
        Response.Write("DeploymentID : " + deploymentId
            + " ServerID :" + serverID); 
        if (deploymentId.Equals(serverID)) 
            lbStatus.Text = "Production"; 
        else 
        { 
            // If the application not in Production slot, try to check Staging slot. 
            string stagingString = string.Format(
                "https://management.core.windows.net/{0}/services/hostedservices/{1}/deploymentslots/{2}",
                subscriptionID, hostedServiceName, "Staging"); 
            Uri stagingUri = new Uri(stagingString); 
            httpRequest = (HttpWebRequest)HttpWebRequest.Create(stagingUri); 
            httpRequest.ClientCertificates.Add(certificate); 
            httpRequest.Headers.Add("x-ms-version", "2011-10-01"); 
            httpRequest.KeepAlive = false; 
            httpResponse = httpRequest.GetResponse() as HttpWebResponse; 
            stream = httpResponse.GetResponseStream(); 
            result = string.Empty; 
            using (StreamReader reader = new StreamReader(stream)) 
            { 
                result = reader.ReadToEnd();
            } 
            if (result == null || result.Trim() == string.Empty) 
            {
                return;
            }
            document = XDocument.Parse(result); 
            serverID = string.Empty; 
            list = from item
                   in document.Descendants(XName.Get("PrivateID",
                       "http://schemas.microsoft.com/windowsazure")) 
                   select item; 

            serverID = list.First().Value; 
            Response.Write(" Check Staging:"); 
            Response.Write(" DeploymentID : " + deploymentId
                + " ServerID :" + serverID); 
            if (deploymentId.Equals(serverID)) 
            {
                lbStatus.Text = "Staging";
            }
            else 
            {
                lbStatus.Text = "Do not find this id";
            }
        } 
        httpResponse.Close(); 
        stream.Close(); 
    } 
}

Staging is a temporary deployment slot used mainly for no-downtime upgrades and ability to roll back an upgrade.

It is advised not to couple your system (either in code or in config) with such Azure specifics.


Since Windows Azure Management Libraries and thanks to @GuaravMantri answer to another question you can do it like this :

using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Compute;
using Microsoft.WindowsAzure.Management.Compute.Models;

namespace Configuration
{
    public class DeploymentSlotTypeHelper
    {
        static string subscriptionId = "<subscription-id>";
        static string managementCertContents = "<Base64 Encoded Management Certificate String from Publish Setting File>";// copy-paste it
        static string cloudServiceName = "<your cloud service name>"; // lowercase
        static string ns = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration";

        public DeploymentSlot GetSlotType()
        {
            var managementCertificate = new X509Certificate2(Convert.FromBase64String(managementCertContents));
            var credentials = new CertificateCloudCredentials(subscriptionId, managementCertificate);

            var computeManagementClient = new ComputeManagementClient(credentials);
            var response = computeManagementClient.HostedServices.GetDetailed(cloudServiceName);
            return response.Deployments.FirstOrDefault(d => d.DeploymentSlot == DeploymentSlot.Production) == null ? DeploymentSlot.Staging : DeploymentSlot.Production;
        }
    }
}