Skip to content

Commit

Permalink
Created a Migrations project to migrate the
Browse files Browse the repository at this point in the history
  • Loading branch information
Niek van Weeghel authored and Niek van Weeghel committed May 17, 2023
1 parent 5409f67 commit b479148
Show file tree
Hide file tree
Showing 6 changed files with 169 additions and 5 deletions.
6 changes: 6 additions & 0 deletions IdentityServerConfig.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdentityServerConfig", "src
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdentityServerConfig.UnitTest", "test\IdentityServerConfig.UnitTest.csproj", "{705C1CDB-0DF3-4A30-BCA7-211A3196CACA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdentityServerConfig.Migrations", "migrations\IdentityServerConfig.Migrations.csproj", "{190F93D8-48AB-4F6D-8FFC-01C78A507254}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -21,6 +23,10 @@ Global
{705C1CDB-0DF3-4A30-BCA7-211A3196CACA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{705C1CDB-0DF3-4A30-BCA7-211A3196CACA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{705C1CDB-0DF3-4A30-BCA7-211A3196CACA}.Release|Any CPU.Build.0 = Release|Any CPU
{190F93D8-48AB-4F6D-8FFC-01C78A507254}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{190F93D8-48AB-4F6D-8FFC-01C78A507254}.Debug|Any CPU.Build.0 = Debug|Any CPU
{190F93D8-48AB-4F6D-8FFC-01C78A507254}.Release|Any CPU.ActiveCfg = Release|Any CPU
{190F93D8-48AB-4F6D-8FFC-01C78A507254}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
44 changes: 44 additions & 0 deletions Migrations/DeploymentScripts/InitialCreate.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
END;
GO

BEGIN TRANSACTION;
GO

IF SCHEMA_ID(N'IdentityServerConfig') IS NULL EXEC(N'CREATE SCHEMA [IdentityServerConfig];');
GO

CREATE TABLE [IdentityServerConfig].[AuditLog] (
[ID] int NOT NULL IDENTITY,
[UserId] nvarchar(max) NOT NULL,
[Timestamp] datetime2 NOT NULL,
[Action] nvarchar(max) NOT NULL,
CONSTRAINT [PK_AuditLog] PRIMARY KEY ([ID])
);
GO

INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
VALUES (N'20230516071604_InitialCreate', N'7.0.5');
GO

COMMIT;
GO

BEGIN TRANSACTION;
GO

ALTER TABLE [IdentityServerConfig].[AuditLog] ADD [UserName] nvarchar(max) NOT NULL DEFAULT N'';
GO

INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
VALUES (N'20230516082321_AddedUserName', N'7.0.5');
GO

COMMIT;
GO
22 changes: 22 additions & 0 deletions Migrations/IdentityServerConfig.Migrations.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<UserSecretsId>8d14d57a-5ec9-430f-9b5a-8e40c3558bb2</UserSecretsId>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="DbUp.Reboot.SqlServer" Version="1.5.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
</ItemGroup>

<ItemGroup>
<None Update="DeploymentScripts\InitialCreate.sql">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
12 changes: 12 additions & 0 deletions Migrations/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using IdentityServerConfig.Migrations;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;



var host = Host.CreateDefaultBuilder(args).ConfigureServices((context, services) =>
{
services.AddHostedService<Worker>();
}).Build();

await host.RunAsync();
84 changes: 84 additions & 0 deletions Migrations/Worker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System.Diagnostics;
using DbUp.Reboot;
using DbUp.Reboot.Engine;
using DbUp.Reboot.ScriptProviders;
using DbUp.Reboot.Support;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace IdentityServerConfig.Migrations;

public class Worker : BackgroundService
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
private readonly ILogger<Worker> _logger;
private readonly IConfiguration _configuration;

/// <summary>
/// Initializes a new instance of the <see cref="Worker" /> class.
/// </summary>
public Worker(ILogger<Worker> logger, IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration)
{
_logger = logger;
_hostApplicationLifetime = hostApplicationLifetime;
_configuration = configuration;
}

/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
_logger.LogInformation("Starting migration");

await Task.Run(() =>
{
var connectionString = _configuration.GetConnectionString("AuditLog");
if (connectionString == null)
{
throw new ArgumentException("ConnectionString cannot be null");
}
_logger.LogInformation("Connection string is {ConnectionString}", connectionString);

EnsureDatabase.For.SqlDatabase(connectionString);

var path = Path.GetDirectoryName(Process.GetCurrentProcess()?.MainModule?.FileName);
_logger.LogInformation(path);
var upgradeEngineBuilder = DeployChanges.To
.SqlDatabase(connectionString, null)
.WithScriptsFromFileSystem(path,
new FileSystemScriptOptions { IncludeSubDirectories = true, Filter = (x) => x.Contains("DeploymentScripts") },
new SqlScriptOptions { ScriptType = ScriptType.RunOnce, RunGroupOrder = 1 })
.WithTransaction()
.LogToConsole();

Task.Delay(10000);

var upgrader = upgradeEngineBuilder.Build();
_logger.LogInformation("Is upgrade required: " + upgrader.IsUpgradeRequired());

var result = upgrader.PerformUpgrade();

// Display the result
if (result.Successful)
{
_logger.LogInformation("Success!");
}
else
{
_logger.LogError(result.Error, "Migration failed.");
Environment.ExitCode = 2;
}

_logger.LogInformation("Finished executing migrations, shutting down");
_hostApplicationLifetime.StopApplication();
}, stoppingToken);
}
catch
{
Environment.ExitCode = 1;
throw;
}
}
}
6 changes: 1 addition & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@ You will need to set the connection string using the [.NET's user secrets](https
dotnet user-secrets set ConnectionStrings:AuditLog <your-connection-string>
```

To create the database schema and the needed table, you can use the following command:
```bash
dotnet ef database update --context AuditContext
```
This will create the schema in the database specified in the connection string.
To create the audit log table, run the `IdentityServerConfig.Migrations` project. This will create the table in the database.


## Configuring authentication
Expand Down

0 comments on commit b479148

Please sign in to comment.