Skip to content

Commit

Permalink
Rename API's
Browse files Browse the repository at this point in the history
Signed-off-by: Jonathan Mezach <[email protected]>
  • Loading branch information
jmezach committed Jul 25, 2024
1 parent 5afc966 commit 96b5729
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 84 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,43 +1,42 @@
using Aspire.Hosting;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Lifecycle;
using Microsoft.Extensions.Logging;
using Microsoft.SqlServer.Dac;

namespace MSBuild.Sdk.SqlProj.Aspire;

public class PublishDataTierApplicationLifecycleHook : IDistributedApplicationLifecycleHook
public class PublishSqlProjectLifecycleHook : IDistributedApplicationLifecycleHook
{
private readonly ResourceLoggerService _resourceLoggerService;
private readonly ResourceNotificationService _resourceNotificationService;

public PublishDataTierApplicationLifecycleHook(ResourceLoggerService resourceLoggerService,
ResourceNotificationService resourceNotificationService, DistributedApplicationOptions options)
public PublishSqlProjectLifecycleHook(ResourceLoggerService resourceLoggerService,
ResourceNotificationService resourceNotificationService)
{
_resourceLoggerService = resourceLoggerService ?? throw new ArgumentNullException(nameof(resourceLoggerService));
_resourceNotificationService = resourceNotificationService ?? throw new ArgumentNullException(nameof(resourceNotificationService));
}

public async Task AfterResourcesCreatedAsync(DistributedApplicationModel application, CancellationToken cancellationToken)
{
foreach (var dataTierApplication in application.Resources.OfType<DataTierApplicationResource>())
foreach (var sqlProject in application.Resources.OfType<SqlProjectResource>())
{
var logger = _resourceLoggerService.GetLogger(dataTierApplication);
var logger = _resourceLoggerService.GetLogger(sqlProject);

var dacpacPath = dataTierApplication.GetDacpacPath();
var dacpacPath = sqlProject.GetDacpacPath();
if (!File.Exists(dacpacPath))
{
logger.LogError("Data-tier application package not found at path {DacpacPath}.", dacpacPath);
await _resourceNotificationService.PublishUpdateAsync(dataTierApplication,
logger.LogError("SQL Server Database project package not found at path {DacpacPath}.", dacpacPath);
await _resourceNotificationService.PublishUpdateAsync(sqlProject,
state => state with { State = new ResourceStateSnapshot("Failed", KnownResourceStateStyles.Error) });
continue;
}

var targetDatabaseResourceName = dataTierApplication.Annotations.OfType<TargetDatabaseResourceAnnotation>().Single().TargetDatabaseResourceName;
var targetDatabaseResourceName = sqlProject.Annotations.OfType<TargetDatabaseResourceAnnotation>().Single().TargetDatabaseResourceName;
var targetDatabaseResource = application.Resources.OfType<SqlServerDatabaseResource>().Single(r => r.Name == targetDatabaseResourceName);
var connectionString = await targetDatabaseResource.ConnectionStringExpression.GetValueAsync(cancellationToken);

await _resourceNotificationService.PublishUpdateAsync(dataTierApplication,
await _resourceNotificationService.PublishUpdateAsync(sqlProject,
state => state with { State = new ResourceStateSnapshot("Publishing", KnownResourceStateStyles.Info) });

try
Expand All @@ -48,14 +47,14 @@ await _resourceNotificationService.PublishUpdateAsync(dataTierApplication,
var dacpacPackage = DacPackage.Load(dacpacPath, DacSchemaModelStorageType.Memory);
dacServices.Deploy(dacpacPackage, targetDatabaseResource.Name, true, new DacDeployOptions(), cancellationToken);

await _resourceNotificationService.PublishUpdateAsync(dataTierApplication,
await _resourceNotificationService.PublishUpdateAsync(sqlProject,
state => state with { State = new ResourceStateSnapshot("Published", KnownResourceStateStyles.Success) });
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to publish database project.");

await _resourceNotificationService.PublishUpdateAsync(dataTierApplication,
await _resourceNotificationService.PublishUpdateAsync(sqlProject,
state => state with { State = new ResourceStateSnapshot("Failed", KnownResourceStateStyles.Error) });
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/MSBuild.Sdk.SqlProj.Aspire/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.AddDatabase("test");

builder.AddDataTierApplication<Projects.MySqlProj>("mysqlproj")
builder.AddSqlProject<Projects.MySqlProj>("mysqlproj")
.PublishTo(sql);

builder.Build().Run();
Expand All @@ -33,15 +33,16 @@ builder.Build().Run();
Now when you run your .NET Aspire AppHost project you will see the SQL Database Project being published to the specified SQL Server.

## Local .dacpac file support
If you are sourcing your data-tier application package (.dacpac) file from somewhere other than a project reference, you can also specify the path to the .dacpac file directly:
If you are sourcing your .dacpac file from somewhere other than a project reference, you can also specify the path to the .dacpac file directly:

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var sql = builder.AddSqlServer("sql")
.AddDatabase("test");

builder.AddDataTierApplication("mysqlproj", "path/to/mysqlproj.dacpac")
builder.AddSqlProject("mysqlproj")
.FromDacpac("path/to/mysqlproj.dacpac")
.PublishTo(sql);

builder.Build().Run();
Expand Down
73 changes: 73 additions & 0 deletions src/MSBuild.Sdk.SqlProj.Aspire/SqlProjectBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Lifecycle;
using Microsoft.Build.Locator;
using MSBuild.Sdk.SqlProj.Aspire;

namespace Aspire.Hosting;

public static class SqlProjectBuilderExtensions
{
/// <summary>
/// Adds a SQL Server Database Project resource to the application based on a referenced MSBuild.Sdk.SqlProj project.
/// </summary>
/// <typeparam name="TProject">Type that represents the project that produces the .dacpac file.</typeparam>
/// <param name="builder">An <see cref="IDistributedApplicationBuilder"/> instance to add the SQL Server Database project to.</param>
/// <param name="name">Name of the resource.</param>
/// <returns>An <see cref="IResourceBuilder{T}"/> that can be used to further customize the resource.</returns>
public static IResourceBuilder<SqlProjectResource> AddSqlProject<TProject>(this IDistributedApplicationBuilder builder, string name)
where TProject : IProjectMetadata, new()
{
if (!MSBuildLocator.IsRegistered)
{
MSBuildLocator.RegisterDefaults();
}

var resource = new SqlProjectResource(name);

return builder.AddResource(resource)
.WithAnnotation(new TProject());
}

/// <summary>
/// Adds a SQL Server Database Project resource to the application.
/// </summary>
/// <param name="builder">An <see cref="IDistributedApplicationBuilder"/> instance to add the SQL Server Database project to.</param>
/// <param name="name">Name of the resource.</param>
/// <returns>An <see cref="IResourceBuilder{T}"/> that can be used to further customize the resource.</returns>
public static IResourceBuilder<SqlProjectResource> AddSqlProject(this IDistributedApplicationBuilder builder, string name)
{
var resource = new SqlProjectResource(name);

return builder.AddResource(resource);
}

/// <summary>
/// Specifies the path to the .dacpac file.
/// </summary>
/// <param name="builder">An <see cref="IResourceBuilder{T}"/> representing the SQL Server Database project.</param>
/// <param name="dacpacPath">Path to the .dacpac file.</param>
/// <returns>An <see cref="IResourceBuilder{T}"/> that can be used to further customize the resource.</returns>
public static IResourceBuilder<SqlProjectResource> FromDacpac(this IResourceBuilder<SqlProjectResource> builder, string dacpacPath)
{
if (!Path.IsPathRooted(dacpacPath))
{
dacpacPath = Path.Combine(builder.ApplicationBuilder.AppHostDirectory, dacpacPath);
}

return builder.WithAnnotation(new DacpacMetadataAnnotation(dacpacPath));
}

/// <summary>
/// Publishes the SQL Server Database project to the target <see cref="SqlServerDatabaseResource"/>.
/// </summary>
/// <param name="builder">An <see cref="IResourceBuilder{T}"/> representing the SQL Server Database project to publish.</param>
/// <param name="target">An <see cref="IResourceBuilder{T}"/> representing the target <see cref="SqlServerDatabaseResource"/> to publish the SQL Server Database project to.</param>
/// <returns>An <see cref="IResourceBuilder{T}"/> that can be used to further customize the resource.</returns>
public static IResourceBuilder<SqlProjectResource> PublishTo(
this IResourceBuilder<SqlProjectResource> builder, IResourceBuilder<SqlServerDatabaseResource> target)
{
builder.ApplicationBuilder.Services.TryAddLifecycleHook<PublishSqlProjectLifecycleHook>();
builder.WithAnnotation(new TargetDatabaseResourceAnnotation(target.Resource.Name), ResourceAnnotationMutationBehavior.Replace);
return builder;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace MSBuild.Sdk.SqlProj.Aspire;

public sealed class DataTierApplicationResource(string name) : Resource(name)
public sealed class SqlProjectResource(string name) : Resource(name)
{
public string GetDacpacPath()
{
Expand All @@ -22,6 +22,6 @@ public string GetDacpacPath()
return dacpacMetadata.DacpacPath;
}

throw new InvalidOperationException($"Unable to locate data-tier application package for resource {Name}.");
throw new InvalidOperationException($"Unable to locate SQL Server Database project package for resource {Name}.");
}
}
5 changes: 3 additions & 2 deletions test/TestAspireHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
var sql = builder.AddSqlServer("sql")
.AddDatabase("test");

builder.AddDataTierApplication<Projects.TestProject>("testproject")
builder.AddSqlProject<Projects.TestProject>("testproject")
.PublishTo(sql);

builder.AddDataTierApplication("testprojectwithwarnings", "../TestProjectWithWarnings/bin/Debug/netstandard2.0/TestProjectWithWarnings.dacpac")
builder.AddSqlProject("testprojectwithwarnings")
.FromDacpac("../TestProjectWithWarnings/bin/Debug/netstandard2.0/TestProjectWithWarnings.dacpac")
.PublishTo(sql);

builder.Build().Run();

0 comments on commit 96b5729

Please sign in to comment.