Exemple #1
0
        public override void Execute()
        {
            DacPackage       dacpac  = DacPackage.Load(this.Parameters.PackageFilePath);
            DacDeployOptions options = this.GetDefaultDeployOptions();

            this.DacServices.Deploy(dacpac, this.Parameters.DatabaseName, this.Parameters.UpgradeExisting, options, this.CancellationToken);
        }
Exemple #2
0
        public override void Execute()
        {
            DacPackage       dacpac  = DacPackage.Load(this.Parameters.PackageFilePath);
            DacDeployOptions options = GetDefaultDeployOptions();

            DeployReport = this.DacServices.GenerateDeployReport(dacpac, this.Parameters.DatabaseName, options, this.CancellationToken);
        }
Exemple #3
0
        internal static void PublishDacpacFile(
            ICakeContext context,
            string connectionString,
            string targetDatabaseName,
            string?dacpacFilePath,
            PublishDacpacSettings?settings = null)
        {
            if (string.IsNullOrEmpty(dacpacFilePath))
            {
                throw new ArgumentNullException(nameof(dacpacFilePath));
            }

            Initializer.InitializeNativeSearchPath();
            context.Log.Information($"About to publish dacpac from {dacpacFilePath} into database {targetDatabaseName}");

            using (var dacPackage = DacPackage.Load(dacpacFilePath))
            {
                context.Log.Debug($"Loaded dacpac file {dacpacFilePath}");

                var service = new DacServices(connectionString);

                var options = GetPublishOptions(settings);

                service.Publish(dacPackage, targetDatabaseName, options);
            }

            context.Log.Information($"Finished restoring dacpac file into database {targetDatabaseName}");
        }
Exemple #4
0
        /// <summary>
        ///     Deploys a given database from a dacpac file.
        /// </summary>
        public void Deploy(string connectionString,
                           string databaseName,
                           string dacPacFileName)
        {
            Messages.Add($"Deploying database: {databaseName}");

            var dacOptions = new DacDeployOptions
            {
                BlockOnPossibleDataLoss           = false,
                TreatVerificationErrorsAsWarnings = true,
                AllowIncompatiblePlatform         = true,
                IgnoreFileAndLogFilePath          = true
            };

            var dacServiceInstance = new DacServices(connectionString);

            dacServiceInstance.ProgressChanged += (s, e) => Messages.Add(e.Message);
            dacServiceInstance.Message         += (s, e) => Messages.Add(e.Message.Message);

            try
            {
                using (var dacpac = DacPackage.Load(dacPacFileName))
                {
                    dacServiceInstance.Deploy(dacpac, databaseName,
                                              true, // upgrade existing
                                              dacOptions);
                }
            }
            catch (Exception ex)
            {
                Messages.Add(ex.Message);

                throw;
            }
        }
Exemple #5
0
        public void Deploy(FileInfo dacpacPackage, string targetDatabaseName)
        {
            EnsureConnectionStringComplete();

            if (!dacpacPackage.Exists)
            {
                throw new ArgumentException($"File {dacpacPackage.FullName} does not exist.", nameof(dacpacPackage));
            }

            using var package = DacPackage.Load(dacpacPackage.FullName);
            _console.WriteLine($"Deploying package '{package.Name}' version '{package.Version}' to database '{targetDatabaseName}'");

            try
            {
                var services = new DacServices(ConnectionStringBuilder.ConnectionString);
                services.Message += HandleDacServicesMessage;
                services.Deploy(package, targetDatabaseName, true, DeployOptions);
                _console.WriteLine($"Successfully deployed database '{targetDatabaseName}'");
            }
            catch (DacServicesException ex)
            {
                if (ex.InnerException != null)
                {
                    _console.WriteLine($"ERROR: Deployment of database '{targetDatabaseName}' failed: {ex.InnerException.Message}");
                }
                else
                {
                    _console.WriteLine($"ERROR: Deployment of database '{targetDatabaseName}' failed: {ex.Message}");
                }
            }
            catch (Exception ex)
            {
                _console.WriteLine($"ERROR: An unknown error occurred while deploying database '{targetDatabaseName}': {ex.Message}");
            }
        }
Exemple #6
0
        public void Run(string connectionString)
        {
            var providerConnectionString = new EntityConnectionStringBuilder(connectionString).ProviderConnectionString;

            DbConfiguration.SetConfiguration(new PocDbConfiguration());
            var context = new DbContext(providerConnectionString);

            context.Database.Initialize(true);
            using (var connection = new SqlConnection(providerConnectionString))
            {
                connection.Open();
                var connectionStringBuilder = new SqlConnectionStringBuilder(providerConnectionString)
                {
                    AttachDBFilename = String.Empty
                };
                var dacServices = new DacServices(connectionStringBuilder.ToString());
#if DEBUG
                const string dacpacFile = @"..\..\..\Database\bin\Debug\Database.dacpac";
#else
                const string dacpacFile = @"..\..\..\Database\bin\Release\Database.dacpac";
#endif
                var package = DacPackage.Load(dacpacFile);

                dacServices.Deploy(package, connection.Database, true);
                connection.Close();
            }
        }
Exemple #7
0
        private string GenerateUpgradeScript(DbConnection dbConnection, byte[] dacpac, DbUpgradeOptions options, string databaseNameOverride = "")
        {
            var dacServices  = new DacServices(dbConnection.ConnectionString);
            var databaseName = dbConnection.DatabaseName;

            if (!String.IsNullOrEmpty(databaseNameOverride))
            {
                databaseName = databaseNameOverride;
            }

            using (var stream = new MemoryStream(dacpac))
            {
                var publishResult = dacServices.Script(DacPackage.Load(stream, DacSchemaModelStorageType.Memory), dbConnection.DatabaseName, new PublishOptions
                {
                    GenerateDeploymentScript = true,
                    DeployOptions            = new DacDeployOptions
                    {
                        AllowIncompatiblePlatform  = true,
                        IgnoreNotForReplication    = options.IgnoreNotForReplication,
                        DropConstraintsNotInSource = options.DropConstraintsNotInSource,
                        DropIndexesNotInSource     = options.DropIndexesNotInSource,
                        VerifyDeployment           = options.VerifyDeployment,
                        ExcludeObjectTypes         = options.IgnoreObjectTypes// new ObjectType[] { ObjectType.Users, ObjectType.Views, ObjectType.RoleMembership, ObjectType.Permissions, ObjectType.ExtendedProperties, ObjectType.StoredProcedures, ObjectType.Logins, ObjectType.DatabaseTriggers, ObjectType.ServerTriggers }
                    }
                });

                return(publishResult.DatabaseScript);
            }
        }
        private static void DeployByDacpac(string databaseName)
        {
            string DatabaseConnectionString = ConfigurationManager.ConnectionStrings[databaseName].ConnectionString;
            string DatabaseName             = databaseName;

            var instance = new DacServices(DatabaseConnectionString);
            var path     = System.IO.Path.GetFullPath(@"..\..\..\MGPRM\bin\Debug\MGPRM.dacpac");

            bool success = true;


            var dacOptions = new DacDeployOptions();

            dacOptions.BlockOnPossibleDataLoss = false;

            var dacServiceInstance = new DacServices(DatabaseConnectionString);

            //If the DB has database reference then DACPAC technology not allow to deploy with SQL Variables
            //then temporary you should not use it
            try
            {
                using (DacPackage dacpac = DacPackage.Load(path))
                {
                    dacServiceInstance.Deploy(dacpac, DatabaseName,
                                              upgradeExisting: true,
                                              options: dacOptions);
                }
            }
            catch (Exception ex)
            {
                success = false;
            }
        }
Exemple #9
0
        private static DacPackage Extract(string serverName, string databaseName, FileInfo packageFile, string label)
        {
            SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder
            {
                DataSource         = serverName,
                InitialCatalog     = databaseName,
                IntegratedSecurity = true
            };
            DacServices dacServices = new DacServices(connectionStringBuilder.ConnectionString);

            dacServices.ProgressChanged += (s, e) =>
            {
                if (e.Status == DacOperationStatus.Running)
                {
                    Console.WriteLine("{0} ({1})", e.Message, label);
                }
            };
            DacExtractOptions extractOptions = new DacExtractOptions
            {
                IgnorePermissions       = false,
                IgnoreUserLoginMappings = true,
                Storage = DacSchemaModelStorageType.Memory
            };

            // Ensure the package file directory exists.
            packageFile.Directory.Create();

            dacServices.Extract(packageFile.FullName, databaseName, databaseName, new Version(1, 0), extractOptions: extractOptions);
            return(DacPackage.Load(packageFile.FullName, DacSchemaModelStorageType.Memory));
        }
Exemple #10
0
        public void Run()
        {
            // load dacpacs
            DacPackage pk01 = DacPackage.Load(folderPath01 + file01);
            DacPackage pk02 = DacPackage.Load(folderPath02 + file02);

            // configure (same as .publish xml)
            DacDeployOptions options = new DacDeployOptions
            {
                AdditionalDeploymentContributors = "DBContributorsPack.DropToTxtContributor",

                ExcludeObjectTypes = new ObjectType[]
                {
                    ObjectType.Users,
                    ObjectType.RoleMembership
                },

                DropObjectsNotInSource = true,
                DoNotDropObjectTypes   = new ObjectType[]
                {
                    ObjectType.DatabaseRoles
                }
            };

            // compare
            string s = DacServices.GenerateDeployScript(pk01, pk02, "name", options);

            Console.WriteLine(s);
            Console.ReadLine();
        }
Exemple #11
0
        /// <summary>
        /// Publish dacpac to database
        /// </summary>
        /// <param name="connectionString">connection string</param>
        /// <param name="targetDatbase">taget database name</param>
        /// <param name="dacpacfile">dacpac file</param>
        public void Publish(string connectionString, string targetDatbase, string dacpacfile)
        {
            var dac    = new DacServices(connectionString);
            var dacpac = DacPackage.Load(dacpacfile);

            dac.Deploy(dacpac, targetDatbase, true);
        }
        public override ITestDatabase Build()
        {
            _configurationDatabaseOptions?.Invoke(_databaseOptions);

            if (!_databaseOptions.AlwayCreate && CheckDatabaseExists())
            {
                return(this);
            }

            Drop();

            var deployOptions = new DacDeployOptions();

            foreach (var variable in _databaseOptions.DeployVariables)
            {
                deployOptions.SqlCommandVariableValues.Add(variable.Key, variable.Value);
            }
            var dacpacPath = _databaseOptions.DacpacPath;
            var instance   = new DacServices(_dbBuilder.ConnectionString);

            deployOptions.AllowIncompatiblePlatform = _databaseOptions.AllowIncompatiblePlatform;
            using (var dacpac = DacPackage.Load(dacpacPath))
            {
                instance.Deploy(dacpac, _dbBuilder.InitialCatalog, upgradeExisting: true, options: deployOptions);
            }
            return(this);
        }
Exemple #13
0
        private void GenerateScript(Stream dacpac)
        {
            _log.Info("Building script...");

            _log.Verbose("DacPackage loading...");
            var package = DacPackage.Load(dacpac, DacSchemaModelStorageType.Memory);

            var dacOptions   = GetDacDeployOptions();
            var targetDbName = GetTargetDatabaseName();

            _log.Verbose("Transforming dacpac to create script.");
            var script = DacServices.GenerateCreateScript(package, targetDbName, dacOptions);

            using (var output = GetScriptStreamWriter())
                output.Write(script);
            _log.Success("Schema script created. Total {0:N0}kb.", script.Length / 1024f);

            if (_options.CopyLooseScripts)
            {
                _log.Verbose("Attempting to copy loose files.");

                _log.Info("Loading loose files...");
                var looseFiles = _project.GetLooseFiles().ToList();
                foreach (var file in looseFiles)
                {
                    string src  = file.PhysicalPath;
                    string dest = Path.Combine(_options.Output, file.Path, file.Filename);
                    CopyLooseFile(src, dest);
                }
                _log.Success("{0} loose file(s) copied..", looseFiles.Count);
            }
        }
Exemple #14
0
        public override void Execute()
        {
            DacPackage     dacpac         = DacPackage.Load(this.Parameters.PackageFilePath);
            PublishOptions publishOptions = new PublishOptions();

            publishOptions.GenerateDeploymentReport = this.Parameters.GenerateDeploymentReport;
            publishOptions.CancelToken   = this.CancellationToken;
            publishOptions.DeployOptions = this.GetDefaultDeployOptions();

            this.Result = this.DacServices.Script(dacpac, this.Parameters.DatabaseName, publishOptions);

            // tests don't create a SqlTask, so only add the script when the SqlTask isn't null
            if (this.SqlTask != null)
            {
                this.SqlTask.AddScript(SqlTaskStatus.Succeeded, Result.DatabaseScript);
                if (!string.IsNullOrEmpty(this.Result.MasterDbScript))
                {
                    // master script is only used if the target is Azure SQL db and the script contains all operations that must be done against the master database
                    this.SqlTask.AddScript(SqlTaskStatus.Succeeded, this.Result.MasterDbScript);
                }
            }

            if (this.Parameters.GenerateDeploymentReport && !string.IsNullOrEmpty(this.Parameters.DeploymentReportFilePath))
            {
                File.WriteAllText(this.Parameters.DeploymentReportFilePath, this.Result.DeploymentReport);
            }
        }
Exemple #15
0
        /// <summary>
        /// Loads database from file.
        /// </summary>
        public void LoadDataBase()
        {
            var dacOptions = new DacDeployOptions {
                CreateNewDatabase = true
            };
            var dacServiceInstance = new DacServices(_connectionString);

            var dacpacPath = ConfigurationManager.AppSettings["dacpacFilePath"];

            if (dacpacPath != null && dacpacPath.Contains("AppPath"))
            {
                dacpacPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + dacpacPath.Replace("AppPath", string.Empty);
            }

            if (File.Exists(dacpacPath))
            {
                using (DacPackage dacpac = DacPackage.Load(dacpacPath))
                {
                    dacServiceInstance.Deploy(dacpac, "TicketManagement", true, dacOptions);
                }
            }
            else
            {
                throw new ConfigurationErrorsException("Error load database from dacpac file.");
            }
        }
        public static void Deploy(Stream dacpac, string connectionString, string databaseName)
        {
            var options = new DacDeployOptions()
            {
                BlockOnPossibleDataLoss           = true,
                IncludeTransactionalScripts       = true,
                DropConstraintsNotInSource        = false,
                DropIndexesNotInSource            = false,
                DropDmlTriggersNotInSource        = false,
                DropObjectsNotInSource            = false,
                DropExtendedPropertiesNotInSource = false,
                DropPermissionsNotInSource        = false,
                DropStatisticsNotInSource         = false,
                DropRoleMembersNotInSource        = false,
            };

            var service = new DacServices(connectionString);

            service.Message += (x, y) =>
            {
                Console.WriteLine(y.Message.Message);
            };
            try
            {
                using (var package = DacPackage.Load(dacpac))
                {
                    service.Deploy(package, databaseName, true, options);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message, true);
            }
        }
Exemple #17
0
        private void ExecutePostDeploymentScript(string databaseName, DacPackage dacPackage)
        {
            databaseName = databaseName ?? dacPackage.Name;

            using (IDbConnection connection = _connectionFactory())
            {
                try
                {
                    connection.ChangeDatabase(databaseName);
                }
                catch
                {
                    _logAction(
                        "Could not change connection to database " +
                        databaseName +
                        " before post-deployment script. Database may not yet exist.");
                }

                // Execute the DAC post-deployment script.
                if (dacPackage.PostDeploymentScript != null)
                {
                    using (IDbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = new StreamReader(dacPackage.PostDeploymentScript).ReadToEnd();
                        command.CommandText = command.CommandText.Replace("\nGO", "");
                        command.ExecuteNonQuery();
                    }
                }
            }
        }
        private static bool DeployDatabase(string databaseServerName, string connString)
        {
            MessageList = new List <string>();
            bool success    = true;
            var  dacSvc     = new DacServices(connString);
            var  dacOptions = new DacDeployOptions();

            dacOptions.BlockOnPossibleDataLoss = false;

            try
            {
                using (DacPackage dacpac = DacPackage.Load(@"Database Deployment\SqlResultsCompare.dacpac"))
                {
                    dacSvc.Deploy(dacpac, "SqlResultsCompare", upgradeExisting: true, options: dacOptions);
                }
            }
            catch (Exception ex)
            {
                success = false;
                //TODO: add logging
                //MessageList.Add(ex.Message);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException.ToString());
            }
            return(success);
        }
Exemple #19
0
 internal Package(ILogger logger, IModelFactory modelFactory, string fileName)
 {
     _logger       = logger;
     _modelFactory = modelFactory;
     _package      = DacPackage.Load(fileName);
     _model        = new TSqlModel(fileName);
 }
        protected override async Task OnExecute()
        {
            var connInfo = await GetSqlConnectionInfo();

            var package  = DacPackage.Load(DacPac);
            var services = ConnectDac(connInfo);

            await Console.WriteInfoLine(String.Format(
                                            CultureInfo.CurrentCulture,
                                            Strings.Db_DeployCommand_Deploying,
                                            package.Name,
                                            connInfo.ConnectionString.InitialCatalog,
                                            connInfo.ConnectionString.DataSource));

            if (!WhatIf)
            {
                services.Deploy(
                    package,
                    connInfo.ConnectionString.InitialCatalog,
                    upgradeExisting: true,
                    options: new DacDeployOptions()
                {
                    BlockOnPossibleDataLoss = true
                });
            }
            await Console.WriteInfoLine(Strings.Db_DeployCommand_Deployed);
        }
Exemple #21
0
        public static void Main(string[] args)
        {
            DacpacFileName = args.Any() ? args[0] : DacpacFileName;

            var dacServices = new DacServices(ConnectionString);
            dacServices.Message += DacServices_Message;
            var options = new DacDeployOptions
            {
                CreateNewDatabase = false,
                BlockOnPossibleDataLoss = false,
                GenerateSmartDefaults = true,
                VerifyDeployment = true,
                DropObjectsNotInSource = true
            };

            Console.WriteLine();
            Console.WriteLine("Start process...");
            Console.WriteLine();

            //TODO na pszyłość można to wykorzystać
            //dacServices.GenerateDeployReport(DacPackage.Load(DacpacFileName), DatabaseName, options);

            dacServices.Deploy(DacPackage.Load(DacpacFileName), DatabaseName, true, options);

            Console.ReadKey();
        }
        public static void Deploy(string connectionString, string dacpacFileName, string databaseName)
        {
            try
            {
                var dacServices = new DacServices(connectionString);
                dacServices.Message         += DacServices_Message;
                dacServices.ProgressChanged += DacServices_ProgressChanged;
                var options = new DacDeployOptions
                {
                    CreateNewDatabase       = true,
                    BlockOnPossibleDataLoss = true,
                    GenerateSmartDefaults   = true,
                    VerifyDeployment        = true,
                };

                //TODO na pszyłość można to wykorzystać
                //dacServices.GenerateDeployReport(DacPackage.Load(DacpacFileName), DatabaseName, options);

                var dacpackPackage = DacPackage.Load(dacpacFileName);

                dacServices.Deploy(dacpackPackage, databaseName, true, options);
                GlobalApplicationSettings.IsDbExists = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #23
0
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [Blob("dacpacs/maindb.dacpac", FileAccess.Read)] Stream dacpac,
            ILogger log)
        {
            var sqlDiff = string.Empty;

            try
            {
                // Load the DacPac
                var pkg = DacPackage.Load(dacpac);

                // Connect to the DB
                var dacService = _dacServicesFactory.Create("ckittel", "main");

                // Generate Diff for capture purposes
                sqlDiff = dacService.GenerateDeployScript(pkg, "main");

                // Do the deployment
                dacService.Deploy(pkg, "main", upgradeExisting: true);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                sqlDiff += Environment.NewLine + Environment.NewLine + ex.ToString();
                log.LogInformation(sqlDiff);
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(new OkObjectResult(sqlDiff));
        }
Exemple #24
0
        public void Run()
        {
            DacServices services = new DacServices(@"Server=ITK\DEV17;Integrated Security=true;");
            DacPackage  package  = DacPackage.Load(file01, DacSchemaModelStorageType.Memory, FileAccess.ReadWrite);

            string dbName         = @"MojaBazaDAC";
            bool   updateExisting = true;

            TSqlModel tm01     = new TSqlModel(file01);
            TSqlModel newModel = new TSqlModel(tm01.Version, tm01.CopyModelOptions());

            //package.UpdateModel(filteredModel, new PackageMetadata())

            DacDeployOptions opts = new DacDeployOptions
            {
                ExcludeObjectTypes = new ObjectType[]
                {
                    ObjectType.Users,
                    ObjectType.RoleMembership
                }
            };

            services.Deploy(package,
                            dbName,
                            updateExisting,
                            opts
                            );
        }
        private string GenerateScriptAndOptionallyDeploy(string dbName, DacDeployOptions options, bool runDeployment, int currentIteration)
        {
            if (options == null)
            {
                options = new DacDeployOptions();
            }

            using (DacPackage dacpac = DacPackage.Load(_dacpacPath, DacSchemaModelStorageType.Memory))
            {
                string connectionString = "Data Source=" + DataSourceName + ";Integrated Security=True";

                DacServices dacServices = new DacServices(connectionString);

                // Script then deploy, to support debugging of the generated plan
                string script   = dacServices.GenerateDeployScript(dacpac, dbName, options);
                string filePath = GetTestFilePath(string.Format(CultureInfo.CurrentCulture, "deployscript{0}.sql", currentIteration));
                File.WriteAllText(filePath, script);
                Console.WriteLine("Deployment script written to {0}", filePath);

                if (runDeployment)
                {
                    dacServices.Deploy(dacpac, dbName, true, options);
                    AssertDeploySucceeded(ServerConnectionString, dbName);
                }

                return(script);
            }
        }
Exemple #26
0
        public static void Run()
        {
            string dacpacPath = "relativePath.dacpac";

            // Note that you could read scripts from a file or use TSqlScript objects that are taken from other models.
            // Hand-crafting TSqlScript is quite awkard but could be done programmatically (we do it internally).
            // If you need examples for this let us know and we can look into that too.
            string[] scripts = new[]
            {
                "CREATE TABLE t1 (c1 NVARCHAR(30) NOT NULL)",
                "CREATE TABLE t2 (c2 INT NOT NULL)",
                "CREATE TABLE t3 (c3 INT NOT NULL)",
                "CREATE TABLE t4 (c4 INT NOT NULL)",
            };
            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, new TSqlModelOptions {
            }))
            {
                // Adding objects to the model.
                foreach (string script in scripts)
                {
                    model.AddObjects(script);
                }

                ReadTheModel(model);

                CopyFromTheModel(model);

                // save the model to a new .dacpac
                // Note that the PackageOptions can be used to specify RefactorLog and contributors to include
                DacPackageExtensions.BuildPackage(
                    dacpacPath,
                    model,
                    new PackageMetadata {
                    Name = "MyPackageName", Description = "This is usually ignored", Version = "1.0"
                },
                    new PackageOptions()
                    );
            }

            // Load from a dacpac
            using (TSqlModel modelFromDacpac = new TSqlModel(dacpacPath))
            {
                // Show that all the elements were saved successfully
                ReadTheModel(modelFromDacpac);

                // You can update the model in the dacpac. Other parts of a dacpac can't be updated yet (pre/post deployment scripts)
                modelFromDacpac.AddObjects("CREATE VIEW V1 AS SELECT * FROM T1");

                using (DacPackage dacPackage = DacPackage.Load(dacpacPath,
                                                               DacSchemaModelStorageType.Memory,
                                                               FileAccess.ReadWrite))
                {
                    DacPackageExtensions.UpdateModel(dacPackage, modelFromDacpac, null);
                }
            }

            Console.WriteLine("Press any key to finish");
            Console.ReadKey();
        }
        /// <summary>
        /// Publishes the DacPac to the shard provided in the constructor.
        /// </summary>
        /// <param name="dacPacStream">The dac pac stream.</param>
        /// <param name="dacProfileStream">The dac profile stream.</param>
        /// <returns><c>true</c> if a new database was created, <c>false</c> otherwise.</returns>
        public bool PublishDacPac(Stream dacPacStream, Stream dacProfileStream)
        {
            // read the DacPac package and profile from files
            var dacPackage = DacPackage.Load(dacPacStream);
            var dacProfile = DacProfile.Load(dacProfileStream);

            return(PublishDacPac(dacPackage, dacProfile));
        }
        /// <summary>
        /// Publishes the DacPac to the shard provided in the constructor.
        /// </summary>
        /// <param name="dacPacPath">The dac pac path.</param>
        /// <param name="dacProfilePath">The dac profile path.</param>
        /// <returns><c>true</c> if a new database was created, <c>false</c> otherwise.</returns>
        public bool PublishDacPac(string dacPacPath, string dacProfilePath)
        {
            // read the DacPac package and profile from files
            var dacPackage = DacPackage.Load(dacPacPath);
            var dacProfile = DacProfile.Load(dacProfilePath);

            return(PublishDacPac(dacPackage, dacProfile));
        }
        public DacpacDbFixture()
        {
            Console.WriteLine("Running fixture constructor...");

            _localDb = new SqlLocalDbApi();
            DateTime nowUtc = DateTime.UtcNow;

            LocalDbInstanceName = $"{nowUtc.ToString("yyyyMMddHHmmssFFFFFFF")}";    //something mostly unique
            _instance           = _localDb.GetOrCreateInstance(LocalDbInstanceName);
            _manager            = _instance.Manage();

            if (!_instance.IsRunning)
            {
                _manager.Start();
            }

            var packagePath = "SimpleDb.dacpac";

            var deployOptions = new DacDeployOptions
            {
                CreateNewDatabase     = true,
                GenerateSmartDefaults = true,
            };

            deployOptions.SqlCommandVariableValues["LoginName"] = DatabaseUserName;
            deployOptions.SqlCommandVariableValues["Password"]  = DatabasePassword;

            SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();

            csb.DataSource         = _manager.NamedPipe;
            csb.IntegratedSecurity = true;
            var databaseName          = "SimpleDbUnitTest";
            var debugConnectionString = csb.ConnectionString;
            var dacServices           = new DacServices(debugConnectionString);

            using (var package = DacPackage.Load(packagePath))
            {
                dacServices.Deploy(package, databaseName, true, deployOptions);
            }
            csb.InitialCatalog = databaseName;
            //csb.UserID = DatabaseUserName;
            //csb.Password = DatabasePassword;
            //csb.IntegratedSecurity = false;
            ConnectionString = csb.ConnectionString;

            EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
            string nameOfConnectionString      = "SimpleDbModel";         //NOTE: HACK: this must match the name of my Entity Framework model (the .edmx guy)
            string providerName = "System.Data.SqlClient";

            ecsb.Provider = providerName;
            ecsb.ProviderConnectionString = csb.ConnectionString;
            ecsb.Metadata      = $"res://*/{nameOfConnectionString}.csdl|res://*/{nameOfConnectionString}.ssdl|res://*/{nameOfConnectionString}.msl";
            EfConnectionString = ecsb.ConnectionString;

            NumberOfTimesDacpacWasApplied++;
            Debug.WriteLine($">> The DACPAC has been applied {NumberOfTimesDacpacWasApplied} times");
            Console.WriteLine($">> The DACPAC has been applied {NumberOfTimesDacpacWasApplied} times");
        }
        /// <summary>
        ///     Deploys a Dacpac package into a local database
        /// </summary>
        /// <param name="database"></param>
        /// <param name="packageFilePath"></param>
        /// <param name="deployOptions"></param>
        public static void DeployDacpac(this LocalDatabase database, string packageFilePath, DacDeployOptions deployOptions = null)
        {
            var dacServices = new DacServices(database.ConnectionString);

            using (var package = DacPackage.Load(packageFilePath))
            {
                dacServices.Deploy(package, database.DatabaseName, true, deployOptions);
            }
        }
Exemple #31
0
 public DacPackageImpl(string dacpacPath) {
     _dacpac = DacPackage.Load(dacpacPath);
 }
        private void ExecutePostDeploymentScript(string databaseName, DacPackage dacPackage)
        {
            databaseName = databaseName ?? dacPackage.Name;

             using (IDbConnection connection = _connectionFactory())
             {
            try
            {
               connection.ChangeDatabase(databaseName);
            }
            catch
            {
               _logAction(
                  "Could not change connection to database " +
                  databaseName +
                  " before post-deployment script. Database may not yet exist.");
            }

            // Execute the DAC post-deployment script.
            if (dacPackage.PostDeploymentScript != null)
            {
               using (IDbCommand command = connection.CreateCommand())
               {
                  command.CommandText = new StreamReader(dacPackage.PostDeploymentScript).ReadToEnd();
                  command.CommandText = command.CommandText.Replace("\nGO", "");
                  command.ExecuteNonQuery();
               }
            }
             }
        }