private void SetErrorStatus(string errorMessage)
        {
            //might not be on UI thread
            if (this.InvokeRequired || _errorMessageForm.InvokeRequired)
            {
                SetErrorStatusDelegate SetErrorStatusCallback = new SetErrorStatusDelegate(SetErrorStatus);
                this.Invoke(SetErrorStatusCallback, new object[] { errorMessage });
            }
            else
            {
                picStatus.Image = (_dpiScaleFactor > 1 ? HighDPIUtils.ScaleByDpi(Resources.ProgressError) : Resources.ProgressError);
                lblStatus.Text  = "Error";
                _deployStatus   = DeploymentStatus.Error;

                if (!String.IsNullOrEmpty(errorMessage) && String.IsNullOrEmpty(_errorMessageForm.ErrorMessage)) //just in case already shown
                {
                    _errorMessageForm.ErrorMessage   = errorMessage;
                    _errorMessageForm.StartPosition  = FormStartPosition.CenterParent;
                    _errorMessageForm.DpiScaleFactor = _dpiScaleFactor;
                    _errorMessageForm.ShowDialog();
                }

                btnStopProcessing.Enabled = false;
                btnClose.Enabled          = true;
                btnClose.Select();
            }
        }
Example #2
0
        public async Task <bool> UpdateDeploymentStatus(int id, DeploymentStatus status)
        {
            var updateSql = "UPDATE deployments SET status = @status WHERE id = @id;";
            var result    = await _connection.ExecuteAsync(updateSql, new { status = (byte)status, id });

            return(result == 1);
        }
Example #3
0
        public async Task StartAsync(IProgress <ProgressEventArgs> progress, CancellationToken ct)
        {
            if (Status == DeploymentStatus.Error)
            {
                progress?.Report(new ProgressEventArgs("Error, deployment not valid"));
                return;
            }

            var targetsTasks =
                Targets
                .AsParallel()
                .Select(async(target) =>
                        await OnEachTarget(progress, target, ct)
                        );

            await Task.WhenAll(targetsTasks).ConfigureAwait(false);

            ct.ThrowIfCancellationRequested();
            if (Targets.Where(x => x.DeploymentState != Database.DatabaseDeploymentState.Success).Count() > 0)
            {
                Status = DeploymentStatus.Error;
            }
            else
            {
                Status = DeploymentStatus.Idle;
            }
        }
        private void HandleDeploymentComplete(object sender, DeploymentCompleteEventArgs e)
        {
            switch (e.DeploymentStatus)
            {
            case DeploymentStatus.Success:
                picStatus.Image = (_dpiScaleFactor > 1 ? HighDPIUtils.ScaleByDpi(Resources.ProgressSuccess) : Resources.ProgressSuccess);
                lblStatus.Text  = "Success";
                _deployStatus   = DeploymentStatus.Success;
                break;

            case DeploymentStatus.Cancel:
                picStatus.Image = (_dpiScaleFactor > 1 ? HighDPIUtils.ScaleByDpi(Resources.ProgressCancel) : Resources.ProgressCancel);
                lblStatus.Text  = "Cancelled";
                _deployStatus   = DeploymentStatus.Cancel;
                break;

            case DeploymentStatus.Error:
                SetErrorStatus(e.ErrorMessage);
                break;

            default:
                break;
            }

            btnStopProcessing.Enabled = false;
            btnClose.Enabled          = true;
            //btnClose.Select();
        }
Example #5
0
 public Deployment(
     Guid id,
     string applicationId,
     string imageRepository,
     string updatePath,
     string currentTag,
     string targetTag,
     DeploymentStatus status,
     DeploymentType type,
     string nameSuffix,
     DateTime creationDateTime,
     DateTime?deploymentDateTime = null,
     string instanceId           = "",
     IReadOnlyDictionary <string, string>?parameters = null
     )
 {
     Id              = id;
     ApplicationId   = applicationId;
     ImageRepository = imageRepository;
     UpdatePath      = updatePath;
     CurrentTag      = currentTag;
     TargetTag       = targetTag;
     Status          = status;
     Type            = type;
     NameSuffix      = nameSuffix;
     InstanceId      = instanceId;
     Parameters      = parameters ?? new Dictionary <string, string>();
 }
Example #6
0
        public async Task <bool> UpdateDeployment(int id, string deploymentLocation, DeploymentStatus status)
        {
            var updateSql = "UPDATE deployments SET status = @status, artifact_location = @deploymentLocation WHERE id = @id;";
            var result    = await _connection.ExecuteAsync(updateSql, new { status = (byte)status, deploymentLocation, id });

            return(result == 1);
        }
        private void Replace_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            string parameter = e.Parameter as string;

            string[] split = parameter.Split('|');

            string status = split[1];

            string buildNum = split[0];

            DeploymentStatus state = (DeploymentStatus)Enum.Parse(typeof(DeploymentStatus), status);

            if (buildNum == "1")
            {
                StubDashboardRepository.BuildOneStatus = state;
            }
            if (buildNum == "2")
            {
                StubDashboardRepository.BuildTwoStatus = state;
            }
            if (buildNum == "3")
            {
                StubDashboardRepository.BuildThreeStatus = state;
            }

            e.Handled = true;
        }
Example #8
0
        public static string ToDisplayString(this DeploymentStatus status)
        {
            switch (status)
            {
            case DeploymentStatus.Success:
            case DeploymentStatus.Fixed:
                return("Successful");

            case DeploymentStatus.TimedOut:
            case DeploymentStatus.TimedOutNew:
                return("Timed Out");

            case DeploymentStatus.FailedNew:
                return("Failed");

            case DeploymentStatus.ManualStep:
                return("at a Manual Step");

            case DeploymentStatus.GuidedFailure:
                return("in Guided Failure Mode");

            default:
                return(status.ToString());
            }
        }
        /// <summary>
        /// Overriden in derived classes and used to ping back to determine the state
        /// </summary>
        /// <param name="state">an object state containing details of the command response</param>
        protected override void Pingback(object state)
        {
            DeploymentStatus status;
            var command = new GetDeploymentStatusCommand(HostedServiceName, ProductionOrStaging)
            {
                SubscriptionId = SubscriptionId,
                Certificate    = ManagementCertificate
            };

            try
            {
                command.Execute();
                status = command.DeploymentStatus;
            }
            catch (WebException webx)
            {
                // put this in if we can't get a reading back from this!!
                status = DeploymentStatus.Unknown;
            }

            if (status != CurrentState && RoleStatusChangeHandler != null)
            {
                RoleStatusChangeHandler(this, new CloudServiceState(CurrentState, status));
            }
            CurrentState = status;
        }
Example #10
0
        Task ReportShutdownInternal(AgentState agentState, DeploymentStatus status)
        {
            Option <IEdgeAgentModule> edgeAgentModule = agentState.SystemModules.EdgeAgent
                                                        .Map(ea => ea as IRuntimeStatusModule)
                                                        .Filter(ea => ea != null)
                                                        .Map(ea => (IEdgeAgentModule)ea.WithRuntimeStatus(ModuleStatus.Unknown))
                                                        .Else(agentState.SystemModules.EdgeAgent);

            Option <IEdgeHubModule> edgeHubModule = agentState.SystemModules.EdgeHub
                                                    .Map(eh => eh as IRuntimeStatusModule)
                                                    .Filter(eh => eh != null)
                                                    .Map(eh => (IEdgeHubModule)eh.WithRuntimeStatus(ModuleStatus.Unknown))
                                                    .Else(agentState.SystemModules.EdgeHub);

            IDictionary <string, IModule> updateUserModules = (agentState.Modules ?? ImmutableDictionary <string, IModule> .Empty)
                                                              .Where(m => m.Key != Constants.EdgeAgentModuleName)
                                                              .Where(m => m.Key != Constants.EdgeHubModuleName)
                                                              .Where(m => m.Value is IRuntimeModule)
                                                              .Select(pair =>
            {
                IModule updatedModule = (pair.Value as IRuntimeModule)?.WithRuntimeStatus(ModuleStatus.Unknown) ?? pair.Value;
                return(new KeyValuePair <string, IModule>(pair.Key, updatedModule));
            })
                                                              .ToDictionary(x => x.Key, x => x.Value);

            var currentState =
                new AgentState(
                    agentState.LastDesiredVersion, status, agentState.RuntimeInfo,
                    new SystemModules(edgeAgentModule, edgeHubModule),
                    updateUserModules.ToImmutableDictionary(),
                    agentState.SchemaVersion, this.versionInfo);

            return(this.DiffAndReportAsync(currentState, agentState));
        }
Example #11
0
        public async Task <Exception> ValidateAsync(IProgress <ProgressEventArgs> progress)
        {
            Targets.Select(x => {
                try
                {
                    x.Dispose();
                }
                catch { }
                return(x);
            });
            Targets.Clear();


            if (Sources.Count == 0)
            {
                throw new InvalidOperationException("At least one source needs to be defined.");
            }
            try
            {
                foreach (var source in Sources)
                {
                    if (source.Checked)                 //EBORJA
                    {
                        await source.PopulateTargets(); //Clear and populate

                        foreach (var target in source.Targets)
                        {
                            target.DeploymentStatusMessage = "";
                            //await target.TryConnect(CancellationToken.None);
                            Targets.Add(target);
                        }
                    }
                }

                if (Targets == null || Targets.Count == 0)
                {
                    throw new InvalidOperationException("Cannot start deployment without target.");
                }

                foreach (var scriptFile in ScriptFiles)
                {
                    if (!scriptFile.IsValid)
                    {
                        throw new SqlScriptFileException(scriptFile.ScriptErrors);
                    }
                }
            }
            catch (Exception ex)
            {
                Status = DeploymentStatus.Error;
                progress?.Report(new ProgressEventArgs(ex));
                return(ex);
            }
            await Task.Delay(100);

            progress?.Report(new ProgressEventArgs("Deployment validated!"));

            return(null);
        }
Example #12
0
 public DeviceDeploymentStatusServiceModel(string deviceId, DeploymentStatus deploymentStatus, Dictionary <string, JValue> reportedProperties)
 {
     this.Name             = deviceId;
     this.DeploymentStatus = deploymentStatus.ToString();
     this.Firmware         = reportedProperties.ContainsKey("firmware.currentFwVersion") ? reportedProperties["firmware.currentFwVersion"].Value <string>() : string.Empty;
     this.Start            = reportedProperties.ContainsKey("firmware.lastFwUpdateStartTime") ? DateTimeHelper.FormatDate(reportedProperties["firmware.lastFwUpdateStartTime"], DateFormat) : string.Empty;
     this.End = reportedProperties.ContainsKey("firmware.lastFwUpdateEndTime") ? DateTimeHelper.FormatDate(reportedProperties["firmware.lastFwUpdateEndTime"], DateFormat) : string.Empty;
 }
        public void ShouldCalculateSuccessfulWhenAllStepsAreSuccessful()
        {
            var deployStatus = new DeploymentStatus();

            deployStatus.Add(new DeploymentStepStatus {
                Status = DeploymentStepStatus.Ok
            });
            Assert.That(deployStatus.Status, Is.EqualTo("Successful"));
        }
Example #14
0
        public async Task <bool> UpdateDeployment(int id, string deploymentLocation, DeploymentStatus status)
        {
            await using var dataContext = await _dataContextFactory.Construct();

            var dataBridge = dataContext.GetDeploymentDataBridge();
            var result     = await dataBridge.UpdateDeployment(id, deploymentLocation, status);

            return(result);
        }
Example #15
0
        public async Task ReportShutdown(DeploymentStatus status, CancellationToken token)
        {
            using (await this.sync.LockAsync(token))
            {
                Preconditions.CheckNotNull(status, nameof(status));
                Option <AgentState> agentState = await this.GetReportedStateAsync();

                await agentState.ForEachAsync(state => this.ReportShutdownInternal(state, status));
            }
        }
Example #16
0
        private static void WaitForDeploymentStatus(
            DeploymentStatus deploymentStatus,
            InstanceStatus instanceStatus,
            string subscriptionId,
            string serviceName,
            DeploymentSlot deploymentSlot,
            X509Certificate2 managementCertificate,
            bool mostIsGoodEnough)
        {
            // assume we haven't matched the desired status
            bool statusMatches = false;

            do
            {
                // sleep for a bit...
                Thread.Sleep(TimeSpan.FromSeconds(5));
                WriteStatus(".");

                // get the current status
                FullDeploymentStatus current = Utilities.GetDeploymentSlotStatus(
                    subscriptionId,
                    serviceName,
                    deploymentSlot,
                    managementCertificate);

                // if the main status matches
                if (current.MainStatus == deploymentStatus)
                {
                    // good so far...
                    statusMatches = true;
                    int countMatch = 0;

                    // see if all instance status's also match
                    foreach (InstanceDetails instance in current.Instances)
                    {
                        if (instance.Status != instanceStatus)
                        {
                            // we have a bad apple
                            statusMatches = false;
                        }
                        else
                        {
                            countMatch++;
                        }
                    }

                    if (mostIsGoodEnough && ((double)countMatch / current.Instances.Count) >= 0.8)
                    {
                        statusMatches = true;
                    }
                }
            }while (!statusMatches);

            WriteStatusLine(string.Format(" {0}", deploymentStatus));
        }
 internal DeployedServicePackage(
     string serviceManifestName,
     string servicePackageActivationId,
     string serviceManifestVersion,
     DeploymentStatus deploymentStatus)
 {
     this.ServiceManifestName          = serviceManifestName;
     this.ServicePackageActivationId   = servicePackageActivationId;
     this.ServiceManifestVersion       = serviceManifestVersion;
     this.DeployedServicePackageStatus = deploymentStatus;
 }
        public void ShouldCalculateWarningWhenOneStepHasWarning()
        {
            var deployStatus = new DeploymentStatus();

            deployStatus.Add(new DeploymentStepStatus {
                Status = DeploymentStepStatus.Ok
            });
            deployStatus.Add(new DeploymentStepStatus {
                Status = DeploymentStepStatus.Warning
            });
            Assert.That(deployStatus.Status, Is.EqualTo("Warning"));
        }
Example #19
0
        private async Task <DeploymentStatus> WaitForDeployment(RestAPIClient restApiClient, string sessionId)
        {
            // Do an initial delay to avoid a race condition of the status being checked before the deployment has kicked off.
            await Task.Delay(TimeSpan.FromSeconds(3));

            await WaitUntilHelper.WaitUntil(async() =>
            {
                DeploymentStatus status = (await restApiClient.GetDeploymentStatusAsync(sessionId)).Status;;
                return(status != DeploymentStatus.Executing);
            }, TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(15));

            return((await restApiClient.GetDeploymentStatusAsync(sessionId)).Status);
        }
        public void CanDeserialize()
        {
            var expected = new DeploymentStatus
            {
                Id      = 1,
                Url     = "https://api.github.com/repos/octocat/example/deployments/1/statuses/42",
                State   = DeploymentState.Success,
                Payload = new Dictionary <string, string> {
                    { "environment", "production" }
                },
                TargetUrl   = "https://gist.github.com/628b2736d379f",
                CreatedAt   = DateTimeOffset.Parse("2012-07-20T01:19:13Z"),
                UpdatedAt   = DateTimeOffset.Parse("2012-07-20T01:19:13Z"),
                Description = "Deploy request from hubot"
            };

            var json =
                @"{
              ""id"": 1,
              ""url"": ""https://api.github.com/repos/octocat/example/deployments/1/statuses/42"",
              ""state"": ""success"",
              ""creator"": {
                ""login"": ""octocat"",
                ""id"": 1,
                ""avatar_url"": ""https://github.com/images/error/octocat_happy.gif"",
                ""gravatar_id"": ""somehexcode"",
                ""url"": ""https://api.github.com/users/octocat"",
                ""html_url"": ""https://github.com/octocat"",
                ""followers_url"": ""https://api.github.com/users/octocat/followers"",
                ""following_url"": ""https://api.github.com/users/octocat/following{/other_user}"",
                ""gists_url"": ""https://api.github.com/users/octocat/gists{/gist_id}"",
                ""starred_url"": ""https://api.github.com/users/octocat/starred{/owner}{/repo}"",
                ""subscriptions_url"": ""https://api.github.com/users/octocat/subscriptions"",
                ""organizations_url"": ""https://api.github.com/users/octocat/orgs"",
                ""repos_url"": ""https://api.github.com/users/octocat/repos"",
                ""events_url"": ""https://api.github.com/users/octocat/events{/privacy}"",
                ""received_events_url"": ""https://api.github.com/users/octocat/received_events"",
                ""type"": ""User"",
                ""site_admin"": false
              },
              ""payload"": { ""environment"":""production""},
              ""target_url"": ""https://gist.github.com/628b2736d379f"",
              ""created_at"": ""2012-07-20T01:19:13Z"",
              ""updated_at"": ""2012-07-20T01:19:13Z"",
              ""description"": ""Deploy request from hubot""
            }";

            var actual = new SimpleJsonSerializer().Deserialize <DeploymentStatus>(json);

            Assert.Equal(expected, actual, new DeploymentStatusEqualityComparer());
        }
Example #21
0
        public DeploymentTarget(
            long deploymentId,
            long hostId,
            DeploymentStatus status = DeploymentStatus.Pending,
            string message          = null)
        {
            Ensure.IsValidId(deploymentId, nameof(deploymentId));
            Ensure.IsValidId(hostId, nameof(hostId));

            DeploymentId = deploymentId;
            HostId       = hostId;
            Status       = status;
            Message      = message;
        }
 public VercelDeploymentsController(
     IAuthorizationService authorizationService,
     IDeploymentService deploymentService,
     DeploymentStatusService deploymentStatusService,
     DeploymentStatus serviceState,
     ILogger <VercelDeploymentsController> logger
     )
 {
     _authorizationService    = authorizationService;
     _deploymentService       = deploymentService;
     _deploymentStatusService = deploymentStatusService;
     _serviceState            = serviceState;
     _logger = logger;
 }
Example #23
0
        public void GetDeploymentStatus_DoesntGetReleaseId_ReturnsUnknown()
        {
            IReleaseRepository releaseRepository = Substitute.For <IReleaseRepository>();
            VstsConfig         vstsConfig        = new VstsConfig();

            releaseRepository.GetReleaseId(Arg.Any <string>(), Arg.Any <string>())
            .Returns((string)null);

            this.sut = new VstsDeploymentExecutor(releaseRepository, vstsConfig);

            DeploymentStatus result = this.sut.GetDeploymentStatus("someService", "someEnvironment", "someVersion");

            Assert.Equal(DeploymentStatus.Unknown, result);
        }
        public void ShouldCalculateFailedWhenOneStepIsFailed()
        {
            var deployStatus = new DeploymentStatus();

            deployStatus.Add(new DeploymentStepStatus {
                Status = DeploymentStepStatus.Ok
            });
            deployStatus.Add(new DeploymentStepStatus {
                Status = DeploymentStepStatus.Warning
            });
            deployStatus.Add(new DeploymentStepStatus {
                Status = DeploymentStepStatus.Fail
            });
            Assert.That(deployStatus.Status, Is.EqualTo("Failed"));
        }
Example #25
0
        public void Deploy(
            ProductManifest productManifest,
            string environment,
            string version = null,
            string branch  = null)
        {
            if (productManifest == null)
            {
                throw new ArgumentNullException(nameof(productManifest));
            }
            if (string.IsNullOrWhiteSpace(environment))
            {
                throw new ArgumentException("parameter cannot be null or whitespace", nameof(environment));
            }

            ProductVersion productVersion = productManifest.Versions.FirstOrDefault(
                v => v.Version == version);

            if (productVersion == null)
            {
                return;
            }

            foreach (Service service in productVersion.Services)
            {
                if (this.StartDeployment(
                        service,
                        environment,
                        branch,
                        productManifest.PrereqEnvironment))
                {
                    if (this.options == null || !this.options.WhatIf)
                    {
                        DeploymentStatus status =
                            this.WaitForDeploymentComplete(service, environment);

                        if (status != DeploymentStatus.Succeeded)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }
 internal DeployedApplication(
     Uri applicationName,
     string applicationTypeName,
     DeploymentStatus deploymentStatus,
     string workDirectory,
     string logDirectory,
     string tempDirectory,
     Health.HealthState healthState)
 {
     this.ApplicationName           = applicationName;
     this.ApplicationTypeName       = applicationTypeName;
     this.DeployedApplicationStatus = deploymentStatus;
     this.WorkDirectory             = workDirectory;
     this.LogDirectory  = logDirectory;
     this.TempDirectory = tempDirectory;
     this.HealthState   = healthState;
 }
Example #27
0
 public AgentState(
     long lastDesiredVersion               = 0,
     DeploymentStatus lastDesiredStatus    = null,
     IRuntimeInfo runtimeInfo              = null,
     SystemModules systemModules           = null,
     IDictionary <string, IModule> modules = null,
     string schemaVersion = "",
     VersionInfo version  = null)
 {
     this.SchemaVersion      = schemaVersion ?? string.Empty;
     this.Version            = version ?? VersionInfo.Empty;
     this.LastDesiredVersion = lastDesiredVersion;
     this.LastDesiredStatus  = lastDesiredStatus ?? DeploymentStatus.Unknown;
     this.RuntimeInfo        = runtimeInfo;
     this.SystemModules      = systemModules ?? new SystemModules(UnknownEdgeAgentModule.Instance, UnknownEdgeHubModule.Instance);
     this.Modules            = modules?.ToImmutableDictionary() ?? ImmutableDictionary <string, IModule> .Empty;
 }
Example #28
0
        public void GivenIHaveADashboardWith(int numberOfBuilds, DeploymentStatus status)
        {
            if (DeploymentSummaryEventArgs == null)
            {
                DeploymentSummaryEventArgs = new DeploymentSummaryEventArgs(new Dictionary <DeploymentStatus, int>
                {
                    { status, numberOfBuilds }
                });
            }
            else
            {
                Dictionary <DeploymentStatus, int> newDic = new Dictionary <DeploymentStatus, int>(DeploymentSummaryEventArgs.Summary as IDictionary <DeploymentStatus, int>);
                newDic.Add(status, numberOfBuilds);

                DeploymentSummaryEventArgs = new DeploymentSummaryEventArgs(newDic);
            }
        }
Example #29
0
        public async Task FinishDeploymentUpdate(
            Guid deploymentId,
            DeploymentStatus finalStatus
            )
        {
            await ChangeDeploymentUpdateStatus(deploymentId, finalStatus);

            // var deploymentsDbSet = _deploymentsDbContextConfigurator.Set<Dao.Deployment>();
            // var deploymentDao = await deploymentsDbSet.FindAsync(deploymentId);
            // var application = _applicationService.GetApplication(deploymentDao.ApplicationId);
            // var imageMap = application.Images.ToDictionary(
            //     x => $"{x.Repository}-{x.TagProperty.Path}"
            // );
            // var image = imageMap[$"{deploymentDao.ImageRepository}-{deploymentDao.UpdatePath}"];
            //
            // // TODO: trigger git refresh instead of explicitly setting the tag
            // await _applicationImageInstanceService.SetCurrentTag(application, image, deploymentDao.InstanceId, deploymentDao.TargetImageTag);
        }
Example #30
0
 public static string GetStatus(DeploymentStatus deploymentStatus)
 {
     switch (deploymentStatus)
     {
         case DeploymentStatus.Unset:
             return "Unset";
         case DeploymentStatus.Delete:
             return "Delete";
         case DeploymentStatus.Start:
             return "Start";
         case DeploymentStatus.Stop:
             return "Stop";
         case DeploymentStatus.Swap:
             return "Swap";
         default:
             return ""; //probably wrong thing to do here, throw exception?
     }
 }
Example #31
0
        public void GetDeploymentStatus_GetsEnvironmentStatus_ReturnsStatus()
        {
            IReleaseRepository releaseRepository = Substitute.For <IReleaseRepository>();
            VstsConfig         vstsConfig        = new VstsConfig();

            releaseRepository.GetReleaseId(Arg.Any <string>(), Arg.Any <string>())
            .Returns("123");
            releaseRepository.GetReleaseEnvironmentId(Arg.Any <string>(), Arg.Any <string>())
            .Returns("123");
            releaseRepository.GetReleaseEnvironmentStatus(Arg.Any <string>(), Arg.Any <string>())
            .Returns(DeploymentStatus.Succeeded);

            this.sut = new VstsDeploymentExecutor(releaseRepository, vstsConfig);

            DeploymentStatus result = this.sut.GetDeploymentStatus(
                "someService", "someEnvironment", "someVersion");

            Assert.Equal(DeploymentStatus.Succeeded, result);
        }
 public CloudServiceState(DeploymentStatus oldState, DeploymentStatus newState)
 {
     OldState = oldState;
     NewState = newState;
 }
        /// <summary>
        /// Updates the deployment log status.
        /// </summary>
        /// <param name="solutionName">Name of the solution.</param>
        /// <param name="version">The version.</param>
        /// <param name="deploymentStatus">The deployment status.</param>
        internal static void UpdateDeploymentLogStatus(string solutionName, string version, DeploymentStatus deploymentStatus)
        {
            if (string.IsNullOrEmpty(solutionName))
            {
                throw new ArgumentNullException("Solution Name cannot be null");
            }

            // Retrieve the connection string from the settings file.
            string conString = Properties.Settings.Default.DeploymentTrackerLocalDBConnectionString;

            try
            {
                UpdateAllSolutionFlagsToNull(solutionName);

                // Open the connection using the connection string.
                using (SqlCeConnection con = new SqlCeConnection(conString))
                {
                    con.Open();
                    using (SqlCeCommand com = new SqlCeCommand("Update BuildsRecordTable set status = @status, islatestversion = @islatestversion  where solutionName = @solutionName and version = @version and lastupdate in (select max(lastupdate) from BuildsRecordTable where solutionName = @solutionName and version = @version)", con))
                    {
                        com.Parameters.AddWithValue("@solutionName", solutionName);
                        com.Parameters.AddWithValue("@status", deploymentStatus);
                        com.Parameters.AddWithValue("@version", version);
                        com.Parameters.AddWithValue("@islatestversion", deploymentStatus == DeploymentStatus.Rollback ? string.Empty : (deploymentStatus == DeploymentStatus.Deployed ? DeploymentStatus.Rollback.ToString() : string.Empty));
                        int rowsupdated = com.ExecuteNonQuery();

                        UpdateSolutionFlagsToNull(solutionName, version);
                    }
                }
            }
            catch (SqlCeException ex)
            {
                ex.WriteToLog();
            }
        }
Example #34
0
        public static string UpdateDeployment(
            string subscriptionId,
            string serviceName,
            string deploymentName,
            DeploymentStatus newStatus,
            X509Certificate2 managementCertificate)
        {
            // Build uri string
            // format:https://management.core.windows.net/<subscription-id>/services/
            //                hostedservices/<service-name>/deployments/<deployment-name>
            var url = string.Format("{0}{1}/services/hostedservices/{2}/deployments/{3}/?comp=status",
                Constants.AzureManagementUrlBase,
                subscriptionId,
                serviceName,
                deploymentName);

            // make request
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            // header info
            request.Method = "POST";
            request.ClientCertificates.Add(managementCertificate);
            request.Headers.Add(Constants.VersionHeader, Constants.VersionTarget);
            request.ContentType = Constants.ContentTypeXml;

            // Build uri string
            StringBuilder blob = new StringBuilder();
            blob.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            blob.Append("<UpdateDeploymentStatus xmlns=\"http://schemas.microsoft.com/windowsazure\">\n");

            switch (newStatus)
            {
                case DeploymentStatus.Running:
                    blob.AppendFormat("<Status>{0}</Status>\n", Constants.StartServiceStatus);
                    break;
                case DeploymentStatus.Suspended:
                    blob.AppendFormat("<Status>{0}</Status>\n", Constants.StopServiceStatus);
                    break;
                default:
                    // do nothing
                    break;
            }

            blob.AppendFormat("<Status>{0}</Status>\n", Constants.StartServiceStatus);
            blob.Append("</UpdateDeploymentStatus>\n");

            // encode request body then put it in a byte array
            byte[] byteArray = Encoding.UTF8.GetBytes(blob.ToString());
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();

            // write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // close the Stream object.
            dataStream.Close();

            // Get the response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // Get the x-ms-requestID
            string requestId = response.GetResponseHeader(Constants.RequestIdHeader);

            // Clean up the streams
            response.Close();

            return requestId;
        }
Example #35
0
        private static void WaitForDeploymentStatus(
            DeploymentStatus deploymentStatus,
            InstanceStatus instanceStatus,
            string subscriptionId,
            string serviceName,
            DeploymentSlot deploymentSlot,
            X509Certificate2 managementCertificate,
            bool mostIsGoodEnough)
        {
            // assume we haven't matched the desired status
            bool statusMatches = false;

            do
            {
                // sleep for a bit...
                Thread.Sleep(TimeSpan.FromSeconds(5));
                WriteStatus(".");

                // get the current status
                FullDeploymentStatus current = Utilities.GetDeploymentSlotStatus(
                    subscriptionId,
                    serviceName,
                    deploymentSlot,
                    managementCertificate);

                // if the main status matches
                if (current.MainStatus == deploymentStatus)
                {
                    // good so far...
                    statusMatches = true;
                    int countMatch = 0;

                    // see if all instance status's also match
                    foreach (InstanceDetails instance in current.Instances)
                    {
                        if (instance.Status != instanceStatus)
                        {
                            // we have a bad apple
                            statusMatches = false;
                        }
                        else
                        {
                            countMatch++;
                        }
                    }

                    if (mostIsGoodEnough && ((double)countMatch / current.Instances.Count) >= 0.8)
                    {
                        statusMatches = true;
                    }
                }
            }
            while (!statusMatches);

            WriteStatusLine(string.Format(" {0}", deploymentStatus));
        }
        /// <summary>
        /// Logs the details into database.
        /// </summary>
        /// <param name="isSuccessful">if set to <c>true</c> [is successful].</param>
        /// <param name="status">The status.</param>
        /// <param name="version">The version.</param>
        /// <param name="environment">The environment.</param>
        private void LogDeploymentDetailsIntoDatabase(bool isSuccessful, DeploymentStatus status, string version, string environment)
        {
            string solutionNameFromPackage = Path.GetFileNameWithoutExtension(txtPackagePath.Text);
            BuildTransactionEntry buildItem = new BuildTransactionEntry
            {
                DeploymentDateTime = DateTime.Now,
                DeploymentNotes = txtDeploymentNotes.Text,
                IsSuccess = isSuccessful,
                SolutionName = string.IsNullOrEmpty(txtSolutionName.Text) ? solutionNameFromPackage : txtSolutionName.Text,
                PerformedBy = string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName),
                Tfslabelused = string.IsNullOrEmpty(txtTFSLabelName.Text) ? Constants.EmptyTFSLabel : txtTFSLabelName.Text,
                Status = status,
                Version= version,
                Environment = environment
            };

            buildItem.SaveThisInDB();
        }