I have the below aggregate which contains an aggregate member.
#Aggregate
public class CpaAggregate {
#AggregateIdentifier
private String externalId;
#AggregateMember
private Entity entity;
public CpaAggregate() {
}
#CommandHandler
public CpaAggregate(CreateCpaCommand cmd) {
AggregateLifecycle.apply(new CpaCreatedEvent(...));
}
#EventSourcingHandler
protected void on(CpaCreatedEvent evt) {
....
}
}
public class Entity {
#EntityId
private String entityId;
private Set<Identifier> identifiers = new HashSet<>();
public Entity() {
}
#EventSourcingHandler
public void on(IdentifiantUpdatedEvent evt) {
...
}
}
public class Laboratory extends Entity {
private OperatingSystem operatingSystem;
public Laboratory() {
}
#CommandHandler
public void handle(UpdateIdentifierLABCommand cmd) {
AggregateLifecycle.apply(new IdentifiantUpdatedEvent(....));
}
}
.
commandGateway.sendAndWait(new UpdateIdentifierLABCommand(...));
When i send a command to update an identifier of entity of type laboratory, i get this error
org.axonframework.commandhandling.NoHandlerForCommandException: No
handler was subscribed to command [UpdateIdentifierLABCommand]
I would model your CpaAggregate slightly differently, Aymen.
Instead of using the generic Entity aggregate member, I'd go for more specific entities like the Laboratory instance.
This is, for one, a lot more clear modeling-wise, as the model structure becomes clearer. Secondly, Axon Framework will move up into parent class for specifics. So, you can still have common information in an Entity class, like entity identifiers, command handlers, and event sourcing handlers.
I would thus adjust it like so:
#Aggregate
public class CpaAggregate {
#AggregateIdentifier
private String externalId;
#AggregateMember
private Laboratory laboratory;
public CpaAggregate() {
}
#CommandHandler
public CpaAggregate(CreateCpaCommand cmd) {
AggregateLifecycle.apply(new CpaCreatedEvent(...));
}
#EventSourcingHandler
protected void on(CpaCreatedEvent evt) {
....
}
}
This should ensure Axon Framework spots the command handler inside the aggregate member too, by the way.
Related
I have kafka topic that contains multiple events (of different types), and I'd like to handle those events in different handler classes within single application. So my question is - can I create two classes(spring components) that consumes same topic, but each of them handles different events (from that same topic)?
#Component
#KafkaListener(topics = "topicA")
public class SomeClass {
#KafkaHandler
public void handleEventA(EventA eventA) {
}
}
#Component
#KafkaListener(topics = "topicA")
public class AnotherClass {
#KafkaHandler
public void handleEventB(EventB eventB) {
}
#KafkaHandler
public void handleEventC(EventC eventC) {
}
}
Normally you would have all the #KafkaHandlers in the same class.
You can do what you want, but each listener needs to be in a different consumer group and you need a default method to discard the events you are not interested in.
#Component
#KafkaListener(id = "some", topics = "topicA")
public class SomeClass {
#KafkaHandler
public void handleEventA(EventA eventA) {
}
#KafkaHandler(isDefault = true)
public void handleOthers(Object others) {
// discard
}
}
#Component
#KafkaListener(id = "another", topics = "topicA")
public class AnotherClass {
#KafkaHandler
public void handleEventB(EventB eventB) {
}
#KafkaHandler
public void handleEventC(EventC eventC) {
}
#KafkaHandler(isDefault = true)
public void handleOthers(Object others) {
// discard
}
}
Just share a finding after we tried this approach, the logic of listener container is executed per #KafkaListener class. i.e. the associated logic of FilterStrategy and MessageConverter will be run multiple times for the same event, which is probably not what we want.
I am trying to implement the Observer pattern in a JavaFx application. I've never asked a question here but this is driving me a bit crazy.
Essentially I'm trying to use the Observer pattern to monitor a class that's parsing a file of phone numbers, and update the UI automatically as the file is parsed.
Before I get to my questions, here is my code:
Abstract class Observer.java
public abstract class Observer
{
public PhoneBook numbers;
public abstract void update();
}
I have a class that implements this:
public class PhoneBookObserver extends Observer {
public PhoneBookObserver(PhoneBook numbers)
{
this.numbers = numbers;
this.numbers.attach(this);
}
#Override
public void update()
{
System.out.println(""NUMBER - : " + numbers.GetNumbers());
}
}
In the class doing the parsing, I've created a new PhoneBookObserver
public PhoneBook ParsePhoneBook()
{
PhoneBook nums= new PhoneBook();
PhoneBookObserver p = new PhoneBookObserver(nums);
// ... Parsing of file - works fine
return nums;
}
Currently this runs and my println from update() in PhoneBookObserver is output.
My questions are:
Can the update method of PhoneBookObserver update my UI for me? How would it access JavaFx elements in my controller?
Can I just make my controller an observer, override update() and use that to update my UI elements from within my controller? Is that bad?
To directly answer your question, I would probably implement the Observer as an inner class in the controller. Then it has access to everything in the controller.
Assuming here PhoneBook defines a method of the form
public List<PhoneNumber> getPhoneNumbers() ;
then you could do:
public class Controller {
#FXML
private ListView<PhoneNumber> phoneNumberList ;
private PhoneBook numbers = new PhoneBook() ; // or initialize from elsewhere
public void initialize() {
numbers.attach(new PhoneBookObserver(numbers));
// ...
}
private class PhoneBookObserver extends Observer {
PhoneBookObserver(PhoneBook numbers) {
this.numbers = numbers ;
}
#Override
public void update() {
phoneNumberList.getItems().setAll(numbers.getPhoneNumbers());
}
}
}
Note that in
public abstract class Observer
{
public PhoneBook numbers;
public abstract void update();
}
the field numbers really serves no purpose, as the only method doesn't use it. So you could remove it (subclasses can define such a field if they need). Then you may as well make it an interface, and since it only has one method, it's a #FunctionalInterface:
#FunctionalInterface
public interface Observer {
public void update() ;
}
and now it can be implemented with a lambda expression, so the implementation is so thin that you basically stop having any issues with "accessing the UI":
public class Controller {
#FXML
private ListView<PhoneNumber> phoneNumberList ;
private PhoneBook numbers = new PhoneBook() ; // or initialize from elsewhere
public void initialize() {
numbers.attach(() -> phoneNumberList.getItems().setAll(numbers.getPhoneNumbers());
// ...
}
}
Finally, note that JavaFX Properties and observable lists basically already provide an implementation of the observer pattern, so you're pretty much reinventing the wheel here. You could just have
public class PhoneBook {
private final ObservableList<PhoneNumber> numbers;
public ObservableList<PhoneNumber> getPhoneNumbers() {
return numbers ;
}
}
and then
public class Controller {
#FXML
private ListView<PhoneNumber> phoneNumberList ;
private PhoneBook numbers = new PhoneBook() ; // or initialize from elsewhere
public void initialize() {
phoneNumberList.setItems(numbers.getPhoneNumbers());
}
}
and the list view will observe the (already-observable) list of numbers for you. There is no real need for your Observer or PhoneBookObserver.
Suppose I have two ViewModels and a Screen Conductor in my application.
public class ShellViewModel : Conductor<IScreen>, IShell
{
public ShellViewModel()
{
ShowConnectionScreen();
}
public void ShowConnectionScreen()
{
ActivateItem(new ConnectionViewModel());
}
public void ShowSetupScreen()
{
ActivateItem(new SetupViewModel());
}
}
The first ViewModel is displayed on start up, and contains some setup information and a Connect button which initializes a connect to somewhere.
If the connection is established successfully, then I would like the first ViewModel to close and the second ViewModel to display some information about the connection. If it fails, the first ViewModel should simply display that, and allow the user to attempt connection once again.
Thus I need the actual connection object to be passed from the first ViewModel to the second ViewModel and the Screen Conductor to change viewmodels on success.
How can this be achieved in Caliburn.Micro?
To illustrate #mvermef's comment:
use a common type between the 3 class objects, obviously create this type in question
This would be the connection object that the first view model populates and is used by the second view model.
public class Connection {
// props, methods, etc...
}
and pass it either in constructor or make it a property of all 3 classes
public class ShellViewModel : Conductor<IScreen>, IShell
{
public Connection Connection { get; set; }
public ShellViewModel()
{
Connection = new Connection();
ShowConnectionScreen();
}
public void ShowConnectionScreen()
{
ActivateItem(new ConnectionViewModel(Connection));
}
public void ShowSetupScreen()
{
ActivateItem(new SetupViewModel(Connection));
}
}
Do what you want with the Connection object inside ConnectionViewModel
public class ConnectionViewModel : Screen
{
public Connection Connection { get; set; }
// establish connection
// can call (Parent as IConductor).DeactivateItem(this)
// after connection is established
}
You can notify the parent conductor if a connection is established by (1) registering through ConnectionViewModel's Deactivated event (assuming you subclass Screen). Or (2) you can use EventAggregator to fire an event if the connection is established and having ShellViewModel implement IHandle. You can then call ShowSetupScreen() inside the Deactivated event handler or the Handle method.
Option 1:
// ShellViewModel
public void ShowConnectionScreen()
{
var connectionVM = new ConnectionViewModel();
connectionVM.Deactivated += ConnectionViewModel_Deactivated;
ActivateItem();
}
private void Scheduler_Deactivated1(object sender, DeactivationEventArgs e)
{
ShowSetupScreen();
}
Option 2:
public class ShellViewModel : Conductor<IScreen>,
IShell, IHandle<string>
{
private readonly IEventAggregator _eventAggregator;
public ShellViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}
// from IHandle<string>. you can create a custom object to represent this event
public void Handle(string message)
{
if (message.Equals("connection.successful"))
{
ShowSetupScreen();
}
}
}
public class ConnectionViewModel : Screen
{
private readonly IEventAggregator _eventAggregator;
public ConnectionViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
// call _eventAggregator.PublishOnUIThread("connection.successful");
}
I am going though the Apress ASP.NET MVC 3 book and trying to ensure I create Unit Tests for everything possible but after spending a good part of a day trying to work out why edit's wouldn't save (see this SO question) I wanted to create a unit test for this.
I have worked out that I need to create a unit test for the following class:
public class EFProductRepository : IProductRepository {
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products {
get { return context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
context.Products.Add(product);
}
context.SaveChanges();
}
public void DeleteProduct(Product product) {
context.Products.Remove(product);
context.SaveChanges();
}
}
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
I am using Ninject.MVC3 and Moq and have created several unit tests before (while working though the previously mentioned book) so am slowly getting my head around it. I have already (hopefully correctly) created a constructor method to enable me to pass in _context:
public class EFProductRepository : IProductRepository {
private EFDbContext _context;
// constructor
public EFProductRepository(EFDbContext context) {
_context = context;
}
public IQueryable<Product> Products {
get { return _context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
_context.Products.Add(product);
} else {
_context.Entry(product).State = EntityState.Modified;
}
_context.SaveChanges();
}
public void DeleteProduct(Product product) {
_context.Products.Remove(product);
_context.SaveChanges();
}
}
BUT this is where I start to have trouble... I believe I need to create an Interface for EFDbContext (see below) so I can replace it with a mock repo for the tests BUT it is built on the class DbContext:
public class EFDbContext : DbContext {
public DbSet<Product> Products { get; set; }
}
from System.Data.Entity and I can't for the life of me work out how to create an interface for it... If I create the following interface I get errors due to lack of the method .SaveChanges() which is from the DbContext class and I can't build the interface using "DbContext" like the `EFDbContext is as it's a class not an interface...
using System;
using System.Data.Entity;
using SportsStore.Domain.Entities;
namespace SportsStore.Domain.Concrete {
interface IEFDbContext {
DbSet<Product> Products { get; set; }
}
}
The original Source can be got from the "Source Code/Downloads" on this page encase I have missed something in the above code fragments (or just ask and I will add it).
I have hit the limit of what I understand and no mater what I search for or read I can't seem to work out how I get past this. Please help!
The problem here is that you have not abstracted enough. The point of abstractions/interfaces is to define a contract that exposes behavior in a technology-agnostic way.
In other words, it is a good first step that you created an interface for the EFDbContext, but that interface is still tied to the concrete implementation - DbSet (DbSet).
The quick fix for this is to expose this property as IDbSet instead of DbSet. Ideally you expose something even more abstract like IQueryable (though this doesn't give you the Add() methods, etc.). The more abstract, the easier it is to mock.
Then, you're left with fulfilling the rest of the "contract" that you rely on - namely the SaveChanges() method.
Your updated code would look like this:
public class EFProductRepository : IProductRepository {
private IEFDbContext context;
public EFProductRepository(IEFDbContext context) {
this.context = context;
}
...
}
public interface IEFDbContext {
IDbSet<Product> Products { get; set; }
void SaveChanges();
}
BUT... the main question you have to ask is: what are you trying to test (conversely, what are you trying to mock out/avoid testing)? In other words: are you trying to validate how your application works when something is saved, or are you testing the actual saving.
If you're just testing how your application works and don't care about actually saving to the database, I'd consider mocking at a higher level - the IProductRepository. Then you're not hitting the database at all.
If you want to make sure that your objects actually get persisted to the database, then you should be hitting the DbContext and don't want to mock that part after all.
Personally, I consider both of those scenarios to be different - and equally important - and I write separate tests for each of them: one to test that my application does what it's supposed to do, and another to test that the database interaction works.
I guess your current code looks something like this (I put in the interface):
public class EFProductRepository : IProductRepository {
private IEFDbContext _context;
// constructor
public EFProductRepository(IEFDbContext context) {
_context = context;
}
public IQueryable<Product> Products {
get { return _context.Products; }
}
public void SaveProduct(Product product) {
if (product.ProductID == 0) {
_context.Products.Add(product);
} else {
_context.Entry(product).State = EntityState.Modified;
}
**_context.SaveChanges();**
}
public void DeleteProduct(Product product) {
_context.Products.Remove(product);
**_context.SaveChanges();**
}
}
public class EFDbContext : DbContext, IEFDbContext {
public DbSet<Product> Products { get; set; }
}
public interface IEFDbContext {
DbSet<Product> Products { get; set; }
}
The problem is EFProductRepository now expects an object implementing the IEFDbContext interface, but this interface does not define the SaveChanges method used at the lines I put between the asteriskes so the compiler starts complaining.
Defining the SaveChanges method on the IEFDbContext interface solves your problem:
public interface IEFDbContext {
DbSet<Product> Products { get; set; }
void SaveChanges();
}
I am using unity, entity framework 4 with POCO classes, repository pattern for DAL and services for Business Logic control.
I also want to use Unit of Work so I can package together CRUD operations which I perform on different services and then commit them all together.
My question is what would be the proper way to inject the Unit Of Work mechanism into my application using Microsoft Unity?
I understand that I can put the IUnitOfWork together with the repository on the constructor of the proper service and then if Unity mapping is specified it would auto initiate the proper instances, but this way I do not pass the global unit of work but rather create a new instance on each level, which can't be a smart way to do it (actually the repository is initiated even before the service).
What am I missing? (Attached is constructor code as I wrote it now of service and its repository).
U also understand that I can use Unity's ParameterOverrides method to take some global instance of Unit of Work (lets say from my aspx.cs file) and pass it into the service and then into the repository. But it seems a bit lame. Is this my only option?
Thanks
public class GenericRepository<T> : IUnitOfWorkRepository, IGenericRepository<T> where T : BaseEntity, IAggregateRoot
{
private IUnitOfWork _uow;
/// <summary>
/// Returns the active object context
/// </summary>
private ObjectContext ObjectContext
{
get
{
return ObjectContextManager.GetObjectContext();
}
}
public GenericRepository(IUnitOfWork uow)
{
_uow = uow;
}
//blahhhh...
public void Add(T entity)
{
_uow.RegisterNew(entity, this);
}
public void Delete(T entity)
{
_uow.RegisterRemoved(entity, this);
}
//.....blah blah....
public void PersistCreationOf(IAggregateRoot entity)
{
this.ObjectContext.AddObject(GetEntitySetName(), entity);
}
public void PersistUpdateOf(IAggregateRoot entity)
{
// Do nothing as EF tracks changes
}
public void PersistDeletionOf(IAggregateRoot entity)
{
this.ObjectContext.DeleteObject(entity);
}
}
public class CategoryRepository : GenericRepository<XComSolutions.FB.Domain.Model.Entities.Category>, ICategoryRepository
{
public CategoryRepository(IUnitOfWork uow)
: base(uow)
{ }
}
public class CategoryService : ICategoryService
{
public int myID {get; set;}
private ICategoryRepository _categoryRepository;
private IUnitOfWork _uow;
public CategoryService(ICategoryRepository categoryRepository,
IUnitOfWork uow)
{
_categoryRepository = categoryRepository;
_uow = uow;
}
public List<Category> GetAll()
{
return _categoryRepository.GetAll();
}
}
Define an IUnitOfWorkFactory and inject that in your services:
public class Service
{
private readonly IUnitOfWorkFactory factory;
public Service(IUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void DoOperation()
{
using (UnitOfWork context = this.factory.CreateNew())
{
this.DoSomeStuff(context);
this.DoMoreStuff(context);
context.SubmitChanges();
}
}
}
What I think you need to do is to define unit of work factory. You register this factory with your DI container and you resolve for this factory every time you need your unit of work. Then you get unit of work from the factory, work with it and let it go. You often will see that you need your unit of work within a scope of single method or single class. This article discuss Unit of Work pattern in connection with Entity Framework: http://msdn.microsoft.com/en-us/magazine/dd882510.aspx