-->

使用Microsoft.Build.Evaluation发布数据库项目(.sqlproj)(Usin

2019-06-24 04:03发布

我需要能够以编程方式发布的SSDT项目。 我期待在使用Microsoft.Build这样做,但无法找到任何文件。 这看起来很简单,以创建.dacpac,但我怎么会或者发布到一个现有的数据库,或者至少是一个.sql文件。 这个想法是有它做它,当我在项目点击右键并选择发布。 它应与选定的数据库进行比较,并生成一个升级脚本。

这是我迄今为止创建.dacpac:

partial class DBDeploy
{
  Project project;


  internal void publishChanges()
  {
     Console.WriteLine("Building project " + ProjectPath);
     Stopwatch sw = new Stopwatch();
     sw.Start();

     project = ProjectCollection.GlobalProjectCollection.LoadProject(ProjectPath);
     project.Build();
     //at this point the .dacpac is built and put in the debug folder for the project

     sw.Stop();
     Console.WriteLine("Project build Complete.  Total time: {0}", sw.Elapsed.ToString());

  }
}

从本质上讲,我试图做这样的MSBuild实例说明,但在代码中。

对不起,这是我的全部。 在构建类的doecumentation很差。 任何帮助,将不胜感激。

谢谢。

Answer 1:

我不得不做类似这样的东西,因为这是我们以前使用的VSDBCMD不会部署到SQL Server 2012,我们需要支持它。 我发现是Microsoft.SqlServer.Dac组件,它似乎来作为SQL Server数据工具部分( http://msdn.microsoft.com/en-us/data/tools.aspx )

当您在客户端机器上运行这个你需要和完整版本的.NET框架4的SQL CLR类型和SQL T-SQL ScriptDOM包这里找到: http://www.microsoft.com/en-us/download /details.aspx?id=29065

下面的代码是从样机我测试了新的部署方法制造并部署一个给定的.dacpac文件

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SqlServer.Dac;
    using System.IO;

    namespace ConsoleApplication3
    {
        class Program
        {
            private static TextWriter output = new StreamWriter("output.txt", false);
            static void Main(string[] args)
            {

                Console.Write("Connection String:");
                //Class responsible for the deployment. (Connection string supplied by console input for now)
                DacServices dbServices = new DacServices(Console.ReadLine());

                //Wire up events for Deploy messages and for task progress (For less verbose output, don't subscribe to Message Event (handy for debugging perhaps?)
                dbServices.Message += new EventHandler<DacMessageEventArgs>(dbServices_Message);
                dbServices.ProgressChanged += new EventHandler<DacProgressEventArgs>(dbServices_ProgressChanged);


                //This Snapshot should be created by our build process using MSDeploy
                Console.WriteLine("Snapshot Path:");

                DacPackage dbPackage = DacPackage.Load(Console.ReadLine());




                DacDeployOptions dbDeployOptions = new DacDeployOptions();
                //Cut out a lot of options here for configuring deployment, but are all part of DacDeployOptions
                dbDeployOptions.SqlCommandVariableValues.Add("debug", "false");


                dbServices.Deploy(dbPackage, "trunk", true, dbDeployOptions);
                output.Close();

            }

            static void dbServices_Message(object sender, DacMessageEventArgs e)
            {
                output.WriteLine("DAC Message: {0}", e.Message);
            }

            static void dbServices_ProgressChanged(object sender, DacProgressEventArgs e)
            {
                output.WriteLine(e.Status + ": " + e.Message);
            }
        }
    }

这似乎是SQL Server的所有版本,从2005年起来努力。 有一组类似的Microsoft.SqlServer.Management.Dac可用的对象,但我相信这是在以前的版本DACFx的,不包含在最新的版本。 如果你能因此使用最新版本。



Answer 2:

我们需要有一种方式告诉的MSBuild如何以及在哪里发布。 在Visual Studio中打开您的项目,并开始Publish它。 在对话框中输入所需的所有信息,包括您的数据库连接信息和任何自定义SQLCMD变量值。 Save Profile As...到一个文件中,如Northwind.publish.xml。 (然后你可以Cancel 。)现在,我们可以利用这一点,项目文件创建和发布:

// Create a logger.
FileLogger logger = new FileLogger();
logger.Parameters = @"logfile=Northwind.msbuild.log";
// Set up properties.
var projects = ProjectCollection.GlobalProjectCollection;
projects.SetGlobalProperty("Configuration", "Debug");
projects.SetGlobalProperty("SqlPublishProfilePath", @"Northwind.publish.xml");
// Load and build project.
var dbProject = ProjectCollection.GlobalProjectCollection.LoadProject(@"Northwind.sqlproj");
dbProject.Build(new[]{"Build", "Publish"}, new[]{logger});

这可能需要一段时间,并且可能会出现卡住。 耐心点。 :)



Answer 3:

您应该使用SqlPackage.exe发布您的dacpac。

SqlPackage.exe 
  /Action:Publish 
  /SourceFile:C:/file.dacpac 
  /TargetConnectionString:[Connection string]

也强似参数太多,你可以保存你的设置到DAC发布配置文件(这可以从Visual Studio来完成)



Answer 4:

我想建立和发布基于一个sqlproj文件数据库和日志的有用信息来安慰。 这是我来到:

using Microsoft.Build.Framework;
using Microsoft.Build.Execution;

public void UpdateSchema() {
    var props = new Dictionary<string, string> {
        { "UpdateDatabase", "True" },
        { "PublishScriptFileName", "schema-update.sql" },
        { "SqlPublishProfilePath", "path/to/publish.xml") }
    };

    var projPath = "path/to/database.sqlproj";

    var result = BuildManager.DefaultBuildManager.Build(
        new BuildParameters { Loggers = new[] { new ConsoleLogger() } },
        new BuildRequestData(new ProjectInstance(projPath, props, null), new[] { "Publish" }));

    if (result.OverallResult == BuildResultCode.Success) {
        Console.WriteLine("Schema update succeeded!");
    }
    else {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("Schema update failed!");
        Console.ResetColor();
    }
}

private class ConsoleLogger : ILogger
{
    public void Initialize(IEventSource eventSource) {
        eventSource.ErrorRaised += (sender, e) => {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(e.Message);
            Console.ResetColor();
        };
        eventSource.MessageRaised += (sender, e) => {
            if (e.Importance != MessageImportance.Low)
                Console.WriteLine(e.Message);
        };
    }
    public void Shutdown() { }
    public LoggerVerbosity Verbosity { get; set; }
    public string Parameters { get; set; }
}

这是上述.NET 4和。 请务必并包括对Microsoft.BuildMicrosoft.Build.Framework集引用。



文章来源: Using Microsoft.Build.Evaluation to publish a database project (.sqlproj)