/// <summary>
        /// Attempts to get the user's credentials from the given Storage Context or the current subscription, if the former is null. 
        /// Throws a terminating error if the credentials cannot be determined.
        /// </summary>
        internal static StorageCredentials GetStorageCredentials(this AzureSMCmdlet cmdlet, AzureStorageContext storageContext)
        {
            StorageCredentials credentials = null;

            if (storageContext != null)
            {
                credentials = storageContext.StorageAccount.Credentials;
            }
            else
            {
                var storageAccount = cmdlet.Profile.Context.GetCurrentStorageAccount();
                if (storageAccount != null)
                {
                    credentials = storageAccount.Credentials;
                }
            }

            if (credentials == null)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new UnauthorizedAccessException(Resources.AzureVMDscDefaultStorageCredentialsNotFound),
                        "CredentialsNotFound",
                        ErrorCategory.PermissionDenied,
                        null));
            }

            if (string.IsNullOrEmpty(credentials.AccountName))
            {
                ThrowInvalidArgumentError(cmdlet, Resources.AzureVMDscStorageContextMustIncludeAccountName);
            }

            return credentials;
        }
        protected PSStorageService(StorageServicePropertiesOperationContext account, AzureStorageContext context)
            : this(context)
        {
            this.AccountType = account.AccountType;
            this.AffinityGroup = account.AffinityGroup;
            this.GeoPrimaryLocation = account.GeoPrimaryLocation;
            this.GeoReplicationEnabled = account.GeoReplicationEnabled;
            this.GeoSecondaryLocation = account.GeoSecondaryLocation;
            this.Label = account.Label;
            this.Location = account.Location;
            this.OperationDescription = account.OperationDescription;
            this.OperationId = account.OperationId;
            this.OperationStatus = account.OperationStatus;
            this.StatusOfPrimary = account.StatusOfPrimary;
            this.StatusOfSecondary = account.StatusOfSecondary;
            this.StorageAccountName = account.StorageAccountName;
            this.StorageAccountDescription = account.StorageAccountDescription;
            this.StorageAccountStatus = account.StorageAccountStatus;
            var endpointList = new List<string>();
            foreach (var endpoint in account.Endpoints)
            {
                endpointList.Add(endpoint);
            }

            this.Endpoints = endpointList;
        }
 public SetAzureServiceDiagnosticsExtensionCmdletInfo(string service, AzureStorageContext storageContext, string thumbprint, string algorithm, string config, string[] roles, string slot)
     : this(service, storageContext, config, roles, slot)
 {
     this.cmdletParams.Add(new CmdletParam("CertificateThumbprint", thumbprint));
     if (!string.IsNullOrEmpty(algorithm))
     {
         this.cmdletParams.Add(new CmdletParam("ThumbprintAlgorithm", algorithm));
     }
 }
 public SetAzureServiceDiagnosticsExtensionCmdletInfo(string service, AzureStorageContext storageContext, string config, string[] roles, string slot)
 {
     this.cmdletName = Utilities.SetAzureServiceDiagnosticsExtensionCmdletName;
     this.cmdletParams.Add(new CmdletParam("ServiceName", service));
     this.cmdletParams.Add(new CmdletParam("StorageContext", storageContext));
     this.cmdletParams.Add(new CmdletParam("Slot", slot));
     if (roles != null)
     {
         this.cmdletParams.Add(new CmdletParam("Role", roles));
     }            
     if (config != null)
     {
         this.cmdletParams.Add(new CmdletParam("DiagnosticsConfigurationPath", config));
     }
 }
        /// <summary>
        /// Attempts to get the user's credentials from the given Storage Context or the current subscription, if the former is null. 
        /// Throws a terminating error if the credentials cannot be determined.
        /// </summary>
        internal static StorageCredentials GetStorageCredentials(this AzurePSCmdlet cmdlet, AzureStorageContext storageContext)
        {
            StorageCredentials credentials = null;

            if (storageContext != null)
            {
                credentials = storageContext.StorageAccount.Credentials;
            }
            else
            {
                var storageAccountName = cmdlet.Profile.Context.Subscription.GetProperty(AzureSubscription.Property.StorageAccount);

                var storageClient = AzureSession.ClientFactory.CreateClient<StorageManagementClient>(
                        cmdlet.Profile, cmdlet.Profile.Context.Subscription, AzureEnvironment.Endpoint.ServiceManagement);

                if (!string.IsNullOrEmpty(storageAccountName) && storageClient != null)
                {
                    var keys = storageClient.StorageAccounts.GetKeys(storageAccountName);
                    
                    if (keys != null)
                    {
                        var storageAccountKey = string.IsNullOrEmpty(keys.PrimaryKey) ? keys.SecondaryKey : keys.PrimaryKey;

                        credentials = new StorageCredentials(storageAccountName, storageAccountKey);
                    }
                }
            }

            if (credentials == null)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new UnauthorizedAccessException(Resources.AzureVMDscDefaultStorageCredentialsNotFound),
                        "CredentialsNotFound",
                        ErrorCategory.PermissionDenied,
                        null));
            }

            if (string.IsNullOrEmpty(credentials.AccountName))
            {
                ThrowInvalidArgumentError(cmdlet, Resources.AzureVMDscStorageContextMustIncludeAccountName);
            }

            return credentials;
        }
        /// <summary>
        /// Attempts to get the user's credentials from the given Storage Context or the current subscription, if the former is null. 
        /// Throws a terminating error if the credentials cannot be determined.
        /// </summary>
        public static StorageCredentials GetStorageCredentials(this ServiceManagementBaseCmdlet cmdlet, AzureStorageContext storageContext)
        {
            StorageCredentials credentials = null;

            if (storageContext != null)
            {
                credentials = storageContext.StorageAccount.Credentials;
            }
            else
            {
                var storageAccountName = cmdlet.CurrentContext.Subscription.GetProperty(AzureSubscription.Property.StorageAccount);
                
                if (!string.IsNullOrEmpty(storageAccountName))
                {
                    var keys = cmdlet.StorageClient.StorageAccounts.GetKeys(storageAccountName);
                    
                    if (keys != null)
                    {
                        var storageAccountKey = string.IsNullOrEmpty(keys.PrimaryKey) ? keys.SecondaryKey : keys.PrimaryKey;

                        credentials = new StorageCredentials(storageAccountName, storageAccountKey);
                    }
                }
            }

            if (credentials == null)
            {
                cmdlet.ThrowTerminatingError(
                    new ErrorRecord(
                        new UnauthorizedAccessException(Resources.AzureVMDscDefaultStorageCredentialsNotFound),
                        string.Empty,
                        ErrorCategory.PermissionDenied,
                        null));
            }

            if (string.IsNullOrEmpty(credentials.AccountName))
            {
                cmdlet.ThrowInvalidArgumentError(Resources.AzureVMDscStorageContextMustIncludeAccountName);
            }

            return credentials;
        }
        public SetAzureVMDscExtensionCmdletInfo(
            string              version,
            IPersistentVM       vm,
            string              configurationArchive,
            AzureStorageContext storageContext = null,
            string              containerName = null,
            string              configurationName = null,
            Hashtable           configurationArgument = null,
            string              configurationDataPath = null
        ) 
        {
            cmdletName = Utilities.SetAzureVMDscExtensionCmdletName;

            cmdletParams.AddRange(
                new CmdletParam [] {
                    new CmdletParam("Version", version),
                    new CmdletParam("VM", vm),
                    new CmdletParam("ConfigurationArchive", configurationArchive),
                });

            if (storageContext != null)
            {
                cmdletParams.Add(new CmdletParam("StorageContext", storageContext));
            }
            if (containerName != null)
            {
                cmdletParams.Add(new CmdletParam("ContainerName", containerName));
            }
            if (configurationName != null)
            {
                cmdletParams.Add(new CmdletParam("ConfigurationName", configurationName));
            }
            if (configurationArgument != null)
            {
                cmdletParams.Add(new CmdletParam("ConfigurationArgument", configurationArgument));
            }
            if (configurationDataPath != null)
            {
                cmdletParams.Add(new CmdletParam("ConfigurationDataPath", configurationDataPath));
            }
        }
 public PSStorageService(AzureStorageContext context)
 {
     _context = context;
 }
        protected void InitializeStorageContext(string storageAccountName)
        {
            // lookup storage account by name and retrieve key 
            var storageService = this.StorageClient.StorageAccounts.Get(storageAccountName);
            if (storageService == null)
            {
                ThrowTerminatingError(new ErrorRecord(
                    new Exception("ServiceExtensionCannotFindStorageAccountName"),
                    string.Empty,
                    ErrorCategory.InvalidData,
                    null));
            }
            var storageKeys = this.StorageClient.StorageAccounts.GetKeys(storageService.StorageAccount.Name);
            if (storageKeys == null || storageKeys.PrimaryKey == null || storageKeys.SecondaryKey == null)
            {
                ThrowTerminatingError(new ErrorRecord(
                    new Exception("ServiceExtensionCannotFindStorageAccountKey"),
                    string.Empty,
                    ErrorCategory.InvalidData,
                    null));
            }
            string storageAccountKey = storageKeys.PrimaryKey != null ? storageKeys.PrimaryKey : storageKeys.SecondaryKey;

            // now that key has been retrieved, initialize context and return
            StorageCredentials creds = new StorageCredentials(storageAccountName, storageAccountKey);
            CloudStorageAccount csa = new WindowsAzure.Storage.CloudStorageAccount(creds, true);
            StorageContext = new AzureStorageContext(csa);
        }
 /// <summary>
 /// Init blob management
 /// </summary>
 /// <param name="client">a cloud blob object</param>
 public StorageBlobManagement(AzureStorageContext context)
 {
     internalStorageContext = context;
 }
 public SetAzureServiceDiagnosticsExtensionCmdletInfo(string service, AzureStorageContext storageContext, X509Certificate2 cert, string config, string[] roles, string slot)
     : this(service, storageContext, config, roles, slot)
 {
     this.cmdletParams.Add(new CmdletParam("X509Certificate", cert));
 }
 /// <summary>
 /// Init blob management
 /// </summary>
 /// <param name="client">a cloud blob object</param>
 public StorageBlobManagement(AzureStorageContext context)
 {
     internalStorageContext = context;
     blobClient = internalStorageContext.StorageAccount.CreateCloudBlobClient();
 }
        /// <summary>
        /// Initialize the storage account name if it's not specified.
        /// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is:
        /// 1. The one get from StorageContext parameter
        /// 2. The one parsed from the diagnostics configuration file
        /// </summary>
        public static string InitializeStorageAccountName(AzureStorageContext storageContext = null, string configurationPath = null)
        {
            string storageAccountName = null;
            var configFileType = GetConfigFileType(configurationPath);

            if (storageContext != null)
            {
                storageAccountName = storageContext.StorageAccountName;
            }
            else if (configFileType == ConfigFileType.Xml)
            {
                var publicConfig = GetPublicConfigXElementFromXmlFile(configurationPath);
                var storageNode = publicConfig == null ? null : publicConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == StorageAccountElemStr);
                storageAccountName = storageNode == null ? null : storageNode.Value;
            }
            else if (configFileType == ConfigFileType.Json)
            {
                var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath);
                var properties = publicConfig.Properties().Select(p => p.Name);
                var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase));
                storageAccountName = storageAccountProperty == null ? null : publicConfig[storageAccountProperty].Value<string>();
            }

            return storageAccountName;
        }
 private static string GetEndpointFromStorageContext(AzureStorageContext context)
 {
     var scheme = context.BlobEndPoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "https://" : "http://";
     return scheme + context.EndPointSuffix;
 }
 /// <summary>
 /// Storage table management constructor
 /// </summary>
 /// <param name="client">Cloud table client</param>
 public StorageTableManagement(AzureStorageContext context)
 {
     internalStorageContext = context;
     tableClient = internalStorageContext.StorageAccount.CreateCloudTableClient();
 }
 /// <summary>
 /// Queue management constructor
 /// </summary>
 /// <param name="client">Cloud queue client</param>
 public StorageQueueManagement(AzureStorageContext context)
 {
     internalStorageContext = context;
     queueClient = internalStorageContext.StorageAccount.CreateCloudQueueClient();
 }
 public void GetStorageAccountByConnectionStringAndSasToken()
 {
     // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine")]
     string sasToken = "?st=2013-09-03T04%3A12%3A15Z&se=2013-09-03T05%3A12%3A15Z&sr=c&sp=r&sig=fN2NPxLK99tR2%2BWnk48L3lMjutEj7nOwBo7MXs2hEV8%3D";
     string endpoint = "http://storageaccountname.blob.core.windows.net";
     string connectionString = String.Format("BlobEndpoint={0};QueueEndpoint={0};TableEndpoint={0};SharedAccessSignature={1}", endpoint, sasToken);
     CloudStorageAccount account = command.GetStorageAccountByConnectionString(connectionString);
     AzureStorageContext context = new AzureStorageContext(account);
     connectionString = String.Format("BlobEndpoint={0};SharedAccessSignature={1}", endpoint, sasToken);
     account = command.GetStorageAccountByConnectionString(connectionString);
     context = new AzureStorageContext(account);
 }
        /// <summary>
        /// Start copy operation by source uri
        /// </summary>
        /// <param name="srcICloudBlob">Source uri</param>
        /// <param name="destContainer">Destinaion container name</param>
        /// <param name="destBlobName">Destination blob name</param>
        /// <returns>Destination ICloudBlob object</returns>
        private void StartCopyBlob(IStorageBlobManagement destChannel, string srcUri, string destContainer, string destBlobName, AzureStorageContext context)
        {
            if (context != null)
            {
                Uri sourceUri = new Uri(srcUri);
                Uri contextUri = new Uri(context.BlobEndPoint);

                if (sourceUri.Host.ToLower() == contextUri.Host.ToLower())
                {
                    CloudBlobClient blobClient = context.StorageAccount.CreateCloudBlobClient();
                    ICloudBlob blobReference = blobClient.GetBlobReferenceFromServer(sourceUri);
                    StartCopyBlob(destChannel, blobReference, destContainer, destBlobName);
                }
                else
                {
                    WriteWarning(String.Format(Resources.StartCopySourceContextMismatch, srcUri, context.BlobEndPoint));
                }
            }
            else
            {
                CloudBlobContainer container = destChannel.GetContainerReference(destContainer);
                Func<long, Task> taskGenerator = (taskId) => StartCopyInTransferManager(taskId, destChannel, new Uri(srcUri), container, destBlobName);
                RunTask(taskGenerator);
            }
        }
        /// <summary>
        /// Start copy operation by source uri
        /// </summary>
        /// <param name="srcCloudBlob">Source uri</param>
        /// <param name="destContainer">Destinaion container name</param>
        /// <param name="destBlobName">Destination blob name</param>
        /// <returns>Destination CloudBlob object</returns>
        private void StartCopyBlob(IStorageBlobManagement destChannel, string srcUri, string destContainer, string destBlobName, AzureStorageContext context)
        {
            if (context != null)
            {
                Uri sourceUri = new Uri(srcUri);
                Uri contextUri = new Uri(context.BlobEndPoint);

                if (sourceUri.Host.ToLower() == contextUri.Host.ToLower())
                {
                    CloudBlobClient blobClient = context.StorageAccount.CreateCloudBlobClient();
                    CloudBlob blobReference = null;

                    try
                    {
                        blobReference = Util.GetBlobReferenceFromServer(blobClient, sourceUri);
                    }
                    catch (InvalidOperationException)
                    {
                        blobReference = null;
                    }

                    if (null == blobReference)
                    {
                        throw new ResourceNotFoundException(String.Format(Resources.BlobUriNotFound, sourceUri.ToString()));
                    }

                    StartCopyBlob(destChannel, blobReference, destContainer, destBlobName);
                }
                else
                {
                    WriteWarning(String.Format(Resources.StartCopySourceContextMismatch, srcUri, context.BlobEndPoint));
                }
            }
            else
            {
                CloudBlobContainer container = destChannel.GetContainerReference(destContainer);
                Func<long, Task> taskGenerator = (taskId) => StartCopyAsync(taskId, destChannel, new Uri(srcUri), container, destBlobName);
                RunTask(taskGenerator);
            }
        }
        /// <summary>
        /// Initialize the storage account endpoint if it's not specified.
        /// We can get the value from multiple places, we only take the one with higher precedence. And the precedence is:
        /// 1. The one get from StorageContext parameter
        /// 2. The one get from the storage account
        /// 3. The one get from PrivateConfig element in config file
        /// 4. The one get from current Azure Environment
        /// </summary>
        public static string InitializeStorageAccountEndpoint(string storageAccountName, string storageAccountKey, IStorageManagementClient storageClient,
            AzureStorageContext storageContext = null, string configurationPath = null, AzureContext defaultContext = null)
        {
            string storageAccountEndpoint = null;
            StorageAccount storageAccount = null;

            if (storageContext != null)
            {
                // Get value from StorageContext
                storageAccountEndpoint = GetEndpointFromStorageContext(storageContext);
            }
            else if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount))
            {
                // Get value from StorageAccount
                var endpoints = storageAccount.PrimaryEndpoints;
                var context = CreateStorageContext(endpoints.Blob, endpoints.Queue, endpoints.Table, endpoints.File, storageAccountName, storageAccountKey);
                storageAccountEndpoint = GetEndpointFromStorageContext(context);
            }
            else if (!string.IsNullOrEmpty(
                storageAccountEndpoint = GetStorageAccountInfoFromPrivateConfig(configurationPath, PrivConfEndpointAttr)))
            {
                // We can get the value from PrivateConfig
            }
            else if (defaultContext != null && defaultContext.Environment != null)
            {
                // Get value from default azure environment. Default to use https
                Uri blobEndpoint = defaultContext.Environment.GetStorageBlobEndpoint(storageAccountName);
                Uri queueEndpoint = defaultContext.Environment.GetStorageQueueEndpoint(storageAccountName);
                Uri tableEndpoint = defaultContext.Environment.GetStorageTableEndpoint(storageAccountName);
                Uri fileEndpoint = defaultContext.Environment.GetStorageFileEndpoint(storageAccountName);
                var context = CreateStorageContext(blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, storageAccountName, storageAccountKey);
                storageAccountEndpoint = GetEndpointFromStorageContext(context);
            }

            return storageAccountEndpoint;
        }
        public void AzureServiceDiagnosticsExtensionTest()
        {
            StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);

            // Choose the package and config files from local machine
            string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
            string configName = Convert.ToString(TestContext.DataRow["configName"]);
            var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName);
            var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName);

            Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1);
            Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1);

            string deploymentName = "deployment1";
            string deploymentLabel = "label1";
            DeploymentInfoContext result;

            string storage = defaultAzureSubscription.CurrentStorageAccountName;
            string daConfig = @"da.xml";

            string defaultExtensionId = string.Format("Default-{0}-Production-Ext-0", Utilities.PaaSDiagnosticsExtensionName);

            serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
            vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
            Console.WriteLine("service, {0}, is created.", serviceName);

            vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false);

            result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
            pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2);
            Console.WriteLine("successfully deployed the package");

            string storageKey = vmPowershellCmdlets.GetAzureStorageAccountKey(storage).Primary;

            StorageCredentials creds = new StorageCredentials(storage, storageKey);
            CloudStorageAccount csa = new WindowsAzure.Storage.CloudStorageAccount(creds, true);
            var storageContext = new AzureStorageContext(csa);

            vmPowershellCmdlets.SetAzureServiceDiagnosticsExtension(serviceName, storageContext, daConfig, null, null);

            DiagnosticExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName)[0];

            VerifyDiagExtContext(resultContext, "AllRoles", defaultExtensionId, storage, daConfig);

            vmPowershellCmdlets.RemoveAzureServiceDiagnosticsExtension(serviceName, true);

            Assert.AreEqual(vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName).Count, 0);

            vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true);

            pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production);
        }
        public override void ExecuteCmdlet()
        {
            CloudStorageAccount account = null;
            bool useHttps = (StorageNouns.HTTPS.ToLower() == protocolType.ToLower());

            switch (ParameterSetName)
            {
                case AccountNameKeyParameterSet:
                    account = GetStorageAccountByNameAndKey(StorageAccountName, StorageAccountKey, useHttps, storageEndpoint);
                    break;
                case AccountNameKeyEnvironmentParameterSet:
                    account = GetStorageAccountByNameAndKeyFromAzureEnvironment(StorageAccountName, StorageAccountKey,
                        useHttps, environmentName);
                    break;
                case SasTokenParameterSet:
                    account = GetStorageAccountBySasToken(StorageAccountName, SasToken, useHttps, storageEndpoint);
                    break;
                case SasTokenEnvironmentParameterSet:
                    account = GetStorageAccountBySasTokenFromAzureEnvironment(StorageAccountName, SasToken, useHttps, environmentName);
                    break;
                case ConnectionStringParameterSet:
                    account = GetStorageAccountByConnectionString(ConnectionString);
                    break;
                case LocalParameterSet:
                    account = GetLocalDevelopmentStorageAccount();
                    break;
                case AnonymousParameterSet:
                    account = GetAnonymousStorageAccount(StorageAccountName, useHttps, storageEndpoint);
                    break;
                case AnonymousEnvironmentParameterSet:
                    account = GetAnonymousStorageAccountFromAzureEnvironment(StorageAccountName, useHttps, environmentName);
                    break;
                default:
                    throw new ArgumentException(Resources.DefaultStorageCredentialsNotFound);
            }

            AzureStorageContext context = new AzureStorageContext(account);
            WriteObject(context);
        }
        public void VipSwapWithDiagnosticsExtensionTest()
        {
            StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);

            // Choose the package and config files from local machine
            string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
            string configName = Convert.ToString(TestContext.DataRow["configName"]);
            var packagePath = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName);
            var configPath = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName);

            Assert.IsTrue(File.Exists(packagePath.FullName), "Package file not exist={0}", packagePath);
            Assert.IsTrue(File.Exists(configPath.FullName), "Config file not exist={0}", configPath);

            string deploymentName = "deployment1";
            string deploymentLabel = "label1";
            DeploymentInfoContext result;

            string storage = defaultAzureSubscription.CurrentStorageAccountName;
            string daConfig = @"da.xml";

            string storageKey = vmPowershellCmdlets.GetAzureStorageAccountKey(storage).Primary;
            StorageCredentials creds = new StorageCredentials(storage, storageKey);
            CloudStorageAccount csa = new WindowsAzure.Storage.CloudStorageAccount(creds, true);
            var storageContext = new AzureStorageContext(csa);

            serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
            vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
            Console.WriteLine("service, {0}, is created.", serviceName);

            // deploy staging
            vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath.FullName, configPath.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false);
            result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging);
            pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 2);
            Console.WriteLine("successfully deployed the package");

            vmPowershellCmdlets.SetAzureServiceDiagnosticsExtension(serviceName, storageContext, daConfig, null, slot: DeploymentSlotType.Staging);
            DiagnosticExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName, slot: DeploymentSlotType.Staging)[0];
            VerifyDiagExtContext(resultContext, "AllRoles", "Default-PaaSDiagnostics-Staging-Ext-0", storage, daConfig);

            // swap staging -> production
            // production will be retain diagnosting config from staging, named Default-PaaSDiagnostics-Staging-Ext-0
            vmPowershellCmdlets.MoveAzureDeployment(serviceName);

            // deploy a new staging
            deploymentName = "deployment2";
            deploymentLabel = "label2";

            vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath.FullName, configPath.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false);
            result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging);
            pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 2);
            Console.WriteLine("successfully deployed the package");

            // should detect that Default-PaaSDiagnostics-Staging-Ext-0 is in use 
            vmPowershellCmdlets.SetAzureServiceDiagnosticsExtension(serviceName, storageContext, daConfig, null, slot: DeploymentSlotType.Staging);
            DiagnosticExtensionContext resultContext2 = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName, slot: DeploymentSlotType.Staging)[0];
            VerifyDiagExtContext(resultContext2, "AllRoles", "Default-PaaSDiagnostics-Staging-Ext-1", storage, daConfig);

            // execute again to make sure max number of extensions will handled correctly (1 for production and 1 for staging, 1 unused)
            // should not fail due to ExtensionIdLiveCycleCount limit
            vmPowershellCmdlets.SetAzureServiceDiagnosticsExtension(serviceName, storageContext, daConfig, null, slot: DeploymentSlotType.Staging);
            DiagnosticExtensionContext resultContext3 = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName, slot: DeploymentSlotType.Staging)[0];

            // azure splits config from All Roles to specific role in that case, so role name should not be validated
            VerifyDiagExtContext(resultContext3, null, "Default-PaaSDiagnostics-Staging-Ext-2", storage, daConfig);
            
            vmPowershellCmdlets.RemoveAzureService(serviceName, true);
        }
 public StorageFileManagement(AzureStorageContext context)
 {
     this.StorageContext = context;
 }
        /// <summary>
        /// Make sure we set the correct storage account endpoint.
        /// We can get the value from multiple places, we only take the one with higher precedence. And the precedence is:
        /// 1. Directly specified from command line parameter
        /// 2. The one get from StorageContext parameter
        /// 3. The one get from the storage account we list
        /// 4. The one get from current Azure Environment
        /// </summary>
        /// <param name="storageAccount">The storage account to help get the endpoint.</param>
        private void InitializeStorageAccountEndpoint(StorageAccount storageAccount)
        {
            if (string.IsNullOrEmpty(this.StorageAccountEndpoint))
            {
                var context = this.StorageContext;
                if (context == null)
                {
                    Uri blobEndpoint = null, queueEndpoint = null, tableEndpoint = null, fileEndpoint = null;
                    if (storageAccount != null)
                    {
                        // Create storage context from storage account
                        var endpoints = storageAccount.PrimaryEndpoints;
                        blobEndpoint = endpoints.Blob;
                        queueEndpoint = endpoints.Queue;
                        tableEndpoint = endpoints.Table;
                        fileEndpoint = endpoints.File;
                    }
                    else if (this.DefaultContext != null && this.DefaultContext.Environment != null)
                    {
                        // Create storage context from default azure environment. Default to use https
                        blobEndpoint = DefaultContext.Environment.GetStorageBlobEndpoint(this.StorageAccountName);
                        queueEndpoint = DefaultContext.Environment.GetStorageQueueEndpoint(this.StorageAccountName);
                        tableEndpoint = DefaultContext.Environment.GetStorageTableEndpoint(this.StorageAccountName);
                        fileEndpoint = DefaultContext.Environment.GetStorageFileEndpoint(this.StorageAccountName);
                    }
                    else
                    {
                        // Can't automatically get the endpoint to create storage context
                        throw new ArgumentNullException(Properties.Resources.DiagnosticsExtensionStorageAccountEndpointNotDefined);
                    }
                    var credentials = new StorageCredentials(this.StorageAccountName, this.StorageAccountKey);
                    var cloudStorageAccount = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint);
                    context = new AzureStorageContext(cloudStorageAccount);
                }

                var scheme = context.BlobEndPoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "https://" : "http://";
                this.StorageAccountEndpoint = scheme + context.EndPointSuffix;
            }
        }