Using SignalR with CQRS and Event Sourcing - c#

I am using CQRS with EventSourcing.
I have to use SignalR for updating grid when particular event raised in all opened browsers.
So, I have to push data to all clients once Particular event raised.
Currently when user manually refresh page the query is fired which is pulling the data, but I have to pull data without manual refresh using SignalR.
I am new to SignalR, Can I get any sample code/reference for implementing the same?

You could read this article about this topic.
There is also a public repository with some "basic experimentations" with CQRS+ES and SignalR.
Hope this helps

First, you must create a Hub class so clients can connect to.
Then, in your event handler you do:
var hubContext = GlobalHost.ConnectionManager.GetHubContext<YourHub>();
hubContext.Clients.All.callJavaScriptFunction(parameters);
This way, when the event handler gets executed, SignalR will call the client methods you want with the data you provide.
You must also create the proper connection from the client and define callJavaScriptFunction.
Note: If you are using dependency injection, you might see very unstable behavior from GlobalHost. Let me know if it is the case.
Hope this helps!
Best of luck!

Related

How to get an existing webhook (parse from json) from Calendly?

I am new to StackOverflow, struggling to find a solution to my problem: I am trying to synchornize my asp.net app with the calendly api.
So far, I have managed to create a webhook subscription and I saw that the webhooks are being registered to https://calendly.com/api/v1/hooks/ and I was able to acces a specific webhook using its id (I used Postman to see all this, as I am currently local developing). I am having a lot of trouble since I am not able to understand what call should I make in order to get the webhooks and be able to use their data in my app.
https://developer.calendly.com/docs/sample-webhook-data
This is what I should be parsing, according to Calendly documentation.
I want to get data such as the emails of those participing into the event, also the date and status of the event. How can I do this?
From your question, it seems to me there might be a lack of conceptual understanding of what webhooks are.
As you mention, you had already subscribed to be notified if some event happens in Calendly (I assume invitee.created event).
This means, that
when this event actually happens on Calendly (you may need to make a test scheduling request in the Calendly UI), the notification about this event is sent to the URL you had registered (subscribed).
This registered URL has to be reachable for the notification call. In other words, if the URL is in your local environment (and you mentioned it is so), it's impossible for the notification to reach the registered (subscribed) destination. So this might be the issue you're experiencing.
You need to read incoming raw data. In my script, with PHP, I do it using file_get_contents('php://input')
You need to parse the data. With PHP I use json_decode($inputData). In your language you've got to use whatever tools you have for JSON parsing.
Basically, that's it. In my case, I read invitee email using $parsedData->payload->invitee->email.
Hope it helps.

In NServiceBus 6, can an endpoint subscribe to an event without knowing the publishing endpoint?

I have updated to NServiceBus 6, where the IProvideConfiguration<UnicastBusConfig> and its MessageEndpointMappings are obsolete.
I have followed the publish/subscribe instructions in the documentation. As I understand it, it is now required to explicitly name the publishing endpoints when subscribing to an event.
Before, I could specific the event interface, the endpoint would be the name of the subscriber:
config.MessageEndpointMappings.Add(
new MessageEndpointMapping
{
AssemblyName = MyAssemblyName,
TypeFullName = typeof( IMyEvent ) ),
Endpoint = "SubscribingEndpoint"
} );
Now:
this goes away and I have the following. This entirely replaces the need for an IProvideConfiguration class:
var routing = endpointConfiguration.UseTransport<MsmqTransport>().Routing();
endpointConfiguration.SendFailedMessagesTo( "error" );
endpointConfiguration.AuditProcessedMessagesTo( "audit" );
//register command
routing.RouteToEndpoint( typeof( MyCommand), "SomeEndpoint" );
//subscribe to event
routing.RegisterPublisher(typeof(IMyEvent), "PublishingEndpoint" ); //?
So here I would have to specify the publisher of the IMyEvent, not the subscriber.
In NSB5, this was not necessary.
So what do I do if the event is published by several endpoints?
To answer your question:
So what do I do if the event is published by several endpoints?
You can subscribe to the same event from multiple publishers by having multiple RegisterPublisher calls from your subscriber.
Note that it's usually considered a smell if the same event is publishes from multiple logical endpoints. You might want to consider using different event types for each logical endpoint or maybe switch from an event to a command. If you're not sure about the message design, it's highly recommended to visit the Particular Software Google Group, people are very happy to help you with design questions which extend this SO question.
Regarding the change between V5 and V6:
In NSB5 I a subscriber would subscribe as I have shown above, by using its own endpoint name in the MessageEndpointMapping, and not the publisher's endpoint name.
I'm having a hard time following this statement. V5 and V6 use the same approach to subscribing, just a different syntax.
Since you're using MSMQ, a subscriber has to send a subscription message to each publisher of an event. For the subscriber to know where to send the subscription message, it needs routing information for this. This is where V5 and V6 use a different syntax:
V5 will look for a matching route in it's MessageEndpointMappings. It will send the subscription message to the endpoint specified in the mappings (which would be SubscribingEndpoint in your sample code).
V6 enforces separation between subscription messages and commands. That's why there are different APIs for routing regular commands and for routing subscription messages. Broker based transports (e.g. RabbitMQ) don't need subscription messages and therefore no routing for subscription messages is needed while every transport still requires routing information to send commands.
As you see, there is only a difference in syntax between V5 and V6, there should be no change in concepts. Since you claim that the above example works for you, I can only imagine a few reasons why that is so:
Your logical endpoints share the same subscription storage, which might cause the subscription message sent to the subscriber endpoint to be visible to the publisher by accident.
Your persistent subscription storage used by the publisher already contains a subscription from the subscriber. Although it might no longer receive subscription messages (because with your configuration it shouldn't) it still has an "old" subscription which is used by the publisher.
Whether one of these reasons might explain the behavior your seeing or not, when using MSMQ transport with NServiceBus, a subscriber always needs to have a route configured to the publisher in order for the subscription message to reach the publisher. This design didn't change between V5 and V6.
There is a nice sample demonstrating Publish/Subscribe in both V5 and V6 available on the Particular docs: https://docs.particular.net/samples/pubsub/?version=core_5
I have updated to NServiceBus 6, where the IProvideConfiguration and its MessageEndpointMappings are obsolete.
Please note, that in V6, both these APIs are obsoleted with a warning, but they still continue to work. These APIs will be removed in the next major version.
I hope this clears things up a bit.

How to use command pattern in a WinForms client application?

Background
I'm building a two-tiered C# .net application:
Tier 1: Winforms client application using the MVP (Model-View-Presenter) design pattern.
Tier 2: WebAPI RESTful service sitting on top of Entity Framework and SQL Server.
If you would like more detail on the application I'm building, I gave a probably too thorough explanation here.
Current Development
Currently, I'm working on the Winforms client. Particularly, I'm trying to hash out a adequate implementation of the command pattern within this client. I was fortunate enough to stumble across this excellent blog post that outlines a solid command architecture. To complement that post, the author followed up by explaining how he separates queries from commands. After reading those blogs, it becomes very clear that my tier 2 (web api service) would greatly benefit from implementing both of these. The generic implementation allows for fantastic flexibility, testability, and extensibility.
Question
What is less clear to me is how I go about implementing these patterns on the winforms client side of things (tier 1). Do queries and commands continue to be considered separate here? Consider a basic action, such as a login attempt. Is that a query or a command? Ultimately, you need data back (user information on the server) from the web service, so that would make me think it is a query. What about another case, such as a request to create a new user. I understand that you would create a command object that stores the user information and send that off to the service. Commands are supposed to be fire and forget, but wouldn't you want some sort of confirmation from the service that the command was successful? Furthermore, if a command handler returns void, how would you tell the presenter whether or not the user creation request was successful?
At the end of the day, for any given UI task (say the user creation request), does it end up that you end up having a winforms client based query/command, as well as a web api service version of the command/query which handles the request on that end?
Do queries and commands continue to be considered separate here?
Yes, typically you would fire a command and if you need to update the UI after this action has been performed you would perform a query to get the new information. An example will make this clear.
Let's say you would assign a specific guard to a certain area. The only information the command (which is only a DTO) needs is the Id of the guard and the Id of the area. The associated CommandHandler will perform all tasks to handle this, e.g. removing that guard from another area, booking him as unavailable etc.
Now your UI would want to show the change. The UI has probably some kind of list with all guards and their assigned area. This list will be populated by a single GetActiveGuardsAndAreaQuery which will return a List<GuardWithAreaInformationDto>. This DTO could contain all kinds of information about all guards. Returning this information from the command is not a clean separation of concerns, because the atomic command handling could be very well used from a similar but slightly different UI, which will require a slightly different update of the UI information.
such as a login attempt. Is that a query or a command?
IMO a login attempt is neither. It is a cross cutting concern, an implementation detail that the data is hidden behind a secure connection. The application however should not be concerned with this detail. Consider using the application with another customer where you could host the WebApi service in and Active Directory domain where you can use Windows Authentication. In that case the user only has to login to his machine and the security is handled by the client and server OS while communicating.
With the patterns you're referring to this can be nicely done using a AuthenticateToWebApiServiceCommandHandlerDecorator which makes sure their are login credentials to serve to the service by asking the user in a modal form, reading it from a config file, or whatever.
Checking if the credentials worked can be done by performing a kind of a standard Query your application always needs such as CheckIfUpdateIsAvailableQuery. If the query succeeds the login attempt succeeded otherwise it failed.
if a command handler returns void, how would you tell the presenter whether or not the user creation request was successful?
While it seems that void doesn't return anything this is not really true. Because if it doesn't fail with some exception (with a clear message what went wrong!) it must have succeeded.
In a follow up of the mentioned blog posts #dotnetjunkie describes a way to return information from commands but make notice of the added comment on the top of post.
To summarize, throw clear exceptions from failed commands. You can add an extra layer of abstraction client side to handle this nicely. Instead of injecting a commandhandler directly into the different presenters you can inject an IPromptableCommandHandler which has only one open generic implementation at compile time:
public interface IPromptableCommandHandler<TCommand>
{
void Handle(TCommand command, Action succesAction);
}
public class PromptableCommandHandler<TCommand> : IPromptableCommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> commandHandler;
public PromptableCommandHandler(ICommandHandler<TCommand> commandHandler)
{
this.commandHandler = commandHandler;
}
public void Handle(TCommand command, Action succesAction)
{
try
{
this.commandHandler.Handle(command);
succesAction.Invoke();
}
catch (Exception)
{
MessageBox.Show("An error occured, please try again.");
// possible other actions like logging
}
}
}
// use as:
public void SetGuardActive(Guid guardId)
{
this.promptableCommandHandler.Handle(new SetGuardActiveCommand(guardId),() =>
this.RefreshGuardsList());
}
At the end of the day, for any given UI task (say the user creation request), does it end up that you end up having a winforms client based query/command, as well as a web api service version of the command/query which handles the request on that end?
No!
Client side you should create a single open generic CommandHandlerProxy which solely task is to pass the command dto to the WebApi service.
For the service side architecture you should read another follow up: Writing Highly Maintainable WCF Services which describes an server side architecture to handle this very nicely. The linked project also contains an implementation for WebApi!

Invoke code-behind method when browser is closing

I need to find a way to intercept browser closing and invoke a metod to update a record with several information about logged user in DB. It's very important this record is updated when the user is logging-out or when he close the browser. Obviously when the user clicks 'Logout' I handle the update in the server-side event, but what if the user simply exit from browser?
Someone suggest to use the window.onbeforeunload event and make an asynchronous call to some WS or WebMethod to execute the code, but this doesn't convince me at all: the problem with onbeforeunload is that it shows a confirm prompt. I need to avoid this message and simply invoke the method.
So I'm wondering if there is a 'server-side' solution without using ajax or javascript.
For example... a way to trigger some event on session abandon or session clear, or some other way to solve this problem just working on code-behind...
There is no way you could have a server-side solution to know something that happens in the client browser.
I do not believe there is any way to do what you need server-side only. Client side is the only way. Server has no way of knowing when browser window was closed, this is limitation of HTTP protocol.
Yes, you can put an event in the Global.AsaX which will fire when the session ends. Now if you need data from the client to update the db etc., you'll need a way of getting it there, but if not, then the Session_End will do the trick.
Note: Session end is slightly different than the browser closing, so it this will depend on what you want the event firing to do.
How to handle session end in global.asax?
I'd like to find a 'server-side' solution without using ajax or
javascript.
I suspect that it's impossible with that requirement.
Maybe you could do something like:
Have a hidden IFRAME on the page
Set the Refresh header on this IFRAME (or use a META element) to contact the server every couple of seconds
If you do not hear from the client for some period of time, assume the browser has been closed.
However, I imagine that this solution will not scale well.
Have you considered something like signalr? I use it to detect when someone has a record open.
public class ChatHub : Hub
{
public override Task OnDisconnected()
{
Broadcaster.Disconnected(Context.ConnectionId);
return base.OnDisconnected();
}
}
For the moment I changed radically the approach to my problem.
To update pending rows I implemented a timed job using Quartz.NET framework, that runs every night.

CallBack in WCF?

How we use CallBack in WCF fluently with events and delegates?
If Client give any request or any conditions matches of client then services automatically fire the event which condition or request given from client.
how is it possible?
A cleaner model is an event driven one using a Publish/Subscribe Pattern.
Read this to get inside onto both methods.
http://msdn.microsoft.com/en-us/magazine/cc163537.aspx
You basically define a service method as one-way and also create a message callback. See more here: http://idunno.org/archive/2008/05/29/wcf-callbacks-a-beginners-guide.aspx

Categories

Resources