DacFx import/export (#728)

Adding DacFx import/export/deploy/extract functionality
This commit is contained in:
kisantia
2018-11-27 16:10:46 -08:00
committed by GitHub
parent 7a47db8806
commit d5fd968b3c
17 changed files with 920 additions and 9 deletions

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AssemblyName>MicrosoftSqlToolsCredentials</AssemblyName>
<OutputType>Exe</OutputType>
<OutputType>Exe</OutputType>
<EnableDefaultItems>false</EnableDefaultItems>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<EnableDefaultEmbeddedResourceItems>false</EnableDefaultEmbeddedResourceItems>
@@ -16,21 +16,24 @@
<RuntimeIdentifiers>win7-x64;win7-x86;ubuntu.14.04-x64;ubuntu.16.04-x64;centos.7-x64;rhel.7.2-x64;debian.8-x64;fedora.23-x64;opensuse.13.2-x64;osx.10.11-x64;linux-x64</RuntimeIdentifiers>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Data.SqlClient" />
<Reference Include="System.Data.SqlClient" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.6.0-preview3-27014-02" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" /><PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="2.0.0" />
<PackageReference Include="System.IO.Packaging" Version="4.5.0" />
<PackageReference Include="System.Runtime.Loader" Version="4.3.0" />
<PackageReference Include="System.Composition" Version="1.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
<PackageReference Include="System.Security.Permissions" Version="4.5.0" />
</ItemGroup>
<ItemGroup>
<Compile Include="**\*.cs" />
<Compile Include="**\*.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Microsoft.SqlTools.Hosting/Microsoft.SqlTools.Hosting.csproj" />
<ProjectReference Include="../Microsoft.SqlTools.Hosting/Microsoft.SqlTools.Hosting.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Localization\sr.resx" />

View File

@@ -0,0 +1,44 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.DacFx.Contracts
{
/// <summary>
/// Parameters for a DacFx request.
/// </summary>
public abstract class DacFxParams : IScriptableRequestParams
{
/// <summary>
/// Gets or sets package filepath
/// </summary>
public string PackageFilePath { get; set; }
/// <summary>
/// Gets or sets name for database
/// </summary>
public string DatabaseName { get; set; }
/// <summary>
/// Connection uri
/// </summary>
public string OwnerUri { get; set; }
/// <summary>
/// Executation mode for the operation. Default is execution
/// </summary>
public TaskExecutionMode TaskExecutionMode { get; set; }
}
/// <summary>
/// Parameters returned from a DacFx request.
/// </summary>
public class DacFxResult : ResultStatus
{
public string OperationId { get; set; }
}
}

View File

@@ -0,0 +1,30 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.DacFx.Contracts
{
/// <summary>
/// Parameters for a DacFx deploy request.
/// </summary>
public class DeployParams : DacFxParams
{
/// <summary>
/// Gets or sets if upgrading existing database
/// </summary>
public bool UpgradeExisting { get; set; }
}
/// <summary>
/// Defines the DacFx deploy request type
/// </summary>
class DeployRequest
{
public static readonly RequestType<DeployParams, DacFxResult> Type =
RequestType<DeployParams, DacFxResult>.Create("dacfx/deploy");
}
}

View File

@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.DacFx.Contracts
{
/// <summary>
/// Parameters for a DacFx export request.
/// </summary>
public class ExportParams : DacFxParams
{
}
/// <summary>
/// Defines the DacFx export request type
/// </summary>
class ExportRequest
{
public static readonly RequestType<ExportParams, DacFxResult> Type =
RequestType<ExportParams, DacFxResult>.Create("dacfx/export");
}
}

View File

@@ -0,0 +1,36 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
using System;
namespace Microsoft.SqlTools.ServiceLayer.DacFx.Contracts
{
/// <summary>
/// Parameters for a DacFx extract request.
/// </summary>
public class ExtractParams : DacFxParams
{
/// <summary>
/// Gets or sets the string identifier for the DAC application
/// </summary>
public string ApplicationName { get; set; }
/// <summary>
/// Gets or sets the version of the DAC application
/// </summary>
public Version ApplicationVersion { get; set; }
}
/// <summary>
/// Defines the DacFx extract request type
/// </summary>
class ExtractRequest
{
public static readonly RequestType<ExtractParams, DacFxResult> Type =
RequestType<ExtractParams, DacFxResult>.Create("dacfx/extract");
}
}

View File

@@ -0,0 +1,27 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.ServiceLayer.Utility;
namespace Microsoft.SqlTools.ServiceLayer.DacFx.Contracts
{
/// <summary>
/// Parameters for a DacFx import request.
/// </summary>
public class ImportParams : DacFxParams
{
}
/// <summary>
/// Defines the DacFx import request type
/// </summary>
class ImportRequest
{
public static readonly RequestType<ImportParams, DacFxResult> Type =
RequestType<ImportParams, DacFxResult>.Create("dacfx/import");
}
}

View File

@@ -0,0 +1,93 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Dac;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.Utility;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.SqlTools.ServiceLayer.DacFx
{
/// <summary>
/// Base class for DacFx operations
/// </summary>
abstract class DacFxOperation : ITaskOperation
{
private CancellationTokenSource cancellation = new CancellationTokenSource();
private bool disposed = false;
/// <summary>
/// Gets the unique id associated with this instance.
/// </summary>
public string OperationId { get; private set; }
public SqlTask SqlTask { get; set; }
protected SqlConnection SqlConnection { get; private set; }
protected DacServices DacServices { get; private set; }
protected DacFxOperation(SqlConnection sqlConnection)
{
Validate.IsNotNull("sqlConnection", sqlConnection);
this.SqlConnection = sqlConnection;
this.OperationId = Guid.NewGuid().ToString();
}
protected CancellationToken CancellationToken { get { return this.cancellation.Token; } }
/// <summary>
/// The error occurred during operation
/// </summary>
public string ErrorMessage { get; }
/// <summary>
/// Cancel operation
/// </summary>
public void Cancel()
{
if (!this.cancellation.IsCancellationRequested)
{
Logger.Write(TraceEventType.Verbose, string.Format("Cancel invoked for OperationId {0}", this.OperationId));
this.cancellation.Cancel();
}
}
/// <summary>
/// Disposes the operation.
/// </summary>
public void Dispose()
{
if (!disposed)
{
this.Cancel();
disposed = true;
}
}
public void Execute(TaskExecutionMode mode)
{
if (this.CancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(this.CancellationToken);
}
try
{
this.DacServices = new DacServices(this.SqlConnection.ConnectionString);
Execute();
}
catch (Exception e)
{
Logger.Write(TraceEventType.Error, string.Format("DacFx import operation {0} failed with exception {1}", this.OperationId, e));
throw;
}
}
public abstract void Execute();
}
}

View File

@@ -0,0 +1,215 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.DacFx.Contracts;
using Microsoft.SqlTools.ServiceLayer.Hosting;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using System;
using System.Collections.Concurrent;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Microsoft.SqlTools.ServiceLayer.DacFx
{
/// <summary>
/// Main class for DacFx service
/// </summary>
class DacFxService
{
private static ConnectionService connectionService = null;
private SqlTaskManager sqlTaskManagerInstance = null;
private static readonly Lazy<DacFxService> instance = new Lazy<DacFxService>(() => new DacFxService());
private readonly Lazy<ConcurrentDictionary<string, DacFxOperation>> operations =
new Lazy<ConcurrentDictionary<string, DacFxOperation>>(() => new ConcurrentDictionary<string, DacFxOperation>());
/// <summary>
/// Gets the singleton instance object
/// </summary>
public static DacFxService Instance
{
get { return instance.Value; }
}
/// <summary>
/// Initializes the service instance
/// </summary>
/// <param name="serviceHost"></param>
public void InitializeService(ServiceHost serviceHost)
{
serviceHost.SetRequestHandler(ExportRequest.Type, this.HandleExportRequest);
serviceHost.SetRequestHandler(ImportRequest.Type, this.HandleImportRequest);
serviceHost.SetRequestHandler(ExtractRequest.Type, this.HandleExtractRequest);
serviceHost.SetRequestHandler(DeployRequest.Type, this.HandleDeployRequest);
}
/// <summary>
/// The collection of active operations
/// </summary>
internal ConcurrentDictionary<string, DacFxOperation> ActiveOperations => operations.Value;
/// <summary>
/// Handles request to export a bacpac
/// </summary>
/// <returns></returns>
public async Task HandleExportRequest(ExportParams parameters, RequestContext<DacFxResult> requestContext)
{
try
{
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo != null)
{
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(connInfo, "Export");
ExportOperation operation = new ExportOperation(parameters, sqlConn);
await ExecuteOperation(operation, parameters, "Export bacpac", requestContext);
}
}
catch (Exception e)
{
await requestContext.SendError(e);
}
}
/// <summary>
/// Handles request to import a bacpac
/// </summary>
/// <returns></returns>
public async Task HandleImportRequest(ImportParams parameters, RequestContext<DacFxResult> requestContext)
{
try
{
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo != null)
{
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(connInfo, "Import");
ImportOperation operation = new ImportOperation(parameters, sqlConn);
await ExecuteOperation(operation, parameters, "Import bacpac", requestContext);
}
}
catch (Exception e)
{
await requestContext.SendError(e);
}
}
/// <summary>
/// Handles request to extract a dacpac
/// </summary>
/// <returns></returns>
public async Task HandleExtractRequest(ExtractParams parameters, RequestContext<DacFxResult> requestContext)
{
try
{
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo != null)
{
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(connInfo, "Extract");
ExtractOperation operation = new ExtractOperation(parameters, sqlConn);
await ExecuteOperation(operation, parameters, "Extract dacpac", requestContext);
}
}
catch (Exception e)
{
await requestContext.SendError(e);
}
}
/// <summary>
/// Handles request to deploy a dacpac
/// </summary>
/// <returns></returns>
public async Task HandleDeployRequest(DeployParams parameters, RequestContext<DacFxResult> requestContext)
{
try
{
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo != null)
{
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(connInfo, "Deploy");
DeployOperation operation = new DeployOperation(parameters, sqlConn);
await ExecuteOperation(operation, parameters, "Deploy dacpac", requestContext);
}
}
catch (Exception e)
{
await requestContext.SendError(e);
}
}
private async Task ExecuteOperation(DacFxOperation operation, DacFxParams parameters, string taskName, RequestContext<DacFxResult> requestContext)
{
SqlTask sqlTask = null;
TaskMetadata metadata = TaskMetadata.Create(parameters, taskName, operation, ConnectionServiceInstance);
// put appropriate database name since connection passed was to master
metadata.DatabaseName = parameters.DatabaseName;
sqlTask = SqlTaskManagerInstance.CreateAndRun<SqlTask>(metadata);
await requestContext.SendResult(new DacFxResult()
{
OperationId = operation.OperationId,
Success = true,
ErrorMessage = ""
});
}
private SqlTaskManager SqlTaskManagerInstance
{
get
{
if (sqlTaskManagerInstance == null)
{
sqlTaskManagerInstance = SqlTaskManager.Instance;
}
return sqlTaskManagerInstance;
}
set
{
sqlTaskManagerInstance = value;
}
}
/// <summary>
/// Internal for testing purposes only
/// </summary>
internal static ConnectionService ConnectionServiceInstance
{
get
{
if (connectionService == null)
{
connectionService = ConnectionService.Instance;
}
return connectionService;
}
set
{
connectionService = value;
}
}
/// <summary>
/// For testing purpose only
/// </summary>
/// <param name="operation"></param>
internal void PerformOperation(DacFxOperation operation)
{
operation.Execute(TaskExecutionMode.Execute);
}
}
}

View File

@@ -0,0 +1,34 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Dac;
using Microsoft.SqlTools.ServiceLayer.DacFx.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.Utility;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Microsoft.SqlTools.ServiceLayer.DacFx
{
/// <summary>
/// Class to represent an in-progress deploy operation
/// </summary>
class DeployOperation : DacFxOperation
{
public DeployParams Parameters { get; }
public DeployOperation(DeployParams parameters, SqlConnection sqlConnection) : base(sqlConnection)
{
Validate.IsNotNull("parameters", parameters);
this.Parameters = parameters;
}
public override void Execute()
{
DacPackage dacpac = DacPackage.Load(this.Parameters.PackageFilePath);
this.DacServices.Deploy(dacpac, this.Parameters.DatabaseName, this.Parameters.UpgradeExisting, null, this.CancellationToken);
}
}
}

View File

@@ -0,0 +1,33 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Dac;
using Microsoft.SqlTools.ServiceLayer.DacFx.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.Utility;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Microsoft.SqlTools.ServiceLayer.DacFx
{
/// <summary>
/// Class to represent an in-progress export operation
/// </summary>
class ExportOperation : DacFxOperation
{
public ExportParams Parameters { get; }
public ExportOperation(ExportParams parameters, SqlConnection sqlConnection): base(sqlConnection)
{
Validate.IsNotNull("parameters", parameters);
this.Parameters = parameters;
}
public override void Execute()
{
this.DacServices.ExportBacpac(this.Parameters.PackageFilePath, this.Parameters.DatabaseName, null, this.CancellationToken);
}
}
}

View File

@@ -0,0 +1,33 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Dac;
using Microsoft.SqlTools.ServiceLayer.DacFx.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.Utility;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Microsoft.SqlTools.ServiceLayer.DacFx
{
/// <summary>
/// Class to represent an in-progress extract operation
/// </summary>
class ExtractOperation : DacFxOperation
{
public ExtractParams Parameters { get; }
public ExtractOperation(ExtractParams parameters, SqlConnection sqlConnection): base(sqlConnection)
{
Validate.IsNotNull("parameters", parameters);
this.Parameters = parameters;
}
public override void Execute()
{
this.DacServices.Extract(this.Parameters.PackageFilePath, this.Parameters.DatabaseName, this.Parameters.ApplicationName, this.Parameters.ApplicationVersion, null, null, null, this.CancellationToken);
}
}
}

View File

@@ -0,0 +1,34 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlServer.Dac;
using Microsoft.SqlTools.ServiceLayer.DacFx.Contracts;
using Microsoft.SqlTools.ServiceLayer.TaskServices;
using Microsoft.SqlTools.Utility;
using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Microsoft.SqlTools.ServiceLayer.DacFx
{
/// <summary>
/// Class to represent an in-progress import operation
/// </summary>
class ImportOperation : DacFxOperation
{
public ImportParams Parameters { get; }
public ImportOperation(ImportParams parameters, SqlConnection sqlConnection): base(sqlConnection)
{
Validate.IsNotNull("parameters", parameters);
this.Parameters = parameters;
}
public override void Execute()
{
BacPackage bacpac = BacPackage.Load(this.Parameters.PackageFilePath);
this.DacServices.ImportBacpac(bacpac, this.Parameters.DatabaseName, this.CancellationToken);
}
}
}

View File

@@ -11,6 +11,7 @@ using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Admin;
using Microsoft.SqlTools.ServiceLayer.Agent;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.DacFx;
using Microsoft.SqlTools.ServiceLayer.DisasterRecovery;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.FileBrowser;
@@ -110,6 +111,9 @@ namespace Microsoft.SqlTools.ServiceLayer
SecurityService.Instance.InitializeService(serviceHost);
serviceProvider.RegisterSingleService(SecurityService.Instance);
DacFxService.Instance.InitializeService(serviceHost);
serviceProvider.RegisterSingleService(DacFxService.Instance);
InitializeHostedServices(serviceProvider, serviceHost);
serviceHost.ServiceProvider = serviceProvider;

View File

@@ -16,13 +16,14 @@
<RuntimeIdentifiers>win7-x64;win7-x86;ubuntu.14.04-x64;ubuntu.16.04-x64;centos.7-x64;rhel.7.2-x64;debian.8-x64;fedora.23-x64;opensuse.13.2-x64;osx.10.11-x64;linux-x64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
<PropertyGroup>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.6.0-preview3-27014-02" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" />
<PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4240.1-preview" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.6.0-preview3-26501-04" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,276 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.SqlTools.Hosting.Protocol;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.DacFx;
using Microsoft.SqlTools.ServiceLayer.DacFx.Contracts;
using Microsoft.SqlTools.ServiceLayer.IntegrationTests.Utility;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Moq;
using System;
using System.Data.SqlClient;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.IntegrationTests.DacFx
{
public class DacFxServiceTests
{
private LiveConnectionHelper.TestConnectionResult GetLiveAutoCompleteTestObjects()
{
var result = LiveConnectionHelper.InitLiveConnectionInfo();
return result;
}
private async Task<Mock<RequestContext<DacFxResult>>> SendAndValidateExportRequest()
{
var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<DacFxResult>>();
requestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");
Directory.CreateDirectory(folderPath);
var exportParams = new ExportParams
{
DatabaseName = testdb.DatabaseName,
PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", testdb.DatabaseName))
};
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Export");
DacFxService service = new DacFxService();
ExportOperation operation = new ExportOperation(exportParams, sqlConn);
service.PerformOperation(operation);
// cleanup
VerifyAndCleanup(exportParams.PackageFilePath);
testdb.Cleanup();
return requestContext;
}
private async Task<Mock<RequestContext<DacFxResult>>> SendAndValidateImportRequest()
{
// first export a bacpac
var result = GetLiveAutoCompleteTestObjects();
var exportRequestContext = new Mock<RequestContext<DacFxResult>>();
exportRequestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxImportTest");
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");
Directory.CreateDirectory(folderPath);
var exportParams = new ExportParams
{
DatabaseName = sourceDb.DatabaseName,
PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", sourceDb.DatabaseName))
};
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Import");
DacFxService service = new DacFxService();
ExportOperation exportOperation = new ExportOperation(exportParams, sqlConn);
service.PerformOperation(exportOperation);
// import the created bacpac
var importRequestContext = new Mock<RequestContext<DacFxResult>>();
importRequestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
var importParams = new ImportParams
{
PackageFilePath = exportParams.PackageFilePath,
DatabaseName = string.Concat(sourceDb.DatabaseName, "-imported")
};
ImportOperation importOperation = new ImportOperation(importParams, sqlConn);
service.PerformOperation(importOperation);
SqlTestDb targetDb = SqlTestDb.CreateFromExisting(importParams.DatabaseName);
// cleanup
VerifyAndCleanup(exportParams.PackageFilePath);
sourceDb.Cleanup();
targetDb.Cleanup();
return importRequestContext;
}
private async Task<Mock<RequestContext<DacFxResult>>> SendAndValidateExtractRequest()
{
var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<DacFxResult>>();
requestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExtractTest");
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");
Directory.CreateDirectory(folderPath);
var extractParams = new ExtractParams
{
DatabaseName = testdb.DatabaseName,
PackageFilePath = Path.Combine(folderPath, string.Format("{0}.dacpac", testdb.DatabaseName)),
ApplicationName = "test",
ApplicationVersion = new Version(1, 0)
};
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Extract");
DacFxService service = new DacFxService();
ExtractOperation operation = new ExtractOperation(extractParams, sqlConn);
service.PerformOperation(operation);
// cleanup
VerifyAndCleanup(extractParams.PackageFilePath);
testdb.Cleanup();
return requestContext;
}
private async Task<Mock<RequestContext<DacFxResult>>> SendAndValidateDeployRequest()
{
// first extract a db to have a dacpac to import later
var result = GetLiveAutoCompleteTestObjects();
var extractRequestContext = new Mock<RequestContext<DacFxResult>>();
extractRequestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
SqlTestDb sourceDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxDeployTest");
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");
Directory.CreateDirectory(folderPath);
var extractParams = new ExtractParams
{
DatabaseName = sourceDb.DatabaseName,
PackageFilePath = Path.Combine(folderPath, string.Format("{0}.dacpac", sourceDb.DatabaseName)),
ApplicationName = "test",
ApplicationVersion = new Version(1, 0)
};
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Deploy");
DacFxService service = new DacFxService();
ExtractOperation extractOperation = new ExtractOperation(extractParams, sqlConn);
service.PerformOperation(extractOperation);
// deploy the created dacpac
var deployRequestContext = new Mock<RequestContext<DacFxResult>>();
deployRequestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
var deployParams = new DeployParams
{
PackageFilePath = extractParams.PackageFilePath,
DatabaseName = string.Concat(sourceDb.DatabaseName, "-deployed"),
UpgradeExisting = false
};
DeployOperation deployOperation = new DeployOperation(deployParams, sqlConn);
service.PerformOperation(deployOperation); SqlTestDb targetDb = SqlTestDb.CreateFromExisting(deployParams.DatabaseName);
// cleanup
VerifyAndCleanup(extractParams.PackageFilePath);
sourceDb.Cleanup();
targetDb.Cleanup();
return deployRequestContext;
}
private async Task<Mock<RequestContext<DacFxResult>>> ValidateExportCancellation()
{
var result = GetLiveAutoCompleteTestObjects();
var requestContext = new Mock<RequestContext<DacFxResult>>();
requestContext.Setup(x => x.SendResult(It.IsAny<DacFxResult>())).Returns(Task.FromResult(new object()));
SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest");
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest");
Directory.CreateDirectory(folderPath);
var exportParams = new ExportParams
{
DatabaseName = testdb.DatabaseName,
PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", testdb.DatabaseName))
};
SqlConnection sqlConn = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Export");
DacFxService service = new DacFxService();
ExportOperation operation = new ExportOperation(exportParams, sqlConn);
// set cancellation token to cancel
operation.Cancel();
OperationCanceledException expectedException = null;
try
{
service.PerformOperation(operation);
}
catch(OperationCanceledException canceledException)
{
expectedException = canceledException;
}
Assert.NotNull(expectedException);
// cleanup
testdb.Cleanup();
return requestContext;
}
/// <summary>
/// Verify the export bacpac request
/// </summary>
[Fact]
public async void ExportBacpac()
{
Assert.NotNull(await SendAndValidateExportRequest());
}
/// <summary>
/// Verify the export request being cancelled
/// </summary>
[Fact]
public async void ExportBacpacCancellationTest()
{
Assert.NotNull(await ValidateExportCancellation());
}
/// <summary>
/// Verify the import bacpac request
/// </summary>
[Fact]
public async void ImportBacpac()
{
Assert.NotNull(await SendAndValidateImportRequest());
}
/// <summary>
/// Verify the extract dacpac request
/// </summary>
[Fact]
public async void ExtractDacpac()
{
Assert.NotNull(await SendAndValidateExtractRequest());
}
/// <summary>
/// Verify the deploy dacpac request
/// </summary>
[Fact]
public async void DeployDacpac()
{
Assert.NotNull(await SendAndValidateDeployRequest());
}
private void VerifyAndCleanup(string filePath)
{
// Verify it was created
Assert.True(File.Exists(filePath));
// Remove the file
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
}
}

View File

@@ -35,6 +35,7 @@
<PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.6.0-preview3-27014-02" />
<PackageReference Include="Microsoft.SqlServer.SqlManagementObjects" Version="$(SmoPackageVersion)" />
<PackageReference Include="Microsoft.SqlServer.DacFx" Version="150.4240.1-preview" />
</ItemGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />

View File

@@ -110,6 +110,27 @@ namespace Microsoft.SqlTools.ServiceLayer.Test.Common
return CreateNew(serverType, false, null, null);
}
/// <summary>
/// Represents a test Database that was created in a test
/// </summary>
public static SqlTestDb CreateFromExisting(
string dbName,
TestServerType serverType = TestServerType.OnPrem,
bool doNotCleanupDb = false)
{
SqlTestDb testDb = new SqlTestDb();
if (string.IsNullOrEmpty(dbName))
{
throw new ArgumentOutOfRangeException("dbName");
}
testDb.DatabaseName = dbName;
testDb.ServerType = serverType;
return testDb;
}
/// <summary>
/// Returns a mangled name that unique based on Prefix + Machine + Process
/// </summary>