Skip to content

Commit

Permalink
Added feature to configure username factory and default username
Browse files Browse the repository at this point in the history
  • Loading branch information
Bilal Fazlani committed May 21, 2016
1 parent 67ac7ab commit c77ce49
Show file tree
Hide file tree
Showing 15 changed files with 185 additions and 18 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -155,3 +155,4 @@ $RECYCLE.BIN/

# Mac desktop service store files
.DS_Store
/.vs/config
3 changes: 3 additions & 0 deletions TrackerEnabledDbContext.Common/Interfaces/ITrackerContext.cs
Expand Up @@ -15,6 +15,9 @@ public interface ITrackerContext : IDbContext

event EventHandler<AuditLogGeneratedEventArgs> OnAuditLogGenerated;

void ConfigureUsername(Func<string> usernameFactory);
void ConfigureUsername(string defaultUsername);

IQueryable<AuditLog> GetLogs(string entityFullName);
IQueryable<AuditLog> GetLogs(string entityFullName, object primaryKey);
IQueryable<AuditLog> GetLogs<TEntity>();
Expand Down
Expand Up @@ -39,15 +39,17 @@
<AssemblyOriginatorKeyFile>MyKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework">
<HintPath>..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.dll</HintPath>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.MappingAPI, Version=6.1.0.9, Culture=neutral, PublicKeyToken=7ee2e825d201459e, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.MappingAPI.6.1.0.9\lib\net45\EntityFramework.MappingAPI.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="EntityFramework.SqlServer">
<HintPath>..\packages\EntityFramework.6.1.1\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
Expand Down
2 changes: 1 addition & 1 deletion TrackerEnabledDbContext.Common/packages.config
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.1" targetFramework="net45" />
<package id="EntityFramework" version="6.1.3" targetFramework="net45" />
<package id="EntityFramework.MappingAPI" version="6.1.0.9" targetFramework="net45" />
</packages>
Expand Up @@ -9,7 +9,7 @@
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add name="DefaultTestConnection"
connectionString="Data Source=.\sqlexpress;Initial Catalog=TEDB-Identity-Tests;Integrated Security=True;MultipleActiveResultSets=true"
connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=TEDB-Identity-Tests;Integrated Security=True;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
Expand Down
Expand Up @@ -14,6 +14,7 @@ public class TestTrackerIdentityContext : TrackerIdentityContext<IdentityUser>,
public TestTrackerIdentityContext()
: base(TestConnectionString)
{
Database.SetInitializer(new DropCreateDatabaseAlways<TestTrackerIdentityContext>());
}

public DbSet<NormalModel> NormalModels { get; set; }
Expand Down
Expand Up @@ -79,6 +79,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TestTrackerIdentityContext .cs" />
<Compile Include="TrackerIdentityContextIntegrationTests.cs" />
<Compile Include="UsernameConfigurationTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TrackerEnabledDbContext.Common.Testing\TrackerEnabledDbContext.Common.Testing.csproj">
Expand All @@ -99,7 +100,6 @@
<None Include="MyKey.snk" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup />
<Choose>
<When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
<ItemGroup>
Expand Down
@@ -0,0 +1,66 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TrackerEnabledDbContext.Common.Testing;
using TrackerEnabledDbContext.Common.Testing.Extensions;
using TrackerEnabledDbContext.Common.Testing.Models;

namespace TrackerEnabledDbContext.Identity.IntegrationTests
{
[TestClass]
public class UsernameConfigurationTests : PersistanceTests<TestTrackerIdentityContext>
{
[TestMethod]
public void Can_use_username_factory()
{
Db.ConfigureUsername(()=> "bilal");

NormalModel model =
GetObjectFactory<NormalModel>().Create();
Db.NormalModels.Add(model);
Db.SaveChanges();
model.Id.AssertIsNotZero();

model.AssertAuditForAddition(Db, model.Id,
"bilal",
x => x.Id,
x => x.Description
);
}

[TestMethod]
public void Can_username_factory_override_default_username()
{
Db.ConfigureUsername(() => "bilal");
Db.ConfigureUsername("rahul");

NormalModel model =
GetObjectFactory<NormalModel>().Create();
Db.NormalModels.Add(model);
Db.SaveChanges();
model.Id.AssertIsNotZero();

model.AssertAuditForAddition(Db, model.Id,
"bilal",
x => x.Id,
x => x.Description
);
}

[TestMethod]
public void Can_use_default_username()
{
Db.ConfigureUsername("rahul");

NormalModel model =
GetObjectFactory<NormalModel>().Create();
Db.NormalModels.Add(model);
Db.SaveChanges();
model.Id.AssertIsNotZero();

model.AssertAuditForAddition(Db, model.Id,
"rahul",
x => x.Id,
x => x.Description
);
}
}
}
23 changes: 18 additions & 5 deletions TrackerEnabledDbContext.Identity/TrackerIdentityContext.cs
Expand Up @@ -29,6 +29,19 @@ public class TrackerIdentityContext<TUser, TRole, TKey, TUserLogin, TUserRole, T
{
private readonly CoreTracker _coreTracker;

private Func<string> _usernameFactory;
private string _defaultUsername;

public void ConfigureUsername(Func<string> usernameFactory)
{
_usernameFactory = usernameFactory;
}

public void ConfigureUsername(string defaultUsername)
{
_defaultUsername = defaultUsername;
}

public TrackerIdentityContext()
{
_coreTracker = new CoreTracker(this);
Expand Down Expand Up @@ -86,7 +99,7 @@ public virtual int SaveChanges(object userName)
return base.SaveChanges();
}

_coreTracker.AuditChanges( userName);
_coreTracker.AuditChanges(userName);

IEnumerable<DbEntityEntry> addedEntries = _coreTracker.GetAdditions();
// Call the original SaveChanges(), which will save both the changes made and the audit records...Note that added entry auditing is still remaining.
Expand All @@ -112,8 +125,8 @@ public override int SaveChanges()
{
return base.SaveChanges();
}
//var user = Thread.CurrentPrincipal?.Identity?.Name ?? "Anonymous";
return SaveChanges(null);

return SaveChanges(_usernameFactory?.Invoke() ?? _defaultUsername);
}

/// <summary>
Expand Down Expand Up @@ -243,7 +256,7 @@ public override async Task<int> SaveChangesAsync()
return await base.SaveChangesAsync(CancellationToken.None);
}

return await SaveChangesAsync(null, CancellationToken.None);
return await SaveChangesAsync(_usernameFactory?.Invoke() ?? _defaultUsername, CancellationToken.None);
}

/// <summary>
Expand All @@ -265,7 +278,7 @@ public override async Task<int> SaveChangesAsync(CancellationToken cancellationT
return await base.SaveChangesAsync(cancellationToken);
}

return await SaveChangesAsync(null, cancellationToken);
return await SaveChangesAsync(_usernameFactory?.Invoke() ?? _defaultUsername, cancellationToken);
}

#endregion --
Expand Down
2 changes: 1 addition & 1 deletion TrackerEnabledDbContext.IntegrationTests/App.config
Expand Up @@ -9,7 +9,7 @@
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add name="DefaultTestConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TEDB-Tests;Integrated Security=True;MultipleActiveResultSets=true"
connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=TEDB-Tests;Integrated Security=True;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<runtime>
Expand Down
Expand Up @@ -13,6 +13,7 @@ public class TestTrackerContext : TrackerContext, ITestDbContext
public TestTrackerContext()
: base(TestConnectionString)
{
Database.SetInitializer(new DropCreateDatabaseAlways<TestTrackerContext>());
}

public DbSet<NormalModel> NormalModels { get; set; }
Expand Down
Expand Up @@ -78,6 +78,7 @@
<Compile Include="TestTrackerContext.cs" />
<Compile Include="TrackerContextIntegrationTests.cs" />
<Compile Include="SoftDeleteTests.cs" />
<Compile Include="UsernameConfigurationTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TrackerEnabledDbContext.Common.Testing\TrackerEnabledDbContext.Common.Testing.csproj">
Expand Down
@@ -0,0 +1,66 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TrackerEnabledDbContext.Common.Testing;
using TrackerEnabledDbContext.Common.Testing.Extensions;
using TrackerEnabledDbContext.Common.Testing.Models;

namespace TrackerEnabledDbContext.IntegrationTests
{
[TestClass]
public class UsernameConfigurationTests : PersistanceTests<TestTrackerContext>
{
[TestMethod]
public void Can_use_username_factory()
{
Db.ConfigureUsername(() => "bilal");

NormalModel model =
GetObjectFactory<NormalModel>().Create();
Db.NormalModels.Add(model);
Db.SaveChanges();
model.Id.AssertIsNotZero();

model.AssertAuditForAddition(Db, model.Id,
"bilal",
x => x.Id,
x => x.Description
);
}

[TestMethod]
public void Can_username_factory_override_default_username()
{
Db.ConfigureUsername(() => "bilal");
Db.ConfigureUsername("rahul");

NormalModel model =
GetObjectFactory<NormalModel>().Create();
Db.NormalModels.Add(model);
Db.SaveChanges();
model.Id.AssertIsNotZero();

model.AssertAuditForAddition(Db, model.Id,
"bilal",
x => x.Id,
x => x.Description
);
}

[TestMethod]
public void Can_use_default_username()
{
Db.ConfigureUsername("rahul");

NormalModel model =
GetObjectFactory<NormalModel>().Create();
Db.NormalModels.Add(model);
Db.SaveChanges();
model.Id.AssertIsNotZero();

model.AssertAuditForAddition(Db, model.Id,
"rahul",
x => x.Id,
x => x.Description
);
}
}
}
2 changes: 1 addition & 1 deletion TrackerEnabledDbContext.sln
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.23107.0
VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleLogMaker", "SampleLogMaker\SampleLogMaker.csproj", "{3EE0FE30-1616-4EBE-9694-B4F4017C3C99}"
EndProject
Expand Down
21 changes: 17 additions & 4 deletions TrackerEnabledDbContext/TrackerContext.cs
Expand Up @@ -22,6 +22,19 @@ public class TrackerContext : DbContext, ITrackerContext
{
private readonly CoreTracker _coreTracker;

private Func<string> _usernameFactory;
private string _defaultUsername;

public void ConfigureUsername(Func<string> usernameFactory)
{
_usernameFactory = usernameFactory;
}

public void ConfigureUsername(string defaultUsername)
{
_defaultUsername = defaultUsername;
}

public TrackerContext()
{
_coreTracker = new CoreTracker(this);
Expand Down Expand Up @@ -106,8 +119,8 @@ public virtual int SaveChanges(object userName)
public override int SaveChanges()
{
if (!GlobalTrackingConfig.Enabled) return base.SaveChanges();
//var user = Thread.CurrentPrincipal?.Identity?.Name ?? "Anonymous";
return SaveChanges(null);

return SaveChanges(_usernameFactory?.Invoke() ?? _defaultUsername);
}

/// <summary>
Expand Down Expand Up @@ -225,7 +238,7 @@ public override async Task<int> SaveChangesAsync()
{
if (!GlobalTrackingConfig.Enabled) return await base.SaveChangesAsync(CancellationToken.None);

return await SaveChangesAsync(null, CancellationToken.None);
return await SaveChangesAsync(_usernameFactory?.Invoke() ?? _defaultUsername, CancellationToken.None);
}

/// <summary>
Expand All @@ -244,7 +257,7 @@ public override async Task<int> SaveChangesAsync(CancellationToken cancellationT
{
if (!GlobalTrackingConfig.Enabled) return await base.SaveChangesAsync(cancellationToken);

return await SaveChangesAsync(null, cancellationToken);
return await SaveChangesAsync(_usernameFactory?.Invoke() ?? _defaultUsername, cancellationToken);
}

#endregion
Expand Down

0 comments on commit c77ce49

Please sign in to comment.