public WebDeployOptions(string packagePath, DeploymentBaseOptions sourceBaseOptions, DeploymentBaseOptions destBaseOptions, DeploymentSyncOptions syncOptions) { _packagePath = packagePath; _sourceBaseOptions = sourceBaseOptions; _destBaseOptions = destBaseOptions; _syncOptions = syncOptions; }
private static DeploymentRule GetRuleByName(string ruleName) { var availableRules = DeploymentSyncOptions.GetAvailableRules(); var rule = availableRules.Single(r => string.Equals(r.Name, ruleName, System.StringComparison.InvariantCultureIgnoreCase)); return(rule); }
/// <summary> /// Deletes the file. /// </summary> /// <param name="properties">The properties.</param> /// <param name="relativeRemoteFileName">Name of the relative remote file.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Connection properties cannot be null.;properties</exception> public bool DeleteFile(ConnectionProperties properties, string relativeRemoteFileName) { if (properties == null) throw new ArgumentException("Connection properties cannot be null.", "properties"); properties.Validate(); ServicePointManager.ServerCertificateValidationCallback = (s, c, chain, err) => true; var destionationOptions = new DeploymentBaseOptions { ComputerName = BuildMsDeployUri(properties).ToString(), UserName = properties.Username, Password = properties.Password, UseDelegation = true, AuthenticationType = "Basic" }; var syncOptions = new DeploymentSyncOptions { DeleteDestination = true }; var remotePath = String.Format("{0}/{1}", properties.IISWebsiteName, relativeRemoteFileName.Trim(new[] { '/', '\\' })); using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, remotePath, destionationOptions)) { var results = deploymentObject.SyncTo(destionationOptions, syncOptions); if (results.ObjectsDeleted == 1) return true; } return true; }
public void PublishFolder() { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkGray; // Create temp files for the manifests System.Net.ServicePointManager.ServerCertificateValidationCallback = AllowCertificateCallback; DeploymentBaseOptions RemoteBaseOption = new DeploymentBaseOptions(); DeploymentSyncOptions SyncOption = new DeploymentSyncOptions(); UpdateBaseOptions(RemoteBaseOption, _serviceUrl, _remoteSite, _user, _password); SyncOption.DoNotDelete = true; SyncOption.WhatIf = false; DeploymentBaseOptions localBaseOptions = new DeploymentBaseOptions(); using (DeploymentObject deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, _localSourceFolder, localBaseOptions)) { deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, _remoteSite, RemoteBaseOption, SyncOption); } Console.ForegroundColor = oldColor; }
/// <summary> /// Deploy database from different sources to different destiations using WebDeploy /// </summary> /// <param name="sourceDbType"></param> /// <param name="sourceConnectionString"></param> /// <param name="destinationDbType"></param> /// <param name="destinationConnectionString"></param> /// <param name="includeData"></param> /// <param name="dropDestinationDatabase"></param> public static void DeployDatabase( WebDeployDatabaseType sourceDbType, string sourceConnectionString, WebDeployDatabaseType destinationDbType, string destinationConnectionString, bool includeData = false, bool dropDestinationDatabase = false) { InitializeWebDeployment(); DeploymentWellKnownProvider srcProvider; DeploymentBaseOptions srcBaseOptions; PrepareDatabaseDeployment(sourceDbType, out srcProvider, out srcBaseOptions, includeData, dropDestinationDatabase); DeploymentWellKnownProvider destProvider; DeploymentBaseOptions destBaseOptions; PrepareDatabaseDeployment(destinationDbType, out destProvider, out destBaseOptions, includeData, dropDestinationDatabase); var destSyncOptions = new DeploymentSyncOptions(); ExecuteDeploy( sourceConnectionString, destinationConnectionString, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions); }
public static void SyncWebApps(Profile src, Profile dest) { DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions(); sourceBaseOptions.ComputerName = "https://" + src.publishUrl + "/msdeploy.axd"; sourceBaseOptions.UserName = src.userName; sourceBaseOptions.Password = src.userPwd; sourceBaseOptions.AuthenticationType = "basic"; sourceBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = "https://" + dest.publishUrl + "/msdeploy.axd"; destBaseOptions.UserName = dest.userName; destBaseOptions.Password = dest.userPwd; destBaseOptions.AuthenticationType = "basic"; destBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; DeploymentProviderOptions destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.ContentPath); destProviderOptions.Path = dest.sitename; DeploymentObject sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, src.sitename, sourceBaseOptions); sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions); }
public static void SyncDatabases(Profile src, Profile dest, string dbtype) { DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions(); destBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; DeploymentProviderOptions destProviderOptions = null; DeploymentObject sourceObj = null; if (dbtype.Equals("mysql", StringComparison.InvariantCultureIgnoreCase)) { destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBMySql); destProviderOptions.Path = dest.mysqlConnectionstring; sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBMySql, src.mysqlConnectionstring, sourceBaseOptions); } else if (dbtype.Equals("sql", StringComparison.InvariantCultureIgnoreCase)) { destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBFullSql); destProviderOptions.Path = dest.sqlazureconnectionstring; sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBFullSql, src.sqlazureconnectionstring, sourceBaseOptions); } if (sourceObj != null) { sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions); } }
public static void SyncDatabases(Profile src, Profile dest , string dbtype) { DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions(); destBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; DeploymentProviderOptions destProviderOptions = null; DeploymentObject sourceObj = null; if (dbtype.Equals("mysql", StringComparison.InvariantCultureIgnoreCase)) { destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBMySql); destProviderOptions.Path = dest.mysqlConnectionstring; sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBMySql, src.mysqlConnectionstring, sourceBaseOptions); } else if (dbtype.Equals("sql", StringComparison.InvariantCultureIgnoreCase)) { destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBFullSql); destProviderOptions.Path = dest.sqlazureconnectionstring; sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBFullSql,src.sqlazureconnectionstring, sourceBaseOptions); } if (sourceObj != null) { sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions); } }
private static void Deploy( string sourcePath, string destinationPath, string destinationAddress, string userName, string password, DeploymentWellKnownProvider srcProvider, DeploymentBaseOptions srcBaseOptions, DeploymentWellKnownProvider destProvider, DeploymentBaseOptions destBaseOptions, DeploymentSyncOptions destSyncOptions, Func <string, string> syncParamResolver, IEnumerable <DeploymentSkipDirective> skipDirectives = null, IEnumerable <string> removedParameters = null, TraceLevel tracelevel = TraceLevel.Info, WebDeploySyncDirection direction = (WebDeploySyncDirection.SourceIsLocal | WebDeploySyncDirection.DestinationIsRemote)) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, e) => true; // prepare common source properties srcBaseOptions.Trace += DeployTraceEventHandler; srcBaseOptions.TraceLevel = tracelevel; if (direction.HasFlag(WebDeploySyncDirection.SourceIsRemote)) { srcBaseOptions.ComputerName = destinationAddress; srcBaseOptions.UserName = userName; srcBaseOptions.Password = password; srcBaseOptions.AuthenticationType = "basic"; } // prepare common destination properties destBaseOptions.Trace += DeployTraceEventHandler; destBaseOptions.TraceLevel = tracelevel; destBaseOptions.IncludeAcls = true; // We want to ignore errors to delete files because this is what WebMatrix does. This may result in a partial deployment destBaseOptions.AddDefaultProviderSetting(DeploymentWellKnownProvider.FilePath.ToString(), "ignoreErrors", "0x80070005;0x80070020;0x80070091"); destBaseOptions.AddDefaultProviderSetting(DeploymentWellKnownProvider.DirPath.ToString(), "ignoreErrors", "0x80070005;0x80070020;0x80070091"); if (direction.HasFlag(WebDeploySyncDirection.DestinationIsRemote)) { destBaseOptions.ComputerName = destinationAddress; destBaseOptions.UserName = userName; destBaseOptions.Password = password; destBaseOptions.AuthenticationType = "basic"; } if (skipDirectives != null) { foreach (var skipDirective in skipDirectives) { srcBaseOptions.SkipDirectives.Add(skipDirective); destBaseOptions.SkipDirectives.Add(skipDirective); } } ExecuteDeploy(sourcePath, destinationPath, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions, syncParamResolver, removedParameters); }
private static void ApplyPreserveAppDataDeploymentRule(DeploymentSyncOptions syncOptions, VariableDictionary variables) { // If PreserveAppData variable set, then create SkipDelete rules for App_Data directory if (variables.GetFlag(SpecialVariables.Action.Azure.PreserveAppData)) { syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataFiles", "Delete", "filePath", "\\\\App_Data\\\\.*", null)); syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataDir", "Delete", "dirPath", "\\\\App_Data(\\\\.*|$)", null)); } }
private void AddDeploymentRule(DeploymentSyncOptions syncOptions, string name) { var rules = DeploymentSyncOptions.GetAvailableRules(); if (rules.TryGetValue(name, out var newRule)) { syncOptions.Rules.Add(newRule); } }
void ApplyPreserveAppDataDeploymentRule(DeploymentSyncOptions syncOptions, IVariables variables) { // If PreserveAppData variable set, then create SkipDelete rules for App_Data directory // ReSharper disable once InvertIf if (variables.GetFlag(SpecialVariables.Action.Azure.PreserveAppData)) { syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataFiles", "Delete", "filePath", "\\\\App_Data\\\\.*", null)); syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataDir", "Delete", "dirPath", "\\\\App_Data(\\\\.*|$)", null)); } }
private static void ExecuteDeploy( string sourcePath, string destinationPath, DeploymentWellKnownProvider srcProvider, DeploymentBaseOptions srcBaseOptions, DeploymentWellKnownProvider destProvider, DeploymentBaseOptions destBaseOptions, DeploymentSyncOptions destSyncOptions, Func <string, string> syncParamResolver = null, IEnumerable <string> removedParameters = null) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, e) => true; try { using (DeploymentObject deployObj = DeploymentManager.CreateObject(srcProvider, sourcePath, srcBaseOptions)) { // resolve parameters if any if (syncParamResolver != null) { foreach (var syncParam in deployObj.SyncParameters) { var resolvedValue = syncParamResolver(syncParam.Name); if (resolvedValue != null) { syncParam.Value = resolvedValue; } } } // remove parameters if any if (removedParameters != null) { foreach (var parameter in removedParameters) { deployObj.SyncParameters.Remove(parameter); } } TestEasyLog.Instance.Info(string.Format("Deploying: {0}", sourcePath)); // do action TestEasyLog.Instance.LogObject(deployObj.SyncTo(destProvider, destinationPath, destBaseOptions, destSyncOptions)); } } catch (Exception e) { TestEasyLog.Instance.Info(string.Format("Exception during deployment of '{0}': '{1}'", sourcePath, e.Message)); throw; } }
/// <summary> /// Deploys the content to one site. /// </summary> /// <param name="contentPath">The content path.</param> /// <param name="publishSettingsFile">The publish settings file.</param> /// <param name="password">The password.</param> /// <param name="allowUntrusted">Deploy even if destination certificate is untrusted</param> /// <returns>DeploymentChangeSummary.</returns> public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile, string password = null, bool allowUntrusted = false, bool doNotDelete = true, TraceLevel traceLevel = TraceLevel.Off, bool whatIf = false) { contentPath = Path.GetFullPath(contentPath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = SetBaseOptions(publishSettingsFile, out destBaseOptions, allowUntrusted); destBaseOptions.TraceLevel = traceLevel; destBaseOptions.Trace += destBaseOptions_Trace; // use the password from the command line args if provided if (!string.IsNullOrEmpty(password)) { destBaseOptions.Password = password; } // If the content path is a zip file, use the Package provider DeploymentWellKnownProvider provider; if (Path.GetExtension(contentPath).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { provider = DeploymentWellKnownProvider.Package; } else { provider = DeploymentWellKnownProvider.ContentPath; } var syncOptions = new DeploymentSyncOptions { DoNotDelete = doNotDelete, WhatIf = whatIf }; // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(provider, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return(deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, syncOptions)); } }
private static DeploymentSyncOptions DeploymentSyncOptions(VariableDictionary variables) { var syncOptions = new DeploymentSyncOptions { WhatIf = false, UseChecksum = variables.GetFlag(SpecialVariables.Action.Azure.UseChecksum), DoNotDelete = !variables.GetFlag(SpecialVariables.Action.Azure.RemoveAdditionalFiles), }; ApplyAppOfflineDeploymentRule(syncOptions, variables); ApplyPreserveAppDataDeploymentRule(syncOptions, variables); ApplyPreservePathsDeploymentRule(syncOptions, variables); return(syncOptions); }
private static void ApplyPreservePathsDeploymentRule(DeploymentSyncOptions syncOptions, VariableDictionary variables) { // If PreservePaths variable set, then create SkipDelete rules for each path regex var preservePaths = variables.GetStrings(SpecialVariables.Action.Azure.PreservePaths, ';'); if (preservePaths != null) { for (var i = 0; i < preservePaths.Count; i++) { var path = preservePaths[i]; syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteFiles_" + i, "Delete", "filePath", path, null)); syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDir_" + i, "Delete", "dirPath", path, null)); } } }
public static DeploymentSyncOptions GetSyncOptions(WebDeploySettings settings) { var options = new DeploymentSyncOptions(); options.DoNotDelete = settings.EnableDoNotDeleteRule ?? false; options.WhatIf = settings.ShowWhatIf ?? false; if (settings.EnableAppOfflineRule ?? false) { var appOfflineRule = GetRuleByName("AppOffline"); options.Rules.Add(appOfflineRule); } // TODO MORE RULES return(options); }
public static void DeployPackage(string packageFilePath) { var sourceProvider = DeploymentWellKnownProvider.Package; var sourcePath = packageFilePath; var sourceBaseOptions = new DeploymentBaseOptions(); var destinationProvider = DeploymentWellKnownProvider.Auto; var destinationPath = ""; DeploymentBaseOptions destinationBaseOptions = new DeploymentBaseOptions(); DeploymentSyncOptions destinationSyncOptions = new DeploymentSyncOptions(); using (DeploymentObject deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath, sourceBaseOptions)) { deploymentObject.SyncTo(destinationProvider, destinationPath, destinationBaseOptions, destinationSyncOptions); } }
private static void ApplyAppOfflineDeploymentRule(DeploymentSyncOptions syncOptions, VariableDictionary variables) { if (variables.GetFlag(SpecialVariables.Action.Azure.AppOffline)) { var rules = Microsoft.Web.Deployment.DeploymentSyncOptions.GetAvailableRules(); DeploymentRule rule; if (rules.TryGetValue("AppOffline", out rule)) { syncOptions.Rules.Add(rule); } else { Log.Verbose("Azure Deployment API does not support `AppOffline` deployment rule."); } } }
/// <summary> /// Deploys the content to one site. /// </summary> /// <param name="contentPath">The content path.</param> /// <param name="publishSettingsFile">The publish settings file.</param> /// <param name="password">The password.</param> /// <param name="allowUntrusted">Deploy even if destination certificate is untrusted</param> /// <returns>DeploymentChangeSummary.</returns> public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile, string password = null, bool allowUntrusted = false, bool doNotDelete = true, TraceLevel traceLevel = TraceLevel.Off, bool whatIf = false) { contentPath = Path.GetFullPath(contentPath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = SetBaseOptions(publishSettingsFile, out destBaseOptions, allowUntrusted); destBaseOptions.TraceLevel = traceLevel; destBaseOptions.Trace += destBaseOptions_Trace; // use the password from the command line args if provided if (!string.IsNullOrEmpty(password)) destBaseOptions.Password = password; // If the content path is a zip file, use the Package provider DeploymentWellKnownProvider provider; if (Path.GetExtension(contentPath).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { provider = DeploymentWellKnownProvider.Package; } else { provider = DeploymentWellKnownProvider.ContentPath; } var syncOptions = new DeploymentSyncOptions { DoNotDelete = doNotDelete, WhatIf = whatIf }; // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(provider, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, syncOptions); } }
private static void ApplyAppOfflineDeploymentRule(DeploymentSyncOptions syncOptions, IVariables variables) { // ReSharper disable once InvertIf if (variables.GetFlag(SpecialVariables.Action.Azure.AppOffline)) { var rules = Microsoft.Web.Deployment.DeploymentSyncOptions.GetAvailableRules(); if (rules.TryGetValue("AppOffline", out var rule)) { syncOptions.Rules.Add(rule); } else { Log.Verbose("Azure Deployment API does not support `AppOffline` deployment rule."); } } }
/// <summary> /// Deploy package from different sources to different destiations using WebDeploy /// </summary> /// <param name="sourcePath"></param> /// <param name="destinationPath"></param> /// <param name="destinationAddress"></param> /// <param name="user"></param> /// <param name="password"></param> /// <param name="deleteExisting"></param> /// <param name="paramResolverFunc"></param> public static void DeployPackage( string sourcePath, string destinationPath, string destinationAddress, string user, string password, bool deleteExisting = true, Func <string, string> paramResolverFunc = null) { InitializeWebDeployment(); var skipDirectives = new List <DeploymentSkipDirective> { new DeploymentSkipDirective("skipDbFullSql", @"objectName=dbFullSql", true), new DeploymentSkipDirective("skipDbMySql", @"objectName=dbMySql", true) }; // define a source deployment provider and its properties const DeploymentWellKnownProvider srcProvider = DeploymentWellKnownProvider.Package; var srcBaseOptions = new DeploymentBaseOptions(); // define a destination deployment provider and its properties const DeploymentWellKnownProvider destProvider = DeploymentWellKnownProvider.Auto; var destBaseOptions = new DeploymentBaseOptions(); // define a synchronization options and set if we shoudl delete existing files var destSyncOptions = new DeploymentSyncOptions { DoNotDelete = !deleteExisting }; Deploy( sourcePath, destinationPath, destinationAddress, user, password, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions, paramResolverFunc, skipDirectives.AsEnumerable()); }
/// <summary> /// Deploy directory from different sources to different destiations using WebDeploy /// </summary> /// <param name="sourcePath"></param> /// <param name="destinationPath"></param> /// <param name="destinationAddress"></param> /// <param name="user"></param> /// <param name="password"></param> /// <param name="deleteExisting"></param> /// <param name="paramResolverFunc"></param> public static void DeployDirectory( string sourcePath, string destinationPath, string destinationAddress, string user, string password, bool deleteExisting = true, Func <string, string> paramResolverFunc = null) { InitializeWebDeployment(); // define a source deployment provider and its properties const DeploymentWellKnownProvider srcProvider = DeploymentWellKnownProvider.ContentPath; var srcBaseOptions = new DeploymentBaseOptions(); // define a destination deployment provider and its properties const DeploymentWellKnownProvider destProvider = DeploymentWellKnownProvider.ContentPath; var destBaseOptions = new DeploymentBaseOptions(); // define a synchronization options and set if we shoudl delete existing files var destSyncOptions = new DeploymentSyncOptions { DoNotDelete = !deleteExisting }; Deploy( sourcePath, destinationPath, destinationAddress, user, password, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions, paramResolverFunc); }
public List <string> TestSkipRule(List <SkipRule> skipRules, string contentPath) { DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destOptions = new DeploymentBaseOptions(); DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); _skipRulesTestResults = new List <string>(); AddSkips(skipRules.AsReadOnly(), sourceOptions, destOptions); syncOptions.WhatIf = true; // Puropsely only setting event handler for source so that we don't get duplicate // events being fired sourceOptions.TraceLevel = TraceLevel.Verbose; sourceOptions.Trace += AddSkipRuleResultEventHandler; using (DeploymentObject sourceObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceOptions)) { sourceObject.SyncTo(destOptions, syncOptions); } _skipRulesTestResults.Sort(); return(_skipRulesTestResults); }
private static DeploymentSyncOptions DeploymentSyncOptions(VariableDictionary variables) { var syncOptions = new DeploymentSyncOptions { WhatIf = false, UseChecksum = true, DoNotDelete = !variables.GetFlag(SpecialVariables.Action.Azure.RemoveAdditionalFiles), }; ApplyAppOfflineDeploymentRule(syncOptions, variables); ApplyPreserveAppDataDeploymentRule(syncOptions, variables); ApplyPreservePathsDeploymentRule(syncOptions, variables); return syncOptions; }
public string InstallApplication(string productId, List <DeploymentParameter> updatedValues) { string packageFile = GetApplicationPackagePath(productId); string applicationPath = null; // if (String.IsNullOrEmpty(packageFile)) { return(null); } // Log.WriteInfo("WebApp Package Path: {0}", packageFile); // if (!File.Exists(packageFile)) { throw new Exception(GalleryErrorCodes.FILE_NOT_FOUND); } // // Setup source deployment options DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); // Add tracing capabilities sourceOptions.Trace += new EventHandler <DeploymentTraceEventArgs>(sourceOptions_Trace); sourceOptions.TraceLevel = TraceLevel.Verbose; // Setup deployment provider DeploymentProviderOptions providerOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.Package); // Set the package path location providerOptions.Path = packageFile; // Prepare the package deployment procedure using (DeploymentObject iisApplication = DeploymentManager.CreateObject(providerOptions, sourceOptions)) { // Setup destination deployment options DeploymentBaseOptions destinationOptions = new DeploymentBaseOptions(); // Add tracing capabilities destinationOptions.Trace += new EventHandler <DeploymentTraceEventArgs>(sourceOptions_Trace); destinationOptions.TraceLevel = TraceLevel.Verbose; // MSDEPLOY TEAM COMMENTS: For each parameter that was specified in the UI, set its value foreach (DeploymentParameter updatedValue in updatedValues) { DeploymentSyncParameter parameter = null; // Assert whether a parameter assigned a value Trace.Assert(!String.IsNullOrEmpty(updatedValue.Name)); if (!iisApplication.SyncParameters.TryGetValue(updatedValue.Name, out parameter)) { throw new InvalidOperationException("Could not find a parameter with the name " + updatedValue.Name); } parameter.Value = updatedValue.Value; } // Find database parameter received in updated parameters arrays DeploymentParameter dbNameParam = Array.Find <DeploymentParameter>(updatedValues.ToArray(), p => MatchParameterByNames(p, DeploymentParameter.DATABASE_NAME_PARAMS) || MatchParameterTag(p, DeploymentParameter.DB_NAME_PARAM_TAG)); // MSDEPLOY TEAM COMMENTS: There may be a bunch of hidden parameters that never got set. // set these to their default values (which will probably be calculated based on the other // parameters that were set). foreach (DeploymentSyncParameter parameter in iisApplication.SyncParameters) { // Ensure all syncronization parameters are set if (parameter.Value == null) { throw new InvalidOperationException("Parameter '" + parameter.Name + "' value was not set. This indicates an issue with the package itself. Contact your system administrator."); } // Detect application path parameter in order to return it to the client if (MatchParameterTag(parameter, DeploymentParameter.IISAPP_PARAM_TAG)) { applicationPath = parameter.Value; continue; } // if (dbNameParam == null) { continue; } // if (!MatchParameterTag(parameter, DeploymentParameter.DB_NAME_PARAM_TAG) && !MatchParameterByNames(parameter, DeploymentParameter.DATABASE_NAME_PARAMS)) { continue; } // Application supports both databases MySQL & MSSQL - one of them should be skipped if (MatchParameterTag(parameter, DeploymentParameter.MYSQL_PARAM_TAG) && MatchParameterTag(parameter, DeploymentParameter.SQL_PARAM_TAG)) { if (dbNameParam.Tags.ToLowerInvariant().StartsWith("mssql")) { sourceOptions.SkipDirectives.Add(SkipMySQL); } // Skip MySQL database scripts else if (dbNameParam.Tags.ToLowerInvariant().StartsWith("mysql")) { sourceOptions.SkipDirectives.Add(SkipMsSQL); } } } // Setup deployment options DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); // Add tracing capabilities //syncOptions..Action += new EventHandler<DeploymentActionEventArgs>(syncOptions_Action); // Issue a syncronization signal between the parties iisApplication.SyncTo(DeploymentWellKnownProvider.Auto, applicationPath, destinationOptions, syncOptions); // Log.WriteInfo("{0}: {1}", DeploymentParameter.APPICATION_PATH_PARAM, applicationPath); // } // return(applicationPath); }
/// <summary> /// Publish a WebDeploy package zip file to a web site. /// </summary> /// <param name="websiteName">The name of the web site.</param> /// <param name="slot">The name of the slot.</param> /// <param name="package">The WebDeploy package zip file.</param> /// <param name="connectionStrings">The connection strings to overwrite the ones in the Web.config file.</param> /// <param name="skipAppData">Skip app data</param> /// <param name="doNotDelete">Do not delete files at destination</param> private void PublishWebProjectFromPackageFile(string websiteName, string slot, string package, Hashtable connectionStrings, bool skipAppData, bool doNotDelete) { DeploymentBaseOptions remoteBaseOptions = CreateRemoteDeploymentBaseOptions(websiteName, slot); DeploymentBaseOptions localBaseOptions = new DeploymentBaseOptions(); SetWebDeployToSkipAppData(skipAppData, localBaseOptions, remoteBaseOptions); DeploymentProviderOptions remoteProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.Auto); using (var deployment = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Package, package, localBaseOptions)) { DeploymentSyncParameter providerPathParameter = new DeploymentSyncParameter( "Provider Path Parameter", "Provider Path Parameter", SetWebsiteNameForWebDeploy(websiteName, slot), null); DeploymentSyncParameterEntry iisAppEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.IisApp.ToString(), ".*", null); DeploymentSyncParameterEntry setAclEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.SetAcl.ToString(), ".*", null); providerPathParameter.Add(iisAppEntry); providerPathParameter.Add(setAclEntry); deployment.SyncParameters.Add(providerPathParameter); // Replace the connection strings in Web.config with the ones user specifies from the cmdlet. ReplaceConnectionStrings(deployment, connectionStrings); DeploymentSyncOptions syncOptions = new DeploymentSyncOptions { DoNotDelete = doNotDelete }; deployment.SyncTo(remoteProviderOptions, remoteBaseOptions, syncOptions); } }
public string InstallApplication(string productId, List <DeploymentParameter> updatedParameters) { string packageFile = GetApplicationPackagePath(productId); string applicationPath = null; if (String.IsNullOrEmpty(packageFile)) { return(null); } Log.WriteInfo("WebApp Package Path: {0}", packageFile); if (!File.Exists(packageFile)) { throw new Exception(GalleryErrors.PackageFileNotFound); } // Setup source deployment options DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); // Add tracing capabilities sourceOptions.Trace += new EventHandler <DeploymentTraceEventArgs>(sourceOptions_Trace); sourceOptions.TraceLevel = TraceLevel.Verbose; // Setup deployment provider DeploymentProviderOptions providerOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.Package); // Set the package path location providerOptions.Path = packageFile; // Prepare the package deployment procedure using (DeploymentObject iisApplication = DeploymentManager.CreateObject(providerOptions, sourceOptions)) { // Setup destination deployment options DeploymentBaseOptions destinationOptions = new DeploymentBaseOptions(); // Add tracing capabilities destinationOptions.Trace += new EventHandler <DeploymentTraceEventArgs>(sourceOptions_Trace); destinationOptions.TraceLevel = TraceLevel.Verbose; // MSDEPLOY TEAM COMMENTS: For each parameter that was specified in the UI, set its value DeploymentParameterWellKnownTag databaseEngine = DeploymentParameterWellKnownTag.None; int i = 0; while (i < iisApplication.SyncParameters.Count) { // try to find parameter in updated parameters string name = iisApplication.SyncParameters[i].Name; DeploymentParameter updatedParameter = updatedParameters.Find(p => { return(String.Compare(p.Name, name) == 0); }); if (updatedParameter != null) { // parameter found // update its value iisApplication.SyncParameters[i].Value = updatedParameter.Value; i++; // advance to the next parameter // check for selected database engine if ((updatedParameter.WellKnownTags & DeploymentParameterWellKnownTag.MySql) == DeploymentParameterWellKnownTag.MySql) { databaseEngine = DeploymentParameterWellKnownTag.MySql; } else if ((updatedParameter.WellKnownTags & DeploymentParameterWellKnownTag.Sql) == DeploymentParameterWellKnownTag.Sql) { databaseEngine = DeploymentParameterWellKnownTag.Sql; } // get application path if ((updatedParameter.WellKnownTags & DeploymentParameterWellKnownTag.IisApp) == DeploymentParameterWellKnownTag.IisApp) { applicationPath = updatedParameter.Value; } } else { // parameter not found // delete it iisApplication.SyncParameters.Remove(name); } } // Skip SQL Server database scripts if not SQL Server was selected if (databaseEngine != DeploymentParameterWellKnownTag.Sql) { sourceOptions.SkipDirectives.Add(SkipMsSQL); } // Skip MySQL database scripts if not MySQL was selected if (databaseEngine != DeploymentParameterWellKnownTag.MySql) { sourceOptions.SkipDirectives.Add(SkipMySQL); } // Setup deployment options DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); // Add tracing capabilities //syncOptions..Action += new EventHandler<DeploymentActionEventArgs>(syncOptions_Action); // Issue a syncronization signal between the parties iisApplication.SyncTo(DeploymentWellKnownProvider.Auto, applicationPath, destinationOptions, syncOptions); // Log.WriteInfo("{0}: {1}", "Application path", applicationPath); // } // return(applicationPath); }
private static void Deploy( string sourcePath, string destinationPath, string destinationAddress, string userName, string password, DeploymentWellKnownProvider srcProvider, DeploymentBaseOptions srcBaseOptions, DeploymentWellKnownProvider destProvider, DeploymentBaseOptions destBaseOptions, DeploymentSyncOptions destSyncOptions, Func<string, string> syncParamResolver, IEnumerable<DeploymentSkipDirective> skipDirectives = null, IEnumerable<string> removedParameters = null, TraceLevel tracelevel = TraceLevel.Info, WebDeploySyncDirection direction = (WebDeploySyncDirection.SourceIsLocal | WebDeploySyncDirection.DestinationIsRemote)) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, e) => true; // prepare common source properties srcBaseOptions.Trace += DeployTraceEventHandler; srcBaseOptions.TraceLevel = tracelevel; if (direction.HasFlag(WebDeploySyncDirection.SourceIsRemote)) { srcBaseOptions.ComputerName = destinationAddress; srcBaseOptions.UserName = userName; srcBaseOptions.Password = password; srcBaseOptions.AuthenticationType = "basic"; } // prepare common destination properties destBaseOptions.Trace += DeployTraceEventHandler; destBaseOptions.TraceLevel = tracelevel; destBaseOptions.IncludeAcls = true; // We want to ignore errors to delete files because this is what WebMatrix does. This may result in a partial deployment destBaseOptions.AddDefaultProviderSetting(DeploymentWellKnownProvider.FilePath.ToString(), "ignoreErrors", "0x80070005;0x80070020;0x80070091"); destBaseOptions.AddDefaultProviderSetting(DeploymentWellKnownProvider.DirPath.ToString(), "ignoreErrors", "0x80070005;0x80070020;0x80070091"); if (direction.HasFlag(WebDeploySyncDirection.DestinationIsRemote)) { destBaseOptions.ComputerName = destinationAddress; destBaseOptions.UserName = userName; destBaseOptions.Password = password; destBaseOptions.AuthenticationType = "basic"; } if (skipDirectives != null) { foreach (var skipDirective in skipDirectives) { srcBaseOptions.SkipDirectives.Add(skipDirective); destBaseOptions.SkipDirectives.Add(skipDirective); } } ExecuteDeploy(sourcePath, destinationPath, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions, syncParamResolver, removedParameters); }
/// <summary> /// Deploy directory from different sources to different destiations using WebDeploy /// </summary> /// <param name="sourcePath"></param> /// <param name="destinationPath"></param> /// <param name="destinationAddress"></param> /// <param name="user"></param> /// <param name="password"></param> /// <param name="deleteExisting"></param> /// <param name="paramResolverFunc"></param> public static void DeployDirectory( string sourcePath, string destinationPath, string destinationAddress, string user, string password, bool deleteExisting = true, Func<string, string> paramResolverFunc = null) { InitializeWebDeployment(); // define a source deployment provider and its properties const DeploymentWellKnownProvider srcProvider = DeploymentWellKnownProvider.ContentPath; var srcBaseOptions = new DeploymentBaseOptions(); // define a destination deployment provider and its properties const DeploymentWellKnownProvider destProvider = DeploymentWellKnownProvider.ContentPath; var destBaseOptions = new DeploymentBaseOptions(); // define a synchronization options and set if we shoudl delete existing files var destSyncOptions = new DeploymentSyncOptions { DoNotDelete = !deleteExisting }; Deploy( sourcePath, destinationPath, destinationAddress, user, password, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions, paramResolverFunc); }
public override bool Publish(bool setSize) { var sourceBaseOptions = new DeploymentBaseOptions(); var destBaseOptions = new DeploymentBaseOptions(); if (!setSize) { sourceBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; destBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; } destBaseOptions.ComputerName = _publishSettings.ComputerName; destBaseOptions.UserName = _publishSettings.Username; destBaseOptions.Password = _publishSettings.Password; LogTrace("Publishing as {0}", destBaseOptions.UserName); destBaseOptions.AuthenticationType = "basic"; bool publishSucceeded = true; #region Publish Content try { using (var sourceObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Manifest, GetManifest(isSource: true), sourceBaseOptions)) { var syncOptions = new DeploymentSyncOptions() { DoNotDelete = true, }; if (!setSize) { LogTrace("Started content publish for: {0}", _localSite.SiteName); if (HasDatabase) { var connectionStringParameter = new DeploymentSyncParameter( "ConnectionStringParam", // Name "DBConnectionString Param", // Description _publishSettings.SqlDBConnectionString.ConnectionString, // Default Value to set null); // Tag var entry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.XmlFile, // Kind @"\\web\.config$", // Scope connectionStringXPath, // Match null); // Tag connectionStringParameter.Add(entry); sourceObject.SyncParameters.Add(connectionStringParameter); } } try { syncOptions.WhatIf = setSize; var summary = sourceObject.SyncTo(DeploymentWellKnownProvider.Manifest, GetManifest(isSource: false), destBaseOptions, syncOptions); if (!setSize) { LogTrace("Content Published Succesfully For Site: {0} to {1} ", _localSite.SiteName, _publishSettings.SiteName); Helper.UpdateStatus(_localSite.SiteName, _localSite.ServerName); } else { _control.SetProgressbarMax(this.LocalSite.ServerName + this.LocalSite.SiteName, summary.TotalChanges); } } catch (Exception ex) { string message = string.Format("Error syncing content for site: {0}", _localSite.SiteName); LogTrace(message); LogTrace(ex.ToString()); publishSucceeded = false; } } } catch (Exception ex) { LogTrace("Error starting content publish for site: {0}", _localSite.SiteName); LogTrace(ex.ToString()); publishSucceeded = false; } _control.UpdateStatusLabel(string.Empty); #endregion if (!setSize) { _control.SetContentPublished(this.LocalSite.ServerName + this.LocalSite.SiteName, publishSucceeded); } this.PublishStatus = publishSucceeded; return publishSucceeded; }
public override bool Publish(bool setSize) { var sourceBaseOptions = new DeploymentBaseOptions(); var destBaseOptions = new DeploymentBaseOptions(); if (!setSize) { sourceBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; destBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; } destBaseOptions.ComputerName = _publishSettings.ComputerName; destBaseOptions.UserName = _publishSettings.Username; destBaseOptions.Password = _publishSettings.Password; LogTrace("Publishing as {0}", destBaseOptions.UserName); destBaseOptions.AuthenticationType = "basic"; bool publishSucceeded = true; #region Publish Content try { using (var sourceObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Manifest, GetManifest(isSource: true), sourceBaseOptions)) { var syncOptions = new DeploymentSyncOptions() { DoNotDelete = true, }; if (!setSize) { LogTrace("Started content publish for: {0}", _localSite.SiteName); if (HasDatabase) { var connectionStringParameter = new DeploymentSyncParameter( "ConnectionStringParam", // Name "DBConnectionString Param", // Description _publishSettings.SqlDBConnectionString.ConnectionString, // Default Value to set null); // Tag var entry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.XmlFile, // Kind @"\\web\.config$", // Scope connectionStringXPath, // Match null); // Tag connectionStringParameter.Add(entry); sourceObject.SyncParameters.Add(connectionStringParameter); } } try { syncOptions.WhatIf = setSize; var summary = sourceObject.SyncTo(DeploymentWellKnownProvider.Manifest, GetManifest(isSource: false), destBaseOptions, syncOptions); if (!setSize) { LogTrace("Content Published Succesfully For Site: {0} to {1} ", _localSite.SiteName, _publishSettings.SiteName); Helper.UpdateStatus(_localSite.SiteName, _localSite.ServerName); } else { _control.SetProgressbarMax(this.LocalSite.ServerName + this.LocalSite.SiteName, summary.TotalChanges); } } catch (Exception ex) { string message = string.Format("Error syncing content for site: {0}", _localSite.SiteName); LogTrace(message); LogTrace(ex.ToString()); publishSucceeded = false; } } } catch (Exception ex) { LogTrace("Error starting content publish for site: {0}", _localSite.SiteName); LogTrace(ex.ToString()); publishSucceeded = false; } _control.UpdateStatusLabel(string.Empty); #endregion if (!setSize) { _control.SetContentPublished(this.LocalSite.ServerName + this.LocalSite.SiteName, publishSucceeded); } this.PublishStatus = publishSucceeded; return(publishSucceeded); }
/// <summary> /// Deploys the content of a website /// </summary> /// <param name="settings">The deployment settings.</param> /// <returns>The <see cref="DeploymentChangeSummary"/> that was applied during the deployment.</returns> public DeploymentChangeSummary Deploy(DeploySettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } if (settings.SourcePath == null) { throw new ArgumentNullException("settings.SourcePath"); } DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destOptions = this.GetBaseOptions(settings); FilePath sourcePath = settings.SourcePath.MakeAbsolute(_Environment); string destPath = settings.SiteName; destOptions.TraceLevel = settings.TraceLevel; destOptions.Trace += OnTraceEvent; DeploymentWellKnownProvider sourceProvider = DeploymentWellKnownProvider.ContentPath; DeploymentWellKnownProvider destProvider = DeploymentWellKnownProvider.Auto; //If a target path was specified, it could be virtual or physical if (settings.DestinationPath != null) { if (System.IO.Path.IsPathRooted(settings.DestinationPath.FullPath)) { // If it's rooted (e.g. d:\home\site\foo), use DirPath sourceProvider = DeploymentWellKnownProvider.DirPath; destProvider = DeploymentWellKnownProvider.DirPath; destPath = settings.DestinationPath.FullPath; } else { // It's virtual, so append it to what we got from the publish profile destPath += "/" + settings.DestinationPath.FullPath; } } //When a SiteName is given but no DestinationPath else if (!String.IsNullOrWhiteSpace(settings.SiteName)) { //use ContentPath so it gets deployed to the Path of the named website in IIS //which is the same behaviour as in Visual Studio destProvider = DeploymentWellKnownProvider.ContentPath; } //If the content path is a zip file, use the Package provider string extension = sourcePath.GetExtension(); if (extension != null && extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { // For some reason, we can't combine a zip with a physical target path if (destProvider == DeploymentWellKnownProvider.DirPath) { throw new Exception("A source zip file can't be used with a physical target path"); } sourceProvider = DeploymentWellKnownProvider.Package; } //Sync Options DeploymentSyncOptions syncOptions = new DeploymentSyncOptions { DoNotDelete = !settings.Delete, WhatIf = settings.WhatIf }; //Deploy _Log.Debug(Verbosity.Normal, "Deploying Website..."); _Log.Debug(Verbosity.Normal, String.Format("-siteName '{0}'", settings.SiteName)); _Log.Debug(Verbosity.Normal, String.Format("-destination '{0}'", settings.PublishUrl)); _Log.Debug(Verbosity.Normal, String.Format("-source '{0}'", sourcePath.FullPath)); _Log.Debug(""); using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath.FullPath, sourceOptions)) { foreach (var kv in settings.Parameters) { deploymentObject.SyncParameters[kv.Key].Value = kv.Value; } return deploymentObject.SyncTo(destProvider, destPath, destOptions, syncOptions); } }
/// <summary> /// Deploys the content to one site. /// </summary> /// <param name="sourcePath">The content path.</param> /// <param name="publishSettingsFile">The publish settings file.</param> /// <param name="password">The password.</param> /// <param name="allowUntrusted">Deploy even if destination certificate is untrusted</param> /// <returns>DeploymentChangeSummary.</returns> public DeploymentChangeSummary DeployContentToOneSite(string sourcePath, string publishSettingsFile, string password = null, bool allowUntrusted = false, bool doNotDelete = true, TraceLevel traceLevel = TraceLevel.Off, bool whatIf = false, string targetPath = null) { sourcePath = Path.GetFullPath(sourcePath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string destinationPath = SetBaseOptions(publishSettingsFile, out destBaseOptions, allowUntrusted); destBaseOptions.TraceLevel = traceLevel; destBaseOptions.Trace += destBaseOptions_Trace; // use the password from the command line args if provided if (!string.IsNullOrEmpty(password)) destBaseOptions.Password = password; var sourceProvider = DeploymentWellKnownProvider.ContentPath; var targetProvider = DeploymentWellKnownProvider.ContentPath; // If a target path was specified, it could be virtual or physical if (!string.IsNullOrEmpty(targetPath)) { if (Path.IsPathRooted(targetPath)) { // If it's rooted (e.g. d:\home\site\foo), use DirPath sourceProvider = targetProvider = DeploymentWellKnownProvider.DirPath; destinationPath = targetPath; } else { // It's virtual, so append it to what we got from the publish profile destinationPath += "/" + targetPath; } } // If the content path is a zip file, use the Package provider if (Path.GetExtension(sourcePath).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { // For some reason, we can't combine a zip with a physical target path // Maybe there is some way to make it work? if (targetProvider == DeploymentWellKnownProvider.DirPath) { throw new Exception("A source zip file can't be used with a physical target path"); } sourceProvider = DeploymentWellKnownProvider.Package; } var syncOptions = new DeploymentSyncOptions { DoNotDelete = doNotDelete, WhatIf = whatIf }; // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(targetProvider, destinationPath, destBaseOptions, syncOptions); } }
public string InstallApplication(string productId, List<DeploymentParameter> updatedParameters) { string packageFile = GetApplicationPackagePath(productId); string applicationPath = null; if (String.IsNullOrEmpty(packageFile)) return null; Log.WriteInfo("WebApp Package Path: {0}", packageFile); if (!File.Exists(packageFile)) throw new Exception(GalleryErrors.PackageFileNotFound); // Setup source deployment options DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); // Add tracing capabilities sourceOptions.Trace += new EventHandler<DeploymentTraceEventArgs>(sourceOptions_Trace); sourceOptions.TraceLevel = TraceLevel.Verbose; // Setup deployment provider DeploymentProviderOptions providerOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.Package); // Set the package path location providerOptions.Path = packageFile; // Prepare the package deployment procedure using (DeploymentObject iisApplication = DeploymentManager.CreateObject(providerOptions, sourceOptions)) { // Setup destination deployment options DeploymentBaseOptions destinationOptions = new DeploymentBaseOptions(); // Add tracing capabilities destinationOptions.Trace += new EventHandler<DeploymentTraceEventArgs>(sourceOptions_Trace); destinationOptions.TraceLevel = TraceLevel.Verbose; // MSDEPLOY TEAM COMMENTS: For each parameter that was specified in the UI, set its value DeploymentParameterWellKnownTag databaseEngine = DeploymentParameterWellKnownTag.None; int i = 0; while(i < iisApplication.SyncParameters.Count) { // try to find parameter in updated parameters string name = iisApplication.SyncParameters[i].Name; DeploymentParameter updatedParameter = updatedParameters.Find( p => { return String.Compare(p.Name, name) == 0; }); if(updatedParameter != null) { // parameter found // update its value iisApplication.SyncParameters[i].Value = updatedParameter.Value; i++; // advance to the next parameter // check for selected database engine if ((updatedParameter.WellKnownTags & DeploymentParameterWellKnownTag.MySql) == DeploymentParameterWellKnownTag.MySql) databaseEngine = DeploymentParameterWellKnownTag.MySql; else if ((updatedParameter.WellKnownTags & DeploymentParameterWellKnownTag.Sql) == DeploymentParameterWellKnownTag.Sql) databaseEngine = DeploymentParameterWellKnownTag.Sql; // get application path if ((updatedParameter.WellKnownTags & DeploymentParameterWellKnownTag.IisApp) == DeploymentParameterWellKnownTag.IisApp) applicationPath = updatedParameter.Value; } else { // parameter not found // delete it iisApplication.SyncParameters.Remove(name); } } // Skip SQL Server database scripts if not SQL Server was selected if (databaseEngine != DeploymentParameterWellKnownTag.Sql) sourceOptions.SkipDirectives.Add(SkipMsSQL); // Skip MySQL database scripts if not MySQL was selected if (databaseEngine != DeploymentParameterWellKnownTag.MySql) sourceOptions.SkipDirectives.Add(SkipMySQL); // Setup deployment options DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); // Add tracing capabilities //syncOptions..Action += new EventHandler<DeploymentActionEventArgs>(syncOptions_Action); // Issue a syncronization signal between the parties iisApplication.SyncTo(DeploymentWellKnownProvider.Auto, applicationPath, destinationOptions, syncOptions); // Log.WriteInfo("{0}: {1}", "Application path", applicationPath); // } // return applicationPath; }
/// <summary> /// Web Deploy does not parameterize or run any rules (parameterization is one of the rules) when deletion is used. /// So to work around that deletecontent does a simple publish of empty content to the server and gets the IP that is hosting the volume. /// After finding the IP the deletion is called on that content path. This will effectively delete "\\someipaddress\volumename\guidfolder" /// </summary> /// <param name="unusedState">This is not used. This is the signature for the waitcallback expected by threadpool.</param> private void DeleteContent(object unusedState) { Operation operation = null; try { lock (_pendingDeleteOperations) { operation = _pendingDeleteOperations.Dequeue(); } if (operation == null) { PublishHelper.LogVerboseInformation("DeleteContent: Thread {0} did not find any operations to process", Thread.CurrentThread.ManagedThreadId); return; } operation.ThreadID = Thread.CurrentThread.ManagedThreadId; operation.Status = PublishOperationStatus.Error; DeploymentBaseOptions srcBaseOptions = new DeploymentBaseOptions(); AntaresEventProvider.EventWritePublishFailOverServiceProgressInformation(operation.ThreadID, operation.SiteName); string remoteIP = string.Empty; bool errorOcurred = false; using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, Path.GetTempPath(), srcBaseOptions)) { try { DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = operation.PublishUrl; string modifiedPhysicalPath = operation.PhysicalPath; string ipDefaultValue = GetFileServerIP(ref modifiedPhysicalPath); var queryServerIPParameter = new DeploymentSyncParameter( QueryServerIPParameterName, QueryServerIPParameterDescription, string.Empty, DeploymentWellKnownTag.PhysicalPath.ToString()); var queryServerIPParameterEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.ContentPath.ToString(), string.Empty, string.Empty); queryServerIPParameter.Add(queryServerIPParameterEntry); var contentPathParameter = new DeploymentSyncParameter( ContentPathParameterName, ContentPathParameterDescription, modifiedPhysicalPath, DeploymentWellKnownTag.PhysicalPath.ToString()); var contentParamEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.ContentPath.ToString(), string.Empty, string.Empty); contentPathParameter.Add(contentParamEntry); depObj.SyncParameters.Add(contentPathParameter); depObj.SyncParameters.Add(queryServerIPParameter); destBaseOptions.UserName = operation.AdminCredential.UserName; destBaseOptions.Password = operation.AdminCredential.Password; destBaseOptions.AuthenticationType = "basic"; depObj.SyncTo(destBaseOptions, new DeploymentSyncOptions()); } catch (Exception e) { bool unhandledException = false; // In cases where the site was deleted on the source before it was ever synced to the destination // mark as the destination invalid and set the status so that its never attempted again. if (e is DeploymentDetailedException && ((DeploymentDetailedException)e).ErrorCode == DeploymentErrorCode.ERROR_INVALID_PATH) { string[] messageArray = e.Message.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); if (messageArray.Length > 0) { remoteIP = messageArray[0]; } else { errorOcurred = true; } } else if (e is DeploymentException) { errorOcurred = true; } else { // its not a deployment exception. This is an exception not handled by web deploy such as duplicate key exception. // This needs to be retried. unhandledException = true; errorOcurred = true; } if (errorOcurred) { AntaresEventProvider.EventWritePublishFailOverServiceFailedToPublishSite(operation.SiteName, e.ToString()); operation.Status = unhandledException ? PublishOperationStatus.Error : PublishOperationStatus.SourceOrDestinationInvalid; } } } if (!errorOcurred) { string[] pathParts = operation.PhysicalPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); string remotePath = string.Concat(@"\\", remoteIP, @"\", pathParts[1], @"\", pathParts[2]); using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Auto, string.Empty, srcBaseOptions)) { try { DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = operation.PublishUrl; destBaseOptions.UserName = operation.AdminCredential.UserName; destBaseOptions.Password = operation.AdminCredential.Password; destBaseOptions.AuthenticationType = "basic"; destBaseOptions.Trace += new EventHandler<DeploymentTraceEventArgs>(WebDeployPublishTrace); destBaseOptions.TraceLevel = System.Diagnostics.TraceLevel.Verbose; var syncOptions = new DeploymentSyncOptions(); syncOptions.DeleteDestination = true; depObj.SyncTo(DeploymentWellKnownProvider.ContentPath, remotePath, destBaseOptions, syncOptions); operation.Status = PublishOperationStatus.Completed; AntaresEventProvider.EventWritePublishFailOverServicePublishComplete(operation.SiteName); } catch (Exception e) { var ex = e as DeploymentDetailedException; if (ex != null && ex.ErrorCode == DeploymentErrorCode.FileOrFolderNotFound) { operation.Status = PublishOperationStatus.SourceOrDestinationInvalid; } else { AntaresEventProvider.EventWritePublishFailOverServiceFailedToPublishSite(operation.SiteName, e.ToString()); } } } } } finally { lock (_completedOperations) { PublishHelper.LogVerboseInformation("DeleteContent: Thread {0} queuing completed operation for site: {1}", operation.ThreadID, operation.SiteName); _completedOperations.Enqueue(operation); } _continueEvent.Set(); PublishHelper.LogVerboseInformation("DeleteContent: Thread {0} exiting.", Thread.CurrentThread.ManagedThreadId); } }
/// <summary> /// Deploy package from different sources to different destiations using WebDeploy /// </summary> /// <param name="sourcePath"></param> /// <param name="destinationPath"></param> /// <param name="destinationAddress"></param> /// <param name="user"></param> /// <param name="password"></param> /// <param name="deleteExisting"></param> /// <param name="paramResolverFunc"></param> public static void DeployPackage( string sourcePath, string destinationPath, string destinationAddress, string user, string password, bool deleteExisting = true, Func<string, string> paramResolverFunc = null) { InitializeWebDeployment(); var skipDirectives = new List<DeploymentSkipDirective> { new DeploymentSkipDirective("skipDbFullSql", @"objectName=dbFullSql", true), new DeploymentSkipDirective("skipDbMySql", @"objectName=dbMySql", true) }; // define a source deployment provider and its properties const DeploymentWellKnownProvider srcProvider = DeploymentWellKnownProvider.Package; var srcBaseOptions = new DeploymentBaseOptions(); // define a destination deployment provider and its properties const DeploymentWellKnownProvider destProvider = DeploymentWellKnownProvider.Auto; var destBaseOptions = new DeploymentBaseOptions(); // define a synchronization options and set if we shoudl delete existing files var destSyncOptions = new DeploymentSyncOptions { DoNotDelete = !deleteExisting }; Deploy( sourcePath, destinationPath, destinationAddress, user, password, srcProvider, srcBaseOptions, destProvider, destBaseOptions, destSyncOptions, paramResolverFunc, skipDirectives.AsEnumerable()); }
public static void SyncWebApps(Profile src, Profile dest) { DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions(); sourceBaseOptions.ComputerName = "https://" + src.publishUrl + "/msdeploy.axd"; sourceBaseOptions.UserName = src.userName; sourceBaseOptions.Password = src.userPwd; sourceBaseOptions.AuthenticationType = "basic"; sourceBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = "https://"+dest.publishUrl+"/msdeploy.axd"; destBaseOptions.UserName = dest.userName; destBaseOptions.Password = dest.userPwd; destBaseOptions.AuthenticationType = "basic"; destBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; DeploymentProviderOptions destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.ContentPath); destProviderOptions.Path = dest.sitename; DeploymentObject sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, src.sitename,sourceBaseOptions); sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions); }
private static void ExecuteDeploy( string sourcePath, string destinationPath, DeploymentWellKnownProvider srcProvider, DeploymentBaseOptions srcBaseOptions, DeploymentWellKnownProvider destProvider, DeploymentBaseOptions destBaseOptions, DeploymentSyncOptions destSyncOptions, Func<string, string> syncParamResolver = null, IEnumerable<string> removedParameters = null) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, e) => true; try { using (DeploymentObject deployObj = DeploymentManager.CreateObject(srcProvider, sourcePath, srcBaseOptions)) { // resolve parameters if any if (syncParamResolver != null) { foreach (var syncParam in deployObj.SyncParameters) { var resolvedValue = syncParamResolver(syncParam.Name); if (resolvedValue != null) { syncParam.Value = resolvedValue; } } } // remove parameters if any if (removedParameters != null) { foreach (var parameter in removedParameters) { deployObj.SyncParameters.Remove(parameter); } } TestEasyLog.Instance.Info(string.Format("Deploying: {0}", sourcePath)); // do action TestEasyLog.Instance.LogObject(deployObj.SyncTo(destProvider, destinationPath, destBaseOptions, destSyncOptions)); } } catch (Exception e) { TestEasyLog.Instance.Info(string.Format("Exception during deployment of '{0}': '{1}'", sourcePath, e.Message)); throw; } }
/// <summary> /// Web Deploy does not parameterize or run any rules (parameterization is one of the rules) when deletion is used. /// So to work around that deletecontent does a simple publish of empty content to the server and gets the IP that is hosting the volume. /// After finding the IP the deletion is called on that content path. This will effectively delete "\\someipaddress\volumename\guidfolder" /// </summary> /// <param name="unusedState">This is not used. This is the signature for the waitcallback expected by threadpool.</param> private void DeleteContent(object unusedState) { Operation operation = null; try { lock (_pendingDeleteOperations) { operation = _pendingDeleteOperations.Dequeue(); } if (operation == null) { PublishHelper.LogVerboseInformation("DeleteContent: Thread {0} did not find any operations to process", Thread.CurrentThread.ManagedThreadId); return; } operation.ThreadID = Thread.CurrentThread.ManagedThreadId; operation.Status = PublishOperationStatus.Error; DeploymentBaseOptions srcBaseOptions = new DeploymentBaseOptions(); AntaresEventProvider.EventWritePublishFailOverServiceProgressInformation(operation.ThreadID, operation.SiteName); string remoteIP = string.Empty; bool errorOcurred = false; using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, Path.GetTempPath(), srcBaseOptions)) { try { DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = operation.PublishUrl; string modifiedPhysicalPath = operation.PhysicalPath; string ipDefaultValue = GetFileServerIP(ref modifiedPhysicalPath); var queryServerIPParameter = new DeploymentSyncParameter( QueryServerIPParameterName, QueryServerIPParameterDescription, string.Empty, DeploymentWellKnownTag.PhysicalPath.ToString()); var queryServerIPParameterEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.ContentPath.ToString(), string.Empty, string.Empty); queryServerIPParameter.Add(queryServerIPParameterEntry); var contentPathParameter = new DeploymentSyncParameter( ContentPathParameterName, ContentPathParameterDescription, modifiedPhysicalPath, DeploymentWellKnownTag.PhysicalPath.ToString()); var contentParamEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.ContentPath.ToString(), string.Empty, string.Empty); contentPathParameter.Add(contentParamEntry); depObj.SyncParameters.Add(contentPathParameter); depObj.SyncParameters.Add(queryServerIPParameter); destBaseOptions.UserName = operation.AdminCredential.UserName; destBaseOptions.Password = operation.AdminCredential.Password; destBaseOptions.AuthenticationType = "basic"; depObj.SyncTo(destBaseOptions, new DeploymentSyncOptions()); } catch (Exception e) { bool unhandledException = false; // In cases where the site was deleted on the source before it was ever synced to the destination // mark as the destination invalid and set the status so that its never attempted again. if (e is DeploymentDetailedException && ((DeploymentDetailedException)e).ErrorCode == DeploymentErrorCode.ERROR_INVALID_PATH) { string[] messageArray = e.Message.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); if (messageArray.Length > 0) { remoteIP = messageArray[0]; } else { errorOcurred = true; } } else if (e is DeploymentException) { errorOcurred = true; } else { // its not a deployment exception. This is an exception not handled by web deploy such as duplicate key exception. // This needs to be retried. unhandledException = true; errorOcurred = true; } if (errorOcurred) { AntaresEventProvider.EventWritePublishFailOverServiceFailedToPublishSite(operation.SiteName, e.ToString()); operation.Status = unhandledException ? PublishOperationStatus.Error : PublishOperationStatus.SourceOrDestinationInvalid; } } } if (!errorOcurred) { string[] pathParts = operation.PhysicalPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); string remotePath = string.Concat(@"\\", remoteIP, @"\", pathParts[1], @"\", pathParts[2]); using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Auto, string.Empty, srcBaseOptions)) { try { DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = operation.PublishUrl; destBaseOptions.UserName = operation.AdminCredential.UserName; destBaseOptions.Password = operation.AdminCredential.Password; destBaseOptions.AuthenticationType = "basic"; destBaseOptions.Trace += new EventHandler <DeploymentTraceEventArgs>(WebDeployPublishTrace); destBaseOptions.TraceLevel = System.Diagnostics.TraceLevel.Verbose; var syncOptions = new DeploymentSyncOptions(); syncOptions.DeleteDestination = true; depObj.SyncTo(DeploymentWellKnownProvider.ContentPath, remotePath, destBaseOptions, syncOptions); operation.Status = PublishOperationStatus.Completed; AntaresEventProvider.EventWritePublishFailOverServicePublishComplete(operation.SiteName); } catch (Exception e) { var ex = e as DeploymentDetailedException; if (ex != null && ex.ErrorCode == DeploymentErrorCode.FileOrFolderNotFound) { operation.Status = PublishOperationStatus.SourceOrDestinationInvalid; } else { AntaresEventProvider.EventWritePublishFailOverServiceFailedToPublishSite(operation.SiteName, e.ToString()); } } } } } finally { lock (_completedOperations) { PublishHelper.LogVerboseInformation("DeleteContent: Thread {0} queuing completed operation for site: {1}", operation.ThreadID, operation.SiteName); _completedOperations.Enqueue(operation); } _continueEvent.Set(); PublishHelper.LogVerboseInformation("DeleteContent: Thread {0} exiting.", Thread.CurrentThread.ManagedThreadId); } }
public IReportStatus Sync(IProvide provider, ServerConfig server, bool continueOnError, IReportStatus status, EventHandler <DeploymentTraceEventArgs> onTraceMessage) { _untrappedExitCodeException = null; var destBaseOptions = provider.GetWebDeployDestBaseOptions(); try { var syncOptions = new DeploymentSyncOptions(); var sourceBaseOptions = provider.GetWebDeploySourceBaseOptions(); sourceBaseOptions.Trace += onTraceMessage; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; destBaseOptions.Trace += onTraceMessage; destBaseOptions.TraceLevel = TraceLevel.Verbose; destBaseOptions.ComputerName = server.WebDeployAgentUrl; destBaseOptions.UserName = server.DeploymentUser.UserName; destBaseOptions.Password = server.DeploymentUser.Password; var defaultWaitInterval = destBaseOptions.RetryInterval; var defaultRetryAttempts = destBaseOptions.RetryAttempts; if (provider.WaitIntervalInSeconds > 0) { destBaseOptions.RetryInterval = provider.WaitIntervalInSeconds * 1000; sourceBaseOptions.RetryInterval = provider.WaitIntervalInSeconds * 1000; } if (provider.RetryAttempts > 0) { destBaseOptions.RetryAttempts = provider.RetryAttempts; sourceBaseOptions.RetryAttempts = provider.RetryAttempts; } destBaseOptions.Trace += CheckForUntrappedExitCodes; DeploymentChangeSummary summery; using (var sourceDepObject = DeploymentManager.CreateObject(provider.GetWebDeploySourceProviderOptions(), sourceBaseOptions)) { foreach (var rule in provider.GetReplaceRules()) { syncOptions.Rules.Add(rule); } summery = sourceDepObject.SyncTo(provider.GetWebDeployDestinationProviderOptions(), destBaseOptions, syncOptions); } status.AddSummery(summery); destBaseOptions.RetryInterval = defaultWaitInterval; destBaseOptions.RetryAttempts = defaultRetryAttempts; if (summery.Errors > 0) { throw new ConDepWebDeployProviderException("The provider reported " + summery.Errors + " during deployment."); } } catch { if (!continueOnError) { throw; } } finally { destBaseOptions.Trace -= CheckForUntrappedExitCodes; if (_untrappedExitCodeException != null && !continueOnError) { throw _untrappedExitCodeException; } } return(status); }
private static DeploymentSyncOptions DeploymentSyncOptions(VariableDictionary variables) { var syncOptions = new DeploymentSyncOptions { WhatIf = false, UseChecksum = true, DoNotDelete = !variables.GetFlag(SpecialVariables.Action.Azure.RemoveAdditionalFiles, false) }; // If PreserveAppData variable set, then create SkipDelete rules for App_Data directory if (variables.GetFlag(SpecialVariables.Action.Azure.PreserveAppData, false)) { syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataFiles", "Delete", "filePath", "\\\\App_Data\\\\.*", null)); syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDataDir", "Delete", "dirPath", "\\\\App_Data(\\\\.*|$)", null)); } // If PreservePaths variable set, then create SkipDelete rules for each path regex var preservePaths = variables.GetStrings(SpecialVariables.Action.Azure.PreservePaths, ';'); if (preservePaths != null) { for (var i = 0; i < preservePaths.Count; i++) { var path = preservePaths[i]; syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteFiles_" + i, "Delete", "filePath", path, null)); syncOptions.Rules.Add(new DeploymentSkipRule("SkipDeleteDir_" + i, "Delete", "dirPath", path, null)); } } return syncOptions; }
public DeploymentChangeSummary Deploy(DeploySettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } DeploymentBaseOptions baseOptions1 = new DeploymentBaseOptions(); DeploymentBaseOptions baseOptions2 = this.GetBaseOptions(settings); FilePath sourcePath = settings.SourcePath; string str1; if (sourcePath == null) { str1 = (string)null; } else { ICakeEnvironment environment = this.environment; FilePath filePath = sourcePath.MakeAbsolute(environment); str1 = filePath != null ? ((Path)filePath).FullPath : (string)null; } string path1 = str1; FilePath destinationPath = settings.DestinationPath; string str2; if (destinationPath == null) { str2 = (string)null; } else { ICakeEnvironment environment = this.environment; FilePath filePath = destinationPath.MakeAbsolute(environment); str2 = filePath != null ? ((Path)filePath).FullPath : (string)null; } string path2 = str2; LogExtensions.Information(this.log, (Verbosity)2, "CCC", new object[0]); baseOptions2.TraceLevel = settings.TraceLevel; baseOptions2.Trace += new EventHandler <DeploymentTraceEventArgs>(this.OnTraceEvent); if (settings.DestProvider == DeploymentWellKnownProvider.Auto) { path2 = settings.SiteName; } DeploymentSyncOptions deploymentSyncOptions = new DeploymentSyncOptions(); int num1 = !settings.Delete ? 1 : 0; deploymentSyncOptions.DoNotDelete = num1 != 0; int num2 = settings.WhatIf ? 1 : 0; deploymentSyncOptions.WhatIf = num2 != 0; DeploymentSyncOptions syncOptions = deploymentSyncOptions; if (settings.DeclareParamFile != null) { syncOptions.DeclaredParameters.Load(((Path)settings.DeclareParamFile.MakeAbsolute(this.environment)).FullPath); } foreach (SkipRule skipRule in settings.SkipRules) { syncOptions.Rules.Add((DeploymentRule) new DeploymentSkipRule(skipRule.Name, skipRule.SkipAction, skipRule.ObjectName, skipRule.AbsolutePath, skipRule.XPath)); } LogExtensions.Information(this.log, (Verbosity)2, "Deploying Website...", new object[0]); LogExtensions.Debug(this.log, (Verbosity)2, string.Format("-siteName '{0}'", (object)settings.SiteName), new object[0]); LogExtensions.Debug(this.log, (Verbosity)2, string.Format("-destination '{0}'", (object)settings.PublishUrl), new object[0]); LogExtensions.Debug(this.log, (Verbosity)2, string.Format("-source '{0}'", (object)path1), new object[0]); LogExtensions.Debug(this.log, string.Empty, new object[0]); using (DeploymentObject deploymentObject = DeploymentManager.CreateObject(settings.SourceProvider, path1, baseOptions1)) { foreach (KeyValuePair <string, string> parameter in settings.Parameters) { deploymentObject.SyncParameters[parameter.Key].Value = parameter.Value; } return(deploymentObject.SyncTo(settings.DestProvider, path2, baseOptions2, syncOptions)); } }
/// <summary> /// Deploys the content of a website /// </summary> /// <param name="settings">The deployment settings.</param> /// <returns>The <see cref="DeploymentChangeSummary"/> that was applied during the deployment.</returns> public DeploymentChangeSummary Deploy(DeploySettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } if (settings.SourcePath == null) { throw new ArgumentNullException("settings.SourcePath"); } DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destOptions = this.GetBaseOptions(settings); FilePath sourcePath = settings.SourcePath.MakeAbsolute(_Environment); string destPath = settings.SiteName; destOptions.TraceLevel = settings.TraceLevel; destOptions.Trace += OnTraceEvent; DeploymentWellKnownProvider sourceProvider = DeploymentWellKnownProvider.ContentPath; DeploymentWellKnownProvider destProvider = DeploymentWellKnownProvider.Auto; //If a target path was specified, it could be virtual or physical if (settings.DestinationPath != null) { if (System.IO.Path.IsPathRooted(settings.DestinationPath.FullPath)) { // If it's rooted (e.g. d:\home\site\foo), use DirPath sourceProvider = DeploymentWellKnownProvider.DirPath; destProvider = DeploymentWellKnownProvider.DirPath; destPath = settings.DestinationPath.FullPath; } else { // It's virtual, so append it to what we got from the publish profile destPath += "/" + settings.DestinationPath.FullPath; } } //When a SiteName is given but no DestinationPath else if (!String.IsNullOrWhiteSpace(settings.SiteName)) { //use ContentPath so it gets deployed to the Path of the named website in IIS //which is the same behaviour as in Visual Studio destProvider = DeploymentWellKnownProvider.ContentPath; } //If the content path is a zip file, use the Package provider string extension = sourcePath.GetExtension(); if (extension != null && extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { // For some reason, we can't combine a zip with a physical target path if (destProvider == DeploymentWellKnownProvider.DirPath) { throw new Exception("A source zip file can't be used with a physical target path"); } sourceProvider = DeploymentWellKnownProvider.Package; } //Sync Options DeploymentSyncOptions syncOptions = new DeploymentSyncOptions { DoNotDelete = !settings.Delete, WhatIf = settings.WhatIf }; // Add SkipRules foreach (var rule in settings.SkipRules) { syncOptions.Rules.Add(new DeploymentSkipRule(rule.Name, rule.SkipAction, rule.ObjectName, rule.AbsolutePath, rule.XPath)); } //Deploy _Log.Debug(Verbosity.Normal, "Deploying Website..."); _Log.Debug(Verbosity.Normal, String.Format("-siteName '{0}'", settings.SiteName)); _Log.Debug(Verbosity.Normal, String.Format("-destination '{0}'", settings.PublishUrl)); _Log.Debug(Verbosity.Normal, String.Format("-source '{0}'", sourcePath.FullPath)); _Log.Debug(""); using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath.FullPath, sourceOptions)) { foreach (var kv in settings.Parameters) { if (deploymentObject.SyncParameters.Contains(kv.Key)) { deploymentObject.SyncParameters[kv.Key].Value = kv.Value; } else { deploymentObject.SyncParameters.Add(new DeploymentSyncParameter(kv.Key, kv.Key, "", "") { Value = kv.Value }); } } return(deploymentObject.SyncTo(destProvider, destPath, destOptions, syncOptions)); } }
/// <summary> /// Publish a WebDeploy package zip file to a web site. /// </summary> /// <param name="websiteName">The name of the web site.</param> /// <param name="slot">The name of the slot.</param> /// <param name="package">The WebDeploy package zip file.</param> /// <param name="connectionStrings">The connection strings to overwrite the ones in the Web.config file.</param> /// <param name="skipAppData">Skip app data</param> /// <param name="doNotDelete">Do not delete files at destination</param> private void PublishWebProjectFromPackagePath(string websiteName, string slot, string package, Hashtable connectionStrings, bool skipAppData, bool doNotDelete) { DeploymentBaseOptions remoteBaseOptions = CreateRemoteDeploymentBaseOptions(websiteName, slot); DeploymentBaseOptions localBaseOptions = new DeploymentBaseOptions(); SetWebDeployToSkipAppData(skipAppData, localBaseOptions, remoteBaseOptions); using (var deployment = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, package, localBaseOptions)) { ReplaceConnectionStrings(deployment, connectionStrings); DeploymentSyncOptions syncOptions = new DeploymentSyncOptions { DoNotDelete = doNotDelete }; deployment.SyncTo(DeploymentWellKnownProvider.ContentPath, SetWebsiteNameForWebDeploy(websiteName, slot), remoteBaseOptions, syncOptions); } }
/// <summary> /// Deploys the content to one site. /// </summary> /// <param name="sourcePath">The content path.</param> /// <param name="publishSettingsFile">The publish settings file.</param> /// <param name="password">The password.</param> /// <param name="allowUntrusted">Deploy even if destination certificate is untrusted</param> /// <returns>DeploymentChangeSummary.</returns> public DeploymentChangeSummary DeployContentToOneSite(string sourcePath, string publishSettingsFile, string password = null, bool allowUntrusted = false, bool doNotDelete = true, TraceLevel traceLevel = TraceLevel.Off, bool whatIf = false, string targetPath = null, bool useChecksum = false, bool appOfflineEnabled = false) { sourcePath = Path.GetFullPath(sourcePath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string destinationPath = SetBaseOptions(publishSettingsFile, out destBaseOptions, allowUntrusted); destBaseOptions.TraceLevel = traceLevel; destBaseOptions.Trace += destBaseOptions_Trace; // use the password from the command line args if provided if (!string.IsNullOrEmpty(password)) { destBaseOptions.Password = password; } var sourceProvider = DeploymentWellKnownProvider.ContentPath; var targetProvider = DeploymentWellKnownProvider.ContentPath; // If a target path was specified, it could be virtual or physical if (!string.IsNullOrEmpty(targetPath)) { if (Path.IsPathRooted(targetPath)) { // If it's rooted (e.g. d:\home\site\foo), use DirPath sourceProvider = targetProvider = DeploymentWellKnownProvider.DirPath; destinationPath = targetPath; } else { // It's virtual, so append it to what we got from the publish profile destinationPath += "/" + targetPath; } } // If the content path is a zip file, use the Package provider if (Path.GetExtension(sourcePath).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { // For some reason, we can't combine a zip with a physical target path // Maybe there is some way to make it work? if (targetProvider == DeploymentWellKnownProvider.DirPath) { throw new Exception("A source zip file can't be used with a physical target path"); } sourceProvider = DeploymentWellKnownProvider.Package; } var syncOptions = new DeploymentSyncOptions { DoNotDelete = doNotDelete, WhatIf = whatIf, UseChecksum = useChecksum }; if (appOfflineEnabled) { AddDeploymentRule(syncOptions, "AppOffline"); } // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return(deploymentObject.SyncTo(targetProvider, destinationPath, destBaseOptions, syncOptions)); } }
public List<string> TestSkipRule(List<SkipRule> skipRules, string contentPath) { DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destOptions = new DeploymentBaseOptions(); DeploymentSyncOptions syncOptions = new DeploymentSyncOptions(); _skipRulesTestResults = new List<string>(); AddSkips(skipRules.AsReadOnly(), sourceOptions, destOptions); syncOptions.WhatIf = true; // Puropsely only setting event handler for source so that we don't get duplicate // events being fired sourceOptions.TraceLevel = TraceLevel.Verbose; sourceOptions.Trace += AddSkipRuleResultEventHandler; using (DeploymentObject sourceObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceOptions)) { sourceObject.SyncTo(destOptions, syncOptions); } _skipRulesTestResults.Sort(); return _skipRulesTestResults; }
public IReportStatus Sync(IProvide provider, ServerConfig server, bool continueOnError, IReportStatus status, EventHandler<DeploymentTraceEventArgs> onTraceMessage) { _untrappedExitCodeException = null; var destBaseOptions = provider.GetWebDeployDestBaseOptions(); try { var syncOptions = new DeploymentSyncOptions(); var sourceBaseOptions = provider.GetWebDeploySourceBaseOptions(); sourceBaseOptions.Trace += onTraceMessage; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; destBaseOptions.Trace += onTraceMessage; destBaseOptions.TraceLevel = TraceLevel.Verbose; destBaseOptions.ComputerName = server.WebDeployAgentUrl; destBaseOptions.UserName = server.DeploymentUser.UserName; destBaseOptions.Password = server.DeploymentUser.Password; var defaultWaitInterval = destBaseOptions.RetryInterval; var defaultRetryAttempts = destBaseOptions.RetryAttempts; if (provider.WaitIntervalInSeconds > 0) { destBaseOptions.RetryInterval = provider.WaitIntervalInSeconds * 1000; sourceBaseOptions.RetryInterval = provider.WaitIntervalInSeconds * 1000; } if (provider.RetryAttempts > 0) { destBaseOptions.RetryAttempts = provider.RetryAttempts; sourceBaseOptions.RetryAttempts = provider.RetryAttempts; } destBaseOptions.Trace += CheckForUntrappedExitCodes; DeploymentChangeSummary summery; using (var sourceDepObject = DeploymentManager.CreateObject(provider.GetWebDeploySourceProviderOptions(), sourceBaseOptions)) { foreach (var rule in provider.GetReplaceRules()) { syncOptions.Rules.Add(rule); } summery = sourceDepObject.SyncTo(provider.GetWebDeployDestinationProviderOptions(), destBaseOptions, syncOptions); } status.AddSummery(summery); destBaseOptions.RetryInterval = defaultWaitInterval; destBaseOptions.RetryAttempts = defaultRetryAttempts; if (summery.Errors > 0) { throw new ConDepWebDeployProviderException("The provider reported " + summery.Errors + " during deployment."); } } catch { if (!continueOnError) { throw; } } finally { destBaseOptions.Trace -= CheckForUntrappedExitCodes; if (_untrappedExitCodeException != null && !continueOnError) { throw _untrappedExitCodeException; } } return status; }