public DeploymentResult Execute() { Thread.Sleep(_waitTime); var result = new DeploymentResult(); result.AddGood("Waited for '{0}' seconds", _waitTime.TotalSeconds.ToString()); return result; }
public void CheckForSiteAndVDirExistance(Func<bool> website, Func<bool> vdir, DeploymentResult result) { if (website()) { result.AddGood("Found Website '{0}'", WebsiteName); if (vdir()) { result.AddGood("Found VDir '{0}'", VdirPath); } else { result.AddAlert("Couldn't find VDir '{0}'", VdirPath); if (ShouldCreate) result.AddAlert("The VDir '{0}' will be created", VdirPath); } } else { result.AddAlert("Couldn't find Website '{0}'", WebsiteName); if (ShouldCreate) result.AddAlert("Website '{0}' and VDir '{1}' will be created", WebsiteName, VdirPath); } }
private void PerformReplacements(DeploymentResult result) { var contents = File.ReadAllText(_filePath, _encoding); foreach (var replacement in _replacements) contents = replacement.Replace(contents, result); File.WriteAllText(_filePath, contents, _encoding); }
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); c.Stop(); c.WaitForStatus(ServiceControllerStatus.Stopped, 30.Seconds()); //WaitForProcessToDie(pid); } } result.AddGood("Stopped Service '{0}'", ServiceName); Logging.Coarse("[svc] Stopped service '{0}'", 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 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 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 DeploymentResult Execute() { var deploymentResult = new DeploymentResult(); bool abort = false; Ex(d => { if(!abort) { var o = d.Verify(); deploymentResult.MergedWith(o); if(deploymentResult.ShouldAbort) { abort = true; } if(o.ContainsError()) { //display errors! DisplayResults(o); //stop. report verify error. return; } var result = d.Execute(); DisplayResults(result); deploymentResult.MergedWith(result); if(deploymentResult.ShouldAbort) { abort = true; } } else { Logging.Coarse(LogLevel.Error, "[Skip ] {0}", d.Name); } }); return deploymentResult; }
protected void CopyDirectory(DeploymentResult result, DirectoryInfo source, DirectoryInfo destination, IEnumerable<Regex> ignoredPatterns) { if (!destination.Exists) { destination.Create(); } else { RemoveReadOnlyAttributes(destination, result); } // Copy all files. FileInfo[] files = source.GetFiles(); foreach (FileInfo file in files.Where(f => !IsIgnored(ignoredPatterns, f))) { string fileDestination = _path.Combine(destination.FullName, file.Name); CopyFileToFile(result, file, new FileInfo(fileDestination)); } // Process subdirectories. DirectoryInfo[] dirs = source.GetDirectories(); foreach (var dir in dirs) { // Get destination directory. string destinationDir = _path.Combine(destination.FullName, dir.Name); // Call CopyDirectory() recursively. CopyDirectory(result, dir, new DirectoryInfo(destinationDir), ignoredPatterns); } }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); VerifyInAdministratorRole(result); if (Environment.MachineName.Equals(_serverName)) { //if(MessageQueue.Exists(path)) //{ // result.AddGood("'{0}' does exist"); //} //else //{ // result.AddAlert(string.Format("'{0}' doesn't exist and will be created", _queueName)); //} result.AddAlert("I can't check queue exstance yet"); } else { result.AddAlert(string.Format("Cannot check for queue '{0}' on server '{1}' while on server '{2}'", _queueName, _serverName, Environment.MachineName)); } return result; }
protected void CopyFile(DeploymentResult result, string newFileName, string from, string to) { if (ExtensionsToString.IsNotEmpty(newFileName)) CopyFileToFile(result, new FileInfo(from), new FileInfo(_path.Combine(to,newFileName))); else CopyFileToDirectory(result, new FileInfo(from), new DirectoryInfo(to)); }
public override DeploymentResult Execute() { var result = new DeploymentResult(); var iisManager = ServerManager.OpenRemote(ServerName); BuildApplicationPool(iisManager, result); if (!DoesSiteExist(result)) CreateWebSite(iisManager, WebsiteName, result); Site site = GetSite(iisManager, WebsiteName); BuildVirtualDirectory(site, iisManager, result); try { iisManager.CommitChanges(); result.AddGood("'{0}' was created/updated successfully.", VirtualDirectoryPath); } catch (COMException ex) { if (ProcessModelIdentityType == ProcessModelIdentityType.SpecificUser) throw new DeploymentException("An exception occurred trying to apply deployment changes. If you are attempting to set the IIS " + "Process Model's identity to a specific user then ensure that you are running DropKick with elevated privileges, or UAC is disabled.", ex); throw; } LogCoarseGrain("[iis7] {0}", Name); return result; }
DeploymentResult Ex(Func<DeploymentDetail, DeploymentResult> action) { Console.WriteLine(Name); var result = new DeploymentResult(); foreach (var role in _roles) { Console.WriteLine(" {0}", role.Name); role.ForEachServer(s => { Console.WriteLine(" {0}", s.Name); s.ForEachDetail(d => { Console.WriteLine(" {0}", d.Name); var r = action(d); result.MergedWith(r); foreach (var item in r.Results) { Console.WriteLine(" [{0}] {1}", item.Status, item.Message); } }); }); } 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 override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); //can I connect to the server? IDbConnection conn = null; try { conn = GetConnection(); conn.Open(); result.AddGood("I can talk to the database"); } catch (Exception) { result.AddAlert("I cannot open the connection"); throw; } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } //can I connect to the database? if (OutputSql != null) result.AddAlert(string.Format("I will run the sql '{0}'", OutputSql)); return result; }
public DeploymentResult Execute() { var result = new DeploymentResult(); ValidatePath(result, _to); ValidatePath(result, _from); _from = Path.GetFullPath(_from); _to = Path.GetFullPath(_to); //todo: verify that from exists if (!Directory.Exists(_to)) { Directory.CreateDirectory(_to); } if (Directory.Exists(_from)) { foreach (string file in Directory.GetFiles(_from)) { //need to support recursion string fileName = Path.GetFileName(file); File.Copy(file, Path.Combine(_to, fileName)); //log file was copied / event? } //what do you want to do if the directory DOESN'T exist? } result.AddGood("Copied stuff"); return result; }
void ProcessLocalQueue(DeploymentResult result) { Logging.Coarse("[msmq] Setting default permissions for on local queue '{0}'", _address.ActualUri); try { var q = new MessageQueue(_address.LocalName); q.SetPermissions(WellKnownRoles.Administrators, MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow); result.AddGood("Successfully set permissions for '{0}' on queue '{1}'".FormatWith(WellKnownRoles.Administrators, _address.LocalName)); q.SetPermissions(WellKnownRoles.CurrentUser, MessageQueueAccessRights.FullControl, AccessControlEntryType.Revoke); result.AddGood("Successfully set permissions for '{0}' on queue '{1}'".FormatWith(WellKnownRoles.Administrators, _address.LocalName)); q.SetPermissions(WellKnownRoles.Everyone, MessageQueueAccessRights.FullControl, AccessControlEntryType.Revoke); result.AddGood("Successfully set permissions for '{0}' on queue '{1}'".FormatWith(WellKnownRoles.Administrators, _address.LocalName)); q.SetPermissions(WellKnownRoles.Anonymous, MessageQueueAccessRights.FullControl, AccessControlEntryType.Revoke); result.AddGood("Successfully set permissions for '{0}' on queue '{1}'".FormatWith(WellKnownRoles.Administrators, _address.LocalName)); } catch (MessageQueueException ex) { if (ex.Message.Contains("does not exist")) { var msg = "The queue '{0}' doesn't exist."; throw new DeploymentException(msg, ex); } throw; } }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); ValidateIsFile(result, _filePath); result.AddGood(Name); return result; }
protected void CopyDirectory(DeploymentResult result, DirectoryInfo source, DirectoryInfo destination) { if (!destination.Exists) { destination.Create(); } // Copy all files. FileInfo[] files = source.GetFiles(); foreach (var file in files) { string fileDestination = _path.Combine(destination.FullName, file.Name); CopyFileToFile(result, file, new FileInfo(fileDestination)); } // Process subdirectories. DirectoryInfo[] dirs = source.GetDirectories(); foreach (var dir in dirs) { // Get destination directory. string destinationDir = _path.Combine(destination.FullName, dir.Name); // Call CopyDirectory() recursively. CopyDirectory(result, dir, new DirectoryInfo(destinationDir)); } }
public override DeploymentResult Execute() { var result = new DeploymentResult(); ServiceReturnCode returnCode = WmiService.Delete(MachineName, ServiceName); return result; }
DeploymentResult ReturnResult() { var dr = new DeploymentResult(); _actions[_status](dr); return dr; }
protected void VerifyRegistryHivePermissions(DeploymentResult result) { if (Hive == RegistryHive.CurrentUser) { result.AddNote("Elevated permissions not required for Registry Hive '{0}'", Hive.AsRegistryHiveString()); return; } }
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)); }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); var to = _path.GetFullPath(_to); //TODO figure out a good verify step... result.AddGood(Directory.Exists(to) ? "'{0}' already exists.".FormatWith(to) : Name); return result; }
public override DeploymentResult Execute() { var result = new DeploymentResult(); ExecuteSqlWithNoReturn("CREATE ROLE [{0}]".FormatWith(_role)); return result; }
public DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); VerifyInAdministratorRole(result); return result; }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); //TODO add meaningful verification return result; }
private void verifyKeyExists(DeploymentResult result) { using (var regHive = OpenHive()) using (var regKey = regHive.OpenSubKey(Key)) { if (regKey == null) result.AddAlert(@"Registry Key '{0}' does not exist and will need to be created.", GetRegistryKeyDisplayString(Hive, Key)); } }
protected static void DeleteDestinationFirst(DirectoryInfo directory, DeploymentResult result) { if (directory.Exists) { directory.Delete(true); result.AddGood("'{0}' was successfully deleted".FormatWith(directory.FullName)); //TODO: a delete list? } }
public override void Because() { VerificationResult = Task.VerifyCanRun(); System.Diagnostics.Debug.WriteLine(VerificationResult); if (VerificationResult.ContainsError()) return; ExecutionResult = Task.Execute(); System.Diagnostics.Debug.WriteLine(ExecutionResult); }
private void UpdateValueInFile(DeploymentResult result, XPathNavigator xpathNavigator, string xPath, string value) { foreach (XPathNavigator navigator in xpathNavigator.Select(xPath)) { string original = navigator.Value; navigator.SetValue(value); LogFileChange("[xmlpoke] Updated '{0}' to {1}'.",original,value); } }
public DeploymentResult VerifyCanRun() { var results = new DeploymentResult(); results.AddNote(Name); if (_connectionInfo.WillPromptForUserName()) { results.AddAlert("We are going to prompt for a username."); } if (_connectionInfo.WillPromptForPassword()) { results.AddAlert("We are going to prompt for a password."); } //check you can connect to the _instancename //check that the path _scriptsLocation exists return(results); }
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"); _coarseLog.InfoFormat("[DSN] Created DSN '{0}'", _dsnName); } catch (Exception ex) { result.AddError("Failed to create DSN", ex); _coarseLog.ErrorFormat("[DSN] Error when creating DSN '{0}'", _dsnName); } return(result); }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); VerifyInAdministratorRole(result); try { using (var c = new ServiceController(ServiceName, MachineName)) { ServiceControllerStatus currentStatus = c.Status; result.AddGood(string.Format("Found service '{0}' it is '{1}'", ServiceName, currentStatus)); } } catch (Exception) { result.AddAlert(string.Format("Can't find service '{0}'", ServiceName)); } 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); }
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 override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); base.TestConnectivity(result); if (ScriptToRun != null) { result.AddAlert(string.Format("I will run the sql script at '{0}'", ScriptToRun)); if (File.Exists(ScriptToRun)) { result.AddGood(string.Format("I found the script '{0}'", ScriptToRun)); } else { result.AddAlert("I can't find '{0}'", ScriptToRun); } } return(result); }
private void RemoveReadOnlyAttributes(DirectoryInfo directory, DeploymentResult result) { try { directory.Attributes = (directory.Attributes & ~FileAttributes.ReadOnly); foreach (var subdirectory in directory.GetDirectories("*", SearchOption.AllDirectories)) { subdirectory.Attributes = (subdirectory.Attributes & ~FileAttributes.ReadOnly); } foreach (var file in directory.GetFiles("*", SearchOption.AllDirectories)) { RemoveReadOnlyAttributes(file, result); } } catch (Exception ex) { result.AddAlert("Had an issue when attempting to remove directory readonly attributes:{0}{1}", Environment.NewLine, ex.ToString()); // LogFineGrain("[copy][attributeremoval][warning] Had an error when attempting to remove directory/file attributes:{0}{1}",Environment.NewLine,ex.ToString()); } }
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); }
private void RemovePackage(Package package) { IAsyncOperationWithProgress <DeploymentResult, DeploymentProgress> deploymentOperation = packageManager.RemovePackageAsync(package.Id.FullName); ManualResetEvent opCompletedEvent = new ManualResetEvent(false); deploymentOperation.Completed = (result, progress) => { Logger.Log("Removal operation {1}: {0}", package.Id.Name, result.Status); if (result.Status == AsyncStatus.Error) { DeploymentResult deploymentResult = deploymentOperation.GetResults(); Logger.Log("Error code: {0}", deploymentOperation.ErrorCode); Logger.Log("Error text: {0}", deploymentResult.ErrorText); } opCompletedEvent.Set(); }; opCompletedEvent.WaitOne(); opCompletedEvent.Dispose(); }
private static DeploymentResult GrantMsmqPermissions(string[] args) { var result = new DeploymentResult(); var perm = args[1]; var user = args[2]; var queue = args[3]; var queueAddress = new QueueAddress(queue); int accessRights; if (int.TryParse(perm, out accessRights)) { return(new LocalMsmqGrantAccessRightsTask(queueAddress, user, (MessageQueueAccessRights)accessRights).Execute()); } switch (perm) { case "r": result = new LocalMsmqGrantReadTask(queueAddress, user).Execute(); break; case "w": result = new MsmqGrantWriteTask(queueAddress, user).Execute(); break; case "rw": result = new LocalMsmqGrantReadWriteTask(queueAddress, user).Execute(); break; case "default": result = new SetSensibleMsmqDefaults(queueAddress).Execute(); break; } return(result); }
//todo: there is quite a bit going on in here...this is going to need to be looked at... private void ExecuteOperation(ApplicationPool appPool, DeploymentResult result) { switch (Operation) { case Iis7Operation.StopApplicationPool: if (appPool == null) { result.AddAlert(ApplicationPoolDoesNotExistError); } else if (appPool.CanBeStopped()) { CheckForElevatedPrivileges(appPool.StopAndWaitForCompletion); result.AddGood("Application Pool '{0}' stopped.".FormatWith(ApplicationPool)); } else { result.AddNote("Application Pool '{0}' is not running.".FormatWith(ApplicationPool)); } break; case Iis7Operation.StartApplicationPool: if (appPool == null) { throw new InvalidOperationException(ApplicationPoolDoesNotExistError); } else if (appPool.CanBeStarted()) { IisUtility.WaitForIisToCompleteAnyOperations(); CheckForElevatedPrivileges(appPool.StartAndWaitForCompletion); result.AddGood("Application Pool '{0}' started.".FormatWith(ApplicationPool)); } else { result.AddGood("Application Pool '{0}' is already running.".FormatWith(ApplicationPool)); } break; } }
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); }
private void CopyFileToFile(DeploymentResult result, FileInfo source, FileInfo destination) { var overwrite = destination.Exists; if (overwrite) { RemoveReadOnlyAttributes(destination, result); } source.CopyTo(destination.FullName, true); string copyLogPrefix = "[copy]"; if (overwrite) { copyLogPrefix = "[copy][overwrite]"; } LogFineGrain("{0} '{1}' -> '{2}'", copyLogPrefix, source.FullName, destination.FullName); //TODO: Adjust for remote pathing _fileLog.Info(destination.FullName); //log where files are modified }
public override DeploymentResult Execute() { var result = new DeploymentResult(); var security = Directory.GetAccessControl(_path); var rules = security.GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule rule in rules) { if (WellKnownSecurityRoles.IsInherited(rule) || WellKnownSecurityRoles.IsPreserved(rule)) { continue; } security.RemoveAccessRuleSpecific(rule); LogSecurity("[security][acl] Removed '{0}' on '{1}'", rule.IdentityReference, _path); result.AddGood("Removed '{0}' on '{1}'", rule.IdentityReference, _path); } Directory.SetAccessControl(_path, security); 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); }
/// <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() { 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); }
public override DeploymentResult VerifyCanRun() { var result = new DeploymentResult(); //can I connect to the server? IDbConnection conn = null; try { conn = GetConnection(); conn.Open(); result.AddGood("I can talk to the database"); } catch (Exception) { result.AddAlert("I cannot open the connection"); throw; } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } //can I connect to the database? if (OutputSql != null) { result.AddAlert(string.Format("I will run the sql '{0}'", OutputSql)); } return(result); }
public void TestConnectivity(DeploymentResult result) { IDbConnection conn = null; try { conn = GetConnection(); conn.Open(); result.AddGood("I can talk to the database"); } catch (Exception) { result.AddAlert("I cannot open the connection"); throw; } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } }
private void RunAssertionRedefDeployOrder(EPServiceProvider epService) { string eplClientA = "" + "create schema InputEvent as (col1 string, col2 string);" + "\n" + "@Name('A') " + "insert into OutOne select col1||col2 as outOneCol from InputEvent;\n" + "\n" + "@Name('B') " + "insert into OutTwo select outOneCol||'x'||outOneCol as finalOut from OutOne;"; DeploymentResult deploymentResultOne = epService.EPAdministrator.DeploymentAdmin.ParseDeploy(eplClientA); string eplClientB = "@Name('C') select * from OutTwo;"; // implicily bound to PN1 DeploymentResult deploymentResultTwo = epService.EPAdministrator.DeploymentAdmin.ParseDeploy(eplClientB); epService.EPAdministrator.DeploymentAdmin.Undeploy(deploymentResultOne.DeploymentId); epService.EPAdministrator.DeploymentAdmin.Undeploy(deploymentResultTwo.DeploymentId); string eplClientC = "" + "create schema InputEvent as (col1 string, col2 string);" + "\n" + "@Name('A') " + "insert into OutOne select col1||col2 as outOneCol from InputEvent;" + "\n" + "@Name('B') " + "insert into OutTwo select col2||col1 as outOneCol from InputEvent;"; epService.EPAdministrator.DeploymentAdmin.ParseDeploy(eplClientC); string eplClientD = "@Name('C') select * from OutOne;" + "@Name('D') select * from OutTwo;"; epService.EPAdministrator.DeploymentAdmin.ParseDeploy(eplClientD); UndeployRemoveAll(epService); }
public override DeploymentResult Execute() { var result = new DeploymentResult(); var iisManager = new ServerManager(); if (DoesSiteExist()) { result.AddGood("'{0}' site exists", WebsiteName); Site site = GetSite(iisManager, WebsiteName); if (!DoesVirtualDirectoryExist(site)) { result.AddAlert("'{0}' doesn't exist. creating.", VdirPath); CreateVirtualDirectory(site); result.AddGood("'{0}' was created", VdirPath); } } iisManager.CommitChanges(); return(result); }
private void RunAssertionComparativeGroupByTopLevelSingleAgg(string caseName, int numEvents, string epl, int numSets) { string[] fields = "c0,c1".Split(','); DeploymentResult deployed = epService.EPAdministrator.DeploymentAdmin.ParseDeploy(epl); epService.EPAdministrator.GetStatement("Listen").AddListener(listener); long deltaLoad = PerformanceObserver.TimeNano( () => { for (int i = 0; i < numEvents; i++) { epService.EPRuntime.SendEvent(new SupportBean("E" + i, i)); } }); long deltaQuery = PerformanceObserver.TimeNano( () => { for (int j = 0; j < numSets; j++) { for (int i = 0; i < numEvents; i++) { string key = "E" + i; epService.EPRuntime.SendEvent(new SupportBean_S0(0, key)); EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { key, i }); } } }); Console.WriteLine(caseName + ": Load " + deltaLoad / 1000000d + " Query " + deltaQuery / 1000000d + " Total " + (deltaQuery + deltaLoad) / 1000000d); listener.Reset(); epService.EPAdministrator.DeploymentAdmin.Undeploy(deployed.DeploymentId); }
/// <summary> /// Clears the contents of a given directory. /// </summary> /// <param name="result">The Deployment results.</param> /// <param name="directory">The directory to clear.</param> /// <param name="ignoredPatterns">Regular expressions which match the files to ignore, e.g. "[aA]pp_[Oo]ffline\.htm".</param> protected void CleanDirectoryContents(DeploymentResult result, DirectoryInfo directory, IList <Regex> ignoredPatterns) { if (ignoredPatterns == null) { ignoredPatterns = new List <Regex>(); } // Delete files FileInfo[] files = directory.GetFiles("*", SearchOption.AllDirectories); foreach (FileInfo file in files.Where(f => !IsIgnored(ignoredPatterns, f))) { RemoveReadOnlyAttributes(file, result); File.Delete(file.FullName); } //// Delete subdirectories. //foreach (DirectoryInfo subdirectory in directory.GetDirectories()) //{ // RemoveReadOnlyAttributes(subdirectory, result); // Directory.Delete(subdirectory.FullName, true); //} result.AddGood("'{0}' cleared.".FormatWith(directory.FullName)); }
private static DeploymentResult GrantCertificatePermissions(string[] args) { var result = new DeploymentResult(); var perm = args[1]; var groupArray = args[2]; var thumbprint = args[3]; var storeNameArg = args[4]; var storeLocationArg = args[5]; var groups = groupArray.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries); var storeName = (StoreName)Enum.Parse(typeof(StoreName), storeNameArg, true); var storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocationArg, true); switch (perm) { case "r": result = new GrantReadCertificatePrivateKeyTask(_server, groups, thumbprint, storeName, storeLocation, new DotNetPath()).Execute(); break; } return(result); }
private void TryAssertionComparativeGroupByTopLevelSingleAgg(EPServiceProvider epService, string caseName, int numEvents, string epl, int numSets) { string[] fields = "c0,c1".Split(','); DeploymentResult deployed = epService.EPAdministrator.DeploymentAdmin.ParseDeploy(epl); var listener = new SupportUpdateListener(); epService.EPAdministrator.GetStatement("Listen").Events += listener.Update; long startLoad = PerformanceObserver.NanoTime; for (int i = 0; i < numEvents; i++) { epService.EPRuntime.SendEvent(new SupportBean("E" + i, i)); } long deltaLoad = PerformanceObserver.NanoTime - startLoad; long startQuery = PerformanceObserver.NanoTime; for (int j = 0; j < numSets; j++) { for (int i = 0; i < numEvents; i++) { string key = "E" + i; epService.EPRuntime.SendEvent(new SupportBean_S0(0, key)); EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { key, i }); } } long deltaQuery = PerformanceObserver.NanoTime - startQuery; /** Comment-me-inn: * Log.Info(caseName + ": Load " + deltaLoad/1000000d + * " Query " + deltaQuery / 1000000d + * " Total " + (deltaQuery+deltaLoad) / 1000000d ); */ epService.EPAdministrator.DeploymentAdmin.Undeploy(deployed.DeploymentId); }
/// <summary> /// Installs the unit test app /// </summary> public static void InstallTestAppIfNeeded(string deploymentDir, string packageName, string packageFamilyName) { if (!TestAppxInstalled.Contains(packageFamilyName)) { FileInfo appxFile = new FileInfo(Path.Combine(deploymentDir, packageName + ".appx")); if (appxFile.Exists) { PackageManager packageManager = new PackageManager(); DeploymentResult result = null; var installedPackages = packageManager.FindPackagesForUser(string.Empty, packageFamilyName); foreach (var installedPackage in installedPackages) { Log.Comment("Test AppX package already installed. Removing existing package by name: {0}", installedPackage.Id.FullName); AutoResetEvent removePackageCompleteEvent = new AutoResetEvent(false); var removePackageOperation = packageManager.RemovePackageAsync(installedPackage.Id.FullName); removePackageOperation.Completed = (operation, status) => { if (status != AsyncStatus.Started) { result = operation.GetResults(); removePackageCompleteEvent.Set(); } }; removePackageCompleteEvent.WaitOne(); if (!string.IsNullOrEmpty(result.ErrorText)) { Log.Error("Removal failed!"); Log.Error("Package removal ActivityId = {0}", result.ActivityId); Log.Error("Package removal ErrorText = {0}", result.ErrorText); Log.Error("Package removal ExtendedErrorCode = {0}", result.ExtendedErrorCode); } else { Log.Comment("Removal successful."); } } // The test app has not been installed yet. Install it so tests can pass List <Uri> depsPackages = new List <Uri>(); FileInfo dependenciesTextFile = new FileInfo(Path.Combine(deploymentDir, packageName + ".dependencies.txt")); if (dependenciesTextFile.Exists) { Log.Comment("Including dependencies from {0}", dependenciesTextFile.FullName); foreach (string line in File.ReadAllLines(dependenciesTextFile.FullName)) { var dependencyPackageUri = new Uri(Path.Combine(deploymentDir, line)); Log.Comment("Adding dependency package: {0}", dependencyPackageUri.AbsolutePath); depsPackages.Add(dependencyPackageUri); } } var packageUri = new Uri(Path.Combine(deploymentDir, appxFile.FullName)); Log.Comment("Installing Test Appx Package: {0}", packageUri.AbsolutePath); AutoResetEvent addPackageCompleteEvent = new AutoResetEvent(false); var addPackageOperation = packageManager.AddPackageAsync(packageUri, depsPackages, DeploymentOptions.ForceApplicationShutdown); addPackageOperation.Completed = (operation, status) => { if (status != AsyncStatus.Started) { result = operation.GetResults(); addPackageCompleteEvent.Set(); } }; addPackageCompleteEvent.WaitOne(); if (!string.IsNullOrEmpty(result.ErrorText)) { Log.Error("Installation failed!"); Log.Error("Package installation ActivityId = {0}", result.ActivityId); Log.Error("Package installation ErrorText = {0}", result.ErrorText); Log.Error("Package installation ExtendedErrorCode = {0}", result.ExtendedErrorCode); throw new Exception("Failed to install Test Appx Package: " + result.ErrorText); } else { Log.Comment("Installation successful."); } } else { Log.Comment("Test Appx Package was not found in {0}.", deploymentDir); } TestAppxInstalled.Add(packageFamilyName); } }
private void AssertSuccess(DeploymentResult result) { Assert.IsFalse(result.Any(i => i.Status == DeploymentItemStatus.Alert || i.Status == DeploymentItemStatus.Error)); }
internal static async Task RunTestsAsync(DeploymentResult deploymentResult, ILogger logger) { var httpClientHandler = new HttpClientHandler(); var httpClient = deploymentResult.CreateHttpClient(httpClientHandler); httpClient.Timeout = TimeSpan.FromSeconds(15); // Request to base address and check if various parts of the body are rendered // & measure the cold startup time. var response = await RetryHelper.RetryRequest(async() => { return(await httpClient.GetAsync(string.Empty)); }, logger, cancellationToken : deploymentResult.HostShutdownToken); Assert.False(response == null, "Response object is null because the client could not " + "connect to the server after multiple retries"); var validator = new Validator(httpClient, httpClientHandler, logger, deploymentResult); logger.LogInformation("Verifying home page"); await validator.VerifyHomePage(response); logger.LogInformation("Verifying static files are served from static file middleware"); await validator.VerifyStaticContentServed(); logger.LogInformation("Verifying access to a protected resource should automatically redirect to login page."); await validator.AccessStoreWithoutPermissions(); logger.LogInformation("Verifying mismatched passwords trigger validaton errors during user registration"); await validator.RegisterUserWithNonMatchingPasswords(); logger.LogInformation("Verifying valid user registration"); var generatedEmail = await validator.RegisterValidUser(); logger.LogInformation("Verifying duplicate user email registration"); await validator.RegisterExistingUser(generatedEmail); logger.LogInformation("Verifying incorrect password login"); await validator.SignInWithInvalidPassword(generatedEmail, "InvalidPassword~1"); logger.LogInformation("Verifying valid user log in"); await validator.SignInWithUser(generatedEmail, "Password~1"); logger.LogInformation("Verifying change password"); await validator.ChangePassword(generatedEmail); logger.LogInformation("Verifying old password is not valid anymore"); await validator.SignOutUser(generatedEmail); await validator.SignInWithInvalidPassword(generatedEmail, "Password~1"); await validator.SignInWithUser(generatedEmail, "Password~2"); logger.LogInformation("Verifying authenticated user trying to access unauthorized resource"); await validator.AccessStoreWithoutPermissions(generatedEmail); logger.LogInformation("Verifying user log out"); await validator.SignOutUser(generatedEmail); logger.LogInformation("Verifying admin user login"); await validator.SignInWithUser("*****@*****.**", "YouShouldChangeThisPassword1!"); logger.LogInformation("Verifying admin user's access to store manager page"); await validator.AccessStoreWithPermissions(); logger.LogInformation("Verifying creating a new album"); var albumName = await validator.CreateAlbum(); var albumId = await validator.FetchAlbumIdFromName(albumName); logger.LogInformation("Verifying retrieved album details"); await validator.VerifyAlbumDetails(albumId, albumName); logger.LogInformation("Verifying status code pages for non-existing items"); await validator.VerifyStatusCodePages(); logger.LogInformation("Verifying non-admin view of an album"); await validator.GetAlbumDetailsFromStore(albumId, albumName); logger.LogInformation("Verifying adding album to a cart"); await validator.AddAlbumToCart(albumId, albumName); logger.LogInformation("Verifying cart checkout"); await validator.CheckOutCartItems(); logger.LogInformation("Verifying deletion of album from a cart"); await validator.DeleteAlbum(albumId, albumName); logger.LogInformation("Verifying administrator log out"); await validator.SignOutUser("Administrator"); logger.LogInformation("Variation completed successfully."); }
public DeploymentFinishedEvent(string deploymentId, DeploymentResult result) { _deploymentId = deploymentId; _result = result; }
private void InstallTestAppIfNeeded() { string mostRecentlyBuiltAppx = string.Empty; DateTime timeMostRecentlyBuilt = DateTime.MinValue; var exclude = new[] { "Microsoft.NET.CoreRuntime", "Microsoft.VCLibs" }; var files = Directory.GetFiles(_baseAppxDir, $"{_packageName}*.appx", SearchOption.AllDirectories).Where(f => !exclude.Any(Path.GetFileNameWithoutExtension(f).Contains)); if (files.Count() == 0) { throw new Exception(string.Format("Failed to find '*.appx' in {0}'!", _baseAppxDir)); } foreach (string file in files) { DateTime fileWriteTime = File.GetLastWriteTime(file); if (fileWriteTime > timeMostRecentlyBuilt) { timeMostRecentlyBuilt = fileWriteTime; mostRecentlyBuiltAppx = file; } } PackageManager packageManager = new PackageManager(); DeploymentResult result = null; var installedPackages = packageManager.FindPackagesForUser(string.Empty, _packageFamilyName); foreach (var installedPackage in installedPackages) { Log.Comment("Test AppX package already installed. Removing existing package by name: {0}", installedPackage.Id.FullName); AutoResetEvent removePackageCompleteEvent = new AutoResetEvent(false); var removePackageOperation = packageManager.RemovePackageAsync(installedPackage.Id.FullName); removePackageOperation.Completed = (operation, status) => { if (status != AsyncStatus.Started) { result = operation.GetResults(); removePackageCompleteEvent.Set(); } }; removePackageCompleteEvent.WaitOne(); if (!string.IsNullOrEmpty(result.ErrorText)) { Log.Error("Removal failed!"); Log.Error("Package removal ActivityId = {0}", result.ActivityId); Log.Error("Package removal ErrorText = {0}", result.ErrorText); Log.Error("Package removal ExtendedErrorCode = {0}", result.ExtendedErrorCode); } else { Log.Comment("Removal successful."); } } Log.Comment("Installing AppX..."); Log.Comment("Checking if the app's certificate is installed..."); // If the certificate for the app is not present, installing it requires elevation. // We'll run Add-AppDevPackage.ps1 without -Force in that circumstance so the user // can be prompted to allow elevation. We don't want to run it without -Force all the time, // as that prompts the user to hit enter at the end of the install, which is an annoying // and unnecessary step. The parameter is the SHA-1 hash of the certificate. var certutilProcess = Process.Start(new ProcessStartInfo("certutil.exe", string.Format("-verifystore TrustedPeople {0}", _certSerialNumber)) { UseShellExecute = true }); certutilProcess.WaitForExit(); if (certutilProcess.ExitCode == 0) { Log.Comment("Certificate is installed. Installing app..."); } else { Log.Comment("Certificate is not installed. Installing app and certificate..."); } var powershellProcess = Process.Start(new ProcessStartInfo("powershell", string.Format("-ExecutionPolicy Unrestricted -File {0}\\Add-AppDevPackage.ps1 {1}", Path.GetDirectoryName(mostRecentlyBuiltAppx), certutilProcess.ExitCode == 0 ? "-Force" : "")) { UseShellExecute = true }); powershellProcess.WaitForExit(); if (powershellProcess.ExitCode != 0) { throw new Exception(string.Format("Failed to install AppX for {0}!", _packageName)); } }