Exemple #1
0
 public static void UpdateWith(this ReferenceCollection collection, IEnumerable <string> ids)
 {
     collection.Clear();
     foreach (var id in ids)
     {
         collection.Add(id);
     }
 }
        /// <summary>
        /// Returns the steps that are to be skipped based on two projects step lists.
        /// This is used when managing octopus from octopus.
        /// YES I KNOW.
        /// </summary>
        /// <param name="projectSteps">All steps from the project.</param>
        /// <param name="referenceProject">All Steps to keep.</param>
        /// <returns>Skipped steps as a ReferenceCollection (ugh)</returns>
        public static ReferenceCollection GetStepsToSkipFromProjects(List <DeploymentTemplateStep> projectSteps, List <DeploymentTemplateStep> referenceProject)
        {
            var skippedSteps = new ReferenceCollection();

            if (!referenceProject.Exists(i => i.ActionName.Equals(ResourceStrings.MetaStepName)))
            {
                var skippedStepList = projectSteps.Where(s => !referenceProject.Any(s2 => s2.ActionName.Equals(s.ActionName, StringComparison.OrdinalIgnoreCase)));
                foreach (var stepToSkip in skippedStepList)
                {
                    skippedSteps.Add(stepToSkip.ActionId);
                }
            }
            return(skippedSteps);
        }
Exemple #3
0
        private async Task <DeploymentResource> CreateDeploymentTask(ProjectResource project, ReleaseResource release, DeploymentPromotionTarget promotionTarget, ReferenceCollection specificMachineIds, TenantResource tenant = null)
        {
            var preview = await Repository.Releases.GetPreview(promotionTarget).ConfigureAwait(false);

            // Validate skipped steps
            var skip = new ReferenceCollection();

            foreach (var step in SkipStepNames)
            {
                var stepToExecute =
                    preview.StepsToExecute.SingleOrDefault(s => string.Equals(s.ActionName, step, StringComparison.CurrentCultureIgnoreCase));
                if (stepToExecute == null)
                {
                    Log.Warning("No step/action named '{Step:l}' could be found when deploying to environment '{Environment:l}', so the step cannot be skipped.", step, promotionTarget.Name);
                }
                else
                {
                    Log.Debug("Skipping step: {Step:l}", stepToExecute.ActionName);
                    skip.Add(stepToExecute.ActionId);
                }
            }

            // Validate form values supplied
            if (preview.Form != null && preview.Form.Elements != null && preview.Form.Values != null)
            {
                foreach (var element in preview.Form.Elements)
                {
                    var variableInput = element.Control as VariableValue;
                    if (variableInput == null)
                    {
                        continue;
                    }

                    var value = variables.Get(variableInput.Label) ?? variables.Get(variableInput.Name);

                    if (string.IsNullOrWhiteSpace(value) && element.IsValueRequired)
                    {
                        throw new ArgumentException("Please provide a variable for the prompted value " + variableInput.Label);
                    }

                    preview.Form.Values[element.Name] = value;
                }
            }

            // Log step with no machines
            foreach (var previewStep in preview.StepsToExecute)
            {
                if (previewStep.HasNoApplicableMachines)
                {
                    Log.Warning("Warning: there are no applicable machines roles used by step {Step:l}", previewStep.ActionName);
                }
            }

            var deployment = await Repository.Deployments.Create(new DeploymentResource
            {
                TenantId                 = tenant?.Id,
                EnvironmentId            = promotionTarget.Id,
                SkipActions              = skip,
                ReleaseId                = release.Id,
                ForcePackageDownload     = ForcePackageDownload,
                UseGuidedFailure         = UseGuidedFailure.GetValueOrDefault(preview.UseGuidedFailureModeByDefault),
                SpecificMachineIds       = specificMachineIds,
                ForcePackageRedeployment = ForcePackageRedeployment,
                FormValues               = (preview.Form ?? new Form()).Values,
                QueueTime                = DeployAt == null ? null : (DateTimeOffset?)DeployAt.Value
            })
                             .ConfigureAwait(false);

            Log.Information("Deploying {Project:l} {Release:} to: {PromotionTarget:l} {Tenant:l}(Guided Failure: {GuidedFailure:l})", project.Name, release.Version, promotionTarget.Name,
                            tenant == null ? string.Empty : $"for {tenant.Name} ",
                            deployment.UseGuidedFailure ? "Enabled" : "Not Enabled");

            return(deployment);
        }
        public void DeployRelease(ProjectResource project, ReleaseResource release, List<string> environments)
        {
            if (environments.Count == 0)
                return;

            var deployments = new List<DeploymentResource>();
            var deploymentTasks = new List<TaskResource>();

            var releaseTemplate = Repository.Releases.GetTemplate(release);

            var promotingEnvironments =
                (from environment in environments.Distinct(StringComparer.CurrentCultureIgnoreCase)
                    let promote = releaseTemplate.PromoteTo.FirstOrDefault(p => string.Equals(p.Name, environment))
                    select new {Name = environment, Promote = promote}).ToList();

            var unknownEnvironments = promotingEnvironments.Where(p => p.Promote == null).ToList();
            if (unknownEnvironments.Count > 0)
            {
                throw new CommandException(
                    string.Format("Release '{0}' of project '{1}' cannot be deployed to {2} not in the list of environments that this release can be deployed to. This may be because a) the environment does not exist, b) the name is misspelled, c) you don't have permission to deploy to this environment, or d) the environment is not in the list of environments defined by the lifecycle.",
                        release.Version,
                        project.Name,
                        unknownEnvironments.Count == 1
                            ? "environment '" + unknownEnvironments[0].Name + "' because the environment is"
                            : "environments " + string.Join(", ", unknownEnvironments.Select(e => "'" + e.Name + "'")) + " because the environments are"
                        ));
            }

            var specificMachineIds = new ReferenceCollection();
            if (SpecificMachineNames.Any())
            {
                var machines = Repository.Machines.FindByNames(SpecificMachineNames);
                var missing = SpecificMachineNames.Except(machines.Select(m => m.Name), StringComparer.OrdinalIgnoreCase).ToList();
                if (missing.Any())
                {
                    throw new CommandException("The following specific machines could not be found: " + missing.ReadableJoin());
                }

                specificMachineIds.AddRange(machines.Select(m => m.Id));
            }

            if (DeployAt != null)
            {
                var now = DateTimeOffset.UtcNow;
                Log.InfoFormat("Deployment will be scheduled to start in: {0}", (DeployAt.Value - now).FriendlyDuration());
            }

            foreach (var environment in promotingEnvironments)
            {
                var promote = environment.Promote;
                var preview = Repository.Releases.GetPreview(promote);

                var skip = new ReferenceCollection();
                foreach (var step in SkipStepNames)
                {
                    var stepToExecute = preview.StepsToExecute.SingleOrDefault(s => string.Equals(s.ActionName, step, StringComparison.CurrentCultureIgnoreCase));
                    if (stepToExecute == null)
                    {
                        Log.WarnFormat("No step/action named '{0}' could be found when deploying to environment '{1}', so the step cannot be skipped.", step, environment);
                    }
                    else
                    {
                        Log.DebugFormat("Skipping step: {0}", stepToExecute.ActionName);
                        skip.Add(stepToExecute.ActionId);
                    }
                }

                if (preview.Form != null && preview.Form.Elements != null && preview.Form.Values != null)
                {
                    foreach (var element in preview.Form.Elements)
                    {
                        var variableInput = element.Control as VariableValue;
                        if (variableInput == null)
                        {
                            continue;
                        }

                        var value = variables.Get(variableInput.Label) ?? variables.Get(variableInput.Name);

                        if (string.IsNullOrWhiteSpace(value) && element.IsValueRequired)
                        {
                            throw new ArgumentException("Please provide a variable for the prompted value " + variableInput.Label);
                        }

                        preview.Form.Values[element.Name] = value;
                    }
                }

                var deployment = Repository.Deployments.Create(new DeploymentResource
                {
                    EnvironmentId = promote.Id,
                    SkipActions = skip,
                    ReleaseId = release.Id,
                    ForcePackageDownload = ForcePackageDownload,
                    UseGuidedFailure = UseGuidedFailure.GetValueOrDefault(preview.UseGuidedFailureModeByDefault),
                    SpecificMachineIds = specificMachineIds,
                    ForcePackageRedeployment = ForcePackageRedeployment,
                    FormValues = (preview.Form ?? new Form()).Values,
                    QueueTime = DeployAt == null ? null : (DateTimeOffset?)DeployAt.Value
                });

                Log.InfoFormat("Deploying {0} {1} to: {2} (Guided Failure: {3})", project.Name, release.Version, environment.Name, deployment.UseGuidedFailure ? "Enabled" : "Not Enabled");

                foreach (var previewStep in preview.StepsToExecute)
                {
                    if (previewStep.HasNoApplicableMachines)
                    {
                        Log.Warn("Warning: there are no applicable machines roles used by step " + previewStep.ActionName + " step");
                    }
                }

                deployments.Add(deployment);
                deploymentTasks.Add(Repository.Tasks.Get(deployment.TaskId));
            }

            if (WaitForDeployment)
            {
                WaitForDeploymentToComplete(deploymentTasks, deployments, project, release);
            }
        }
Exemple #5
0
        private bool ProcessTable()
        {
            if (string.IsNullOrEmpty(txtText.Text.Trim()))
            {
                MessageBox.Show("There are no columns specified!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            txtText.Text.Trim().Replace("\r\n", "\n");
            var lines  = txtText.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var errors = new  List <string>();
            var index  = 1;

            foreach (var line in lines)
            {
                var arr = line.Split(',');
                if (arr.Length == 0)
                {
                    errors.Add("There was an error on line " + index);
                }
                else
                {
                    //Add column
                    var column = ((ModelRoot)_table.Root).Database.Columns.Add();
                    _columnList.Add(column.CreateRef());
                    var tableRef = _table.CreateRef();
                    column.ParentTableRef = tableRef;
                    column.Name           = arr[0].Trim();

                    //Datatype
                    if (arr.Length > 1 && !string.IsNullOrEmpty(arr[1]))
                    {
                        try
                        {
                            column.DataType = (SqlDbType)Enum.Parse(typeof(SqlDbType), arr[1], true);
                        }
                        catch (Exception ex)
                        {
                            errors.Add("There was an error with the datatype on line " + index);
                        }
                    }

                    //Length
                    if (arr.Length > 2 && !string.IsNullOrEmpty(arr[2]))
                    {
                        int l;
                        if (!int.TryParse(arr[2], out l))
                        {
                            errors.Add("There was an error with the length on line " + index);
                        }
                        else
                        {
                            column.Length = l;
                        }
                    }

                    //AllowNull
                    if (arr.Length > 3)
                    {
                        bool b;
                        if (!bool.TryParse(arr[3], out b))
                        {
                            errors.Add("There was an error with allow null on line " + index);
                        }
                        else
                        {
                            column.AllowNull = b;
                        }
                    }
                }
                index++;
            }

            if (errors.Count > 0)
            {
                MessageBox.Show("There were errors.\r\n" + string.Join("\r\n", errors.ToArray()), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(true);
        }
        private async Task<DeploymentResource> CreateDeploymentTask(ProjectResource project, ReleaseResource release, DeploymentPromotionTarget promotionTarget, ReferenceCollection specificMachineIds, TenantResource tenant = null)
        {
            
            var preview = await Repository.Releases.GetPreview(promotionTarget).ConfigureAwait(false);

            // Validate skipped steps
            var skip = new ReferenceCollection();
            foreach (var step in SkipStepNames)
            {
                var stepToExecute =
                    preview.StepsToExecute.SingleOrDefault(s => string.Equals(s.ActionName, step, StringComparison.CurrentCultureIgnoreCase));
                if (stepToExecute == null)
                {
                    Log.Warning("No step/action named '{Step:l}' could be found when deploying to environment '{Environment:l}', so the step cannot be skipped.", step, promotionTarget.Name);
                }
                else
                {
                    Log.Debug("Skipping step: {Step:l}", stepToExecute.ActionName);
                    skip.Add(stepToExecute.ActionId);
                }
            }

            // Validate form values supplied
            if (preview.Form != null && preview.Form.Elements != null && preview.Form.Values != null)
            {
                foreach (var element in preview.Form.Elements)
                {
                    var variableInput = element.Control as VariableValue;
                    if (variableInput == null)
                    {
                        continue;
                    }

                    var value = variables.Get(variableInput.Label) ?? variables.Get(variableInput.Name);

                    if (string.IsNullOrWhiteSpace(value) && element.IsValueRequired)
                    {
                        throw new ArgumentException("Please provide a variable for the prompted value " + variableInput.Label);
                    }

                    preview.Form.Values[element.Name] = value;
                }
            }

            // Log step with no machines
            foreach (var previewStep in preview.StepsToExecute)
            {
                if (previewStep.HasNoApplicableMachines)
                {
                    Log.Warning("Warning: there are no applicable machines roles used by step {Step:l}", previewStep.ActionName);
                }
            }

            var deployment = await Repository.Deployments.Create(new DeploymentResource
            {
                TenantId = tenant?.Id,
                EnvironmentId = promotionTarget.Id,
                SkipActions = skip,
                ReleaseId = release.Id,
                ForcePackageDownload = ForcePackageDownload,
                UseGuidedFailure = UseGuidedFailure.GetValueOrDefault(preview.UseGuidedFailureModeByDefault),
                SpecificMachineIds = specificMachineIds,
                ForcePackageRedeployment = ForcePackageRedeployment,
                FormValues = (preview.Form ?? new Form()).Values,
                QueueTime = DeployAt == null ? null : (DateTimeOffset?) DeployAt.Value
            })
            .ConfigureAwait(false);

            Log.Information("Deploying {Project:l} {Release:} to: {PromotionTarget:l} {Tenant:l}(Guided Failure: {GuidedFailure:l})", project.Name, release.Version, promotionTarget.Name,
                tenant == null ? string.Empty : $"for {tenant.Name} ",
                deployment.UseGuidedFailure ? "Enabled" : "Not Enabled");

            return deployment;
        }
        public void DeployRelease(ProjectResource project, ReleaseResource release, List <string> environments)
        {
            if (environments.Count == 0)
            {
                return;
            }

            var deployments     = new List <DeploymentResource>();
            var deploymentTasks = new List <TaskResource>();

            var releaseTemplate = Repository.Releases.GetTemplate(release);

            var promotingEnvironments =
                (from environment in environments.Distinct(StringComparer.CurrentCultureIgnoreCase)
                 let promote = releaseTemplate.PromoteTo.FirstOrDefault(p => string.Equals(p.Name, environment))
                               select new { Name = environment, Promote = promote }).ToList();

            var unknownEnvironments = promotingEnvironments.Where(p => p.Promote == null).ToList();

            if (unknownEnvironments.Count > 0)
            {
                throw new CommandException(string.Format("Release '{0}' of project '{1}' cannot be deployed to {2} not in the list of environments that this release can be deployed to. This may be because a) the environment does not exist, b) the name is misspelled, c) you don't have permission to deploy to this environment, or d) the environment is not in the list of environments defined by the project group.",
                                                         release.Version,
                                                         project.Name,
                                                         unknownEnvironments.Count == 1 ? "environment '" + unknownEnvironments[0].Name + "' because the environment is"
                    : "environments " + string.Join(", ", unknownEnvironments.Select(e => "'" + e.Name + "'")) + " because the environments are"
                                                         ));
            }

            var specificMachineIds = new ReferenceCollection();

            if (SpecificMachineNames.Any())
            {
                var machines = Repository.Machines.FindByNames(SpecificMachineNames);
                var missing  = SpecificMachineNames.Except(machines.Select(m => m.Name), StringComparer.OrdinalIgnoreCase).ToList();
                if (missing.Any())
                {
                    throw new CommandException("The following specific machines could not be found: " + missing.ReadableJoin());
                }

                specificMachineIds.AddRange(machines.Select(m => m.Id));
            }

            foreach (var environment in promotingEnvironments)
            {
                var promote = environment.Promote;
                var preview = Repository.Releases.GetPreview(promote);

                var skip = new ReferenceCollection();
                foreach (var step in SkipStepNames)
                {
                    var stepToExecute = preview.StepsToExecute.SingleOrDefault(s => string.Equals(s.ActionName, step, StringComparison.CurrentCultureIgnoreCase));
                    if (stepToExecute == null)
                    {
                        Log.WarnFormat("No step/action named '{0}' could be found when deploying to environment '{1}', so the step cannot be skipped.", step, environment);
                    }
                    else
                    {
                        Log.DebugFormat("Skipping step: {0}", stepToExecute.ActionName);
                        skip.Add(stepToExecute.ActionId);
                    }
                }

                var deployment = Repository.Deployments.Create(new DeploymentResource
                {
                    EnvironmentId            = promote.Id,
                    SkipActions              = skip,
                    ReleaseId                = release.Id,
                    ForcePackageDownload     = ForcePackageDownload,
                    UseGuidedFailure         = UseGuidedFailure.GetValueOrDefault(preview.UseGuidedFailureModeByDefault),
                    SpecificMachineIds       = specificMachineIds,
                    ForcePackageRedeployment = ForcePackageRedeployment
                });

                Log.InfoFormat("Deploying {0} {1} to: {2} (Guided Failure: {3})", project.Name, release.Version, environment.Name, deployment.UseGuidedFailure ? "Enabled" : "Not Enabled");

                foreach (var previewStep in preview.StepsToExecute)
                {
                    if (previewStep.HasNoApplicableMachines)
                    {
                        Log.Warn("Warning: there are no applicable machines roles used by step " + previewStep.ActionName + " step");
                    }
                }

                deployments.Add(deployment);
                deploymentTasks.Add(Repository.Tasks.Get(deployment.TaskId));
            }

            if (WaitForDeployment)
            {
                WaitForDeploymentToComplete(deploymentTasks, deployments, project, release);
            }
        }
        public ReferenceReplacer(string text, ref ReferenceCollection references, ReferenceOrder order)
        {
            _usedReferences = new ReferenceCollection();
            _badIds = new HashSet<string>();
            _unknownIds = new HashSet<int>();
            _unknownTags = new HashSet<string>();
            _replacements = new Dictionary<string, Reference[]>();

            var re = new Regex(@"\[\[(([" + RefIdPrefix + @"\d\w\s" + RefDelimiter + @"]+)?)\]\]", RegexOptions.IgnoreCase);

            foreach (Match match in re.Matches(text))
            {
                var refText = match.Groups[0].Captures[0].Value;
                var refList = match.Groups[1].Captures[0].Value;

                if (_replacements.ContainsKey(refText)) continue;

                var parts = refList.Split(new[] {RefDelimiter}, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length < 1)
                {
                    // Replacements with no references supposed to be deleted from document
                    _replacements.Add(refText, null);
                    continue;
                }

                var refs = new HashSet<Reference>();

                foreach (var part in parts.Select(part => part.Trim()).Where(p => p.Length != 0))
                {
                    Reference reference;
                    if (part[0] == '#')
                    {
                        int id;
                        if (!Int32.TryParse(part.Substring(1), NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out id))
                        {
                            _badIds.Add(part);
                            continue;
                        }

                        reference = references.GetById(id);

                        if (reference == null)
                        {
                            _unknownIds.Add(id);
                            continue;
                        }
                    }
                    else
                    {
                        reference = references.GetByTag(part);

                        if (reference == null)
                        {
                            _unknownTags.Add(part);
                            continue;
                        }
                    }

                    refs.Add(reference);
                    if (!_usedReferences.Contains(reference))
                    {
                        _usedReferences.Add(reference);
                    }
                }

                _replacements.Add(refText, refs.ToArray());
            }

            _usedReferences.Sort(order);
            for (var i = 0; i < _usedReferences.Count; i++)
            {
                _usedReferences[i].RefNum = i + 1;
            }
        }