How can I make Cirqus stop automatically creating new instances? - cqrs

I have an aggregate root with a few events and commands. One of those commands is a CreateCommand. That command should create a new aggregate root with a given ID. Every other event/command should just update an existing aggregate root and fail if the aggregate root with the given ID doesn't exist.
How can I make Cirqus work this way?
This is how I configure my CommandProcessor:
var commandProcessor = CommandProcessor
.With()
#if DEBUG
.Logging(l =>
{
if (_useConsoleForLogging)
{
l.UseConsole(Logger.Level.Debug);
}
else
{
l.UseDebug(Logger.Level.Debug);
}
})
#endif
.EventStore(e => e.UseSqlServer(_connectionString, _eventsTableName))
.EventDispatcher(e => e.UseViewManagerEventDispatcher(viewManagers))
.Create();
This is the CreateCommand:
public class CreateCommand : ExecutableCommand
{
public CreateCommand()
{
CreatedGuid = Guid.NewGuid();
}
public Guid CreatedGuid { get; }
public override void Execute(ICommandContext context)
{
var root = context.Create<MyAggregateRoot>(CreatedGuid.ToString());
}
}
Of course this CreateCommand contains more code that emits a few events to immediately update some properties of the created instance, but I've removed them as they're not vital to this question.

You can do that by using ExecutableCommand to implement your own update command - you could call it UpdateCommand.
It could look something like this:
public abstract class UpdateCommand<TAggregateRoot>
{
readonly string _aggregateRootId;
protected UpdateCommand(string aggregateRootId)
{
_aggregateRootId = aggregateRootId;
}
public override void Execute(ICommandContext context)
{
var instance = context.Load<TAggregateRoot>(_aggregateRootId);
Update(instance);
}
public abstract void Update(TAggregateRoot instance);
}
and then all commands derived off of UpdateCommand would experience exceptions if they tried to address non-existing instances.
Similarly, you could ensure creation with a CreateCommand base class that would use ICommandContext's Create<TAggregateRoot> method to ensure that an existing instance was not accidentally being addressed.

Related

Roslyn codefix and fixall action not executed properly under unit test

I've 'successfully' written a CodeFix and FixAllProvider, BUT...
The diagnostic I'm trying to handle can occur multiple times in the same document on the same line. However, the behavior under unit test (CSharpCodeFixTest) stumps me.
If a test generates only one instance of the diagnostic, CSharpCodeFix<> calls the CodeFix initially then calls the FixAllProvider multiple times during Verification. The test succeeds.
If a test generates more than one diagnostic, CSharpCodeFix<> calls the CodeFix once. CSharpCodeFix<> never calls the FixAllProvider, and since the CodeFix cannot fix all instances. the test fails the before/after document comparison.
Note that in these samples, namespaces (not shown) disambiguate the classes from their bases. I've removed the fix implementations because I believe them irrelevant to the problem.
First the CodeFix
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CodeFixProvider)), Shared]
public class CodeFixProvider : Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(EGNT0003NoInlineInstantiationAnalyzer.DiagnosticId); }
}
public sealed override Microsoft.CodeAnalysis.CodeFixes.FixAllProvider GetFixAllProvider()
{
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider provider = FixAllProvider.Instance;
return provider;
}
public static readonly string EquivalenceKey = "EG0003CodeFixProvider";
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (Diagnostic diagnostic in context.Diagnostics.Where(d => FixableDiagnosticIds.Contains(d.Id)))
{
context.RegisterCodeFix(CodeAction.Create(title: "Introduce local variable",
token => GetTransformedDocumentAsync(context.Document, diagnostic, token),
equivalenceKey: EquivalenceKey), diagnostic);
}
return Task.CompletedTask;
}
;
Here is the FixAllProvider
public sealed class FixAllProvider : Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
{
private FixAllProvider()
{
}
private static readonly Lazy<FixAllProvider> lazy = new Lazy<FixAllProvider>(() => new FixAllProvider());
public static FixAllProvider Instance
{
get
{
return lazy.Value;
}
}
public override IEnumerable<string> GetSupportedFixAllDiagnosticIds(Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider originalCodeFixProvider)
{
string[] diagnosticIds = new[]
{
EGNT0003NoInlineInstantiationAnalyzer.DiagnosticId,
};
return diagnosticIds;
}
public override async Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
{
:
Finally here is the CodeAction invoked by the FixAllProvider.
public class FixAllCodeAction : CodeAction
{
private readonly List<KeyValuePair<Document, ImmutableArray<Diagnostic>>> _diagnosticsToFix;
private readonly Solution _solution;
public FixAllCodeAction(string title, Solution solution, List<KeyValuePair<Document, ImmutableArray<Diagnostic>>> diagnosticsToFix)
{
this.Title = title;
_solution = solution;
_diagnosticsToFix = diagnosticsToFix;
}
public override string Title { get; }
public override string EquivalenceKey => "EG0003CodeFixProvider";
protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
Solution newSolution = _solution;
:
I've debugged through CSharpCodeFixTest<> and continue to do so. I'm hoping someone has seen this issue before and can see my mistake.
I expected to see the code fix tests to complete successfully. I verified through other means that the documents produced by the CodeFix and the FixAllProvider are valid and correct.

Entity Framework Core 1.1 In Memory Database fails adding new entities

I am using the following code in a unit test for the test setup:
var simpleEntity = new SimpleEntity();
var complexEntity = new ComplexEntity
{
JoinEntity1List = new List<JoinEntity1>
{
new JoinEntity1
{
JoinEntity2List = new List<JoinEntity2>
{
new JoinEntity2
{
SimpleEntity = simpleEntity
}
}
}
}
};
var anotherEntity = new AnotherEntity
{
ComplexEntity = complexEntity1
};
using (var context = databaseFixture.GetContext())
{
context.Add(anotherEntity);
await context.SaveChangesAsync();
}
When SaveChangesAsync is reached EF throws an ArgumentException with the following message:
An item with the same key has already been added. Key: 1
I'm using a fixture as well for the unit test class which populates the database with objects of the same types, though for this test I want this particular setup so I want to add these new entities to the in memory database. I've tried adding the entities on the DbSet (not the DbContext) and adding all three entities separatly to no avail. I can however add "simpleEntity" separately (because it is not added in the fixture) but EF complains as soon as I try to add "complexEntity" or "anotherEntity".
It seems like EF in memory database cannot handle several Add's over different instances of the context. Is there any workaround for this or am I doing something wrong in my setup?
The databaseFixture in this case is an instance of this class:
namespace Test.Shared.Fixture
{
using Data.Access;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
public class InMemoryDatabaseFixture : IDatabaseFixture
{
private readonly DbContextOptions<MyContext> contextOptions;
public InMemoryDatabaseFixture()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
var builder = new DbContextOptionsBuilder<MyContext>();
builder.UseInMemoryDatabase()
.UseInternalServiceProvider(serviceProvider);
contextOptions = builder.Options;
}
public MyContext GetContext()
{
return new MyContext(contextOptions);
}
}
}
You can solve this problem by using Collection Fixtures so you can share this fixture across several test classes. This way you don't build you context several times and thus you won't get this exception:
Some information about collection Fixture
My own example:
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{ }
[Collection("Database collection")]
public class GetCitiesCmdHandlerTests : IClassFixture<MapperFixture>
{
private readonly TecCoreDbContext _context;
private readonly IMapper _mapper;
public GetCitiesCmdHandlerTests(DatabaseFixture dbFixture, MapperFixture mapFixture)
{
_context = dbFixture.Context;
_mapper = mapFixture.Mapper;
}
[Theory]
[MemberData(nameof(HandleTestData))]
public async void Handle_ShouldReturnCountries_AccordingToRequest(
GetCitiesCommand command,
int expectedCount)
{
(...)
}
public static readonly IEnumerable<object[]> HandleTestData
= new List<object[]>
{
(...)
};
}
}
Good luck,
Seb

Autofac LifetimeScope with BeginLifetimeScope not working

I am trying to evaluate the scoping of Autofac and as I understand it, when an instance has been declared as InstancePerLifetimeScope, then within the using(container.BeginLifetimeScope()) block, we should get the same instance. But in another such block, we should get a different instance. But my code (in linqpad) gives me the same instance. Windsor's lifestylescope however works as I think it should.
Code:
static IContainer glkernel;
void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<Controller>();
builder.RegisterType<A>().As<IInterface>().InstancePerLifetimeScope();
glkernel = builder.Build();
using (glkernel.BeginLifetimeScope()){
Controller c1 = glkernel.Resolve<Controller>();
c1.GetA();//should get instance 1
c1.GetA();//should get instance 1
}
using (glkernel.BeginLifetimeScope()){
Controller d = glkernel.Resolve<Controller>();
d.GetA();//should get instance 2
d.GetA();//should get instance 2
}
}
public interface IInterface
{
void DoWork(string s);
}
public class A : IInterface
{
public A()
{
ID = "AAA-"+Guid.NewGuid().ToString().Substring(1,4);
}
public string ID { get; set; }
public string Name { get; set; }
public void DoWork(string s)
{
Display(ID,"working...."+s);
}
}
public static void Display(string id, string mesg)
{
mesg.Dump(id);
}
public class Controller
{
public Controller()
{
("controller ins").Dump();
}
public void GetA()
{
//IInterface a = _kernel.Resolve<IInterface>();
foreach(IInterface a in glkernel.Resolve<IEnumerable<IInterface>>())
{
a.DoWork("from A");
}
}
}
The output is:
controller ins
AAA-04a0
working....from A
AAA-04a0
working....from A
controller ins
AAA-04a0
working....from A
AAA-04a0
working....from A
Perhaps my understanding of scoping is wrong. If so, can you please explain.
What do I have to do to get a different instance in the second block?
The problem is you're resolving things out of the container - the glkernel instead of out of the lifetime scope. A container is a lifetime scope - the root lifetime scope.
Resolve out of the lifetime scope instead. That may mean you need to change up your controller to pass in the list of components rather than using service location.
public class Controller
{
private IEnumerable<IInterface> _interfaces;
public Controller(IEnumerable<IInterface> interfaces)
{
this._interfaces = interfaces;
("controller ins").Dump();
}
public void GetA()
{
foreach(IInterface a in this._interfaces)
{
a.DoWork("from A");
}
}
}
Then it's easy enough to switch your resolution code.
using (var scope1 = glkernel.BeginLifetimeScope()){
Controller c1 = scope1.Resolve<Controller>();
c1.GetA();
c1.GetA();
}
using (var scope2 = glkernel.BeginLifetimeScope()){
Controller c2 = scope2.Resolve<Controller>();
c2.GetA();
c2.GetA();
}
The Autofac wiki has some good information on lifetime scopes you might want to check out.

passing value from activity to another in WF

I'm working with WF.
I made a custom activity called Draft_Doc:
public sealed class Draft_Doc : CodeActivity<string>
{
protected override string Execute(CodeActivityContext context)
{
C.Send_Task_Msg(unique_name, "Draft");
return "Draft";
}
}
I made another activity that contains a bookmark.
public sealed class WaitingTheApproval : NativeActivity
{
WorkflowInstanceProxy instance;
Service1Client C = new Service1Client();
public InArgument<string> previous_stage { get; set; }
public string stageName;
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
base.CacheMetadata(metadata);
metadata.AddDefaultExtensionProvider<MyExtension>(() => new MyExtension());
//RuntimeArgument argSql = new RuntimeArgument("SqlConnectionString", typeof(String), ArgumentDirection.In);
}
protected override bool CanInduceIdle
{
get { return true; }
}
protected override void Execute(NativeActivityContext context)
{
var bookmark = context.CreateBookmark("MyBookmark", BookmarkResumed);
var extension = context.GetExtension<MyExtension>();
instance = extension._instance;
stageName = context.GetValue(this.previous_stage);
stageName = previous_stage.Get(context);
WaitSome(bookmark);
}
}
What I want is, when I drag and drop these two activities in rehosted workflow. I want to drag Draft_Doc first then I will link the WaitingTheApproval with it.
So, I want the return value from Draft_Doc set in the InArgument previous_stage in WaitingTheApproval at runtime.
Anyhelp?
There is no way to pass a value from one activity to another directly. you should assign the value to a Variable in the first activity and use the variable which has been assigned in the second activity.

DataAnnotations and FluentValidation not working in MVC 2 project

I have edited the original question since the same error is occurring the difference being the implementation, I have now added Ninject to the mix.
I have created a class for the validation rules
public class AlbumValidator : AbstractValidator<Album> {
public AlbumValidator() {
RuleFor(a => a.Title).NotEmpty();
}
}
I have created a ValidatorModule for Ninject
internal class FluentValidatorModule : NinjectModule {
public override void Load() {
AssemblyScanner.FindValidatorsInAssemblyContaining<AlbumValidator>()
.ForEach(result => Bind(result.InterfaceType).To(result.ValidatorType).InSingletonScope());
}
}
Here is my ValidatorFactory
public class NinjectValidatorFactory : ValidatorFactoryBase {
public override IValidator CreateInstance(Type validatorType) {
if (validatorType.GetGenericArguments()[0].Namespace.Contains("DynamicProxies")) {
validatorType = Type.GetType(string.Format("{0}.{1}[[{2}]], {3}",
validatorType.Namespace,
validatorType.Name,
validatorType.GetGenericArguments()[0].BaseType.AssemblyQualifiedName,
validatorType.Assembly.FullName));
}
return Container.Get(validatorType) as IValidator;
}
IKernel Container { get; set; }
public NinjectValidatorFactory(IKernel container) {
Container = container;
}
}
and the relevant parts from my Global
protected override void OnApplicationStarted() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
var factory = new NinjectValidatorFactory(Container);
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(factory));
DataAnnotationsModelValidatorProvider
.AddImplicitRequiredAttributeForValueTypes = false;
}
protected override IKernel CreateKernel() {
return Container;
}
IKernel Container {
get { return new StandardKernel(new FluentValidatorModule()); }
}
I load the sample site click on the create new album link and then click the create button leaving the title empty I am then greeted with the error protected override void OnApplicationStarted() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
var factory = new NinjectValidatorFactory(Container);
ModelValidatorProviders.Providers.Add(
new FluentValidationModelValidatorProvider(factory));
DataAnnotationsModelValidatorProvider
.AddImplicitRequiredAttributeForValueTypes = false;
}
protected override IKernel CreateKernel() {
return Container;
}
IKernel Container {
get { return new StandardKernel(
new Bootstrapper(),
new FluentValidatorModule()); }
}
I load up the create form and click create leaving the title empty low and behold an error
This property cannot be set to a null value.
The line it references is within the Entity Framework auto generated class, I traced the
Namespace.Contains("DynamicProxies")
and it was returning false, is this because I told EF to use a custom namespace SampleMusicStore.Web?
Or am I missing something else?
Cheers.
The problem is that Entity Framework is generating dynamic proxies on your classes, and then your system is trying to validate against the proxy classes instead of the classes you defined.
The way to resolve this is the same as this answer.