NServiceBus - Aggregate Root - Saga - Synchronous Command - microservices

Having an aggregate root User modeled as NServiceBus Saga
User.cs
public class User {
....
public string Rename(string name) {
.// some validation logic
}
...
}
UserSagaData.cs
public class UserSagaData : ContainSagaData
{
public User User { get; set;}
}
UserSaga.cs
public partial class UserSaga : Saga<RenameUser>
{
...
public async Task Handle(RenameUserimportAttendees, IMessageHandlerContext context)
{
Data.User.rename(...
}
...
}
Now i have a requirement to accept RenameUser command via REST API and give the feedback in HTTP Response, hence sending RegisterUser to message broker from Controller.Action is not an option. I need to perform command synchronously, get feedback and send http response.
First thing that came to mind is to use ISagaPersister, that is, retrieve saga by id, then invoke a command and then persist saga back to the datastore with ISagaPersister (which takes care of optimistic locking). Any thoughts on that ?
Is there alternative solutions to this problem ?

What type of feedback would you expect the RenameUser command to result in?
Can’t you just return a HTTP OK and queue up the rename command? (assuming that you have validation of the new name in place the chances of something going wrong should be slim and could be dealt with offline should the command end up in the error queue?)
An option if you really have to wait for the response is to use our callbacks package, https://docs.particular.net/nservicebus/messaging/callbacks, to enable your REST API block until the response has arrived, this way you can still using messaging behind the scenes.
What do you think?

Related

How to handle Optional from Service to Controller in Spring?

Spring JPA returns an Optional. I return the Optional from the Service. There if Optional is not present I pass error to model. The other case if there is a database error for example database not available, I do not catch these exceptions. If that happens user will see this exception in browser. I do not know how to handle this very rare error. For me this should never happen and if it does, ok . I do not want to handle this exception all the time. What do you think about my architecture.
Service:
#Override
public Optional<Client> findClientById(Long id) {
return clientRepository.findById(id);
}
Controller:
Optional<Client> client= clientService.findClientById(id);
if(client.isPresent())
{
model.addAttribute("client", client.get());
}
else
{
model.addAttribute("error", "No clientfound with this ID!!");
}
Firstly, you shouldn't pass error as an attribute in your model - that's REST anti-pattern. The best way to hand this is to use HTTP codes, e.g. return 502. To do so, you may wrap your exceptions up your code into HttpResponse. To catch your exception, you may approach similar to method that explained here, i.e. catch spring data exception, wrap it up a way you wanted and throw on higher level for processing.

Update clients in asp.net core 2.0 using SignalR

I am going through several examples on Asp.net Core WebAPI with SignalR where most of them are demonstrating simple chat application where this is what Hub returns:
return Clients.All.InvokeAsync("Send", message);
And this is how it gets called in Startup.cs
routes.MapHub<Chat>("chat");
The above example is good if message is not be send and updated to all the clients. In my case I have several APIs to be called whenever a data is changed:
Like Bank Transaction is done, I have to update ledger and several other reports at client side. But I don't see any option to pass Json.
Not finding exactly how to do this so that WebAPI gets refreshed everytime a change is there in the database.
As far as I understood, here "chat" is the endpoint which will be called from the frontend.
In this case what will happen to the endpoint I have created so far. Have a look at the below code example:
This api is to be called every time an entry is done:
public async Task<object> GetMarket(string marketshortcode)
{
Markets market = new Markets(marketshortcode);
return market.GetMarket();
}
and this the entry:
[Authorize]
[HttpPost]
public async Task<object> sellCurUser([FromBody] SellCur model)
{
if (model != null)
{
SellCurUser suser = new SellCurUser();
suser.sellcur = model;
my addition code...
}
return ....
}
There are several more endpoints which needs to be called at certain update/creation.
Now the point is how these apis will be changed or even not changed at all.
Do anyone have any example to understand it simply.

How to delay the response of my Web API

I am working on a Web API project and that has an Artist Web API Controller. On there, there is the api/artist method that is a GET for all artists.
When making the call to this method, I would like a 3 second delay before I serve the data, how can I achieve this?
CODE
public class ArtistController : ApiController
{
private GlContext db = new GlContext();
// GET api/Artist
public IQueryable<Artist> GetArtists()
{
return db.Artists;
}
}
I know that you wouldn't want to do this in a production environment, but I am playing with preloaders, and in order to test them properly I need to introduce this delay.
If it is just for testing you can always go for Thread.Sleep(3000)
http://msdn.microsoft.com/en-us/library/d00bd51t%28v=vs.110%29.aspx

Grails + RESTful URL mapping + Filters + Routes

Member have many jobs. A member can add, delete or update Jobs. Currently there are actions (add, delete or update) defined in a controller which are called through jQuery.ajax(). We are sending job id and member id to perform the operation. Member id is necessary because there is a role admin who can modify the job on behalf of members, so we need to identify the member. But sending member id is dangerous as anyone can send the request by modifying the member id.
I know, we can add constraint do restrict that only admin can modify the jobs or a member can modify only his jobs. My question is, Do I need to add these constraints in the action of the controller or Is there any Grails way to do that. I have google, the same thing is handled in Ruby and Rails by using routes. And in grails I have skim through RESTful URL mapping, which is perhaps used for this purpose.
Can anyone points me to right direction, thanks. I am using Grails 2.1.1.
You can implement some realization of AbstractPersistenceEventListenerService to not allow perform actions with entity that constains id of not logged in user. Example:
class MultiTenantPersistenceEventListenerService extends AbstractPersistenceEventListenerService {
def springSecurityService
#Override
protected AbstractPersistenceEventListener createPersistenceEventListener(Datastore datastore) {
return new MultiTenantPersistenceEventListener(datastore)
}
}
class MultiTenantPersistenceEventListener extends AbstractPersistenceEventListener {
MultiTenantPersistenceEventListener(final Datastore datastore) {
super(datastore)
}
#Override
protected void onPersistenceEvent(AbstractPersistenceEvent event) {
def entity = event.getEntityObject() // could be your Job domain entity
def user = springSecurityService.getCurrentUser() //current logged in user
if(entity.hasProperty('userId')){ // every job belongs to User
if(entity.userId != user.id){
throw new AccessDeniedException("Acces Denied !")
}
}
}
}
I'd recomment to use grails spring-security-plugin. There is a lot of information in web about plugin and it's easy configurable. Plugin allows you to perfrom controller's action in secure way. For example:
#Secured(['ROLE_USER'])
def followAjax = { ... }
#Secured(['IS_AUTHENTICATED_REMEMBERED'])
def personal = { ... }
For more information - plugin and spring-security with grails.
You can use Authorize attribute to authorize the user,
e.g
[CustomAuthorize(Roles=SiteRoles.Admin|SiteRoles.HelpDesk)]
public ActionResult Index()
{
return View();
}
This is a nice approach for making website secure.
go through these link, this will help you.
custom authorization with asp.net mvc
asp.net mvc authorization

How do I bind a simple POST value in ASP.NET WebAPI RC?

I have a POST method on one of my API controllers that takes a single string value:
public string Post([FromBody] string foo) {
return(fooOracle.ValidateFoo(foo) ? "success" : "failure");
}
I'm POSTing to this with the body of the post request as:
foo=123412341234
(i.e. it's a regular HTTP POST that you can initiate by submitting a browser form as well as using an HTTP client)
In the release candidate of WebAPI, this has silently stopped working - it just doesn't bind foo any more. To get the code working, I've had to replace the method with this:
public string Post(FormDataCollection form) {
var foo = form.Get("foo");
return(fooOracle.ValidateFoo(foo) ? "success" : "failure");
}
This works, but it's kinda messy and involves rather more plumbing to test than the previous version.
Have I missed some subtle change, or has the [FromBody] binding syntax been deprecated in favour of this rather verbose binding syntax? The attribute is still there but it's really not clear what it actually does in the RC version.
It's actually there is a subtle change that it cannot handle inputs like 'foo=123412341234' but will handle '=123412341234' as the input. Can you make the client send it as later?
If not you could create a wrapper class as below and make your action expect stringwrapper as a parameter rather than String itself.
Class StringWrapper { public string Foo {get; set;} }

Resources