简体   繁体   English

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

[英]Using Microsoft.Build.Evaluation to publish a database project (.sqlproj)

I need to be able to publish an SSDT project programmatically. 我需要能够以编程方式发布SSDT项目。 I am looking at using Microsoft.Build to do so but can not find any documentation. 我正在使用Microsoft.Build这样做,但找不到任何文档。 It seems pretty simple to create the .dacpac, but how would I either publish to an existing database or at the very least to a .sql file. 创建.dacpac似乎很简单,但是如何发布到现有数据库或者至少发布到.sql文件。 The idea is to have it do what it does when I right click on the project and select publish. 我的想法是让它在我右键单击项目并选择发布时执行它所做的工作。 It should compare with a selected database and generate an upgrade script. 它应与选定的数据库进行比较并生成升级脚本。

This is what I have so far to create the .dacpac: 这是我到目前为止创建的.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());

  }
}

Essentially I am trying to do what this MSBuild Example shows but in code. 基本上我试图做这个MSBuild示例显示但在代码中。

Sorry that this is all I have. 对不起,这就是我的全部。 The doecumentation on the Build classes is very poor. Build类的doecumentation很差。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks. 谢谢。

I had to do something similar to this because VSDBCMD which we previously used does not deploy to SQL Server 2012 and we needed to support it. 我不得不做类似的事情,因为我们以前使用的VSDBCMD没有部署到SQL Server 2012,我们需要支持它。 What I found was the Microsoft.SqlServer.Dac assembly which seems to come as part of the SQL Server data tools ( http://msdn.microsoft.com/en-us/data/tools.aspx ) 我发现的是Microsoft.SqlServer.Dac程序集,它似乎是SQL Server数据工具的一部分( http://msdn.microsoft.com/en-us/data/tools.aspx

When you run this on the client machine you will need the full version of the .NET 4 framework and the SQL CLR types and SQL T-SQL ScriptDOM pack found here: http://www.microsoft.com/en-us/download/details.aspx?id=29065 在客户端计算机上运行它时,您将需要完整版本的.NET 4框架以及SQL CLR类型和SQL T-SQL ScriptDOM包,可在此处找到: http//www.microsoft.com/en-us/download /details.aspx?id=29065

Code below is from a mockup I made for testing the new deployment method and deploys a given .dacpac file 下面的代码来自我为测试新部署方法而生成的模型,并部署了一个给定的.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);
            }
        }
    }

This seems to work on all versions of SQL Server from 2005 and up. 这似乎适用于2005年及以后的所有SQL Server版本。 There is a similar set of objects available in Microsoft.SqlServer.Management.Dac, however I believe this is in the previous version of DACFx and is not included in the latest version. Microsoft.SqlServer.Management.Dac中有一组类似的对象可用,但我相信这是在以前版本的DACFx中,并不包含在最新版本中。 So use the latest version if you can. 如果可以,请使用最新版本。

We need a way tell msbuild how and where to publish. 我们需要一种方法告诉msbuild如何以及在何处发布。 Open your project in Visual Studio and begin to Publish it. 在Visual Studio中打开您的项目并开始Publish它。 Enter all needed info in the dialog, including your DB connection info and any custom SQLCMD variable values. 在对话框中输入所有需要的信息,包括数据库连接信息和任何自定义SQLCMD变量值。 Save Profile As... to a file, eg Northwind.publish.xml. Save Profile As...文件Save Profile As...到文件,例如Northwind.publish.xml。 (You may then Cancel .) Now we can use this and the project file to build and publish: (然后你可以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});

This can take awhile and may appear to get stuck. 这可能需要一段时间,似乎可能会卡住。 Be patient. 耐心一点。 :) :)

You should use SqlPackage.exe to publish your dacpac. 您应该使用SqlPackage.exe来发布您的dacpac。

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

Also instead of passing too many parameters you could save your settings into DAC Publish Profile (this can be done from visual studio) 此外,您可以将设置保存到DAC发布配置文件中,而不是传递太多参数(这可以通过visual studio完成)

I wanted to build and publish a database based on a sqlproj file and log helpful information to console. 我想基于sqlproj文件构建和发布数据库,并将有用的信息记录到控制台。 Here's what I arrived at: 这是我到达的地方:

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; }
}

This is for .NET 4 and above. 这适用于.NET 4及更高版本。 Be sure and include assembly references to Microsoft.Build and Microsoft.Build.Framework . 确保并包含对Microsoft.BuildMicrosoft.Build.Framework的程序集引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 microsoft.build.evaluation 以编程方式添加新的 dll 参考 - How to add new dll reference programmatically using microsoft.build.evaluation 无法在 VS2017 中使用 Microsoft.Build.Evaluation - Can't use Microsoft.Build.Evaluation in VS2017 使用 Microsoft.Build.Evaluation(而不是 Engine)以编程方式修改 csproj 文件 - Modify programatically csproj files with Microsoft.Build.Evaluation (instead of Engine) Microsoft.Build.Evaluation(快进到 2021 年)的正确用法是什么? - What's the correct usage of Microsoft.Build.Evaluation (fast forward to 2021)? 为什么Microsoft.Build.Evaluation在64位PC上将$(ProgramFiles)评估为“ c:\\ program files”? - Why does Microsoft.Build.Evaluation evaluate $(ProgramFiles) as “c:\program files” on 64 bit PC? 使用Microsoft.Build.Evaluation.Project.RemoveItem删除的项目 - Removed item using Microsoft.Build.Evaluation.Project.RemoveItem 如何使用 Microsoft.Build.Evaluation.Project.RemoveItem - How to use Microsoft.Build.Evaluation.Project.RemoveItem 不发布sqlproj - Do not publish sqlproj 从C#运行Microsoft.Build.Evaluation.Project的并行构建 - Run parallel build of Microsoft.Build.Evaluation.Project from C# 弄清楚为什么 Microsoft.Build.Evaluation.Project.Build() 返回 false - Figure out why Microsoft.Build.Evaluation.Project.Build() returns false
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM