protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var client = new ProGetClient(this.Server, this.FeedName, this.UserName, this.Password, this, context.CancellationToken);

            try
            {
                this.LogInformation($"Pushing package {this.Name} to ProGet...");

                string path = context.ResolvePath(this.FilePath);

                this.LogDebug("Using package file: " + path);

                if (!FileEx.Exists(path))
                {
                    this.LogError(this.FilePath + " does not exist.");
                    return(null);
                }

                if (string.IsNullOrWhiteSpace(this.Name) || string.IsNullOrWhiteSpace(this.Version))
                {
                    try
                    {
                        using (var package = new UniversalPackage(path))
                        {
                            if (string.IsNullOrWhiteSpace(package.Name) || package.Version == null)
                            {
                                this.LogError("Name and Version properties are required unless pushing a package that already has those properties set.");
                                return(null);
                            }
                        }
                    }
                    catch
                    {
                        this.LogError("Name and Version properties are required unless pushing a package that already has those properties set.");
                        return(null);
                    }
                }

                using (var file = FileEx.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new ProGetPackagePushData
                    {
                        Title        = this.Title,
                        Description  = this.Description,
                        Icon         = this.Icon,
                        Dependencies = this.Dependencies?.ToArray()
                    };

                    await client.PushPackageAsync(this.Group, this.Name, this.Version, data, file);
                }
            }
            catch (ProGetException ex)
            {
                this.LogError(ex.FullMessage);
                return(null);
            }

            this.LogInformation("Package pushed.");
            return(null);
        }
Ejemplo n.º 2
0
        private async Task <string> GetMSBuildToolsPath(IRemoteOperationExecutionContext context)
        {
            if (!string.IsNullOrWhiteSpace(this.MSBuildToolsPath))
            {
                this.LogDebug("MSBuildToolsPath: " + this.MSBuildToolsPath);
                return(this.MSBuildToolsPath);
            }

            string path = await this.FindMSBuildPathUsingVSWhereAsync(context).ConfigureAwait(false);

            if (path != null)
            {
                this.LogDebug("MSBuildToolsPath: " + path);
                return(path);
            }

            this.LogDebug("Could not find MSBuildToolsPath using vswhere.exe, falling back to registry...");

            path = this.FindMSBuildUsingRegistry();

            if (path != null)
            {
                this.LogDebug("MSBuildToolsPath: " + path);
                return(path);
            }

            this.LogError(@"Could not determine MSBuildToolsPath value on this server. To resolve this issue, ensure that MSBuild is available on this server (e.g. by installing the Visual Studio Build Tools) and retry the build, or create a server-scoped variable named $MSBuildToolsPath set to the location of the MSBuild tools. For example, the tools included with Visual Studio 2017 could be installed to C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin");
            return(null);
        }
Ejemplo n.º 3
0
        protected override Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            using (var baseKey = RegistryKey.OpenBaseKey(this.Hive, RegistryView.Default))
            {
                using (var key = baseKey.OpenSubKey(this.Key))
                {
                    if (key == null)
                    {
                        this.Log(this.FailIfNotFound ? MessageLevel.Error : MessageLevel.Information, $"Key \"{this.Key}\" not found.");
                        return(Complete);
                    }

                    var value = key.GetValue(this.ValueName);
                    if (value == null)
                    {
                        this.Log(this.FailIfNotFound ? MessageLevel.Error : MessageLevel.Information, $"Value \"{this.ValueName}\" not found in key \"{this.Key}\".");
                        return(Complete);
                    }

                    var kind = key.GetValueKind(this.ValueName);
                    if (kind == RegistryValueKind.MultiString)
                    {
                        this.Value = new RuntimeValue(((string[])value).Select(v => new RuntimeValue(v)).ToList());
                    }
                    else
                    {
                        this.Value = value.ToString();
                    }
                }
            }

            return(Complete);
        }
Ejemplo n.º 4
0
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            this.LogInformation($"Downloading TFS artifact {this.ArtifactName} with build number \"{this.BuildNumber ?? "latest"}\" from TFS...");

            var downloader = new ArtifactDownloader(this, this);

            using (var artifact = await downloader.DownloadAsync(this.TeamProject, this.BuildNumber, this.BuildDefinition, this.ArtifactName).ConfigureAwait(false))
            {
                string targetDirectory = context.ResolvePath(this.TargetDirectory);
                if (this.ExtractFilesToTargetDirectory)
                {
                    this.LogDebug("Extracting artifact files to: " + targetDirectory);
                    AH.ExtractZip(artifact.Content, targetDirectory);
                }
                else
                {
                    string path = PathEx.Combine(targetDirectory, artifact.FileName);
                    this.LogDebug("Saving artifact as zip file to: " + path);

                    using (var file = FileEx.Open(path, FileMode.Create, FileAccess.Write, FileShare.None, FileOptions.Asynchronous | FileOptions.SequentialScan))
                    {
                        await artifact.Content.CopyToAsync(file).ConfigureAwait(false);
                    }
                }
            }

            this.LogInformation("Artifact downloaded.");

            return(null);
        }
Ejemplo n.º 5
0
        private async Task <int> InvokeMSBuildAsync(IRemoteOperationExecutionContext context, string arguments, string workingDirectory)
        {
            var msbuildLoggerPath = Path.Combine(
                Path.GetDirectoryName(typeof(BuildMSBuildProjectOperation).Assembly.Location),
                "BmBuildLogger.dll"
                );

            var allArgs = $"\"/logger:{msbuildLoggerPath}\" /noconsolelogger " + arguments;

            var msBuildPath = await this.GetMSBuildToolsPath(context).ConfigureAwait(false);

            if (msBuildPath == null)
            {
                return(-1);
            }

            msBuildPath = Path.Combine(msBuildPath, "msbuild.exe");

            var startInfo = new RemoteProcessStartInfo
            {
                FileName         = msBuildPath,
                Arguments        = allArgs,
                WorkingDirectory = workingDirectory
            };

            this.LogDebug("Process: " + startInfo.FileName);
            this.LogDebug("Arguments: " + startInfo.Arguments);
            this.LogDebug("Working directory: " + startInfo.WorkingDirectory);

            return(await this.ExecuteCommandLineAsync(context, startInfo).ConfigureAwait(false));
        }
Ejemplo n.º 6
0
        protected override Task RemoteConfigureAsync(IRemoteOperationExecutionContext context)
        {
            using (var baseKey = RegistryKey.OpenBaseKey(this.Template.Hive, RegistryView.Default))
            {
                using (var key = createOrOpenKey())
                {
                    if (key != null)
                    {
                        if (this.Template.Exists)
                        {
                            key.SetValue(this.Template.ValueName, this.GetRegistryValue(), this.Template.ValueKind);
                        }
                        else
                        {
                            key.DeleteValue(this.Template.ValueName, false);
                        }
                    }
                }

                RegistryKey createOrOpenKey()
                {
                    if (this.Template.Exists)
                    {
                        return(baseKey.CreateSubKey(this.Template.Key));
                    }
                    else
                    {
                        return(baseKey.OpenSubKey(this.Template.Key));
                    }
                }
            }

            return(Complete());
        }
Ejemplo n.º 7
0
        protected override Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var sourcePath = context.ResolvePath(this.SourceDirectory);

            this.LogInformation($"Finding matching files in {sourcePath}...");
            if (!DirectoryEx.Exists(sourcePath))
            {
                this.LogError($"Directory {sourcePath} does not exist.");
                return(Complete);
            }

            var mask    = new MaskingContext(this.Includes, this.Excludes);
            var matches = DirectoryEx.GetFileSystemInfos(sourcePath, mask)
                          .OfType <SlimFileInfo>()
                          .Where(f => f.FullName.EndsWith(".sql", StringComparison.OrdinalIgnoreCase))
                          .ToList();

            if (matches.Count == 0)
            {
                this.LogError($"No matching .sql files were found in {sourcePath}.");
                return(Complete);
            }

            var outputFileName = context.ResolvePath(this.OutputFile);

            DirectoryEx.Create(PathEx.GetDirectoryName(outputFileName));

            using (var buffer = new TemporaryStream())
            {
                using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, true))
                {
                    foreach (var f in matches)
                    {
                        var entryName = getEntryName(f.FullName);
                        this.LogDebug($"Adding {entryName}...");
                        zip.CreateEntryFromFile(f.FullName, entryName, CompressionLevel.Optimal);
                    }
                }

                buffer.Position = 0;

                using (var outputStream = FileEx.Open(outputFileName, FileMode.Create, FileAccess.Write, FileShare.None, FileOptions.SequentialScan))
                {
                    using (var inedoSqlStream = typeof(BundleSqlScriptsOperation).Assembly.GetManifestResourceStream("Inedo.Extensions.SqlServer.Operations.inedosql.exe"))
                    {
                        inedoSqlStream.CopyTo(outputStream);
                    }

                    buffer.CopyTo(outputStream);
                }
            }

            this.LogInformation($"{outputFileName} created.");
            return(Complete);

            string getEntryName(string fullName) => fullName.Substring(0, sourcePath.Length).TrimStart('\\', '/').Replace('\\', '/');
        }
Ejemplo n.º 8
0
        protected override Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            this.LogInformation($"Apply label '{this.Label}' to '{this.SourcePath}'...");

            using (var client = new TfsSourceControlClient(this.TeamProjectCollectionUrl, this.UserName, this.PasswordOrToken, this.Domain, this))
            {
                client.ApplyLabel(new TfsSourcePath(this.SourcePath), this.Label, AH.CoalesceString(this.Comment, "Label applied by BuildMaster"));
            }

            this.LogInformation("Label applied.");

            return(Complete);
        }
Ejemplo n.º 9
0
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var projectFullPath = context.ResolvePath(this.ProjectPath);

            this.LogInformation($"Building {projectFullPath}...");

            var buildProperties = string.Join(";", this.MSBuildProperties ?? Enumerable.Empty <string>());

            var config = "Configuration=" + this.BuildConfiguration;

            if (!string.IsNullOrEmpty(this.TargetPlatform))
            {
                config += ";Platform=" + this.TargetPlatform;
            }

            if (!string.IsNullOrEmpty(buildProperties))
            {
                config += ";" + buildProperties;
            }

            var args = $"\"{projectFullPath}\" \"/p:{config}\"";

            if (!string.IsNullOrWhiteSpace(this.TargetDirectory))
            {
                args += $" \"/p:OutDir={context.ResolvePath(this.TargetDirectory).TrimEnd('\\')}\\\\\"";
            }

            if (!string.IsNullOrWhiteSpace(this.AdditionalArguments))
            {
                args += " " + this.AdditionalArguments;
            }

            var workingDir = PathEx.GetDirectoryName(projectFullPath);

            if (!DirectoryEx.Exists(workingDir))
            {
                throw new DirectoryNotFoundException($"Directory {workingDir} does not exist.");
            }

            int result = await this.InvokeMSBuildAsync(context, args, workingDir).ConfigureAwait(false);

            if (result != 0)
            {
                this.LogError($"Build failed (msbuild returned {result}).");
            }

            return(null);
        }
Ejemplo n.º 10
0
        private async Task <string> FindMSBuildPathUsingVSWhereAsync(IRemoteOperationExecutionContext context)
        {
            this.LogDebug("$MSBuildToolsPath variable is not set. Attempting to find the path to the latest version using vswhere.exe...");

            string vsWherePath = PathEx.Combine(
                Path.GetDirectoryName(typeof(BuildMSBuildProjectOperation).Assembly.Location),
                "vswhere.exe"
                );

            string outputFile = Path.GetTempFileName();

            // vswhere.exe documentation: https://github.com/Microsoft/vswhere/wiki
            // component IDs documented here: https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids
            var startInfo = new RemoteProcessStartInfo
            {
                FileName         = vsWherePath,
                WorkingDirectory = Path.GetDirectoryName(vsWherePath),
                Arguments        = @"-products * -nologo -format xml -utf8 -latest -sort -requires Microsoft.Component.MSBuild -find **\MSBuild.exe",
                OutputFileName   = outputFile
            };

            this.LogDebug("Process: " + startInfo.FileName);
            this.LogDebug("Arguments: " + startInfo.Arguments);
            this.LogDebug("Working directory: " + startInfo.WorkingDirectory);

            await this.ExecuteCommandLineAsync(context, startInfo).ConfigureAwait(false);

            var xdoc = XDocument.Load(outputFile);

            var files = from f in xdoc.Root.Descendants("file")
                        let file = f.Value
                                   // prefer 32-bit MSBuild
                                   orderby file.IndexOf("amd64", StringComparison.OrdinalIgnoreCase) > -1 ? 1 : 0
                                   select file;

            var filePath = files.FirstOrDefault();

            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(null);
            }

            return(Path.GetDirectoryName(filePath));
        }
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var client = new ProGetClient(this.Server, this.FeedName, this.UserName, this.Password, this);

            try
            {
                this.LogInformation($"Pushing package {this.Name} to ProGet...");

                string path = context.ResolvePath(this.FilePath);

                this.LogDebug("Using package file: " + path);

                if (!FileEx.Exists(path))
                {
                    this.LogError(this.FilePath + " does not exist.");
                    return(null);
                }

                using (var file = FileEx.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new ProGetPackagePushData
                    {
                        Title        = this.Title,
                        Description  = this.Description,
                        Icon         = this.Icon,
                        Dependencies = this.Dependencies?.ToArray()
                    };

                    await client.PushPackageAsync(this.Group, this.Name, this.Version, data, file).ConfigureAwait(false);
                }
            }
            catch (ProGetException ex)
            {
                this.LogError(ex.FullMessage);
                return(null);
            }

            this.LogInformation("Package pushed.");
            return(null);
        }
Ejemplo n.º 12
0
        protected override Task RemoteConfigureAsync(IRemoteOperationExecutionContext context)
        {
            using (var baseKey = RegistryKey.OpenBaseKey(this.Template.Hive, RegistryView.Default))
            {
                if (this.Template.Exists)
                {
                    using (var key = baseKey.CreateSubKey(this.Template.Key))
                    {
                        if (!string.IsNullOrWhiteSpace(this.Template.DefaultValue))
                        {
                            key.SetValue(null, this.Template.DefaultValue);
                        }
                    }
                }
                else
                {
                    baseKey.DeleteSubKeyTree(this.Template.Key, false);
                }
            }

            return(Complete());
        }
        protected override Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            if (this.ReadOnly ?? this.Hidden ?? this.System == null)
            {
                this.LogWarning("No file attributes have been specified.");
                return(Complete);
            }

            var mask       = new MaskingContext(this.Includes, this.Excludes);
            var sourcePath = context.ResolvePath(this.SourceDirectory);

            this.LogInformation($"Getting list of files in {sourcePath} matching {mask}...");
            var matches = DirectoryEx.GetFileSystemInfos(sourcePath, mask)
                          .OfType <SlimFileInfo>()
                          .ToList();

            if (matches.Count == 0)
            {
                this.LogWarning("No files match the specified mask.");
                return(Complete);
            }

            FileAttributes attributesToChange = 0;

            if (this.ReadOnly.HasValue)
            {
                attributesToChange |= FileAttributes.ReadOnly;
            }
            if (this.Hidden.HasValue)
            {
                attributesToChange |= FileAttributes.Hidden;
            }
            if (this.System.HasValue)
            {
                attributesToChange |= FileAttributes.System;
            }

            FileAttributes attributeValues = 0;

            if (this.ReadOnly.GetValueOrDefault())
            {
                attributeValues |= FileAttributes.ReadOnly;
            }
            if (this.Hidden.GetValueOrDefault())
            {
                attributeValues |= FileAttributes.Hidden;
            }
            if (this.System.GetValueOrDefault())
            {
                attributeValues |= FileAttributes.System;
            }

            if (this.VerboseLogging)
            {
                this.LogDebug("Attributes to change: " + attributesToChange);
                this.LogDebug("Attribute values: " + attributeValues);
            }

            this.LogDebug($"Found {matches.Count} matching files.");
            this.LogInformation("Applying attributes...");
            foreach (var file in matches)
            {
                context.CancellationToken.ThrowIfCancellationRequested();

                var attributes = file.Attributes;

                if (((attributes & attributesToChange) ^ attributeValues) != 0)
                {
                    attributes &= ~attributesToChange;
                    attributes |= attributeValues;
                    if (this.VerboseLogging)
                    {
                        this.LogDebug("Changing " + file.FullName + "...");
                    }
                    FileEx.SetAttributes(file.FullName, attributes);
                }
            }

            this.LogInformation("Attributes applied.");

            return(Complete);
        }
Ejemplo n.º 14
0
        protected override Task RemoteConfigureAsync(IRemoteOperationExecutionContext context)
        {
            if (this.Template == null)
            {
                throw new InvalidOperationException("Template is not set.");
            }

            lock (iisManagerLock)
            {
                using (var manager = new ServerManager())
                {
                    var site = manager.Sites[this.Template.SiteName];
                    if (site == null)
                    {
                        if (this.Template.Exists)
                        {
                            this.LogWarning($"Site \"{this.Template.SiteName}\" does not exist, cannot ensure an application on it.");
                        }
                        return(Complete());
                    }
                    var app = site.Applications[this.Template.ApplicationPath];
                    if (this.Template.Exists)
                    {
                        if (app == null)
                        {
                            this.LogDebug("Does not exist. Creating...");
                            if (!context.Simulation)
                            {
                                app = site.Applications.Add(this.Template.ApplicationPath, this.Template.PhysicalPath);
                                manager.CommitChanges();
                            }

                            this.LogInformation($"Application \"{this.Template.ApplicationPath}\" added.");
                            site = manager.Sites[this.Template.SiteName];
                            app  = site.Applications[this.Template.ApplicationPath];
                        }

                        this.LogDebug("Applying configuration...");
                        if (!context.Simulation)
                        {
                            IisApplicationConfiguration.SetMwaApplication(this, this.Template, app);
                        }
                    }
                    else
                    {
                        if (app == null)
                        {
                            this.LogWarning("Application doesn't exist.");
                            return(Complete());
                        }

                        this.LogDebug("Exists. Deleting...");
                        if (!context.Simulation)
                        {
                            site.Applications.Remove(app);
                        }
                    }

                    this.LogDebug("Committing configuration...");
                    if (!context.Simulation)
                    {
                        manager.CommitChanges();
                    }

                    this.LogInformation($"Application \"{this.Template.ApplicationPath}\" {(this.Template.Exists ? "configured" : "removed")}.");
                }
            }

            return(Complete());
        }
        protected override Task RemoteConfigureAsync(IRemoteOperationExecutionContext context)
        {
            this.LogDebug($"Looking for Site \"{this.Template.Name}\"...");
            using (var manager = new ServerManager())
            {
                var site = manager.Sites[this.Template.Name];
                if (this.Template.Exists)
                {
                    if (!string.IsNullOrWhiteSpace(this.Template.ApplicationPoolName))
                    {
                        if (manager.ApplicationPools[this.Template.ApplicationPoolName] == null)
                        {
                            this.Log(
                                context.Simulation ? MessageLevel.Warning : MessageLevel.Error,
                                $"The specified application pool ({this.Template.ApplicationPoolName}) does not exist."
                                );

                            if (!context.Simulation)
                            {
                                return(Complete());
                            }
                        }
                    }

                    if (site == null)
                    {
                        this.LogDebug("Does not exist. Creating...");
                        if (!context.Simulation)
                        {
                            var templateBinding = this.Template.Bindings?.FirstOrDefault();
                            if (templateBinding == null)
                            {
                                throw new ExecutionFailureException("When creating a new IIS site, at least one binding is required.");
                            }

                            var binding = BindingInfo.FromMap(templateBinding);
                            if (binding == null)
                            {
                                throw new ExecutionFailureException("Binding info could not be parsed. At a minimum, 'IPAddress' and 'Port' must be specified.");
                            }

                            site = manager.Sites.Add(this.Template.Name, this.Template.VirtualDirectoryPhysicalPath, int.Parse(binding.Port));
                            manager.CommitChanges();
                        }

                        this.LogInformation($"Site \"{this.Template.Name}\" added.");
                        this.LogDebug("Reloading configuration...");
                        if (!context.Simulation)
                        {
                            site = manager.Sites[this.Template.Name];
                        }
                    }

                    this.LogDebug("Applying configuration...");
                    if (!context.Simulation)
                    {
                        IisSiteConfiguration.SetMwaSite(this, this.Template, site);
                    }
                }
                else
                {
                    if (site == null)
                    {
                        this.LogWarning("Site does not exist.");
                        return(Complete());
                    }

                    if (!context.Simulation)
                    {
                        manager.Sites.Remove(site);
                    }
                }

                this.LogDebug("Committing configuration...");
                if (!context.Simulation)
                {
                    manager.CommitChanges();
                }

                this.LogInformation($"Site \"{this.Template.Name}\" {(this.Template.Exists ? "configured" : "removed")}.");
            }

            return(Complete());
        }
Ejemplo n.º 16
0
        protected async override Task RemoteConfigureAsync(IRemoteOperationExecutionContext context)
        {
            if (this.Template == null)
            {
                throw new InvalidOperationException("Template is not set.");
            }

            this.LogDebug($"Looking for service \"{this.Template.Name}\"...");

            bool userWasChanged = false;

            using (var service = GetOrCreateService(!context.Simulation))
            {
                if (this.Template.Exists)
                {
                    if (service == null)
                    {
                        // simulation
                        this.LogInformation($"{this.Template.Name} service does not exist.");
                        return;
                    }

                    if (this.Template.DisplayName != null && this.Template.DisplayName != service.DisplayName)
                    {
                        service.DisplayName = this.Template.DisplayName;
                    }

                    if (this.Template.Description != null && this.Template.Description != service.Description)
                    {
                        service.Description = this.Template.Description;
                    }

                    if (this.Template.Path != null && this.Template.Path != service.FileName)
                    {
                        service.FileName = this.Template.Path;
                    }

                    if (this.Template.StartMode != null && this.Template.StartMode != service.StartMode)
                    {
                        service.StartMode = this.Template.StartMode.Value;
                    }

                    if (this.Template.DelayedStart != null && this.Template.DelayedStart != service.DelayedStart)
                    {
                        service.DelayedStart = this.Template.DelayedStart.Value;
                    }

                    if (this.Template.UserAccount != null && this.Template.UserAccount != service.UserAccountName)
                    {
                        userWasChanged = true;
                        service.SetUserAccount(this.Template.UserAccount, this.Template.Password);
                    }

                    if (this.Template.Dependencies != null && !this.Template.Dependencies.ToHashSet().SetEquals(service.Dependencies))
                    {
                        service.SetDependencies(this.Template.Dependencies.ToList());
                    }

                    if (FailureActionsChanged(service))
                    {
                        var timeDelay = this.Template.RestartDelay != null?TimeSpan.FromMinutes(this.Template.RestartDelay.Value) : TimeSpan.Zero;

                        var newFailureActions = new ServiceFailureActions(
                            resetPeriod: this.Template.RestartDelay,
                            rebootMessage: this.Template.RebootMessage,
                            command: this.Template.OnFailureProgramPath,
                            actions: new[]
                        {
                            new ServiceControllerAction(this.Template.OnFirstFailure ?? ServiceControllerActionType.None, timeDelay),
                            new ServiceControllerAction(this.Template.OnSecondFailure ?? ServiceControllerActionType.None, timeDelay),
                            new ServiceControllerAction(this.Template.OnSubsequentFailures ?? ServiceControllerActionType.None, timeDelay)
                        });

                        service.FailureActions = newFailureActions;
                    }

                    if (this.Template.Status != null)
                    {
                        if (!IsPending(this.Template.Status.Value))
                        {
                            await this.EnsureServiceStatusAsync(service.Name, this.Template.Status.Value);
                        }
                        else
                        {
                            this.LogWarning($"Specified service status \"{this.Template.Status.Value}\" is invalid, therefore the service's status will not be modified.");
                        }
                    }
                }
                else
                {
                    if (service == null)
                    {
                        this.LogWarning("Service doesn't exist.");
                        return;
                    }

                    this.LogDebug("Service exists. Stopping before deleting...");
                    await this.EnsureServiceStatusAsync(service.Name, ServiceControllerStatus.Stopped);

                    this.LogDebug($"Deleting {service.Name} service...");
                    service.Delete();
                }
            }

            if (userWasChanged && this.Template.Status == ServiceControllerStatus.Running)
            {
                this.LogDebug("The service user was changed, therefore the service will be restarted.");
                await this.EnsureServiceStatusAsync(this.Template.Name, ServiceControllerStatus.Stopped);

                await this.EnsureServiceStatusAsync(this.Template.Name, ServiceControllerStatus.Running);
            }
        }
Ejemplo n.º 17
0
        protected override Task RemoteConfigureAsync(IRemoteOperationExecutionContext context)
        {
            if (this.Template == null)
            {
                throw new InvalidOperationException("Template is not set.");
            }

            this.LogDebug($"Looking for Application Pool \"{this.Template.Name}\"...");

            lock (syncLock)
            {
                using (var manager = new ServerManager())
                {
                    var pool = manager.ApplicationPools[this.Template.Name];
                    if (this.Template.Exists)
                    {
                        if (pool == null)
                        {
                            this.LogDebug("Does not exist. Creating...");
                            if (!context.Simulation)
                            {
                                pool = manager.ApplicationPools.Add(this.Template.Name);
                                manager.CommitChanges();
                            }

                            this.LogInformation($"Application Pool \"{this.Template.Name}\" added.");
                            this.LogDebug("Reloading configuration...");
                            pool = manager.ApplicationPools[this.Template.Name];
                        }

                        this.LogDebug("Applying configuration...");
                        if (!context.Simulation)
                        {
                            IisAppPoolConfiguration.SetMwaApplicationPool(this, this.Template, pool);
                            manager.CommitChanges();
                        }

                        if (this.Template.Status.HasValue)
                        {
                            this.LogDebug("Reloading configuration...");
                            pool = manager.ApplicationPools[this.Template.Name];

                            if (this.Template.Status.Value == IisObjectState.Started && pool.State == ObjectState.Stopped)
                            {
                                this.LogDebug($"Starting application pool...");
                                if (!context.Simulation)
                                {
                                    pool.Start();
                                }
                            }
                            else if (this.Template.Status.Value == IisObjectState.Stopped && pool.State == ObjectState.Started)
                            {
                                this.LogDebug($"Stopping application pool...");
                                if (!context.Simulation)
                                {
                                    pool.Stop();
                                }
                            }
                            else
                            {
                                this.LogDebug($"State not changed to {this.Template.Status.Value} because state is currently {pool.State}.");
                            }
                        }
                    }
                    else
                    {
                        if (pool == null)
                        {
                            this.LogWarning("Application pool doesn't exist.");
                            return(Complete());
                        }

                        this.LogDebug("Exists. Deleting...");
                        if (!context.Simulation)
                        {
                            manager.ApplicationPools.Remove(pool);
                        }
                    }

                    this.LogDebug("Committing configuration...");
                    if (!context.Simulation)
                    {
                        manager.CommitChanges();
                    }

                    this.LogInformation($"Application Pool \"{this.Template.Name}\" {(this.Template.Exists ? "configured" : "removed")}.");
                }
            }

            return(Complete());
        }
Ejemplo n.º 18
0
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var fullPath = context.ResolvePath(this.FileName);

            this.LogInformation($"Changing \"{fullPath}\" package version to {AH.CoalesceString(this.NewVersion, "remove pre-release label")}...");

            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("n"));

            try
            {
                DirectoryEx.Create(tempPath);
                UniversalPackageMetadata currentMetadata;
                using (var upack = new UniversalPackage(fullPath))
                {
                    currentMetadata = upack.GetFullMetadata();
                    await upack.ExtractAllItemsAsync(tempPath, context.CancellationToken);

                    FileEx.Delete(PathEx.Combine(tempPath, "upack.json"));
                }

                var newMetadata = currentMetadata.Clone();
                if (string.IsNullOrEmpty(this.NewVersion))
                {
                    newMetadata.Version = new UniversalPackageVersion(currentMetadata.Version.Major, currentMetadata.Version.Minor, currentMetadata.Version.Patch);
                }
                else
                {
                    newMetadata.Version = UniversalPackageVersion.Parse(this.NewVersion);
                }

                if (currentMetadata.Version == newMetadata.Version)
                {
                    this.LogWarning($"Current package version {currentMetadata.Version} and the new version {newMetadata.Version} are the same; nothing to do.");
                    return(null);
                }

                this.LogInformation("New version: " + newMetadata.Version);

                this.LogDebug("Adding repacking entry...");
                newMetadata.RepackageHistory.Add(
                    new RepackageHistoryEntry
                {
                    Id     = new UniversalPackageId(currentMetadata.Group, currentMetadata.Name) + ":" + currentMetadata.Version,
                    Date   = DateTimeOffset.Now,
                    Using  = SDK.ProductName + "/" + SDK.ProductVersion,
                    Reason = this.Reason
                }
                    );

                using (var builder = new UniversalPackageBuilder(fullPath, newMetadata))
                {
                    await builder.AddRawContentsAsync(tempPath, string.Empty, true, c => true, context.CancellationToken);
                }

                this.LogInformation("Package version changed.");

                return(null);
            }
            finally
            {
                try
                {
                    this.LogDebug($"Deleting temporary files from {tempPath}...");
                    DirectoryEx.Clear(tempPath);
                    DirectoryEx.Delete(tempPath);
                }
                catch (Exception ex)
                {
                    this.LogWarning("Unable to delete temporary files: " + ex.Message);
                }
            }
        }
Ejemplo n.º 19
0
        protected override async Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
        {
            var packagePath = context.ResolvePath(this.PackagePath);

            this.LogInformation($"Pushing {packagePath} to {this.ServerUrl}...");

            if (!FileEx.Exists(packagePath))
            {
                this.LogError(packagePath + " does not exist.");
                return(null);
            }

            var handler = new HttpClientHandler {
                Proxy = WebRequest.DefaultWebProxy
            };

            if (string.IsNullOrWhiteSpace(this.UserName) || string.IsNullOrEmpty(this.Password))
            {
                this.LogDebug("No credentials specified; sending default credentials.");
                handler.PreAuthenticate       = true;
                handler.UseDefaultCredentials = true;
            }

            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.UserAgent.Clear();
                client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("BuildMaster", typeof(Operation).Assembly.GetName().Version.ToString()));
                client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("NuGet-Extension", typeof(PublishPackageOperation).Assembly.GetName().Version.ToString()));

                if (!string.IsNullOrWhiteSpace(this.ApiKey))
                {
                    this.LogDebug("API key is specified; adding X-NuGet-ApiKey request header.");
                    client.DefaultRequestHeaders.Add("X-NuGet-ApiKey", this.ApiKey);
                }

                if (!string.IsNullOrWhiteSpace(this.UserName) && !string.IsNullOrEmpty(this.Password))
                {
                    this.LogDebug($"Sending basic auth credentials (user={this.UserName}).");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(InedoLib.UTF8Encoding.GetBytes(this.UserName + ":" + this.Password)));
                }

                using (var packageStream = FileEx.Open(packagePath, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan | FileOptions.Asynchronous))
                    using (var contentStream = new StreamContent(packageStream))
                        using (var formData = new MultipartFormDataContent())
                        {
                            contentStream.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                            formData.Add(contentStream, "package", "package");
                            using (var response = await client.PutAsync(this.ServerUrl, formData, context.CancellationToken).ConfigureAwait(false))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    this.LogInformation("Package pushed!");
                                }
                                else
                                {
                                    this.LogError($"Server responded with {(int)response.StatusCode}: {response.ReasonPhrase}");
                                    this.LogError(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
                                }
                            }
                        }
            }

            return(null);
        }
Ejemplo n.º 20
0
 protected override Task <object> RemoteExecuteAsync(IRemoteOperationExecutionContext context)
 {
     this.LogInformation($"Getting source from TFS {(string.IsNullOrEmpty(this.Label) ? "(latest)" : $"labeled '{this.Label}'")}...");