Beispiel #1
0
        public void Gets_Column_Definition()
        {
            var path = Path.Combine(Environment.CurrentDirectory, "dacServicesTest.dac");

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, new TSqlModelOptions {
            }))
            {
                model.AddObjects("CREATE TABLE t1 (c1 NVARCHAR(30) NOT NULL, id int primary key clustered)", new TSqlObjectOptions());

                DacPackageExtensions.BuildPackage(path, model,
                                                  new PackageMetadata()
                {
                    Description = "Test Package", Name = "ssss", Version = "1"
                });
            }

            var dac = new DacServices.DacParser(path);

            Assert.AreEqual(1, dac.GetTableDefinitions().Count);

            var table = dac.GetTableDefinitions().FirstOrDefault();

            Assert.AreEqual("c1", table.Columns.FirstOrDefault().Name.Value);
            Assert.AreEqual(LiteralType.String, table.Columns.FirstOrDefault().LiteralType);
        }
Beispiel #2
0
 public void Build(string dacpacPath, string packageName, IEnumerable <string> scripts)
 {
     using (var model = new TSqlModel(SqlServerVersion.Sql110, new TSqlModelOptions {
     })) {
         // Adding objects to the model.
         foreach (string script in scripts)
         {
             model.AddObjects(script);
         }
         try {
             // 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 = packageName, Description = string.Empty, Version = "1.0"
             },
                                               new PackageOptions());
             var message = Environment.NewLine +
                           string.Format(CultureInfo.InvariantCulture, Resources.SqlPublish_PublishDacpacSuccess, dacpacPath) +
                           Environment.NewLine;
             _outputWindow.WriteAsync(MessageCategory.General, message).DoNotWait();
         } catch (DacServicesException ex) {
             var error = Environment.NewLine +
                         string.Format(CultureInfo.InvariantCulture, Resources.SqlPublishDialog_UnableToBuildDacPac, ex.Message) +
                         Environment.NewLine;
             _outputWindow.WriteAsync(MessageCategory.Error, error).DoNotWait();
             // _coreShell.ShowErrorMessage(error);
         }
     }
 }
        protected override void ProcessRecord()
        {
            string script = string.Empty;

            try
            {
                // create an instance of a tsqmodel to store the sql records
                using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql130, new TSqlModelOptions()))
                {
                    // iterate through each file and add the sql script to the model
                    foreach (string file in System.IO.Directory.GetFiles(FileDirectory, "*.sql", SearchOption.AllDirectories))
                    {
                        using (StreamReader sr = new StreamReader(file))
                        {
                            script = sr.ReadToEnd();
                            model.AddObjects(script);
                        }
                    }

                    // build the sql directory and add to the output path
                    DacPackageExtensions.BuildPackage(
                        OutputPath,
                        model,
                        new PackageMetadata(), // Describes the dacpac.
                        new PackageOptions()); // Use this to specify the deployment contributors, refactor log to include in package
                }
            }
            catch (Exception ex)
            {
                WriteWarning(ex.ToString());
                WriteWarning(script);
                throw (ex);
            }
        }
Beispiel #4
0
        public void Sets_KeyColumns_To_Empty_List_When_No_Primary_Key()
        {
            var path = Path.Combine(Environment.CurrentDirectory, "dacServicesTest.dac");

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, new TSqlModelOptions {
            }))
            {
                model.AddObjects("CREATE TABLE t1 (c1 NVARCHAR(30) NOT NULL, id int)", new TSqlObjectOptions());

                DacPackageExtensions.BuildPackage(path, model,
                                                  new PackageMetadata()
                {
                    Description = "Test Package", Name = "ssss", Version = "1"
                });
            }

            var dac = new DacServices.DacParser(path);

            Assert.AreEqual(1, dac.GetTableDefinitions().Count);

            var table = dac.GetTableDefinitions().FirstOrDefault();

            Assert.AreEqual(0, table.KeyColumns.Count);
        }
Beispiel #5
0
        public static void GeneratePackage()
        {
            try
            {
                //TSqlModel sqlModel = TSqlModel.LoadFromDacpac(@"D:\testdb.dacpac", new ModelLoadOptions());
                TSqlModel sqlModel1 = new TSqlModel(SqlServerVersion.Sql150, new TSqlModelOptions());
                var       files     = Directory.GetFiles(@"D:\Visual Studio Projects\DacPacSample\Oracle", "regions.sql", SearchOption.AllDirectories);

                foreach (var file in files)
                {
                    var model = new TSqlModel(file, DacSchemaModelStorageType.File);
                    model.Validate();
                }

                var messages = sqlModel1.Validate();
                foreach (var item in messages)
                {
                    Console.WriteLine(item.Message);
                }

                DacPackageExtensions.BuildPackage(@"D:\test.dacpac", sqlModel1, new PackageMetadata {
                    Name = "TestDacPac"
                }, new PackageOptions {
                    TreatWarningsAsErrors = false
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #6
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();
        }
Beispiel #7
0
        private void WriteFinalDacpac(TSqlModel model, string preScript, string postScript)
        {
            var metadata = new PackageMetadata();

            metadata.Name = "dacpac";

            DacPackageExtensions.BuildPackage(_targetPath, model, metadata);
            AddScripts(preScript, postScript, _targetPath);
        }
Beispiel #8
0
        public void Build()
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            _log.Info("Build started.");

            LoadDacProfile();

            if (!Enum.TryParse(_options.SqlServerVersion, out SqlServerVersion sqlServerVersion))
            {
                sqlServerVersion = SqlServerVersion.Sql150;
            }

            TSqlModel model = new TSqlModel(sqlServerVersion, new TSqlModelOptions {
            });
            //model.EngineVersion = _options.EngineVersion;
            PackageMetadata meta = new PackageMetadata {
                Name    = _options.TargetDacVersion,
                Version = _options.TargetDacVersion,
            };

            _log.Info("Loading build files...");
            var sqlFiles = _project.GetBuildFiles().ToList();

            foreach (var sqlFile in sqlFiles)
            {
                var sql = File.ReadAllText(sqlFile.PhysicalPath);
                model.AddObjects(sql);
            }
            _log.Info("{0} file(s) added to build queue.", sqlFiles.Count);

            using (Stream buffer = GetDacpacStream())
            {
                _log.Info("Building dacpac...");
                DacPackageExtensions.BuildPackage(buffer, model, meta);
                buffer.Seek(0, SeekOrigin.Begin);
                _log.Success("Dacpac generated ({0}).", _options.GenerateDacPac ? "file" : "in-memory");

                if (_options.GenerateScript)
                {
                    GenerateScript(buffer);
                }
            }

            _log.Success("\nBuild complete. Elapsed {0:F3}s.", stopwatch.Elapsed.TotalSeconds);
            if (_options.GenerateDacPac)
            {
                _log.Success("  Dacpac: " + _dacpacFilename ?? "N/A");
            }
            if (_options.GenerateScript)
            {
                _log.Success("  Script: " + _scriptFileName ?? "N/A");
            }

            Environment.ExitCode = 0;
        }
Beispiel #9
0
        public void TestStopDeployment()
        {
            // Given database name
            string dbName = TestContext.TestName;

            // Delete any existing artifacts from a previous run
            TestUtils.DropDatabase(TestUtils.ServerConnectionString, dbName);

            // When deploying using the deployment stopping contributor
            try
            {
                DacDeployOptions options = new DacDeployOptions
                {
                    AdditionalDeploymentContributors = DeploymentStoppingContributor.ContributorId
                };

                // Deploy initial schema, should pass as no data motion
                using (DacPackage dacpac = DacPackage.Load(_dacpacPath, DacSchemaModelStorageType.Memory))
                {
                    DacServices dacServices = new DacServices(TestUtils.ServerConnectionString);
                    dacServices.Deploy(dacpac, dbName, false, options);
                }

                // Create schema that will cause data motion by adding column before existing one
                using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, null))
                {
                    model.AddObjects("CREATE TABLE [dbo].[t1] (motion int NOT NULL, c1 INT NOT NULL PRIMARY KEY)");
                    DacPackageExtensions.BuildPackage(_dacpacPath, model, new PackageMetadata());
                }

                // Attempt to deploy and verify it fails as there's now data motion blocking it
                using (DacPackage dacpac = DacPackage.Load(_dacpacPath, DacSchemaModelStorageType.Memory))
                {
                    DacServices dacServices = new DacServices(TestUtils.ServerConnectionString);

                    try
                    {
                        dacServices.GenerateDeployScript(dacpac, dbName, options);
                        Assert.Fail("Expected Deployment to fail and exception to be thrown");
                    }
                    catch (DacServicesException expectedException)
                    {
                        Assert.IsTrue(expectedException.Message.Contains(DeploymentStoppingContributor.ErrorViaPublishMessage),
                                      "Expected Severity.Error message passed to base.PublishMessage to block deployment");
                        Assert.IsTrue(expectedException.Message.Contains(DeploymentStoppingContributor.ErrorViaThrownException),
                                      "Expected thrown exception to block deployment");
                    }
                }
            }
            finally
            {
                TestUtils.DropDatabase(TestUtils.ServerConnectionString, dbName);
            }
        }
Beispiel #10
0
        public void TestIncludePlanFiltererInDacpac()
        {
            // Given a model with objects that use "dev", "test" and "prod" schemas
            // and the contributor information built in
            var    model = CreateTestModel();
            string existingPackagePath = GetTestFilePath("includesContributor.dacpac");

            Console.WriteLine("Build dacpac to \n" + existingPackagePath);
            DacPackageExtensions.BuildPackage(existingPackagePath, model, new PackageMetadata(), new PackageOptions()
            {
                DeploymentContributors = new[] { new DeploymentContributorInformation()
                                                 {
                                                     ExtensionId = PlanFilterer.PlanFiltererContributorId
                                                 } }
            });

            DacServices services = new DacServices("Server=(localdb)\\MSSQLLocalDB;Integrated Security=true;");

            // When publishing to production (filtering to exclude "dev" and "test" schemas)
            string productionDbName = "ProductionDB";

            using (DacPackage package = DacPackage.Load(existingPackagePath, DacSchemaModelStorageType.Memory))
            {
                DacDeployOptions options = new DacDeployOptions();

                // Specify the filter to use and what arguments it needs. Note that this is a little limited by
                // having to pass string-based arguments. This could be worked around by serializing arguments to a
                // file and passing the file path to the contributor if you need to do anything advanced.
                options.AdditionalDeploymentContributorArguments =
                    PlanFilterer.BuildPlanFiltererArgumentString("SchemaBasedFilter", new Dictionary <string, string>()
                {
                    { "Schema1", "dev" },
                    { "Schema2", "test" },
                });

                // For test purposes, always create a new database (otherwise previous failures might mess up our result)
                options.CreateNewDatabase = true;

                // Run the deployment with the options as specified
                services.Deploy(package, productionDbName, upgradeExisting: true, options: options);
            }

            // Then expect only the "prod" schema objects to remain in the new package
            // Extract the dacpac back from the database and ensure that only production elements are there

            string extractedPackagePath = GetTestFilePath("extracted.dacpac");

            services.Extract(extractedPackagePath, productionDbName, "AppName", new Version(1, 0));
            var extractedModel = _trash.Add(new TSqlModel(extractedPackagePath, DacSchemaModelStorageType.Memory));

            Assert.AreEqual(TopLevelProdElementCount, CountTablesViewsAndSchemas(extractedModel));
            AssertAllObjectsHaveSchemaName(extractedModel, "prod");
        }
Beispiel #11
0
        public void InitializeTest()
        {
            Directory.CreateDirectory(GetTestDir());

            _trash      = new DisposableList();
            _dacpacPath = GetTestFilePath("myDatabase.dacpac");
            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, null))
            {
                model.AddObjects(CreateOneTable);
                DacPackageExtensions.BuildPackage(_dacpacPath, model, new PackageMetadata());
            }
        }
        public void InitializeTest()
        {
            Directory.CreateDirectory(GetTestDir());

            _trash      = new DisposableList();
            _dacpacPath = GetTestFilePath("myDatabase.dacpac");
            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, null))
            {
                model.AddObjects("CREATE TABLE [dbo].[t1] (c1 INT NOT NULL PRIMARY KEY)");
                DacPackageExtensions.BuildPackage(_dacpacPath, model, new PackageMetadata());
            }
        }
Beispiel #13
0
        public void Save(string fileName)
        {
            DacPackageExtensions.BuildPackage(fileName, _model, Metadata);

            if (_package.PreDeploymentScript != null || _package.PostDeploymentScript != null)
            {
                using (var package = System.IO.Packaging.Package.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
                {
                    AddScript(package, _package.PreDeploymentScript, "predeploy");
                    AddScript(package, _package.PostDeploymentScript, "postdeploy");
                }
            }
        }
Beispiel #14
0
        public void SaveToDisk(FileInfo outputFile, PackageOptions packageOptions = null)
        {
            // Ensure that the model has been created and metadata has been set
            EnsureModelCreated();
            EnsureModelValidated();
            EnsureMetadataCreated();
            
            // Check if the file already exists
            if (outputFile.Exists)
            {
                // Delete the existing file
                Console.WriteLine($"Deleting existing file {outputFile.FullName}");
                outputFile.Delete();
            }

            Console.WriteLine($"Writing model to {outputFile.FullName}");
            DacPackageExtensions.BuildPackage(outputFile.FullName, Model, Metadata, packageOptions ?? new PackageOptions { });
        }
Beispiel #15
0
        private void WriteFinalDacpac(TSqlModel model, string preScript, string postScript)
        {
            var metadata = new PackageMetadata();

            metadata.Name = "dacpac";

            DacPackageExtensions.BuildPackage(_targetPath, model, metadata);

            var writer = new HeaderWriter(_targetPath, new DacHacFactory());

            foreach (var customData in _globalHeaders)
            {
                writer.AddCustomData(customData);
            }
            writer.Close();

            AddScripts(preScript, postScript, _targetPath);
            model.Dispose();
        }
Beispiel #16
0
        /// <summary>
        /// Runs the model filtering example. This shows how to filter a model and save a new
        /// dacpac with the updated model. You can also update the model in the existing dacpac;
        /// the unit tests in TestFiltering.cs show how this is performed.
        /// </summary>
        public static void RunFilteringExample()
        {
            // Given a model with objects that use "dev", "test" and "prod" schemas
            string devPackagePath = GetFilePathInCurrentDirectory("dev.dacpac");
            var    scripts        = SampleScripts;
            string productionPackagePath;

            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql110, new TSqlModelOptions()))
            {
                AddScriptsToModel(model, scripts);

                Console.WriteLine("Saving test scripts to package '" + devPackagePath + "'");
                DacPackageExtensions.BuildPackage(devPackagePath, model, new PackageMetadata());


                Console.WriteLine("Objects found in original package: '" + devPackagePath + "'");
                PrintTablesViewsAndSchemas(model);

                productionPackagePath = GetFilePathInCurrentDirectory("production.dacpac");

                // When saving a dacpac for deployment to production (filtering to exclude "dev" and "test" schemas)
                var           schemaFilter  = new SchemaBasedFilter(model.CollationComparer, new [] { "dev", "test" });
                ModelFilterer modelFilterer = new ModelFilterer(schemaFilter);


                Console.WriteLine("Creating filtered 'production' package: '" + productionPackagePath + "'");
                modelFilterer.CreateFilteredDacpac(devPackagePath, productionPackagePath);
            }


            // Then expect only the "prod" schema objects to remain in the new package
            using (TSqlModel filteredModel = new TSqlModel(productionPackagePath))
            {
                Console.WriteLine("Objects found in filtered package: '" + productionPackagePath + "'");
                PrintTablesViewsAndSchemas(filteredModel);
            }

            // If we publish the dacpac to a database, we can see that only the production schema is
            // present (debug into this method or view the console output listing only production elements)
            PublishProductionDacpacAndVerifyContents(productionPackagePath);
        }
Beispiel #17
0
        public void Run()
        {
            TSqlModel tm01     = new TSqlModel(folderPath01 + file01);
            TSqlModel newModel = new TSqlModel(tm01.Version, tm01.CopyModelOptions());

            List <TSqlObject> objs = tm01.GetObjects(DacQueryScopes.UserDefined).ToList();
            List <TSqlObject> delt = new List <TSqlObject>();

            foreach (var r in objs.Where(x => x.ObjectType.Name == "Schema"))
            {
                delt.Add(r);
                AddChildren(r, delt);
            }

            objs.RemoveAll(z => delt.Contains(z));

            foreach (TSqlObject o in objs.Where(z => !delt.Contains(z)))
            {
                if (o.TryGetScript(out string s))
                {
                    newModel.AddObjects(s);
                }
            }

            PackageMetadata m = new PackageMetadata()
            {
                Name        = "Nazwa",
                Version     = "1.0",
                Description = ""
            };

            DacPackageExtensions.BuildPackage
            (
                @"C:\Users\XTOKO\Desktop\NewDacpacSchemaFilter.dacpac"
                , newModel
                , m
            );

            Console.WriteLine("==> koniec");
            Console.ReadLine();
        }
Beispiel #18
0
        /// <summary>
        /// Builds a dacpac and returns the path to that dacpac.
        /// If the file already exists it will be deleted
        /// </summary>
        private string BuildDacpacFromModel(TSqlModel model)
        {
            string path = this.DacpacPath;

            Assert.IsFalse(string.IsNullOrWhiteSpace(this.DacpacPath), "DacpacPath must be set if target for analysis is a Dacpac");

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            string dacpacDir = Path.GetDirectoryName(path);

            if (!Directory.Exists(dacpacDir))
            {
                Directory.CreateDirectory(dacpacDir);
            }

            DacPackageExtensions.BuildPackage(path, model, new PackageMetadata());
            return(path);
        }
Beispiel #19
0
        public static void Run()
        {
            Directory.CreateDirectory(GetTestDir(_ModelCompareDacsPath));
            Directory.CreateDirectory(GetTestDir(_compareResultsPath));
            _sourceDacpacPath = GetTestFilePath(_ModelCompareDacsPath, "sourceDatabase.dacpac");
            DacPackageExtensions.BuildPackage(_sourceDacpacPath, CreateTestModel(_testSourceScripts), new PackageMetadata());
            _destinationDacPacPath = GetTestFilePath(_ModelCompareDacsPath, "destinationDatabase.dacpac");
            DacPackageExtensions.BuildPackage(_destinationDacPacPath, CreateTestModel(_testDestinationScripts), new PackageMetadata());

            using (TSqlModel sourcemodel = new TSqlModel(_sourceDacpacPath),
                   destmodel = new TSqlModel(_destinationDacPacPath))
            {
                // Filtering to exclude log schema
                var           schemaFilter  = new SchemaBasedFilter("log");
                ModelFilterer modelFilterer = new ModelFilterer(schemaFilter);
                TSqlModel     smodel        = modelFilterer.CreateFilteredModel(sourcemodel);
                TSqlModel     dmodel        = modelFilterer.CreateFilteredModel(destmodel);

                CompareTSqlModels(smodel, dmodel);
            }
        }
Beispiel #20
0
        private static void Build(string projectPath, string outputPath, SqlServerVersion targetVersion)
        {
            var outputFilePath           = EnusreOutputPath(projectPath, outputPath);
            IEnumerable <string> dbFiles = GetInputFiles(projectPath);

            var sqlModel = new TSqlModel(targetVersion, new TSqlModelOptions()
            {
            });

            foreach (var scriptFile in dbFiles)
            {
                Console.WriteLine($"Loading file into model: {scriptFile}");
                var script = File.ReadAllText(scriptFile);
                sqlModel.AddObjects(script);
            }

            Console.WriteLine($"Building Dac Package to {outputFilePath}");
            DacPackageExtensions.BuildPackage(outputFilePath, sqlModel, new PackageMetadata()
            {
            });
        }
Beispiel #21
0
        public bool Write(TSqlModel model)
        {
            try
            {
                var dummyModel = BuildInitialEmptyModel();

                DacPackageExtensions.BuildPackage(_outputPath, dummyModel, new PackageMetadata());

                AddReferences();

                AddPrePostScripts();

                WriteFinalDacpac(model);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(false);
            }

            return(true);
        }
Beispiel #22
0
        /// <summary>
        /// Creates a new dacpac based on the filtered model. This implementation loads from and saves to
        /// disk, but the API supports loading from and saving to a memory stream. This can be useful if you
        /// want to support a scenario where you load a dacpac, filter its model, then immediately deploy the filtered
        /// model to a database.
        /// </summary>
        public void CreateFilteredDacpac(string dacpacPath, string filteredDacpacPath)
        {
            DisposableList disposables = new DisposableList();

            try
            {
                TSqlModel model         = disposables.Add(new TSqlModel(dacpacPath, DacSchemaModelStorageType.Memory));
                TSqlModel filteredModel = disposables.Add(CreateFilteredModel(model));

                DacPackageExtensions.BuildPackage(
                    filteredDacpacPath,
                    filteredModel,
                    new PackageMetadata(), // Describes the dacpac.
                    new PackageOptions()); // Use this to specify the deployment contributors, refactor log to include in package
            }
            finally
            {
                // Models and DacPackage objects are disposable - either use a "using" statement or dispose of them in a finally block.
                // In these examples we'd end up with a large amount of indentation and to avoid that I'm using a try/finally block.
                disposables.Dispose();
            }
        }
Beispiel #23
0
 public void Build(string dacpacPath, string packageName, IEnumerable <string> scripts)
 {
     using (var model = new TSqlModel(SqlServerVersion.Sql130, new TSqlModelOptions {
     })) {
         // Adding objects to the model.
         foreach (string script in scripts)
         {
             model.AddObjects(script);
         }
         try {
             // 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 = packageName, Description = string.Empty, Version = "1.0"
             },
                                               new PackageOptions());
         } catch (DacServicesException ex) {
             throw new SqlPublishException(ex.Message);
         }
     }
 }
Beispiel #24
0
        /// <summary>
        /// Runs the model filtering example. This shows how to filter a model and save a new
        /// dacpac with the updated model. You can also update the model in the existing dacpac;
        /// the unit tests in TestFiltering.cs show how this is performed.
        /// </summary>
        public static void RunAnalysisExample()
        {
            // Given a model with objects that use "dev", "test" and "prod" schemas
            string scaPackagePath     = GetFilePathInCurrentDirectory("sca.dacpac");
            string scriptAnalysisPath = GetFilePathInCurrentDirectory("scriptResults.xml");
            string dacpacAnalysisPath = GetFilePathInCurrentDirectory("dacpacResults.xml");
            string dbAnalysisPath     = GetFilePathInCurrentDirectory("databaseResults.xml");
            var    scripts            = SampleScripts;

            using (TSqlModel model = new TSqlModel(SqlServerVersion.Sql120, new TSqlModelOptions()))
            {
                AddScriptsToModel(model, scripts);

                // Analyze scripted model
                RunAnalysis(model, scriptAnalysisPath);

                // Save dacpac to
                Console.WriteLine("Saving scripts to package '" + scaPackagePath + "'");
                DacPackageExtensions.BuildPackage(scaPackagePath, model, new PackageMetadata());
            }

            RunDacpacAnalysis(scaPackagePath, dacpacAnalysisPath);
            RunAnalysisAgainstDatabase(scaPackagePath, dbAnalysisPath);
        }
Beispiel #25
0
        static void BuildDac(string dacpacPath, DacPacVersion dacpacVersion)
        {
            Console.WriteLine("\n------- Building DacPac -------");

            if (mySQLScripts.Scripts.Count >= 0)
            {
                // Figure out which version we want to build.

                Microsoft.SqlServer.Dac.Model.SqlServerVersion modelVersion;
                switch (dacpacVersion)
                {
                case DacPacVersion.SQL2012:
                    modelVersion = Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql110;
                    break;

                case DacPacVersion.SQL2014:
                    modelVersion = Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql120;
                    break;

                case DacPacVersion.SQL2016:
                    modelVersion = Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql130;
                    break;

                default:
                    modelVersion = Microsoft.SqlServer.Dac.Model.SqlServerVersion.Sql110;
                    break;
                }

                using (TSqlModel model = new TSqlModel(modelVersion, new TSqlModelOptions {
                }))
                {
                    foreach (string SQLScript in mySQLScripts.Scripts)
                    {
                        // Add it to the model
                        model.AddObjects(SQLScript);
                    }

                    // Now write the model
                    try
                    {
                        DacPackageExtensions.BuildPackage(
                            dacpacPath,
                            model,
                            new PackageMetadata {
                            Name = "Mini_DacPac", Description = "Built by DacMini.", Version = "1.0"
                        },
                            new PackageOptions()
                            );

                        Console.WriteLine("DAC package created.");
                    }
                    catch (Microsoft.SqlServer.Dac.DacServicesException e)
                    {
                        Console.WriteLine("DAC creation failed:");
                        Console.WriteLine("Error: " + e.Message);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("DAC creation may have failed:");
                        Console.WriteLine("Error: " + e.Message);
                    }
                }
            }
            else
            {
                Console.WriteLine("Warning - No scripts were found to package into DacPac.");
            }
        }
Beispiel #26
0
 private void BuildPackage(TSqlModel model, string path)
 {
     DacPackageExtensions.BuildPackage(path, model, new PackageMetadata());
 }