/// <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 WebDeployOptions(string packagePath, DeploymentBaseOptions sourceBaseOptions, DeploymentBaseOptions destBaseOptions, DeploymentSyncOptions syncOptions) { _packagePath = packagePath; _sourceBaseOptions = sourceBaseOptions; _destBaseOptions = destBaseOptions; _syncOptions = syncOptions; }
/// <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> /// <returns>DeploymentChangeSummary.</returns> public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile, string password = null) { contentPath = Path.GetFullPath(contentPath); var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = SetBaseOptions(publishSettingsFile, out destBaseOptions); // 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; } // 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, new DeploymentSyncOptions()); } }
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 void UpdateBaseOptions(DeploymentBaseOptions baseOption, string serviceUrl, string remoteSite, string user, string password) { baseOption.ComputerName = ConstructServiceUrlForDeployThruWMSVC(serviceUrl, remoteSite); baseOption.TempAgent = false; baseOption.AuthenticationType = "Basic"; baseOption.Trace += new EventHandler<DeploymentTraceEventArgs>(LogTrace); baseOption.UserName = user; baseOption.Password = password; }
public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile) { var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = SetBaseOptions(publishSettingsFile, out destBaseOptions); Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile)); // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()); } }
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 DeploymentBaseOptions DeploymentOptions(PublishProfile publishProfile) { var options = new DeploymentBaseOptions { AuthenticationType = "Basic", RetryAttempts = 3, RetryInterval = 1000, TraceLevel = TraceLevel.Verbose, UserName = publishProfile.UserName, Password = publishProfile.UserPassword, UserAgent = "OctopusDeploy/1.0", ComputerName = string.Format("https://{0}/msdeploy.axd?site={1}", publishProfile.PublishUrl, publishProfile.MSDeploySite), }; options.Trace += (sender, eventArgs) => LogDeploymentEvent(eventArgs); return options; }
private string SetBaseOptions(string publishSettingsPath, out DeploymentBaseOptions deploymentBaseOptions) { PublishSettings publishSettings = new PublishSettings(publishSettingsPath); deploymentBaseOptions = new DeploymentBaseOptions { ComputerName = publishSettings.ComputerName, UserName = publishSettings.Username, Password = publishSettings.Password, AuthenticationType = publishSettings.AuthenticationType }; if (publishSettings.AllowUntrusted) { ServicePointManager.ServerCertificateValidationCallback = AllowCertificateCallback; } return publishSettings.SiteName; }
private static void PrepareDatabaseDeployment(WebDeployDatabaseType dbType, out DeploymentWellKnownProvider provider, out DeploymentBaseOptions options, bool includeData = false, bool dropDestinationDatabase = false) { provider = DeploymentWellKnownProvider.DBDacFx; options = new DeploymentBaseOptions(); switch (dbType) { case WebDeployDatabaseType.SqlCe: case WebDeployDatabaseType.FullSql: provider = DeploymentWellKnownProvider.DBDacFx; break; case WebDeployDatabaseType.MySql: provider = DeploymentWellKnownProvider.DBMySql; break; } options.AddDefaultProviderSetting(provider.ToString(), "dropDestinationDatabase", dropDestinationDatabase); options.AddDefaultProviderSetting(provider.ToString(), "includeData", includeData); }
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> /// 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); } }
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 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> /// Create remote deployment base options using the web site publish profile. /// </summary> /// <returns>The remote deployment base options.</returns> private DeploymentBaseOptions CreateRemoteDeploymentBaseOptions(string websiteName, string slot) { // Get the web site publish profile. var publishProfile = GetWebDeployPublishProfile(websiteName, slot); DeploymentBaseOptions remoteBaseOptions = new DeploymentBaseOptions() { UserName = publishProfile.UserName, Password = publishProfile.UserPassword, ComputerName = string.Format(Resources.WebSiteWebDeployUriTemplate, publishProfile.PublishUrl, SetWebsiteNameForWebDeploy(websiteName, slot)), AuthenticationType = "Basic", TempAgent = false }; return remoteBaseOptions; }
/// <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()); }
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 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); } }
private void Publish(object unusedState) { Operation operation = null; try { lock (_pendingPublishOperations) { operation = _pendingPublishOperations.Dequeue(); } if (operation == null) { PublishHelper.LogVerboseInformation("Publish: Thread {0} did not find any operations to process", Thread.CurrentThread.ManagedThreadId); return; } // This was not required earlier but now that every site will be synced twice for every incoming publish (Look at the postsync override in publishextender), // there are chances that same operation might get scheduled in concurrent threads which is not a supported web deploy scenario. bool canContinue = true; lock (_operationsInProgress) { if (_operationsInProgress.Contains(operation.SiteName)) { PublishHelper.LogVerboseInformation("Publish: An operation for {0} is already in progress. Thread {1} will mark it as not started to be scheduled later.", operation.SiteName, Thread.CurrentThread.ManagedThreadId); operation.Status = PublishOperationStatus.NotStarted; canContinue = false; } else { _operationsInProgress.Add(operation.SiteName); } } if (!canContinue) { lock (_completedOperations) { _completedOperations.Enqueue(operation); } return; } operation.ThreadID = Thread.CurrentThread.ManagedThreadId; operation.Status = PublishOperationStatus.Error; DeploymentBaseOptions srcBaseOptions = new DeploymentBaseOptions(); AntaresEventProvider.EventWritePublishFailOverServiceProgressInformation(operation.ThreadID, operation.SiteName); using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Manifest, PublishHelper.GetPublishManifest(operation.PhysicalPath), srcBaseOptions)) { try { DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = operation.PublishUrl; string modifiedPhysicalPath = operation.PhysicalPath; string ipDefaultValue = GetFileServerIP(ref modifiedPhysicalPath); var fileServerIPParameter = new DeploymentSyncParameter( FileServerIPParameterName, FileServerIPParameterDescription, ipDefaultValue, string.Empty); var fileServerIPEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.ContentPath.ToString(), string.Empty, string.Empty); fileServerIPParameter.Add(fileServerIPEntry); 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); var setAclParameter = new DeploymentSyncParameter( SetAclParameterName, SetAclParameterDescription, modifiedPhysicalPath, DeploymentWellKnownTag.SetAcl.ToString()); var setAclParamEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.SetAcl.ToString(), string.Empty, string.Empty); setAclParameter.Add(setAclParamEntry); depObj.SyncParameters.Add(fileServerIPParameter); depObj.SyncParameters.Add(contentPathParameter); depObj.SyncParameters.Add(setAclParameter); 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; depObj.SyncTo(destBaseOptions, new DeploymentSyncOptions()); operation.Status = PublishOperationStatus.Completed; AntaresEventProvider.EventWritePublishFailOverServicePublishComplete(operation.SiteName); } catch (Exception e) { AntaresEventProvider.EventWritePublishFailOverServiceFailedToPublishSite(operation.SiteName, e.ToString()); } } } catch (Exception e) { if ((e is DeploymentDetailedException && ((DeploymentDetailedException)e).ErrorCode == DeploymentErrorCode.FileOrFolderNotFound) || e is WebHostingObjectNotFoundException) { operation.Status = PublishOperationStatus.SourceOrDestinationInvalid; } AntaresEventProvider.EventWritePublishFailOverServiceFailedToGetSourceSite(operation.SiteName, e.ToString()); } finally { lock (_completedOperations) { PublishHelper.LogVerboseInformation("Publish: Thread {0} qeuing completed operation for site: {1}", operation.ThreadID, operation.SiteName); _completedOperations.Enqueue(operation); } lock (_operationsInProgress) { _operationsInProgress.Remove(operation.SiteName); } _continueEvent.Set(); PublishHelper.LogVerboseInformation("Publish: Thread {0} exiting", Thread.CurrentThread.ManagedThreadId); } }
/// <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); } }
//Helpers private DeploymentBaseOptions GetBaseOptions(DeploySettings settings) { DeploymentBaseOptions options = new DeploymentBaseOptions { ComputerName = settings.PublishUrl, UserName = settings.Username, Password = settings.Password, AuthenticationType = settings.NTLM ? "ntlm" : "basic" }; if (settings.AllowUntrusted) { ServicePointManager.ServerCertificateValidationCallback = OnCertificateValidation; } return options; }
public DeploymentChangeSummary DeployContentToOneSite( IConfigRepository repository, string contentPath, string publishSettingsFile) { var sourceBaseOptions = new DeploymentBaseOptions(); DeploymentBaseOptions destBaseOptions; string siteName = SetDestBaseOptions(publishSettingsFile, out destBaseOptions); bool success = true; DeploymentChangeSummary summary = null; AddSkips(repository.Config.SkipRules, sourceBaseOptions, destBaseOptions); Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile)); using (StatusFile status = new StatusFile(siteName)) using (LogFile logFile = new LogFile(siteName, false)) { sourceBaseOptions.Trace += logFile.LogEventHandler; destBaseOptions.Trace += logFile.LogEventHandler; try { logFile.Log(TraceLevel.Info, "Beginning sync"); status.State = Models.DeployState.Deploying; status.Save(); // Publish the content to the remote site using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions)) { // Note: would be nice to have an async flavor of this API... summary = deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()); } string summaryString = string.Format("Total Changes: {0} ({1} added, {2} deleted, {3} updated, {4} parameters changed, {5} bytes copied)", summary.TotalChanges, summary.ObjectsAdded, summary.ObjectsDeleted, summary.ObjectsUpdated, summary.ParameterChanges, summary.BytesCopied); status.ObjectsAdded = summary.ObjectsAdded; status.ObjectsDeleted = summary.ObjectsDeleted; status.ObjectsUpdated = summary.ObjectsUpdated; status.ParametersChanged = summary.ParameterChanges; status.BytesCopied = summary.BytesCopied; logFile.Log(TraceLevel.Info, summaryString); logFile.Log(TraceLevel.Info, "Sync completed successfully"); } catch (Exception e) { logFile.Log(TraceLevel.Error, e.ToString()); success = false; status.State = Models.DeployState.Failed; } if (success) { status.State = Models.DeployState.Succeeded; } }// Close log file and status file return(summary); }
/// <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 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; }
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> /// 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 static DeploymentBaseOptions GetSourceOptions() { var options = new DeploymentBaseOptions(); return(options); }
/// <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); }
/// <summary> /// Fetches the remote servers file list. /// </summary> /// <param name="properties">The properties.</param> /// <returns></returns> /// <exception cref="System.ArgumentException">Connection properties cannot be null.;properties</exception> public DeploymentObjectList FetchFileList(ConnectionProperties properties) { if (properties == null) throw new ArgumentException("Connection properties cannot be null.", "properties"); properties.Validate(); var results = new DeploymentObjectList { Folders = new List<string>(), Files = new List<string>() }; if (properties.AllowUntrustedCertificates) { ServicePointManager.ServerCertificateValidationCallback = (s, c, chain, err) => true; } var destOptions = new DeploymentBaseOptions { ComputerName = BuildMsDeployUri(properties).ToString(), UserName = properties.Username, Password = properties.Password, UseDelegation = true, AuthenticationType = "Basic" }; foreach (var extension in destOptions.LinkExtensions.Where(extension => extension.Name == "ContentExtension")) { extension.Enabled = false; break; } using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, properties.IISWebsiteName, destOptions)) { var xmlResult = GetDeploymentObjectAsXmlDocument(deploymentObject); TextReader tr = new StringReader(xmlResult.InnerXml); var doc = XDocument.Load(tr); results.Files = (from f in doc.Element("MSDeploy.contentPath").Element("contentPath") .Element("dirPath") .Elements("filePath") select f.Attribute("path").Value).ToList(); results.Folders = (from f in doc.Element("MSDeploy.contentPath").Element("contentPath") .Element("dirPath") .Elements("dirPath") select f.Attribute("path").Value).ToList(); } return results; }
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); }
public bool PublishDatabase(DeploymentBaseOptions sourceBaseOptions, DeploymentBaseOptions destBaseOptions, string provider, bool logException) { bool publishSucceeded = true; this.LogTrace("Starting db publish for {0}", _localSite.SiteName); try { var providerOption = new DeploymentProviderOptions(provider); foreach (var providerSetting in providerOption.ProviderSettings) { var setting = ConfigurationManager.AppSettings[providerSetting.Name]; if (!string.IsNullOrEmpty(setting)) { try { providerSetting.Value = setting; } catch (Exception ex) { this.LogTrace("Error trying to set value: {0} for setting: {1}, {2}", setting, providerSetting.Name, ex.ToString()); } } } string path = _localSite.Databases[0].DBConnectionString; if (path.Contains("|DataDirectory|")) { // TODO: is there a better way to do this? Can we lookup |DataDirectory| path = path.Replace("|DataDirectory|", this._localSite.PhysicalPath + @"\App_Data\"); } providerOption.Path = path; RemoteSystemInfo remoteSystemInfo = null; if (RemoteSystemInfos.Servers.Any() && UseTrustedConnection(_localSite.Databases[0].DBConnectionString)) { remoteSystemInfo = RemoteSystemInfos.Servers[_localSite.ServerName]; } using (Impersonator.ImpersonateUser(remoteSystemInfo)) { using (var sourceObject = DeploymentManager.CreateObject(providerOption, sourceBaseOptions)) { LogTrace("Starting DB Sync for: {0} using {1}", (string)_localSite.Databases[0].DbConnectionStringBuilder["Initial Catalog"], provider); this.LogTrace("Publishing database as: {0}", destBaseOptions.UserName); try { sourceObject.SyncTo(provider, _publishSettings.SqlDBConnectionString.ConnectionString, destBaseOptions, new DeploymentSyncOptions()); this.LogTrace("DB Synced successfully"); Helper.UpdateStatus(_localSite.SiteName, _localSite.ServerName, true); } catch (Exception ex) { if (logException) { LogTrace("Error starting publish for db: {0}", (string)_localSite.Databases[0].DbConnectionStringBuilder["Initial Catalog"]); this.LogTrace(ex.ToString()); } publishSucceeded = false; } } } } catch (Exception ex) { if (logException) { LogTrace("Error syncing db: {0}", (string)_localSite.Databases[0].DbConnectionStringBuilder["Initial Catalog"]); LogTrace(ex.ToString()); } publishSucceeded = false; } return publishSucceeded; }
private void AddSkippedFoldersToWebDeploy(IEnumerable <string> skippedFoldersRegexps, DeploymentBaseOptions sourceBaseOptions, DeploymentBaseOptions destinationBaseOptions) { foreach (var skippedFoldersRegexp in skippedFoldersRegexps) { var skippedDirective = new DeploymentSkipDirective($"Skip_{skippedFoldersRegexp}", $"objectName=dirPath,absolutePath={skippedFoldersRegexp}", true); sourceBaseOptions.SkipDirectives.Add(skippedDirective); destinationBaseOptions.SkipDirectives.Add(skippedDirective); } }
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; }
private static void SetWebDeployToSkipAppData(bool skipAppData, DeploymentBaseOptions localBaseOptions, DeploymentBaseOptions remoteBaseOptions) { if (skipAppData) { var skipAppDataDirective = new DeploymentSkipDirective("skipAppData", @"objectName=dirPath,absolutePath=.*app_data", true); localBaseOptions.SkipDirectives.Add(skipAppDataDirective); remoteBaseOptions.SkipDirectives.Add(skipAppDataDirective); } }
/// <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 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); } }
/// <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 bool PublishDatabase(DeploymentBaseOptions sourceBaseOptions, DeploymentBaseOptions destBaseOptions, string provider, bool logException) { bool publishSucceeded = true; this.LogTrace("Starting db publish for {0}", _localSite.SiteName); try { var providerOption = new DeploymentProviderOptions(provider); foreach (var providerSetting in providerOption.ProviderSettings) { var setting = ConfigurationManager.AppSettings[providerSetting.Name]; if (!string.IsNullOrEmpty(setting)) { try { providerSetting.Value = setting; } catch (Exception ex) { this.LogTrace("Error trying to set value: {0} for setting: {1}, {2}", setting, providerSetting.Name, ex.ToString()); } } } string path = _localSite.Databases[0].DBConnectionString; if (path.Contains("|DataDirectory|")) { // TODO: is there a better way to do this? Can we lookup |DataDirectory| path = path.Replace("|DataDirectory|", this._localSite.PhysicalPath + @"\App_Data\"); } providerOption.Path = path; RemoteSystemInfo remoteSystemInfo = null; if (RemoteSystemInfos.Servers.Any() && UseTrustedConnection(_localSite.Databases[0].DBConnectionString)) { remoteSystemInfo = RemoteSystemInfos.Servers[_localSite.ServerName]; } using (Impersonator.ImpersonateUser(remoteSystemInfo)) { using (var sourceObject = DeploymentManager.CreateObject(providerOption, sourceBaseOptions)) { LogTrace("Starting DB Sync for: {0} using {1}", (string)_localSite.Databases[0].DbConnectionStringBuilder["Initial Catalog"], provider); this.LogTrace("Publishing database as: {0}", destBaseOptions.UserName); try { sourceObject.SyncTo(provider, _publishSettings.SqlDBConnectionString.ConnectionString, destBaseOptions, new DeploymentSyncOptions()); this.LogTrace("DB Synced successfully"); Helper.UpdateStatus(_localSite.SiteName, _localSite.ServerName, true); } catch (Exception ex) { if (logException) { LogTrace("Error starting publish for db: {0}", (string)_localSite.Databases[0].DbConnectionStringBuilder["Initial Catalog"]); this.LogTrace(ex.ToString()); } publishSucceeded = false; } } } } catch (Exception ex) { if (logException) { LogTrace("Error syncing db: {0}", (string)_localSite.Databases[0].DbConnectionStringBuilder["Initial Catalog"]); LogTrace(ex.ToString()); } publishSucceeded = false; } return(publishSucceeded); }
private void Publish(object unusedState) { Operation operation = null; try { lock (_pendingPublishOperations) { operation = _pendingPublishOperations.Dequeue(); } if (operation == null) { PublishHelper.LogVerboseInformation("Publish: Thread {0} did not find any operations to process", Thread.CurrentThread.ManagedThreadId); return; } // This was not required earlier but now that every site will be synced twice for every incoming publish (Look at the postsync override in publishextender), // there are chances that same operation might get scheduled in concurrent threads which is not a supported web deploy scenario. bool canContinue = true; lock (_operationsInProgress) { if (_operationsInProgress.Contains(operation.SiteName)) { PublishHelper.LogVerboseInformation("Publish: An operation for {0} is already in progress. Thread {1} will mark it as not started to be scheduled later.", operation.SiteName, Thread.CurrentThread.ManagedThreadId); operation.Status = PublishOperationStatus.NotStarted; canContinue = false; } else { _operationsInProgress.Add(operation.SiteName); } } if (!canContinue) { lock (_completedOperations) { _completedOperations.Enqueue(operation); } return; } operation.ThreadID = Thread.CurrentThread.ManagedThreadId; operation.Status = PublishOperationStatus.Error; DeploymentBaseOptions srcBaseOptions = new DeploymentBaseOptions(); AntaresEventProvider.EventWritePublishFailOverServiceProgressInformation(operation.ThreadID, operation.SiteName); using (DeploymentObject depObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.Manifest, PublishHelper.GetPublishManifest(operation.PhysicalPath), srcBaseOptions)) { try { DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.ComputerName = operation.PublishUrl; string modifiedPhysicalPath = operation.PhysicalPath; string ipDefaultValue = GetFileServerIP(ref modifiedPhysicalPath); var fileServerIPParameter = new DeploymentSyncParameter( FileServerIPParameterName, FileServerIPParameterDescription, ipDefaultValue, string.Empty); var fileServerIPEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.ContentPath.ToString(), string.Empty, string.Empty); fileServerIPParameter.Add(fileServerIPEntry); 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); var setAclParameter = new DeploymentSyncParameter( SetAclParameterName, SetAclParameterDescription, modifiedPhysicalPath, DeploymentWellKnownTag.SetAcl.ToString()); var setAclParamEntry = new DeploymentSyncParameterEntry( DeploymentSyncParameterEntryKind.ProviderPath, DeploymentWellKnownProvider.SetAcl.ToString(), string.Empty, string.Empty); setAclParameter.Add(setAclParamEntry); depObj.SyncParameters.Add(fileServerIPParameter); depObj.SyncParameters.Add(contentPathParameter); depObj.SyncParameters.Add(setAclParameter); 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; depObj.SyncTo(destBaseOptions, new DeploymentSyncOptions()); operation.Status = PublishOperationStatus.Completed; AntaresEventProvider.EventWritePublishFailOverServicePublishComplete(operation.SiteName); } catch (Exception e) { AntaresEventProvider.EventWritePublishFailOverServiceFailedToPublishSite(operation.SiteName, e.ToString()); } } } catch (Exception e) { if ((e is DeploymentDetailedException && ((DeploymentDetailedException)e).ErrorCode == DeploymentErrorCode.FileOrFolderNotFound) || e is WebHostingObjectNotFoundException) { operation.Status = PublishOperationStatus.SourceOrDestinationInvalid; } AntaresEventProvider.EventWritePublishFailOverServiceFailedToGetSourceSite(operation.SiteName, e.ToString()); } finally { lock (_completedOperations) { PublishHelper.LogVerboseInformation("Publish: Thread {0} qeuing completed operation for site: {1}", operation.ThreadID, operation.SiteName); _completedOperations.Enqueue(operation); } lock (_operationsInProgress) { _operationsInProgress.Remove(operation.SiteName); } _continueEvent.Set(); PublishHelper.LogVerboseInformation("Publish: Thread {0} exiting", Thread.CurrentThread.ManagedThreadId); } }
public override bool Publish(bool getSize) { var sourceBaseOptions = new DeploymentBaseOptions(); sourceBaseOptions.Trace += TraceEventHandler; sourceBaseOptions.TraceLevel = TraceLevel.Verbose; var destBaseOptions = new DeploymentBaseOptions(); destBaseOptions.Trace += TraceEventHandler; destBaseOptions.TraceLevel = TraceLevel.Verbose; bool publishSucceeded = true; this.LogTrace("Starting db publish for {0}", _localSite.SiteName); publishSucceeded = PublishDatabase(sourceBaseOptions, destBaseOptions, "dbfullsql", true); if (!publishSucceeded) { // this tends to get stuck... destBaseOptions.RetryAttempts = 1; publishSucceeded = PublishDatabase(sourceBaseOptions, destBaseOptions, "dbDacfx", true); } _control.SetDbPublished(this.LocalSite.ServerName + this.LocalSite.SiteName, publishSucceeded); _control.UpdateStatusLabel(string.Empty); this.PublishStatus = publishSucceeded; return publishSucceeded; }
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); }