Esempio n. 1
0
        public static void AreEqualPublishContext(ServiceSettings settings, string configPath, string deploymentName, string label, string packagePath, string subscriptionId, PublishContext actual)
        {
            AreEqualServiceSettings(settings, actual.ServiceSettings);
            Assert.AreEqual<string>(configPath, actual.CloudConfigPath);
            Assert.AreEqual<string>(deploymentName, actual.DeploymentName);
            Assert.AreEqual<string>(label, actual.ServiceName);
            Assert.AreEqual<string>(packagePath, actual.PackagePath);
            Assert.AreEqual<string>(subscriptionId, actual.SubscriptionId);

            Assert.IsTrue(File.Exists(actual.CloudConfigPath));
            Assert.IsTrue(File.Exists(actual.PackagePath));
        }
        private Uri UploadPackage(PublishContext context)
        {
            WriteVerboseWithTimestamp(
                Resources.PublishUploadingPackageMessage,
                context.ServiceSettings.StorageServiceName);

            return(CloudBlobUtility.UploadPackageToBlob(
                       StorageClient,
                       context.ServiceSettings.StorageServiceName,
                       context.PackagePath,
                       new BlobRequestOptions()));
        }
        private void SetupStorageService(PublishContext context)
        {
            WriteVerboseWithTimestamp(
                Resources.PublishVerifyingStorageMessage,
                context.ServiceSettings.StorageServiceName);

            CreateStorageServiceIfNotExist(
                context.ServiceSettings.StorageServiceName,
                context.ServiceName,
                context.ServiceSettings.Location,
                context.ServiceSettings.AffinityGroup);
        }
Esempio n. 4
0
        private PublishContext CreatePublishContext(
            string name,
            string slot,
            string location,
            string affinityGroup,
            string storageServiceName,
            string deploymentName,
            CloudServiceProject cloudServiceProject)
        {
            string serviceName;

            // If the name provided is different than existing name change it
            if (!string.IsNullOrEmpty(name) && name != cloudServiceProject.ServiceName)
            {
                cloudServiceProject.ChangeServiceName(name, cloudServiceProject.Paths);
            }

            // If there's no storage service provided, try using the default one
            if (string.IsNullOrEmpty(storageServiceName))
            {
                storageServiceName = Subscription.GetProperty(AzureSubscription.Property.StorageAccount);
            }

            ServiceSettings serviceSettings = ServiceSettings.LoadDefault(
                cloudServiceProject.Paths.Settings,
                slot,
                location,
                affinityGroup,
                Subscription.Name,
                storageServiceName,
                name,
                cloudServiceProject.ServiceName,
                out serviceName
                );

            // Use default location if not location and affinity group provided
            serviceSettings.Location = string.IsNullOrEmpty(serviceSettings.Location) &&
                                       string.IsNullOrEmpty(serviceSettings.AffinityGroup) ?
                                       GetDefaultLocation() : serviceSettings.Location;

            PublishContext context = new PublishContext(
                serviceSettings,
                Path.Combine(GetCurrentDirectory(), cloudServiceProject.Paths.CloudPackage),
                Path.Combine(GetCurrentDirectory(), cloudServiceProject.Paths.CloudConfiguration),
                serviceName,
                deploymentName,
                cloudServiceProject.Paths.RootPath);

            context.ServiceProject = cloudServiceProject;

            return(context);
        }
 private Uri UploadPackageIfNeeded(PublishContext context)
 {
     Uri packageUri;
     if (context.PackageIsFromStorageAccount)
     {
         packageUri = new Uri(context.PackagePath);
     }
     else
     {
         packageUri = UploadPackage(context);
     }
     return packageUri;
 }
Esempio n. 6
0
        /// <summary>
        /// Publishes a service project on Microsoft Azure.
        /// </summary>
        /// <param name="name">The cloud service name</param>
        /// <param name="slot">The deployment slot</param>
        /// <param name="location">The deployment location</param>
        /// <param name="affinityGroup">The deployment affinity group</param>
        /// <param name="storageAccount">The storage account to store the package</param>
        /// <param name="deploymentName">The deployment name</param>
        /// <param name="launch">Launch the service after publishing</param>
        /// <param name="forceUpgrade">force the service upgrade even if this would result in loss of any local data on the vm (for example, changing the vm size)</param>
        /// <returns>The created deployment</returns>
        public Deployment PublishCloudService(
            string name           = null,
            string slot           = null,
            string location       = null,
            string affinityGroup  = null,
            string storageAccount = null,
            string deploymentName = null,
            bool launch           = false,
            bool forceUpgrade     = false)
        {
            CloudServiceProject cloudServiceProject = GetCurrentServiceProject();

            // Initialize publish context
            PublishContext context = CreatePublishContext(
                name,
                slot,
                location,
                affinityGroup,
                storageAccount,
                deploymentName,
                cloudServiceProject);

            WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName));

            // Set package runtime information
            WriteVerboseWithTimestamp(Resources.RuntimeDeploymentStart, context.ServiceName);
            PrepareCloudServicePackagesRuntime(context);

            // Verify storage account exists
            SetupStorageService(context);

            // Update cache worker roles configuration
            WriteVerboseWithTimestamp(
                Resources.PublishPreparingDeploymentMessage,
                context.ServiceName,
                Subscription.Id);
            UpdateCacheWorkerRolesCloudConfiguration(context);

            // Create cloud package
            AzureTool.Validate();
            if (File.Exists(context.PackagePath))
            {
                File.Delete(context.PackagePath);
            }
            cloudServiceProject.CreatePackage(DevEnv.Cloud);

            DeploymentGetResponse deployment = DeployPackage(launch, forceUpgrade, context);

            return(new Deployment(deployment));
        }
        public void TestDeploymentSettingsTestWithDefaultServiceSettings()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;
            settings.Subscription = "TestSubscription2";
            PublishContext deploySettings = new PublishContext(
                settings,
                packagePath,
                configPath,
                label,
                deploymentName,
                rootPath);

            AzureAssert.AreEqualPublishContext(settings, configPath, deploymentName, label, packagePath, "f62b1e05-af8f-4205-8f98-325079adc155", deploySettings);
        }
Esempio n. 8
0
        public Deployment PublishCloudService(
            string package,
            string configuration,
            string slot           = null,
            string location       = null,
            string affinityGroup  = null,
            string storageAccount = null,
            string deploymentName = null,
            bool launch           = false,
            bool forceUpgrade     = false)
        {
            string workingDirectory = GetCurrentDirectory();

            string cloudConfigFullPath = configuration;

            if (!Path.IsPathRooted(configuration))
            {
                cloudConfigFullPath = Path.Combine(workingDirectory, configuration);
            }

            CloudServiceProject cloudServiceProject = new CloudServiceProject(cloudConfigFullPath);

            // Initialize publish context
            PublishContext context = CreatePublishContext(
                cloudServiceProject.ServiceName,
                slot,
                location,
                affinityGroup,
                storageAccount,
                deploymentName,
                cloudServiceProject);

            context.ConfigPackageSettings(package, workingDirectory);

            // Verify storage account exists
            if (!context.PackageIsFromStorageAccount)
            {
                SetupStorageService(context);
            }

            WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName));

            DeploymentGetResponse deployment = DeployPackage(launch, forceUpgrade, context);

            return(new Deployment(deployment));
        }
Esempio n. 9
0
        private void UpgradeDeployment(PublishContext context)
        {
            var upgradeParams = new DeploymentUpgradeParameters
            {
                Configuration = General.GetConfiguration(context.ConfigPath),
                PackageUri    = UploadPackage(context),
                Label         = context.ServiceName,
                Mode          = DeploymentUpgradeMode.Auto
            };

            WriteVerboseWithTimestamp(Resources.PublishUpgradingMessage);

            var uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);

            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.UpgradeBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot), upgradeParams);
        }
        private void CreateDeployment(PublishContext context)
        {
            var deploymentParams = new DeploymentCreateParameters
            {
                PackageUri      = UploadPackage(context),
                Configuration   = General.GetConfiguration(context.ConfigPath),
                Label           = context.ServiceName,
                Name            = context.DeploymentName,
                StartDeployment = true
            };

            WriteVerboseWithTimestamp(Resources.PublishStartingMessage);

            ServiceCertificateListResponse uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);

            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.Create(context.ServiceName, GetSlot(context.ServiceSettings.Slot),
                                             deploymentParams);
        }
        private string GetDeploymentId(PublishContext context)
        {
            Deployment deployment = new Deployment();

            do
            {
                // If a deployment has many roles to initialize, this
                // thread must throttle requests so the Azure portal
                // doesn't reply with a "too many requests" error
                Thread.Sleep(SleepDuration);

                try
                {
                    deployment = new Deployment(
                        ComputeClient.Deployments.GetBySlot(context.ServiceName,
                        GetSlot(context.ServiceSettings.Slot)));
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode != HttpStatusCode.InternalServerError)
                    {
                        throw;
                    }
                }
            }
            while (deployment.Status != DeploymentStatus.Starting && deployment.Status != DeploymentStatus.Running);

            return deployment.PrivateID;
        }
        private void VerifyDeployment(PublishContext context)
        {
            try
            {
                WriteVerboseWithTimestamp(Resources.PublishInitializingMessage);

                var roleInstanceSnapshot = new Dictionary<string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment;
                do
                {
                    deployment = new Deployment(
                        ComputeClient.Deployments.GetBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot)));

                    // The goal of this loop is to output a message whenever the status of a role 
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.BusyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.ReadyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.CreatingRole))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!string.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                    case RoleInstanceStatus.BusyRole:
                                        statusResource = Resources.PublishInstanceStatusBusy;
                                        break;

                                    case RoleInstanceStatus.ReadyRole:
                                        statusResource = Resources.PublishInstanceStatusReady;
                                        break;

                                    default:
                                        statusResource = Resources.PublishInstanceStatusCreating;
                                        break;
                                }

                                WriteVerboseWithTimestamp(
                                    Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName,
                                    currentInstance.RoleName,
                                    statusResource);
                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(SleepDuration);
                }
                while (deployment.RoleInstanceList.Any(r => r.InstanceStatus != RoleInstanceStatus.ReadyRole));

                WriteVerboseWithTimestamp(Resources.PublishCreatedWebsiteMessage, deployment.Url);

            }
            catch (CloudException)
            {
                throw new InvalidOperationException(
                    string.Format(Resources.CannotFindDeployment, context.ServiceName, context.ServiceSettings.Slot));
            }
        }
        private void UpgradeDeployment(PublishContext context)
        {
            var upgradeParams = new DeploymentUpgradeParameters
            {
                Configuration = General.GetConfiguration(context.ConfigPath),
                PackageUri = UploadPackage(context),
                Label = context.ServiceName,
                Mode = DeploymentUpgradeMode.Auto
            };

            WriteVerboseWithTimestamp(Resources.PublishUpgradingMessage);

            var uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);
            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.UpgradeBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot), upgradeParams);
        }
 private void AddCertificates(ServiceCertificateListResponse uploadedCertificates, PublishContext context)
 {
     string name = context.ServiceName;
     CloudServiceProject cloudServiceProject = new CloudServiceProject(context.RootPath, null);
     if (cloudServiceProject.Components.CloudConfig.Role != null)
     {
         foreach (ConfigCertificate certElement in cloudServiceProject.Components.CloudConfig.Role.
             SelectMany(r => r.Certificates ?? new ConfigCertificate[0]).Distinct())
         {
             if (uploadedCertificates == null || (uploadedCertificates.Certificates.Count(c => c.Thumbprint.Equals(
                 certElement.thumbprint, StringComparison.OrdinalIgnoreCase)) < 1))
             {
                 X509Certificate2 cert = General.GetCertificateFromStore(certElement.thumbprint);
                 UploadCertificate(cert, certElement, name);
             }
         }
     }
 }
        private void CreateDeployment(PublishContext context)
        {
            var deploymentParams = new DeploymentCreateParameters
            {
                PackageUri = UploadPackage(context),
                Configuration = General.GetConfiguration(context.ConfigPath),
                Label = context.ServiceName,
                Name = context.DeploymentName,
                StartDeployment = true
            };

            WriteVerboseWithTimestamp(Resources.PublishStartingMessage);

            ServiceCertificateListResponse uploadedCertificates = ComputeClient.ServiceCertificates.List(context.ServiceName);
            AddCertificates(uploadedCertificates, context);

            ComputeClient.Deployments.Create(context.ServiceName, GetSlot(context.ServiceSettings.Slot),
                deploymentParams);
        }
        private void UpdateCacheWorkerRolesCloudConfiguration(PublishContext context)
        {
            string connectionString = GetStorageServiceConnectionString(context.ServiceSettings.StorageServiceName);
            var cloudServiceProject = new CloudServiceProject(context.RootPath, null);

            var connectionStringConfig = new ConfigConfigurationSetting
            {
                name = Resources.CachingConfigStoreConnectionStringSettingName,
                value = string.Empty
            };

            cloudServiceProject.Components.ForEachRoleSettings(
                r => Array.Exists(r.ConfigurationSettings, c => c.Equals(connectionStringConfig)),
                r =>
                    {
                        int index = Array.IndexOf(r.ConfigurationSettings, connectionStringConfig);
                        r.ConfigurationSettings[index] = new ConfigConfigurationSetting
                        {
                            name = Resources.CachingConfigStoreConnectionStringSettingName,
                            value = connectionString
                        };
                    });

            cloudServiceProject.Components.Save(cloudServiceProject.Paths);
        }
Esempio n. 17
0
        private void AddCertificates(ServiceCertificateListResponse uploadedCertificates, PublishContext context)
        {
            string name = context.ServiceName;
            CloudServiceProject cloudServiceProject = context.ServiceProject;

            if (cloudServiceProject.Components.CloudConfig.Role != null)
            {
                foreach (ConfigCertificate certElement in cloudServiceProject.Components.CloudConfig.Role.
                         SelectMany(r => r.Certificates ?? new ConfigCertificate[0]).Distinct())
                {
                    if (uploadedCertificates == null || (uploadedCertificates.Certificates.Count(c => c.Thumbprint.Equals(
                                                                                                     certElement.thumbprint, StringComparison.OrdinalIgnoreCase)) < 1))
                    {
                        X509Certificate2 cert = GeneralUtilities.GetCertificateFromStore(certElement.thumbprint);
                        UploadCertificate(cert, certElement, name);
                    }
                }
            }
        }
        private DeploymentGetResponse DeployPackage(bool launch, bool forceUpgrade, PublishContext context)
        {
            // Publish cloud service
            WriteVerboseWithTimestamp(Resources.PublishConnectingMessage);
            CreateCloudServiceIfNotExist(
                context.ServiceName,
                affinityGroup: context.ServiceSettings.AffinityGroup,
                location: context.ServiceSettings.Location);

            if (DeploymentExists(context.ServiceName, context.ServiceSettings.Slot))
            {
                // Upgrade the deployment
                UpgradeDeployment(context, forceUpgrade);
            }
            else
            {
                // Create new deployment
                CreateDeployment(context);
            }

            // Get the deployment id and show it.
            WriteVerboseWithTimestamp(Resources.PublishCreatedDeploymentMessage, GetDeploymentId(context));

            // Verify the deployment succeeded by checking that each of the roles are running
            VerifyDeployment(context);

            // Get object of the published deployment
            DeploymentGetResponse deployment = ComputeClient.Deployments.GetBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot));

            if (launch)
            {
                GeneralUtilities.LaunchWebPage(deployment.Uri.ToString());
            }
            return deployment;
        }
Esempio n. 19
0
 public static void AreEqualDeploymentSettings(PublishContext expected, PublishContext actual)
 {
     AreEqualPublishContext(expected.ServiceSettings, expected.CloudConfigPath, expected.DeploymentName, expected.ServiceName, expected.PackagePath, expected.SubscriptionId, actual);
 }
        public void TestDeploymentSettingsTestNullLabelFail()
        {
            string deploymentName = service.ServiceName;

            try
            {
                PublishContext deploySettings = new PublishContext(
                    settings,
                    packagePath,
                    configPath,
                    null,
                    deploymentName,
                    rootPath);
                Assert.True(false, "No exception was thrown");
            }
            catch (Exception ex)
            {
                Assert.True(ex is ArgumentException);
                Assert.True(string.Compare(
                    string.Format(Resources.InvalidOrEmptyArgumentMessage,
                    "serviceName"), ex.Message, true) == 0);
            }
        }
        public void TestDeploymentSettingsTestNullSettingsFail()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;

            try
            {
                PublishContext deploySettings = new PublishContext(
                    null,
                    packagePath,
                    configPath,
                    label,
                    deploymentName,
                    rootPath);
                Assert.True(false, "No exception was thrown");
            }
            catch (Exception ex)
            {
                Assert.True(ex is ArgumentException);
                Assert.Equal<string>(Resources.InvalidServiceSettingMessage, ex.Message);
            }
        }
Esempio n. 22
0
        private void VerifyDeployment(PublishContext context)
        {
            try
            {
                WriteVerboseWithTimestamp(Resources.PublishInitializingMessage);

                var roleInstanceSnapshot = new Dictionary <string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment;
                do
                {
                    deployment = new Deployment(
                        ComputeClient.Deployments.GetBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot)));

                    // The goal of this loop is to output a message whenever the status of a role
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.BusyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.ReadyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.CreatingRole))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!string.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                case RoleInstanceStatus.BusyRole:
                                    statusResource = Resources.PublishInstanceStatusBusy;
                                    break;

                                case RoleInstanceStatus.ReadyRole:
                                    statusResource = Resources.PublishInstanceStatusReady;
                                    break;

                                default:
                                    statusResource = Resources.PublishInstanceStatusCreating;
                                    break;
                                }

                                WriteVerboseWithTimestamp(
                                    Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName,
                                    currentInstance.RoleName,
                                    statusResource);
                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(SleepDuration);
                }while (deployment.RoleInstanceList.Any(r => r.InstanceStatus != RoleInstanceStatus.ReadyRole));

                WriteVerboseWithTimestamp(Resources.PublishCreatedWebsiteMessage, deployment.Url);
            }
            catch (CloudException)
            {
                throw new InvalidOperationException(
                          string.Format(Resources.CannotFindDeployment, context.ServiceName, context.ServiceSettings.Slot));
            }
        }
        private Uri UploadPackage(PublishContext context)
        {
            WriteVerboseWithTimestamp(
                    Resources.PublishUploadingPackageMessage,
                    context.ServiceSettings.StorageServiceName);

            return CloudBlobUtility.UploadPackageToBlob(
                StorageClient,
                context.ServiceSettings.StorageServiceName,
                context.PackagePath,
                new BlobRequestOptions());
        }
        private void PrepareCloudServicePackagesRuntime(PublishContext context)
        {
            CloudServiceProject cloudServiceProject = new CloudServiceProject(context.RootPath, null);
            string warning = cloudServiceProject.ResolveRuntimePackageUrls();

            if (!string.IsNullOrEmpty(warning))
            {
                WriteWarning(Resources.RuntimeMismatchWarning, context.ServiceName);
                WriteWarning(warning);
            }
        }
        private PublishContext CreatePublishContext(
            string name,
            string slot,
            string location,
            string affinityGroup,
            string storageServiceName,
            string deploymentName)
        {
            string serviceName;
            CloudServiceProject cloudServiceProject = GetCurrentServiceProject();

            // If the name provided is different than existing name change it
            if (!string.IsNullOrEmpty(name) && name != cloudServiceProject.ServiceName)
            {
                cloudServiceProject.ChangeServiceName(name, cloudServiceProject.Paths);
            }

            // If there's no storage service provided, try using the default one
            if (string.IsNullOrEmpty(storageServiceName))
            {
                storageServiceName = Subscription.CurrentStorageAccountName;
            }

            // Use default location if not location and affinity group provided
            location = string.IsNullOrEmpty(location) && string.IsNullOrEmpty(affinityGroup) ? 
                GetDefaultLocation() : 
                location;

            ServiceSettings serviceSettings = ServiceSettings.LoadDefault(
                cloudServiceProject.Paths.Settings,
                slot,
                location,
                affinityGroup,
                Subscription.SubscriptionName,
                storageServiceName,
                name,
                cloudServiceProject.ServiceName,
                out serviceName
                );

            PublishContext context = new PublishContext(
                serviceSettings,
                Path.Combine(GetCurrentDirectory(), cloudServiceProject.Paths.CloudPackage),
                Path.Combine(GetCurrentDirectory(), cloudServiceProject.Paths.CloudConfiguration),
                serviceName,
                deploymentName,
                cloudServiceProject.Paths.RootPath);

            return context;
        }
        /// <summary>
        /// Publishes a service project on Windows Azure.
        /// </summary>
        /// <param name="name">The cloud service name</param>
        /// <param name="slot">The deployment slot</param>
        /// <param name="location">The deployment location</param>
        /// <param name="affinityGroup">The deployment affinity group</param>
        /// <param name="storageAccount">The storage account to store the package</param>
        /// <param name="deploymentName">The deployment name</param>
        /// <param name="launch">Launch the service after publishing</param>
        /// <param name="forceUpgrade">force the service upgrade even if this would result in loss of any local data on the vm (for example, changing the vm size)</param>
        /// <returns>The created deployment</returns>
        public Deployment PublishCloudService(
            string name           = null,
            string slot           = null,
            string location       = null,
            string affinityGroup  = null,
            string storageAccount = null,
            string deploymentName = null,
            bool launch           = false,
            bool forceUpgrade     = false)
        {
            // Initialize publish context
            PublishContext context = CreatePublishContext(
                name,
                slot,
                location,
                affinityGroup,
                storageAccount,
                deploymentName);

            WriteVerbose(string.Format(Resources.PublishServiceStartMessage, context.ServiceName));

            // Set package runtime information
            WriteVerboseWithTimestamp(Resources.RuntimeDeploymentStart, context.ServiceName);
            PrepareCloudServicePackagesRuntime(context);

            // Verify storage account exists
            WriteVerboseWithTimestamp(
                Resources.PublishVerifyingStorageMessage,
                context.ServiceSettings.StorageServiceName);

            CreateStorageServiceIfNotExist(
                context.ServiceSettings.StorageServiceName,
                context.ServiceName,
                context.ServiceSettings.Location,
                context.ServiceSettings.AffinityGroup);

            // Update cache worker roles configuration
            WriteVerboseWithTimestamp(
                Resources.PublishPreparingDeploymentMessage,
                context.ServiceName,
                Subscription.SubscriptionId);
            UpdateCacheWorkerRolesCloudConfiguration(context);

            // Create cloud package
            AzureTool.Validate();
            if (File.Exists(context.PackagePath))
            {
                File.Delete(context.PackagePath);
            }
            CloudServiceProject cloudServiceProject = new CloudServiceProject(context.RootPath, null);
            string unused;

            cloudServiceProject.CreatePackage(DevEnv.Cloud, out unused, out unused);

            // Publish cloud service
            WriteVerboseWithTimestamp(Resources.PublishConnectingMessage);
            CreateCloudServiceIfNotExist(
                context.ServiceName,
                affinityGroup: context.ServiceSettings.AffinityGroup,
                location: context.ServiceSettings.Location);

            if (DeploymentExists(context.ServiceName, context.ServiceSettings.Slot))
            {
                // Upgrade the deployment
                UpgradeDeployment(context, forceUpgrade);
            }
            else
            {
                // Create new deployment
                CreateDeployment(context);
            }

            // Get the deployment id and show it.
            WriteVerboseWithTimestamp(Resources.PublishCreatedDeploymentMessage, GetDeploymentId(context));

            // Verify the deployment succeeded by checking that each of the roles are running
            VerifyDeployment(context);

            // Get object of the published deployment
            DeploymentGetResponse deployment = ComputeClient.Deployments.GetBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot));

            if (launch)
            {
                General.LaunchWebPage(deployment.Uri.ToString());
            }

            return(new Deployment(deployment));
        }
        public void TestDeploymentSettingsTestDoesNotConfigPathFail()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;
            string doesNotExistDir = Path.Combine(Directory.GetCurrentDirectory(), "qewindw443298.cscfg");

            try
            {
                PublishContext deploySettings = new PublishContext(
                    settings,
                    packagePath,
                    doesNotExistDir,
                    label,
                    deploymentName,
                    rootPath);
                Assert.True(false, "No exception was thrown");
            }
            catch (Exception ex)
            {
                Assert.True(ex is FileNotFoundException);
                Assert.Equal<string>(string.Format(Resources.PathDoesNotExistForElement, Resources.ServiceConfiguration, doesNotExistDir), ex.Message);
            }
        }
 private Uri UploadPackageIfNeeded(PublishContext context)
 {
     Uri packageUri;
     if (context.PackageIsFromStorageAccount)
     {
         packageUri = new Uri(context.PackagePath);
     }
     else
     {
         packageUri = UploadPackage(context);
     }
     return packageUri;
 }
        public void TestDeploymentSettingsTestWithFullServiceSettings()
        {
            string label = "MyLabel";
            string deploymentName = service.ServiceName;
            ServiceSettings fullSettings = ServiceSettingsTestData.Instance.Data[ServiceSettingsState.Sample1];
            PublishContext deploySettings = new PublishContext(
                fullSettings,
                packagePath,
                configPath,
                label,
                deploymentName,
                rootPath);

            AzureAssert.AreEqualPublishContext(
                fullSettings,
                configPath,
                deploymentName,
                label,
                packagePath,
                "f62b1e05-af8f-4205-8f98-325079adc155",
                deploySettings);
        }
        private void SetupStorageService(PublishContext context)
        {
            WriteVerboseWithTimestamp(
                Resources.PublishVerifyingStorageMessage,
                context.ServiceSettings.StorageServiceName);

            CreateStorageServiceIfNotExist(
                context.ServiceSettings.StorageServiceName,
                context.ServiceName,
                context.ServiceSettings.Location,
                context.ServiceSettings.AffinityGroup);
        }