private string GenerateScriptAs(Server server, UrnCollection urns, ScriptingOptions options) { SqlServer.Management.Smo.Scripter scripter = null; string resultScript = string.Empty; try { scripter = new SqlServer.Management.Smo.Scripter(server); if (this.Parameters.Operation == ScriptingOperationType.Alter) { options.ScriptForAlter = true; foreach (var urn in urns) { SqlSmoObject smoObject = server.GetSmoObject(urn); // without calling the toch method, no alter script get generated from smo smoObject.Touch(); } } scripter.Options = options; scripter.ScriptingError += ScripterScriptingError; var result = scripter.Script(urns); resultScript = GetScript(options, result); } catch { throw; } finally { if (scripter != null) { scripter.ScriptingError -= this.ScripterScriptingError; } } return(resultScript); }
public override void Execute() { SqlServer.Management.Smo.Scripter scripter = null; try { this.CancellationToken.ThrowIfCancellationRequested(); this.ValidateScriptDatabaseParams(); this.CancellationToken.ThrowIfCancellationRequested(); string resultScript = string.Empty; // TODO: try to use one of the existing connections using (SqlConnection sqlConnection = new SqlConnection(this.Parameters.ConnectionString)) { sqlConnection.Open(); ServerConnection serverConnection = new ServerConnection(sqlConnection); Server server = new Server(serverConnection); scripter = new SqlServer.Management.Smo.Scripter(server); ScriptingOptions options = new ScriptingOptions(); SetScriptBehavior(options); PopulateAdvancedScriptOptions(this.Parameters.ScriptOptions, options); options.WithDependencies = false; options.ScriptData = false; SetScriptingOptions(options); // TODO: Not including the header by default. We have to get this option from client options.IncludeHeaders = false; scripter.Options = options; scripter.Options.ScriptData = false; scripter.ScriptingError += ScripterScriptingError; UrnCollection urns = CreateUrns(serverConnection); var result = scripter.Script(urns); resultScript = GetScript(options, result); } this.CancellationToken.ThrowIfCancellationRequested(); Logger.Write( LogLevel.Verbose, string.Format( "Sending script complete notification event for operation {0}", this.OperationId )); ScriptText = resultScript; this.SendCompletionNotificationEvent(new ScriptingCompleteParams { Success = true, }); } catch (Exception e) { if (e.IsOperationCanceledException()) { Logger.Write(LogLevel.Normal, string.Format("Scripting operation {0} was canceled", this.OperationId)); this.SendCompletionNotificationEvent(new ScriptingCompleteParams { Canceled = true, }); } else { Logger.Write(LogLevel.Error, string.Format("Scripting operation {0} failed with exception {1}", this.OperationId, e)); this.SendCompletionNotificationEvent(new ScriptingCompleteParams { OperationId = OperationId, HasError = true, ErrorMessage = e.Message, ErrorDetails = e.ToString(), }); } } finally { if (scripter != null) { scripter.ScriptingError -= this.ScripterScriptingError; } } }