Queuing domain events in C# - c#

This article describes a great pattern called 'Domain Events': http://www.udidahan.com/2009/06/14/domain-events-salvation/
One major flaw with this pattern however is highlighted in comment 27 by user Andy: If a transaction fails, we don't want our domain events to execute. Therefore, we need to create some sort of queuing mechanism.
Unfortunately this sounds like it is going to massively complicate a technique that was supposed to simplify the system.
Does anyone know of some good examples or discussions of queuing domain events, particular a solution that integrates well with NHibernate?

I worked out how to do this: The secret is the RegisterSynchronization method of NHibernate's ITransaction.
As an example, here is how I might send an email to a customer only when the transaction is committed:
public class NotifyCustomerEmail
{
private void MailMessage { get; set; }
public void SendAsyncOnceTransactionCommits()
{
if (MailMessage == null)
ComposeMailMessage();
NHibernateSessionManager
.CurrentSession
.Transaction
.RegisterSynchronization(new SendEmailSynchronization(this.MailMessage));
}
}

Related

How to raise domain Event When I don't want to share actual domain model

I'm trying to implement DDD in my small project but Not able to understand how to raise domain event in below case.
Account Domain
public class Account : BaseEntity
{
public string PhoneNumber { get; set; }
public int OTP { get; set; }
public Account()
{
}
public Account(string phoneNumber, short otp)
{
this.PhoneNumber = phoneNumber;
this.OTP = otp;
CreatedDate = DateTime.Now;
RowKey = Guid.NewGuid().ToString();
PartitionKey = phoneNumber;
}
}
Account Service
public async Task<bool> GenerateOTP(string phoneNumber)
{
if (phoneNumber.Length != 10)
throw new ArgumentException(ApplicationConstraint.InvalidNumber);
var otp = Convert.ToInt16(new Random().Next(1000, 9999));
var account = new Account(phoneNumber, otp);
await this.accountRepository.AddEntity(account);
return true;
}
Account Repository Azure Storage table is my database
public virtual async Task AddEntity(TEntity entity)
{
TableOperation insertOperation = TableOperation.Insert(entity);
await table.ExecuteAsync(insertOperation);
}
I want to raise domain event only when data get saved in the database. For a workaround, I'm calling messaging service from account service.
Given the limited information provided, one option would be to create an AccountCreated event, (or an EntityCreated event if this is a cross-cutting concern) and publish it through some bus where consumers can asynchronousle receive it and do any subsequent processing needed.
The event need not use domain entities, and it can contain the information/data necessary to do any subsequent processing without the need to access a shared db (and as such adhering to DDD & microservice guidelines).
----Edit----
In the above I assumed that this is an established system and Azure storage isn't something that can change. Publishing an event, and handling it is pretty simple, but there are some things you need to be aware of. In general, you have 3 options here:
Publishing right after saving isn't wrong. It's simple way to do it, and (if you adopt an event-first methodology) you can do it in a generic way across your entities, minimal work. However, you need to be concious of how to deal with errors. Specifically, the issue is that if you store the entity first, before publishing the event, and then the process crashes for whatever reason, the event may be missed, so later workflows will not kick-off. If you do the reverse (publish then store), you run the risk of double-publishing the event. In this case you have two options:
If you store-then-publish: just accept the (really rare) possiblity of not publishing an event. This is something you need to speak to the business, and you can minigate the severity by logging the event before trying to save the entity.
If you publish-then-store: (you'll need to do this if the cost of fixing any issues ad-hoc are too great) you can fix the problem by having your consumers check the id of the incoming message if they ever have processed it before and reject it if they did OR make the process idempotent (if possible), meaning that doing the process twice isn't a problem
Using event sourcing. This isn't difficult in my opinion, but obviously it's an overhead if this is a a simple application, and while not difficult, it does need a significant amount of reading up if you're not familiar with it. If this is a non-trivial application, event sourcing can help a lot, because observers can just observe the events in the buffer and respond to that (so not need to explicitly publish the changes).
Append the event in a separate table within the same transaction where you're storing the entity, and use the outbox pattern implementation (publish those events from a separate service, marking them as published once they've been published). Honestly, the pattern shown on that is a bit simplistic, and there are a lot of tricky and small complexities, so prefer to use an existing one if you can find.
Honestly, if you can get away with 1.1, do that. It's simple and problems only very rarely appear. Just log the operation before you do it so that you can manually do it in the rare case of issues.

How do I implement AOP in an Azure Mobile App Services client?

On an Azure Mobile App Services server side app using MVC 5, Web API 2.0, and EF Core 1.0, controllers can be decorated like so to implement token based authentication:
// Server-side EF Core 1.0 / Web API 2 REST API
[Authorize]
public class TodoItemController : TableController<TodoItem>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
DomainManager = new EntityDomainManager<TodoItem>(context, Request);
}
// GET tables/TodoItem
public IQueryable<TodoItem> GetAllTodoItems()
{
return Query();
}
...
}
I want to be able to do something similar on the client side where I decorate a method with something like [Authorize] from above, perhaps with a, [Secured], decoration, below:
public class TodoItem
{
string id;
string name;
bool done;
[JsonProperty(PropertyName = "id")]
public string Id
{
get { return id; }
set { id = value;}
}
[JsonProperty(PropertyName = "text")]
public string Name
{
get { return name; }
set { name = value;}
}
[JsonProperty(PropertyName = "complete")]
public bool Done
{
get { return done; }
set { done = value;}
}
[Version]
public string Version { get; set; }
}
// Client side code calling GetAllTodoItems from above
[Secured]
public async Task<ObservableCollection<TodoItem>> GetTodoItemsAsync()
{
try
{
IEnumerable<TodoItem> items = await todoTable
.Where(todoItem => !todoItem.Done)
.ToEnumerableAsync();
return new ObservableCollection<TodoItem>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
}
return null;
}
Where [Secured] might be defined something like this:
public class SecuredFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Check if user is logged in, if not, redirect to the login page.
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Check some globally accessible member to see if user is logged out.
}
}
Unfortunately, the above code only works in Controllers in MVC 1.0 applications and above according to the Microsoft article on "Creating Custom Action Filters": https://msdn.microsoft.com/en-us/library/dd381609(v=vs.100).aspx
How do I implement something like a "Custom Action Filter" that allows me to use the "[Secured]" decoration in a Mobile App Service client instead of the server? The answer will help me create custom authentication from the client side and keep the code in one location without complicating the implementation, i.e., it is a cross-cutting concern like performance metrics, custom execution plans for repeated attempts, logging, etc.
Complicating the scenario, the client also implements Xamarin.Forms for iOS and has to be a functional Ahead of Time pattern due to iOS's requirement for native code, JIT is not yet possible.
The reason attributes work in the scenarios you describe is because other code is responsible for actually invoking the methods or reading the properties, and this other code will look for the attributes and modify behaviour accordingly. When you are just running C# code, you don't normally get that; there isn't a native way to, say, execute the code in an attribute before a method is executed.
From what you are describing, it sounds like you are after Aspect Oriented Programming. See What is the best implementation for AOP in .Net? for a list of frameworks.
In essence, using an appropriate AOP framework, you can add attributes or other markers and have code executed or inserted at compile time. There are many approaches to it, hence why I am not being very specific, sorry.
You do need to understand that the AOP approach is different from how things like ASP.Net MVC works as AOP will typically modify your runtime code (in my understanding anyway and I'm sure there are variations on that as well).
As to whether AOP is really the way to go will depend on your requirements, but I would proceed with caution - it's not for the faint of heart.
One completely alternative solution to this problem is to look at something like Mediatr or similar to break your logic into a set of commands, which you can call via a message bus. The reason that helps is that you can decorate your message bus (or pipeline) with various types of logic, including authorization logic. That solution is very different from what you are asking for - but may be preferable anyway.
Or just add a single-line authorisation call as the first line inside each method instead of doing it as an attribute...
What you are more generally describing in known by a few different names/terms. The first that comes to mind is "Aspect Oriented Programming" (or AOP for short). It deals with what are known as cross cutting concerns. Im willing to bet you want to do one of two things
Log exceptions/messages in a standardized meaningful way
Record times/performance of areas of your system
And in the generala sense, yes C# is able to do such things. There will be countless online tutorials on how to do so, it is much too broad to answer in this way.
However, the authors of asp.net MVC have very much thought of these things and supply you with many attributes just as you describe, which can be extended as you please, and provide easy access to the pipeline to provide the developer with all the information they need (such as the current route, any parameters, any exception, any authorization/authentication request etc etc)
This would be a good place to start: http://www.strathweb.com/2015/06/action-filters-service-filters-type-filters-asp-net-5-mvc-6/
This also looks good: http://www.dotnetcurry.com/aspnet-mvc/976/aspnet-mvc-custom-action-filter

Is an Action-based Observer not recommended?

For those of us who are new to the great power of IObserver<T> and IObservable<T>, we need to remember that these two interfaces are part of the core of .NET (literally in mscorlib). This is totally different from the Reactive Extensions NuGet package, which can be sadly dismissed as “non-standard.” For pathetic political reasons, I am motivated to confine Rx to one Visual Studio project. This effectively forces me to think up stuff like this:
public class CommunicatorObserver : IObserver<CommunicatorResult>
{
public CommunicatorObserver(Action<CommunicatorResult> actionForObservableNext)
{
this.SetActions(actionForObservableNext, null, null);
}
public CommunicatorObserver(Action<CommunicatorResult> actionForObservableNext, Action<Exception> actionForObservableError)
{
this.SetActions(actionForObservableNext, actionForObservableError, null);
}
public CommunicatorObserver(Action<CommunicatorResult> actionForObservableNext, Action<Exception> actionForObservableError, Action actionForObservableCompleted)
{
this.SetActions(actionForObservableNext, actionForObservableError, actionForObservableCompleted);
}
public void OnCompleted()
{
if (this._actionForObservableCompleted != null) this._actionForObservableCompleted.Invoke();
}
public void OnError(Exception error)
{
if (this._actionForObservableError != null) this._actionForObservableError.Invoke(error);
}
public void OnNext(CommunicatorResult value)
{
if (this._actionForObservableNext != null) this._actionForObservableNext.Invoke(value);
}
public virtual void Subscribe(IObservable<CommunicatorResult> provider)
{
if (provider == null) return;
this._unsubscriber = provider.Subscribe(this);
}
public virtual void Unsubscribe()
{
if (this._unsubscriber != null) this._unsubscriber.Dispose();
}
void SetActions(Action<CommunicatorResult> actionForObservableNext, Action<Exception> actionForObservableError, Action actionForObservableCompleted)
{
this._actionForObservableCompleted = actionForObservableCompleted;
this._actionForObservableError = actionForObservableError;
this._actionForObservableNext = actionForObservableNext;
}
Action _actionForObservableCompleted;
Action<Exception> _actionForObservableError;
Action<CommunicatorResult> _actionForObservableNext;
IDisposable _unsubscriber;
}
My intent is to write my own, general-purpose-but-domain-specific Observer and avoid using the Rx .Subscribe() extension throughout my solution. Are there any pitfalls here? Is this the wrong way to go?
In my opinion, this is a very naive idea.
Rx is much more than just just the implementation you have there (and it appears broken already with the UnSubscribe concept you have).
Will your implementation cater for
Serialization guarantees
a Concurrency model that has been deeply thought through
a concurrency model that can be unit tested deterministicly and at great spped
Cancellation as a first class citizen for both subscriptions and concurrent/scheduled work
The piles of operators that make Rx useful beyond a primitive event model.
The man decades of in the field testing the Rx.NET has been put through
The thousands of Unit tests already in the Rx code base.
Community support when things get more complex than you have initially considered
As per James' advice. Step back and walk away. To go down the path of trying to implement IObservable and IObserver is fool hardy and will cost you in the long run. If your politics dictate that you need to do this, I would look for a new role too.
I've worked in many investment banks with draconian antiquated policies like this; Rx is open source though and even banks allowed me to pull in the source and compile it locally. Can't you even do that?
Rx addresses many non obvious issues that are only going to play out in certain scenarios, so it's hard to comment on your code; but if the source code idea doesn't fly, I can recommend you find a more reasonable employer!
Rx was developed by some very smart people at Microsoft and has been used actively in the field for several years now. You should definitely lobby harder if you can.

is there a best practice to attach email notifications to some methods without editing the methods inner code?

I am working on a website and we will need to send the user some email notifications when some actions happen on the website, such as if someone else sent the user a message or invite him to an event.
Is there a standard good way to attach a notification to any method without changing the method code?
For example I was thinking if I can put an attribute on the method this attribute will make this method to call the notification module with some parameters.
note: I am working on an ASP.Net MVC 3 website, using entity framework codefirst.
I do not believe there is a standard process.
Aspect Oriented approaches (such as attributes) can be handy only if there are used in conjunction with AOP frameworks (such as AspectSharp) or when used on the MVC Action itself: you can use action filters to achieve the requirement and send use the notification if the events are mapped to MVC actions.
Event Listeners. You do have to change the code, but you don't actually send the email within the code.
Basically, any code that does stuff that other code might be interested in has hooks so that listeners can attach to it and listen for events.
In Pseudo-java:
public class OrderProcessor {
protected final List<OrderProcessorListener> listeners = new ArrayList<OrderProcessorListener>();
public void addListener(OrderProcessorListener orderProcessorListener) {
listeners.add(orderProcessorListener);
}
public void notifyListeners(OrderProcessorEvent event) {
for(OrderProcessorListener listener : listeners) {
listener.handle(event);
}
}
public void randomMethod() {
// ... do stuff
notifyListeners(new SomeEvent(...)); // notify listeners
}
public interface OrderProcessorListener {
public void handle(OrderProcessorEvent event);
}
}
then, other interested code can do...
public class EmailSender implements OrderProcessorListener {
public void handleEvent(OrderProcessorEvent event) {
// do whatever...
}
}
When you construct your OrderProcessor and your EmailSender, you then add the EmailSender as a listener and voila. You can use this pattern everywhere you need to react to actions from a piece of code- and you don't need to put the actions in the same code...
Would be pretty hard without any change to the original code. How would you know an action succeeded? And what type of notification should be sent, to whom, etc.
If not changing the original code is a must, you could do it in a hacky way: add a global filter, inspect the controller name, action name, the action result, and maybe you could decide from those parameters if an email should be sent. But this would be extremely fragile, and a maintenance nightmare.
Unless your notifications are extremely simple, like always send e-mail to all event attendees, if any modification is done to the event. But that could cover only some of the basic use-cases...
IMO it would be better if you integrated sending notifications into your existing code. If you extend the meaning of a repository (and you use one) to "take database actions, and anything else related to creation/update/delete of an object".
No changes to controller actions, and your EventRepository.Create/Modify methods would know already have all the parameters to send the notifications...

Registering change notification with Active Directory using C#

This link http://msdn.microsoft.com/en-us/library/aa772153(VS.85).aspx says:
You can register up to five notification requests on a single LDAP connection. You must have a dedicated thread that waits for the notifications and processes them quickly. When you call the ldap_search_ext function to register a notification request, the function returns a message identifier that identifies that request. You then use the ldap_result function to wait for change notifications. When a change occurs, the server sends you an LDAP message that contains the message identifier for the notification request that generated the notification. This causes the ldap_result function to return with search results that identify the object that changed.
I cannot find a similar behavior looking through the .NET documentation. If anyone knows how to do this in C# I'd be very grateful to know. I'm looking to see when attributes change on all the users in the system so I can perform custom actions depending on what changed.
I've looked through stackoverflow and other sources with no luck.
Thanks.
I'm not sure it does what you need, but have a look at http://dunnry.com/blog/ImplementingChangeNotificationsInNET.aspx
Edit: Added text and code from the article:
There are three ways of figuring out things that have changed in Active Directory (or ADAM). These have been documented for some time over at MSDN in the aptly titled "Overview of Change Tracking Techniques". In summary: Polling for Changes using uSNChanged. This technique checks the 'highestCommittedUSN' value to start and then performs searches for 'uSNChanged' values that are higher subsequently. The 'uSNChanged' attribute is not replicated between domain controllers, so you must go back to the same domain controller each time for consistency. Essentially, you perform a search looking for the highest 'uSNChanged' value + 1 and then read in the results tracking them in any way you wish. Benefits This is the most compatible way. All languages and all versions of .NET support this way since it is a simple search. Disadvantages There is a lot here for the developer to take care of. You get the entire object back, and you must determine what has changed on the object (and if you care about that change). Dealing with deleted objects is a pain. This is a polling technique, so it is only as real-time as how often you query. This can be a good thing depending on the application. Note, intermediate values are not tracked here either. Polling for Changes Using the DirSync Control. This technique uses the ADS_SEARCHPREF_DIRSYNC option in ADSI and the LDAP_SERVER_DIRSYNC_OID control under the covers. Simply make an initial search, store the cookie, and then later search again and send the cookie. It will return only the objects that have changed. Benefits This is an easy model to follow. Both System.DirectoryServices and System.DirectoryServices.Protocols support this option. Filtering can reduce what you need to bother with. As an example, if my initial search is for all users "(objectClass=user)", I can subsequently filter on polling with "(sn=dunn)" and only get back the combination of both filters, instead of having to deal with everything from the intial filter. Windows 2003+ option removes the administrative limitation for using this option (object security). Windows 2003+ option will also give you the ability to return only the incremental values that have changed in large multi-valued attributes. This is a really nice feature. Deals well with deleted objects. Disadvantages This is .NET 2.0+ or later only option. Users of .NET 1.1 will need to use uSNChanged Tracking. Scripting languages cannot use this method. You can only scope the search to a partition. If you want to track only a particular OU or object, you must sort out those results yourself later. Using this with non-Windows 2003 mode domains comes with the restriction that you must have replication get changes permissions (default only admin) to use. This is a polling technique. It does not track intermediate values either. So, if an object you want to track changes between the searches multiple times, you will only get the last change. This can be an advantage depending on the application. Change Notifications in Active Directory. This technique registers a search on a separate thread that will receive notifications when any object changes that matches the filter. You can register up to 5 notifications per async connection. Benefits Instant notification. The other techniques require polling. Because this is a notification, you will get all changes, even the intermediate ones that would have been lost in the other two techniques. Disadvantages Relatively resource intensive. You don't want to do a whole ton of these as it could cause scalability issues with your controller. This only tells you if the object has changed, but it does not tell you what the change was. You need to figure out if the attribute you care about has changed or not. That being said, it is pretty easy to tell if the object has been deleted (easier than uSNChanged polling at least). You can only do this in unmanaged code or with System.DirectoryServices.Protocols. For the most part, I have found that DirSync has fit the bill for me in virtually every situation. I never bothered to try any of the other techniques. However, a reader asked if there was a way to do the change notifications in .NET. I figured it was possible using SDS.P, but had never tried it. Turns out, it is possible and actually not too hard to do. My first thought on writing this was to use the sample code found on MSDN (and referenced from option #3) and simply convert this to System.DirectoryServices.Protocols. This turned out to be a dead end. The way you do it in SDS.P and the way the sample code works are different enough that it is of no help. Here is the solution I came up with:
public class ChangeNotifier : IDisposable
{
LdapConnection _connection;
HashSet<IAsyncResult> _results = new HashSet<IAsyncResult>();
public ChangeNotifier(LdapConnection connection)
{
_connection = connection;
_connection.AutoBind = true;
}
public void Register(string dn, SearchScope scope)
{
SearchRequest request = new SearchRequest(
dn, //root the search here
"(objectClass=*)", //very inclusive
scope, //any scope works
null //we are interested in all attributes
);
//register our search
request.Controls.Add(new DirectoryNotificationControl());
//we will send this async and register our callback
//note how we would like to have partial results
IAsyncResult result = _connection.BeginSendRequest(
request,
TimeSpan.FromDays(1), //set timeout to a day...
PartialResultProcessing.ReturnPartialResultsAndNotifyCallback,
Notify,
request);
//store the hash for disposal later
_results.Add(result);
}
private void Notify(IAsyncResult result)
{
//since our search is long running, we don't want to use EndSendRequest
PartialResultsCollection prc = _connection.GetPartialResults(result);
foreach (SearchResultEntry entry in prc)
{
OnObjectChanged(new ObjectChangedEventArgs(entry));
}
}
private void OnObjectChanged(ObjectChangedEventArgs args)
{
if (ObjectChanged != null)
{
ObjectChanged(this, args);
}
}
public event EventHandler<ObjectChangedEventArgs> ObjectChanged;
#region IDisposable Members
public void Dispose()
{
foreach (var result in _results)
{
//end each async search
_connection.Abort(result);
}
}
#endregion
}
public class ObjectChangedEventArgs : EventArgs
{
public ObjectChangedEventArgs(SearchResultEntry entry)
{
Result = entry;
}
public SearchResultEntry Result { get; set;}
}
It is a relatively simple class that you can use to register searches. The trick is using the GetPartialResults method in the callback method to get only the change that has just occurred. I have also included the very simplified EventArgs class I am using to pass results back. Note, I am not doing anything about threading here and I don't have any error handling (this is just a sample). You can consume this class like so:
static void Main(string[] args)
{
using (LdapConnection connect = CreateConnection("localhost"))
{
using (ChangeNotifier notifier = new ChangeNotifier(connect))
{
//register some objects for notifications (limit 5)
notifier.Register("dc=dunnry,dc=net", SearchScope.OneLevel);
notifier.Register("cn=testuser1,ou=users,dc=dunnry,dc=net", SearchScope.Base);
notifier.ObjectChanged += new EventHandler<ObjectChangedEventArgs>(notifier_ObjectChanged);
Console.WriteLine("Waiting for changes...");
Console.WriteLine();
Console.ReadLine();
}
}
}
static void notifier_ObjectChanged(object sender, ObjectChangedEventArgs e)
{
Console.WriteLine(e.Result.DistinguishedName);
foreach (string attrib in e.Result.Attributes.AttributeNames)
{
foreach (var item in e.Result.Attributes[attrib].GetValues(typeof(string)))
{
Console.WriteLine("\t{0}: {1}", attrib, item);
}
}
Console.WriteLine();
Console.WriteLine("====================");
Console.WriteLine();
}

Categories

Resources