public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); if (Operation == Iis7Operation.Unspecified) { result.AddError("IIS7 Operation has not been specified."); } if (String.IsNullOrEmpty(ServerName)) { result.AddError("IIS7 Server Name has not been specified."); } if (String.IsNullOrEmpty(ApplicationPool)) { result.AddError("IIS7 Application Pool has not been specified."); } IisUtility.CheckForIis7(result); using (var iisManager = ServerManager.OpenRemote(ServerName)) { CheckApplicationPoolExists(iisManager, result); } return(result); }
//http://www.west-wind.com/weblog/posts/4072.aspx public void SetFileSystemRights(string target, string group, FileSystemRights permission, DeploymentResult r) { if (!IsDirectory(target) && !IsFile(target)) { return; } var oldSecurity = Directory.GetAccessControl(target); var newSecurity = new DirectorySecurity(); newSecurity.SetSecurityDescriptorBinaryForm(oldSecurity.GetSecurityDescriptorBinaryForm()); var accessRule = new FileSystemAccessRule(group, permission, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); bool result; newSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out result); if (!result) { r.AddError("Something wrong happened"); } accessRule = new FileSystemAccessRule(group, permission, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); result = false; newSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result); if (!result) { r.AddError("Something wrong happened"); } Directory.SetAccessControl(target, newSecurity); if (result) { r.AddGood("Permissions set for '{0}' on folder '{1}'", group, target); } if (!result) { r.AddError("Something wrong happened"); } }
void ValidateFile(DeploymentResult result, string path) { if (!_path.IsFile(path)) { result.AddError("'{0}' is not an acceptable path. It doesn't appear to be a file.".FormatWith(path)); } }
public static X509Certificate2 FindCertificateBy(string thumbprint, StoreName storeName, StoreLocation storeLocation, PhysicalServer server, DeploymentResult result) { if (string.IsNullOrEmpty(thumbprint)) return null; var certstore = new X509Store(storeName, storeLocation); try { certstore.Open(OpenFlags.ReadOnly); thumbprint = thumbprint.Trim(); thumbprint = thumbprint.Replace(" ", ""); foreach (var cert in certstore.Certificates) { if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase)) { return cert; } } result.AddError("Could not find a certificate with thumbprint '{0}' on '{1}'".FormatWith(thumbprint, server.Name)); return null; } finally { certstore.Close(); } }
public override DeploymentResult Execute() { //http://weblogs.asp.net/avnerk/archive/2007/05/10/granting-user-rights-in-c.aspx var result = new DeploymentResult(); try { var serverName = _server.Name; if (!_server.IsLocal) serverName = "\\\\{0}".FormatWith(_server.Name); LsaUtility.SetRight(serverName, _userAccount, "SeServiceLogonRight"); //using (var lsa = new LsaWrapper()) //{ // lsa.AddPrivileges(_userAccount, "SeServiceLogonRight"); //} LogSecurity("[security][lpo] Grant '{0}' LogOnAsService on '{1}'", _userAccount, _server.Name); } catch (Win32Exception ex) { var sb = new StringBuilder(); sb.AppendFormat("Error while attempting to grant '{0}' the right '{1}'", _userAccount, "SeServiceLogonRight"); result.AddError(sb.ToString(), ex); } return result; }
public static X509Certificate2 FindCertificateBy(string thumbprint, StoreName storeName, StoreLocation storeLocation, PhysicalServer server, DeploymentResult result) { if (string.IsNullOrEmpty(thumbprint)) { return(null); } var certstore = new X509Store(storeName, storeLocation); try { certstore.Open(OpenFlags.ReadOnly); thumbprint = thumbprint.Trim(); thumbprint = thumbprint.Replace(" ", ""); foreach (var cert in certstore.Certificates) { if (string.Equals(cert.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase) || string.Equals(cert.Thumbprint, thumbprint, StringComparison.InvariantCultureIgnoreCase)) { return(cert); } } result.AddError("Could not find a certificate with thumbprint '{0}' on '{1}'".FormatWith(thumbprint, server.Name)); return(null); } finally { certstore.Close(); } }
public DeploymentResult Execute() { var result = new DeploymentResult(); var connOptions = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = true }; var manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", Machine), connOptions); manScope.Connect(); var objectGetOptions = new ObjectGetOptions(); var managementPath = new ManagementPath("Win32_Process"); var processClass = new ManagementClass(manScope, managementPath, objectGetOptions); var inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = Command; var outParams = processClass.InvokeMethod("Create", inParams, null); int returnVal = Convert.ToInt32(outParams["returnValue"]); if (returnVal != 0) { result.AddError(_status[returnVal]); } //TODO: how to tell DK to stop executing? return(result); }
public override DeploymentResult Execute() { //http://weblogs.asp.net/avnerk/archive/2007/05/10/granting-user-rights-in-c.aspx var result = new DeploymentResult(); try { var serverName = _server.Name; if (!_server.IsLocal) { serverName = "\\\\{0}".FormatWith(_server.Name); } LsaUtility.SetRight(serverName, _userAccount, "SeBatchLogonRight"); //using (var lsa = new LsaWrapper(_serverName)) //{ // lsa.AddPrivileges(_userAccount, "SeBatchLogonRight"); //} LogSecurity("[security][lpo] Grant '{0}' LogOnAsBatch on '{1}'", _userAccount, _server.Name); } catch (Win32Exception ex) { var sb = new StringBuilder(); sb.AppendFormat("Error while attempting to grant '{0}' the right '{1}'", _userAccount, "SeBatchLogonRight"); result.AddError(sb.ToString(), ex); } return(result); }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); if (Operation == Iis7Operation.Unspecified) result.AddError("IIS7 Operation has not been specified."); if (String.IsNullOrEmpty(ServerName)) result.AddError("IIS7 Server Name has not been specified."); if (String.IsNullOrEmpty(ApplicationPool)) result.AddError("IIS7 Application Pool has not been specified."); IisUtility.CheckForIis7(result); using (var iisManager = ServerManager.OpenRemote(ServerName)) { CheckApplicationPoolExists(iisManager, result); } return result; }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); result.AddNote(_reason); if(_filesShouldExist.Count > 0) { var tmpDR = new DeploymentResult(); foreach(var filePath in _filesShouldExist) { string actualPath = _path.GetFullPath(filePath); if(!File.Exists(actualPath)) { tmpDR.AddError(" File '{0}' should exist!.".FormatWith(actualPath)); } } result.MergedWith(tmpDR); //errors show up anyway, give some feedback if everything OK. if(!tmpDR.ContainsError()) { result.AddNote(" All {0} files found!".FormatWith(_filesShouldExist.Count)); } } else { result.AddNote(" No Files that should exist."); } if(_directoriesShouldExist.Count > 0) { var tmpDR = new DeploymentResult(); foreach(var dirPath in _directoriesShouldExist) { string actualPath = _path.GetFullPath(dirPath); if(!Directory.Exists(actualPath)) { tmpDR.AddError(" Directory '{0}' should exist".FormatWith(actualPath)); } } result.MergedWith(tmpDR); //errors show up anyway, give some feedback if everything OK. if(!tmpDR.ContainsError()) { result.AddNote(" All {0} directories found!".FormatWith(_directoriesShouldExist.Count)); } } else { result.AddNote(" No Directories that should exist."); } if(_filesShould_NOT_Exist.Count > 0) { var tmpDR = new DeploymentResult(); foreach(var filePath in _filesShould_NOT_Exist) { string actualPath = _path.GetFullPath(filePath); if(File.Exists(actualPath)) { tmpDR.AddError(" File '{0}' should NOT exist!.".FormatWith(actualPath)); } } result.MergedWith(tmpDR); if(!tmpDR.ContainsError()) { result.AddNote(" None of the {0} files exist!".FormatWith(_filesShould_NOT_Exist.Count)); } } else { result.AddNote(" No Files that should NOT exist."); } if(_directoriesShould_NOT_Exist.Count > 0) { var tmpDR = new DeploymentResult(); foreach(var dirPath in _directoriesShould_NOT_Exist) { string actualPath = _path.GetFullPath(dirPath); if(Directory.Exists(actualPath)) { tmpDR.AddError(" Directory '{0}' should NOT exist".FormatWith(actualPath)); } } result.MergedWith(tmpDR); if(!tmpDR.ContainsError()) { result.AddNote(" None of the {0} directories exist!".FormatWith(_directoriesShould_NOT_Exist.Count)); } } else { result.AddNote(" No Directories that should NOT exist."); } if(_shouldAbortOnError && result.ContainsError()) { result.AddAbort(_reason); } return result; }
public override DeploymentResult Execute() { var result = new DeploymentResult(); if (ServiceExists()) { using (var c = new ServiceController(ServiceName, MachineName)) { Logging.Coarse("[svc] Starting service '{0}'", ServiceName); try { c.Start(); LogCoarseGrain("[svc] Waiting up to {0} seconds because Windows can be silly", _timeout.TotalSeconds); c.WaitForStatus(ServiceControllerStatus.Running, _timeout); } catch (InvalidOperationException ex) { result.AddError("The service '{0}' did not start, most likely due to a logon issue.".FormatWith(ServiceName), ex); LogCoarseGrain("The service '{0}' did not start, most likely due to a logon issue.{1}{2}", ServiceName, Environment.NewLine, ex); return result; } catch (TimeoutException) { if (ErrorOnFailure) result.AddError(string.Format("Service '{0}' did not finish starting during the specified timeframe.", ServiceName)); else result.AddAlert("Service '{0}' did not finish starting during the specified timeframe. You will need to manually verify if the service started successfully.", ServiceName); LogCoarseGrain("Service '{0}' did not finish starting during the specified timeframe. You will need to manually verify if the service started successfully.", ServiceName); return result; } } result.AddGood("Started the service '{0}'", ServiceName); } else { if (ErrorOnFailure) result.AddError(string.Format("Service '{0}' does not exist so it cannot be started", ServiceName)); else result.AddAlert("Service '{0}' does not exist so it cannot be started", ServiceName); } return result; }
private void testArchive(DeploymentResult result) { if (!ZipFile.IsZipFile(_zipArchiveFilename)) result.AddError(String.Format("The file '{0}' is not a valid zip archive.", _zipArchiveFilename)); using (var zip = ZipFile.Read(_zipArchiveFilename)) { result.AddGood("{0} items will be extracted from '{1}' to '{2}'", zip.Count, _zipArchiveFilename, _to); } }
public override DeploymentResult Execute() { var result = new DeploymentResult(); ServiceReturnCode returnCode = WmiService.Delete(MachineName, ServiceName); if (ErrorOnFailure && returnCode != ServiceReturnCode.Success) result.AddError(string.Format("Failed to delete service '{0}': {1}", ServiceName, returnCode)); return result; }
protected void ValidateIsDirectory(DeploymentResult result, string path) { if (!(new DirectoryInfo(_path.GetFullPath(path)).Exists)) { result.AddAlert("'{0}' does not exist and will be created.".FormatWith(path)); } if (!_path.IsDirectory(path)) { result.AddError("'{0}' is not a directory.".FormatWith(path)); } }
private void testArchive(DeploymentResult result) { if (!ZipFile.IsZipFile(_zipArchiveFilename)) { result.AddError(String.Format("The file '{0}' is not a valid zip archive.", _zipArchiveFilename)); } using (var zip = ZipFile.Read(_zipArchiveFilename)) { result.AddGood("{0} items will be extracted from '{1}' to '{2}'", zip.Count, _zipArchiveFilename, _to); } }
protected void ValidateIsFile(DeploymentResult result, string path) { if (!(new FileInfo(_path.GetFullPath(path)).Exists)) { result.AddAlert("'{0}' does not exist.".FormatWith(path)); } if (!_path.IsFile(path)) { result.AddError("'{0}' is not a file.".FormatWith(path)); } }
public DeploymentResult Execute() { var result = new DeploymentResult(); var p = Path.Combine(ExecutableIsLocatedAt, Command); ProcessReturnCode returnCode = WmiProcess.Run(Machine, Command, Args, ExecutableIsLocatedAt); //TODO: Get the output file. Parse it out to get ERRORS and other things and add them to the results if (returnCode != ProcessReturnCode.Success) result.AddError(_status[(int)returnCode] + " (" + p + ")"); return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); try { bool value = SQLConfigDataSource((IntPtr) 0, (int) _action, _driver.Value, "SERVER={0}\0DSN={1}\0DESCRIPTION=NewDSN\0DATABASE={2}\0TRUSTED_CONNECTION=YES".FormatWith(_serverName, _dsnName, _databaseName)); result.AddGood("Created DSN"); } catch (Exception ex) { result.AddError("Failed to create DSN", ex); } return result; }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); try { File.GetAttributes(_target); result.AddGood(string.Format("'{0}' exists", _target)); } catch (Exception ex) { result.AddError(string.Format("'{0}' doesn't exist: {1}", _target, ex.Message)); } return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); var p = Path.Combine(ExecutableIsLocatedAt, Command); ProcessReturnCode returnCode = WmiProcess.Run(Machine, Command, Args, ExecutableIsLocatedAt); //TODO: how can I get the output back from the computer? if (returnCode != ProcessReturnCode.Success) { result.AddError(_status[(int)returnCode]); } return(result); }
public DeploymentResult Execute() { var result = new DeploymentResult(); var p = Path.Combine(ExecutableIsLocatedAt, Command); ProcessReturnCode returnCode = WmiProcess.Run(Machine, Command, Args, ExecutableIsLocatedAt); //TODO: Get the output file. Parse it out to get ERRORS and other things and add them to the results if (returnCode != ProcessReturnCode.Success) { result.AddError(_status[(int)returnCode] + " (" + p + ")"); } return(result); }
public override DeploymentResult Execute() { var result = new DeploymentResult(); if (ServiceExists()) { using (var c = new ServiceController(ServiceName, MachineName)) { Logging.Coarse("[svc] Stopping service '{0}'", ServiceName); if (c.CanStop) { int pid = GetProcessId(ServiceName); try { c.Stop(); c.WaitForStatus(ServiceControllerStatus.Stopped, _timeout); LogCoarseGrain("[svc] Service stopped, waiting for process to exit..."); WaitForProcessToDie(result, pid); } catch (TimeoutException) { var error = string.Format("Service '{0}' did not finish stopping during the specified timeframe.", ServiceName); result.AddError(error); LogCoarseGrain(error); } } } if (!result.ContainsError()) { result.AddGood("Stopped Service '{0}'", ServiceName); Logging.Coarse("[svc] Stopped service '{0}'", ServiceName); } } else { if (ErrorOnFailure) result.AddError(string.Format("Service '{0}' does not exist and could not be stopped", ServiceName)); else result.AddAlert("Service '{0}' does not exist and could not be stopped", ServiceName); Logging.Coarse("[svc] Service '{0}' does not exist.", ServiceName); } return result; }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); VerifyInAdministratorRole(result); if (ServiceExists()) { result.AddGood(string.Format("Found service '{0}'", ServiceName)); } else { result.AddError(string.Format("Can't find service '{0}'", ServiceName)); } return(result); }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); ValidateFile(result, _target); if (File.Exists(_target)) { result.AddGood(string.Format("'{0}' exists", _target)); } else { result.AddError(string.Format("'{0}' doesn't exist", _target)); } return(result); }
public DeploymentResult Execute() { var result = new DeploymentResult(); try { bool value = SQLConfigDataSource((IntPtr)0, (int)_action, _driver.Value, "SERVER={0}\0DSN={1}\0DESCRIPTION=NewDSN\0DATABASE={2}\0TRUSTED_CONNECTION=YES".FormatWith(_serverName, _dsnName, _databaseName)); result.AddGood("Created DSN"); } catch (Exception ex) { result.AddError("Failed to create DSN", ex); } return(result); }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); ValidateFile(result, _target); if (File.Exists(_target)) { result.AddGood(string.Format("'{0}' exists", _target)); } else { result.AddError(string.Format("'{0}' doesn't exist", _target)); } return result; }
public void ExecuteLocalTask(DeploymentResult result) { var cert = FindCertificateBy(_thumbprint, _storeName, _storeLocation, _server, result); if (cert == null) { result.AddError("Certificate with thumbprint '{0}' was not found in the '{1}' \\ '{2}' store.".FormatWith(_thumbprint, _storeLocation, _storeName)); return; } foreach (string group in _groups) { AddAccessToPrivateKey(cert, group, FileSystemRights.Read, _storeLocation, _dotNetPath, _server, result); LogSecurity("[security][cert] Granted READ to X509 Certificate's private key to '{0}' for thumbprint '{1}'", group, _thumbprint); } result.AddGood(Name); }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); var to = new DotNetPath().GetFullPath(_to); string toParent = GetRootShare(to); try { using(var context = Authenticator.BeginFileShareAuthentication(toParent, _userName, _password)) { result.AddGood(System.IO.Directory.Exists(to) ? "'{0}' already exists.".FormatWith(to) : Name); } } catch(Exception err) { result.AddError("Failed to access '{0}' as user '{1}'".FormatWith(toParent, _userName), err); } //TODO figure out a good verify step... return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); var to = new DotNetPath().GetFullPath(_to); var toParent = GetRootShare(to); try { using(var context = Authenticator.BeginFileShareAuthentication(toParent, _userName, _password)) { result.AddGood("'{0}' authenticated with {1}.".FormatWith(to, _userName)); } } catch(Exception err) { result.AddError("Failed to access '{0}' as user '{1}'".FormatWith(toParent, _userName), err); } return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); var to = new DotNetPath().GetFullPath(_to); var toParent = GetRootShare(to); try { using (var context = FileShareAuthenticator.BeginFileShareAuthentication(toParent, _userName, _password)) { result.AddGood("'{0}' authenticated with {1}.".FormatWith(to, _userName)); } } catch (Exception err) { result.AddError("Failed to access '{0}' as user '{1}'".FormatWith(toParent, _userName), err); } return(result); }
public DeploymentResult Execute() { var results = new DeploymentResult(); var scriptsPath = Path.GetFullPath(_scriptsLocation); var log = new DeploymentLogger(results); try { if (_dropDatabase) RoundhousEClientApi.Run(log, _instanceName, _databaseType, _databaseName, true, scriptsPath, _environmentName, _useSimpleRecoveryMode); RoundhousEClientApi.Run(log, _instanceName, _databaseType, _databaseName, false, scriptsPath, _environmentName, _useSimpleRecoveryMode); } catch (Exception ex) { results.AddError("An error occured during RoundhousE execution.", ex); } return results; }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); var to = new DotNetPath().GetFullPath(_to); string toParent = GetRootShare(to); try { using (var context = FileShareAuthenticator.BeginFileShareAuthentication(toParent, _userName, _password)) { result.AddGood(System.IO.Directory.Exists(to) ? "'{0}' already exists.".FormatWith(to) : Name); } } catch (Exception err) { result.AddError("Failed to access '{0}' as user '{1}'".FormatWith(toParent, _userName), err); } //TODO figure out a good verify step... return(result); }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); base.VerifyInAdministratorRole(result); if (_server.IsLocal) { var cert = FindCertificateBy(_thumbprint, _storeName, _storeLocation, _server, result); if (cert == null) { result.AddError("Certificate with thumbprint '{0}' was not found in the '{1}' \\ '{2}' store.".FormatWith(_thumbprint, _storeLocation, _storeName)); } } else { result.AddAlert("Cannot verify if '{0}' exists because '{1}' is a remote server".FormatWith(_thumbprint, _server.Name)); } return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); var psi = new ProcessStartInfo(Command, Args); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardOutput = true; if (!string.IsNullOrEmpty(WorkingDirectory)) { psi.WorkingDirectory = WorkingDirectory; } psi.FileName = _path.Combine(WorkingDirectory, Command); string output; try { using (Process p = Process.Start(psi)) { //what to do here? p.WaitForExit(30.Seconds().Milliseconds); output = p.StandardOutput.ReadToEnd(); result.AddNote(output); } result.AddGood("Command Line Executed"); } catch (Win32Exception ex) { result.AddError( "An exception occured while attempting to execute the following remote command. Working Directory:'{0}' Command:'{1}' Args:'{2}'{3}{4}" .FormatWith(WorkingDirectory, Command, Args, Environment.NewLine, ex)); } return(result); }
public DeploymentResult Execute() { var results = new DeploymentResult(); var scriptsPath = Path.GetFullPath(_scriptsLocation); var useSimpleRecovery = _recoveryMode == DatabaseRecoveryMode.Simple ? true : false; try { var connectionString = _connectionInfo.BuildConnectionString(); switch (_roundhouseMode) { case RoundhousEMode.Drop: RoundhousEClientApi.Run(connectionString, scriptsPath, _environmentName, true, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath); break; case RoundhousEMode.Restore: RoundhousEClientApi.Run(connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, true, _restorePath, _restoreTimeout, _restoreCustomOptions, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath); break; case RoundhousEMode.DropCreate: RoundhousEClientApi.Run(connectionString, @".\", _environmentName, true, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath); goto case RoundhousEMode.Normal; case RoundhousEMode.Normal: RoundhousEClientApi.Run(connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath); break; default: goto case RoundhousEMode.Normal; } results.AddGood("[roundhouse] Deployed migrations changes successfully"); } catch (Exception ex) { results.AddError("[roundhouse] An error occured during RoundhousE execution.", ex); } return(results); }
//Reference http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2062983 //Reference http://stackoverflow.com/questions/425688/how-to-set-read-permission-on-the-private-key-file-of-x-509-certificate-from-net protected static void AddAccessToPrivateKey(X509Certificate2 cert, string group, FileSystemRights rights, StoreLocation storeLocation, Path dotNetPath, PhysicalServer server, DeploymentResult result) { var rsa = cert.PrivateKey as RSACryptoServiceProvider; if (rsa == null) { result.AddError("Certificate does not contain a private key that is accessible"); return; } var keyfilepath = FindKeyLocation(storeLocation, dotNetPath); var file = dotNetPath.Combine(keyfilepath, rsa.CspKeyContainerInfo.UniqueKeyContainerName); file = PathConverter.Convert(server, file); dotNetPath.SetFileSystemRights(file, group, rights, result); //var account = new NTAccount(group); //var fs = file.GetAccessControl(); //fs.AddAccessRule(new FileSystemAccessRule(account, rights, AccessControlType.Allow)); //file.SetAccessControl(fs); }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); base.VerifyInAdministratorRole(result); if (_server.IsLocal) { var cert = FindCertificateBy(_thumbprint, _storeName, _storeLocation, _server, result); if (cert == null) { result.AddError("Certificate with thumbprint '{0}' was not found in the '{1}' \\ '{2}' store.".FormatWith(_thumbprint, _storeLocation, _storeName)); } } else { result.AddAlert("Cannot verify if '{0}' exists because '{1}' is a remote server".FormatWith(_thumbprint, _server.Name)); } return(result); }
public override DeploymentResult Execute() { //http://weblogs.asp.net/avnerk/archive/2007/05/10/granting-user-rights-in-c.aspx var result = new DeploymentResult(); try { using (var lsa = new LsaWrapper()) { lsa.AddPrivileges(_userAccount, "SeBatchLogonRight"); } LogSecurity("[security][lpo] Grant '{0}' LogOnAsBatch on '{1}'", _userAccount, _serverName); } catch (Win32Exception ex) { var sb = new StringBuilder(); sb.AppendFormat("Error while attempting to grant '{0}' the right '{1}'", _userAccount, "SeBatchLogonRight"); result.AddError(sb.ToString(), ex); } return result; }
public DeploymentResult Execute() { var results = new DeploymentResult(); var scriptsPath = Path.GetFullPath(_scriptsLocation); var log = new DeploymentLogger(results); try { if (_dropDatabase) { RoundhousEClientApi.Run(log, _instanceName, _databaseType, _databaseName, true, scriptsPath, _environmentName, _useSimpleRecoveryMode); } RoundhousEClientApi.Run(log, _instanceName, _databaseType, _databaseName, false, scriptsPath, _environmentName, _useSimpleRecoveryMode); } catch (Exception ex) { results.AddError("An error occured during RoundhousE execution.", ex); } return(results); }
/// <summary> /// /// </summary> /// <param name="mgr"></param> /// <param name="result"></param> /// <param name="doUpdate">true: do the update; false: just verify it</param> private void ConfigureAuthentication(ServerManager mgr, DeploymentResult result, bool doUpdate) { if (AuthenticationToSet != null && AuthenticationToSet.Count > 0) { Configuration config = mgr.GetApplicationHostConfiguration(); foreach (var item in AuthenticationToSet) { ConfigurationSection section = config.GetSection("system.webServer/security/authentication/" + item.Key, WebsiteName + "/" + VirtualDirectoryPath);// settings.WFSiteName + "/" + settings.WFDirectoryName if (section == null) { result.AddError(String.Format(@"authentication type '{0}' not found!", item.Key)); } else { if (doUpdate) { LogCoarseGrain("[iis7] Setting authentication for application '{0}': '{1}' from '{2}' to '{3}'", VirtualDirectoryPath, item.Key, section["enabled"], item.Value); section["enabled"] = item.Value; } } } } }
public override DeploymentResult Execute() { //http://weblogs.asp.net/avnerk/archive/2007/05/10/granting-user-rights-in-c.aspx var result = new DeploymentResult(); try { using (var lsa = new LsaWrapper()) { lsa.AddPrivileges(_userAccount, "SeServiceLogonRight"); } LogSecurity("[security][lpo] Grant '{0}' LogOnAsService on '{1}'", _userAccount, _serverName); } catch (Win32Exception ex) { var sb = new StringBuilder(); sb.AppendFormat("Error while attempting to grant '{0}' the right '{1}'", _userAccount, "SeServiceLogonRight"); result.AddError(sb.ToString(), ex); } return(result); }
public override DeploymentResult Execute() { var result = new DeploymentResult(); if (ServiceExists()) { using (var c = new ServiceController(ServiceName, MachineName)) { Logging.Coarse("[svc] Starting service '{0}'", ServiceName); try { c.Start(); LogCoarseGrain("[svc] Waiting up to 60 seconds because Windows can be silly"); c.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60)); } catch (InvalidOperationException ex) { result.AddError("The service '{0}' did not start, most likely due to a logon issue.".FormatWith(ServiceName), ex); LogCoarseGrain("The service '{0}' did not start, most likely due to a logon issue.{1}{2}", ServiceName, Environment.NewLine, ex); return(result); } catch (TimeoutException) { result.AddAlert("Service '{0}' did not finish starting during the specified timeframe. You will need to manually verify if the service started successfully.", ServiceName); LogCoarseGrain("Service '{0}' did not finish starting during the specified timeframe. You will need to manually verify if the service started successfully.", ServiceName); return(result); } } result.AddGood("Started the service '{0}'", ServiceName); } else { result.AddAlert("Service '{0}' does not exist so it cannot be started", ServiceName); } return(result); }
void ProcessRemoteQueue(DeploymentResult result) { var message = "Cannot set permissions for the remote queue '{0}' while on server '{1}'.".FormatWith(_address.ActualUri, Environment.MachineName); result.AddError(message); }
public void log_an_error_event_containing(string message, params object[] args) { _results.AddError(message.FormatWith(args)); }
void ValidateFile(DeploymentResult result, string path) { if (!_path.IsFile(path)) result.AddError("'{0}' is not an acceptable path. It doesn't appear to be a file.".FormatWith(path)); }
public override DeploymentResult Execute() { var result = new DeploymentResult(); if (ServiceExists()) { if (!dropkick.Wmi.WmiService.AuthenticationSpecified) { using (var c = new ServiceController(ServiceName, MachineName)) { Logging.Coarse("[svc] Starting service '{0}'", ServiceName); try { c.Start(); LogCoarseGrain("[svc] Waiting up to 60 seconds because Windows can be silly"); c.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60)); } catch (InvalidOperationException ex) { result.AddError("The service '{0}' did not start, most likely due to a logon issue.".FormatWith(ServiceName), ex); LogCoarseGrain("The service '{0}' did not start, most likely due to a logon issue.{1}{2}", ServiceName, Environment.NewLine, ex); return(result); } catch (TimeoutException) { result.AddAlert("Service '{0}' did not finish starting during the specified timeframe. You will need to manually verify if the service started successfully.", ServiceName); LogCoarseGrain("Service '{0}' did not finish starting during the specified timeframe. You will need to manually verify if the service started successfully.", ServiceName); return(result); } } } else { Logging.Coarse("[svc] Starting service '{0}'", ServiceName); if (ServiceIsRunning()) { LogCoarseGrain("[svc] Service '{0}' is already running".FormatWith(ServiceName)); } else { try { var returnCode = dropkick.Wmi.WmiService.Start(MachineName, ServiceName); switch (returnCode) { case Wmi.ServiceReturnCode.Success: if (!ServiceIsRunning()) { result.AddError("Failed to start service '{0}', most likely due to a logon issue.".FormatWith(ServiceName)); LogCoarseGrain("The service '{0}' did not start, most likely due to a logon issue.", ServiceName); break; } else { //good! } break; default: result.AddError("Failed to start service '{0}', most likely due to a logon issue, result: {1}".FormatWith(ServiceName, returnCode)); LogCoarseGrain("The service '{0}' did not start, most likely due to a logon issue.", ServiceName); break; } } catch (Exception ex) { result.AddError("The service '{0}' did not start, most likely due to a logon issue.".FormatWith(ServiceName), ex); LogCoarseGrain("The service '{0}' did not start, most likely due to a logon issue.{1}{2}", ServiceName, Environment.NewLine, ex); } } } result.AddGood("Started the service '{0}'", ServiceName); } else { result.AddAlert("Service '{0}' does not exist so it cannot be started", ServiceName); } return(result); }
/// <summary> /// /// </summary> /// <param name="mgr"></param> /// <param name="result"></param> /// <param name="doUpdate">true: do the update; false: just verify it</param> private void ConfigureAuthentication(ServerManager mgr, DeploymentResult result, bool doUpdate) { if(AuthenticationToSet != null && AuthenticationToSet.Count > 0) { Configuration config = mgr.GetApplicationHostConfiguration(); foreach(var item in AuthenticationToSet) { ConfigurationSection section = config.GetSection("system.webServer/security/authentication/" + item.Key, WebsiteName + "/" + VirtualDirectoryPath);// settings.WFSiteName + "/" + settings.WFDirectoryName if(section == null) { result.AddError(String.Format(@"authentication type '{0}' not found!", item.Key)); } else { if(doUpdate) { LogCoarseGrain("[iis7] Setting authentication for application '{0}': '{1}' from '{2}' to '{3}'", VirtualDirectoryPath, item.Key, section["enabled"], item.Value); section["enabled"] = item.Value; } } } } }
public DeploymentResult Execute() { var results = new DeploymentResult(); var log = new DeploymentLogger(results); var scriptsPath = Path.GetFullPath(_scriptsLocation); var useSimpleRecovery = _recoveryMode == DatabaseRecoveryMode.Simple ? true : false; try { switch (_roundhouseMode) { case RoundhousEMode.Drop: RoundhousEClientApi.Run(log, _connectionString, scriptsPath, _environmentName, true, useSimpleRecovery,_repositoryPath,_versionFile,_versionXPath); break; case RoundhousEMode.Restore: RoundhousEClientApi.Run(log, _connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, true, _restorePath); break; case RoundhousEMode.DropCreate: RoundhousEClientApi.Run(log, _connectionString, @".\", _environmentName, true, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath); goto case RoundhousEMode.Normal; case RoundhousEMode.Normal: RoundhousEClientApi.Run(log, _connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath); break; default: goto case RoundhousEMode.Normal; } } catch (Exception ex) { results.AddError("An error occured during RoundhousE execution.", ex); } return results; }
public DeploymentResult Execute() { var results = new DeploymentResult(); var scriptsPath = Path.GetFullPath(_scriptsLocation); var useSimpleRecovery = _recoveryMode == DatabaseRecoveryMode.Simple; try { var connectionString = _connectionInfo.BuildConnectionString(); switch (_roundhouseMode) { case RoundhousEMode.Drop: RoundhousEClientApi.Run(connectionString, scriptsPath, _environmentName, true, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath, _alterDatabaseFolderName, _runAfterCreateDatabaseFolderName, _runBeforeUpFolderName, _runFirstAfterUpFolderName, _indexesFolderName, _runAfterOtherAnyTimeScriptsFolderName, _permissionsFolderName); break; case RoundhousEMode.Restore: RoundhousEClientApi.Run(connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, true, _restorePath, _restoreTimeout, _restoreCustomOptions, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath, _alterDatabaseFolderName, _runAfterCreateDatabaseFolderName, _runBeforeUpFolderName, _runFirstAfterUpFolderName, _indexesFolderName, _runAfterOtherAnyTimeScriptsFolderName, _permissionsFolderName); break; case RoundhousEMode.DropCreate: RoundhousEClientApi.Run(connectionString, @".\", _environmentName, true, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath, _alterDatabaseFolderName, _runAfterCreateDatabaseFolderName, _runBeforeUpFolderName, _runFirstAfterUpFolderName, _indexesFolderName, _runAfterOtherAnyTimeScriptsFolderName, _permissionsFolderName); goto case RoundhousEMode.Normal; case RoundhousEMode.Normal: RoundhousEClientApi.Run(connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, _functionsFolderName, _sprocsFolderName, _viewsFolderName, _upFolderName, _versionTable, _scriptsRunTable, _scriptsRunErrorTable, _warnOnOneTimeScriptChanges, _outputPath, _alterDatabaseFolderName, _runAfterCreateDatabaseFolderName, _runBeforeUpFolderName, _runFirstAfterUpFolderName, _indexesFolderName, _runAfterOtherAnyTimeScriptsFolderName, _permissionsFolderName); break; default: goto case RoundhousEMode.Normal; } results.AddGood("[roundhouse] Deployed migrations changes successfully"); } catch (Exception ex) { results.AddError("[roundhouse] An error occured during RoundhousE execution.", ex); } return results; }
public DeploymentResult Execute() { var results = new DeploymentResult(); var scriptsPath = Path.GetFullPath(_scriptsLocation); var useSimpleRecovery = _recoveryMode == DatabaseRecoveryMode.Simple ? true : false; try { switch (_roundhouseMode) { case RoundhousEMode.Drop: RoundhousEClientApi.Run( _connectionString, scriptsPath, _environmentName, true, useSimpleRecovery,_repositoryPath,_versionFile,_versionXPath,_commandTimeout,_commandTimeoutAdmin); break; case RoundhousEMode.Restore: RoundhousEClientApi.Run(_connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin, true, _restorePath,_restoreTimeout,_restoreCustomOptions); break; case RoundhousEMode.DropCreate: RoundhousEClientApi.Run(_connectionString, @".\", _environmentName, true, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin); goto case RoundhousEMode.Normal; case RoundhousEMode.Normal: RoundhousEClientApi.Run(_connectionString, scriptsPath, _environmentName, false, useSimpleRecovery, _repositoryPath, _versionFile, _versionXPath, _commandTimeout, _commandTimeoutAdmin); break; default: goto case RoundhousEMode.Normal; } results.AddGood("[roundhouse] Deployed migrations changes successfully"); } catch (Exception ex) { results.AddError("[roundhouse] An error occured during RoundhousE execution.", ex); } return results; }
public DeploymentResult Execute() { var result = new DeploymentResult(); var p = Path.Combine(ExecutableIsLocatedAt, Command); ProcessReturnCode returnCode = WmiProcess.Run(Machine, Command, Args, ExecutableIsLocatedAt); //TODO: how can I get the output back from the computer? if (returnCode != ProcessReturnCode.Success) { result.AddError(_status[(int)returnCode]); } return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); var connOptions = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = true }; var manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", Machine), connOptions); manScope.Connect(); var objectGetOptions = new ObjectGetOptions(); var managementPath = new ManagementPath("Win32_Process"); var processClass = new ManagementClass(manScope, managementPath, objectGetOptions); var inParams = processClass.GetMethodParameters("Create"); inParams["CommandLine"] = Command; var outParams = processClass.InvokeMethod("Create", inParams, null); int returnVal = Convert.ToInt32(outParams["returnValue"]); if (returnVal != 0) result.AddError(_status[returnVal]); //TODO: how to tell DK to stop executing? return result; }
protected void ValidateIsDirectory(DeploymentResult result, string path) { if (!(new DirectoryInfo(_path.GetFullPath(path)).Exists)) result.AddAlert("'{0}' does not exist and will be created.".FormatWith(path)); if (!_path.IsDirectory(path)) result.AddError("'{0}' is not a directory.".FormatWith(path)); }
protected void ValidateIsFile(DeploymentResult result, string path) { if (!(new FileInfo(_path.GetFullPath(path)).Exists)) result.AddAlert("'{0}' does not exist.".FormatWith(path)); if (!_path.IsFile(path)) result.AddError("'{0}' is not a file.".FormatWith(path)); }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); result.AddNote(_reason); if (_filesShouldExist.Count > 0) { var tmpDR = new DeploymentResult(); foreach (var filePath in _filesShouldExist) { string actualPath = _path.GetFullPath(filePath); if (!File.Exists(actualPath)) { tmpDR.AddError(" File '{0}' should exist!.".FormatWith(actualPath)); } } result.MergedWith(tmpDR); //errors show up anyway, give some feedback if everything OK. if (!tmpDR.ContainsError()) { result.AddNote(" All {0} files found!".FormatWith(_filesShouldExist.Count)); } } else { result.AddNote(" No Files that should exist."); } if (_directoriesShouldExist.Count > 0) { var tmpDR = new DeploymentResult(); foreach (var dirPath in _directoriesShouldExist) { string actualPath = _path.GetFullPath(dirPath); if (!Directory.Exists(actualPath)) { tmpDR.AddError(" Directory '{0}' should exist".FormatWith(actualPath)); } } result.MergedWith(tmpDR); //errors show up anyway, give some feedback if everything OK. if (!tmpDR.ContainsError()) { result.AddNote(" All {0} directories found!".FormatWith(_directoriesShouldExist.Count)); } } else { result.AddNote(" No Directories that should exist."); } if (_filesShould_NOT_Exist.Count > 0) { var tmpDR = new DeploymentResult(); foreach (var filePath in _filesShould_NOT_Exist) { string actualPath = _path.GetFullPath(filePath); if (File.Exists(actualPath)) { tmpDR.AddError(" File '{0}' should NOT exist!.".FormatWith(actualPath)); } } result.MergedWith(tmpDR); if (!tmpDR.ContainsError()) { result.AddNote(" None of the {0} files exist!".FormatWith(_filesShould_NOT_Exist.Count)); } } else { result.AddNote(" No Files that should NOT exist."); } if (_directoriesShould_NOT_Exist.Count > 0) { var tmpDR = new DeploymentResult(); foreach (var dirPath in _directoriesShould_NOT_Exist) { string actualPath = _path.GetFullPath(dirPath); if (Directory.Exists(actualPath)) { tmpDR.AddError(" Directory '{0}' should NOT exist".FormatWith(actualPath)); } } result.MergedWith(tmpDR); if (!tmpDR.ContainsError()) { result.AddNote(" None of the {0} directories exist!".FormatWith(_directoriesShould_NOT_Exist.Count)); } } else { result.AddNote(" No Directories that should NOT exist."); } if (_shouldAbortOnError && result.ContainsError()) { result.AddAbort(_reason); } return(result); }
private XPathNavigator[] GetNodes(DeploymentResult result, XPathNavigator xpathNavigator, string xPath, XmlNamespaceManager nsManager) { var nodes = xpathNavigator.Select(xPath, nsManager).OfType<XPathNavigator>().ToArray(); if (!nodes.Any()) { result.AddError("No nodes found matching XPath: " + xPath); } return nodes; }
public override DeploymentResult Execute() { var result = new DeploymentResult(); _filePath = _path.GetFullPath(_filePath); ValidateIsFile(result, _filePath); UpdateXmlFile(result, _filePath, _replacementItems, _replaceOrInsertItems, _removeItems, _namespacePrefixes); if (result.ContainsError()) result.AddError("Failed to " + Name); else result.AddGood(Name); return result; }