I need help testing NServiceBus.Send(command).Register(delegate) in a MVC 4 Web API service call - testing

I'm implementing a call to NServiceBus.Send() inside a MVC 4 Web API Service call. I'm doing this in .Net 4, so I don't have access to C# 5 features (async, etc.).
I'm very new to Moq, so I'd appreciate some advice creating the correct way to Setup Moq for this. I did look at [Mocking a delegate wrapper using Moq][1] and [Testing Bus Send in an application using NServiceBus][2] but my understanding of Moq is still to primitive to adapt for my testing needs, especially with the Tasks involved to deal with the asynchronous calls:
public Task<HttpResponseMessage> Post(Command command)
{
var commandCompletion = new TaskCompletionSource<HttpResponseMessage>();
var commandCompletionTask = commandCompletion.Task;
Bus.Send(command).Register<CommandResult>(status =>
{
var response = new HttpResponseMessage { StatusCode = HttpStatusCode(status) };
commandCompletion.SetResult(response);
});
return commandCompletionTask;
}
I run into trouble because I don't know how to reference the commandCompletionTask within the mockedBus... My failed attempt looks like this:
_commandController = new CommandController(MockBus.Object);
MockBus.Setup(b => b.Send(It.IsAny<ICommand>()).Register<CommandResult>((Action<CommandResult> s) =>
{
var response = new HttpResponseMessage { StatusCode = HttpStatusCode(s) };
commandCompletion.SetResult(response);
}));
Writing this allowed my brain to come up with a couple of ideas...
To Moq TaskCompletionSource, but that doesn't have an interface, so can't be Moq'd apparently.
To use a real TaskCompletionTask, (which allows me to test for the Task returned from CommandController.Post()). Sadly this didn't work any better, as I get an error from LINQ as it tries to process the delegate.
Ideas/suggestions?

Related

Running data downloading on background thread

Im building a new app and since i want it to be smooth as everyone, I want to use a background thread that would be responsible for all the data downloading using restsharp. Im also following the MVVM pattern.
I've been reading a lot about task.run and how to use it properly and the whole async-await topic. But since Im new to all this, Im not sure how I should procceed to do things right. I have a lot of code so I will breifly try to explain what Im doing and then put a snippet.
So I started with creating a service class that contains all the functions that are using restsharp to get the data. And inside my ViewModel Im calling those functions in the very begining. Im trying to use tasks and run those functions on the background thread but the app get blocked on the splash screen. And abviously thats because Im doing things wrong ... so I decided to ask you guys.
I have this function for exemple :
public string GetResPor()
{
var restClient = new RestClient { BaseUrl = new Uri("http://xxx.xxx.xxx.xxx:xxxx") };
var request = new RestRequest
{
Resource = "getCliPor",
Method = Method.GET
};
request.AddParameter(new Parameter { Name = "idt", Value = GetImAsync().GetAwaiter().GetResult(), Type = ParameterType.GetOrPost });
var result = restClient.Execute(request);
Port = result.Content;
return Port;
}
When I convert this on a Task :
public async Task<string> GetResPor()
{
var restClient = new RestClient { BaseUrl = new Uri("http://xxx.xxx.xxx.xxx:xxxx") };
var request = new RestRequest
{
Resource = "getCliPor",
Method = Method.GET
};
request.AddParameter(new Parameter { Name = "idt", Value = GetImAsync().GetAwaiter().GetResult(), Type = ParameterType.GetOrPost });
var result = await restClient.ExecuteTaskAsync(request);
Port = result.Content;
return Port;
}
on the ViewModel I start by creating a new instance of my service class and then:
Port = RD.GetRestauPort().GetAwaiter().GetResult();
And this is where the app get blocked, no exceptions no nothing.
To keep things simple, let's start with the basics. The easiest thing to do, in order to run something in a background thread, is to call it inside a Task.Run(). What this does is:
Queues the specified work to run on the ThreadPool and returns a task or Task<TResult> handle for that work.
Basically, you are delegating your work to the TreadPool and it handles everything for you - looks for a worker, waits for the worker to finish its job (on a new thread) and then notifies you of the result.
So, basically, whatever you want to be in a background thread, the simples solution will be to wrap it inside a Task.Run() and await its result, in case you need it.
Also, avoid using GetAwaiter().GetResult(). The simple rule in asynchronous programming is - if you can await, await all the way up.
You can read more about the topics in
this SO post
Advanced Tips for Using Task.Run With Async/Await
Using Task.Run in Conjunction with Async/Await

How to perform async ModelState validation with FluentValidation in Web API using .NET Core

This question is a follow up to this post - How to perform async ModelState validation with FluentValidation in Web API?.
I was wondering if FluentValidation has a way to perform async ModelState validation in .net core web api. I have a FluentValidation Validator class which contains async validation methods such as "MustAsync", which means in my business service class I call the validator manually using "ValidateAsync". I also want to use this same validator class to validate the model coming in from the request. I went through the documents and read that the only way to do this is to manually call the "ValidateAsync()" method since the .net pipeline is synchronous. I would rather not manually have to call this method from within my controller, I would prefer to either register it in the startup (have the framework automatically call the the validator on my model) or decorate my request model with the validator.
Has anyone been able to achieve this?
Thanks!
Based on the linked question, I've adapted the code slightly to be compatible with ASP.NET Core (2.2, in my case). In general, this is using the IAsyncActionFilter interface. You can read about it in the official docs.
public class ModelValidationActionFilter : IAsyncActionFilter
{
private readonly IValidatorFactory _validatorFactory;
public ModelValidationActionFilter(IValidatorFactory validatorFactory) => _validatorFactory = validatorFactory;
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var allErrors = new Dictionary<string, object>();
// Short-circuit if there's nothing to validate
if (context.ActionArguments.Count == 0)
{
await next();
return;
}
foreach (var (key, value) in context.ActionArguments)
{
// skip null values
if (value == null)
continue;
var validator = _validatorFactory.GetValidator(value.GetType());
// skip objects with no validators
if (validator == null)
continue;
// validate
var result = await validator.ValidateAsync(value);
// if it's valid, continue
if (result.IsValid) continue;
// if there are errors, copy to the response dictonary
var dict = new Dictionary<string, string>();
foreach (var e in result.Errors)
dict[e.PropertyName] = e.ErrorMessage;
allErrors.Add(key, dict);
}
if (allErrors.Any())
{
// Do anything you want here, if the validation failed.
// For example, you can set context.Result to a new BadRequestResult()
// or implement the Post-Request-Get pattern.
}
else
await next();
}
}
If you want to apply this filter globally, you can add the filter to the AddMvc call in your Startup class. For example:
services.AddMvc(options =>
{
options.Filters.Add<ModelValidationActionFilter>();
// uncomment the following line, if you want to disable the regular validation
// options.ModelValidatorProviders.Clear();
});
I had trouble getting the code in #nachtjasmin's answer to work with newer versions of FluentValidation. Specifically, the trouble is that ValidateAsync now takes an IValidationContext instead of the model being validated, and the context can't be created without knowing the type of the model at compile time.
Eventually I stumbled upon this answer, which points out that the exact type is not important and uses object instead.
So, instead of:
var result = await validator.ValidateAsync(value);
You can use:
var context = new ValidationContext<object>(value);
var result = await validator.ValidateAsync(context);
Based on the answer above by #nachtjasmin, you can add this in two ways,
Using AddMvc
services.AddControllersWithViews(options =>
{
options.Filters.Add<FluentValidationActionFilter>();
});
Using AddControllersWithViews
services.AddControllersWithViews(options =>
{
options.Filters.Add<FluentValidationActionFilter>();
});
If your's is just a Web API and you don't have any Razor pages involved, then you can consider using AddControllersWithViews over AddMvc, as the AddMvc uses the AddControllersWithViews internally and add the services.AddRazorPages() on top of that.
You can see this info here for AddMvc and here for AddControllersWithViews

Ajax call for JSON using EF Core is failing/aborting

I'm at a loss with why this isn't working...
I have a .NET Core app using EF Core, and I'm making an Ajax call via jQuery to my controller to retrieve some data from the database via EF Core. Debugging the call via my developer tools in the browser (IE/Chrome) results in a status of failed/aborted. Yet when I step through my method in my controller, the method seems to be able to retrieve the data from the database via EF Core just fine.
Here's my controller:
public ActionResult GetInfo(string term)
{
using (var dbContext = new DatabaseContext())
{
// use DbContext to get data from the database
var retrievedData = dbContext.TableName.Where(...);
return Json(retrievedData.Select(data => new {
id = data.id,
text = data.text
}));
}
}
And here's the jQuery:
$(#element).select2({
...
ajax: {
url: $(#element).attr("data-getinfo"),
dataType: 'json', // tried this with jsonp and application/JSON with no luck
contentType: 'application/json; charset=utf-8',
delay: 250,
data: function (params) {
return: { term: params.term};
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.id, text: item.text
}
})
}
},
},
....
});
The Ajax calls work with previous apps I've worked on, but they used MVC 5 and EF 6. This also works if I retrieve dummy data, IE instead of using EF Core to get the data, I return fake data built into the controller. What gives?
To clarify the root of your problem: You are querying your database and returning an IEnumerable as a JsonResult. But first, you need to understand one step before. Calling .Where returns an IQueryable. You can think of an IQueryable as if it is a TSQL command that was not yet execute on the database. Only calls that will enumerate the results will trigger the materialization of the query.
So you did this:
// .Where returns an IQueryable. You can "chain" more wheres later.
// the query will still not be executed
var retrievedData = dbContext.TableName.Where(...);
// This then returns an IEnumerable to the client.
// The Select will materialize (execute) the query
return Json(retrievedData.Select(data => new {
id = data.id,
text = data.text
}));
The problem with your code is: .Select returns an IEnumerable which enumerates the results. But, by the time the browser or whatever client you are dealing with starts to enumerate the results, your database connection is already closed, because you used using block around your dbContext (which is kind of correct.. see comments in the end).
So, to fix it, you need basically to enumerate the results yourself or not close the connection (let the framework close for you when the request is finished..). This minor change fix the problem:
// ToList() will enumerate all the results in memory
var retrievedData = dbContext.TableName.Where(...).ToList();
Other comments:
You don't need (also shouldn't) manage the creation of the dbContext by yourself. You can register it in the DI container and the framework will do the rest for you. You can take a look in the EF Core docs to have an idea on how it is done.
Not an ideal solution, but I got it working. I suspect it might have to do with how .NET Core or EF Core was returning data to the browser, but I can't say for sure yet.
I ended up using Json.NET for a workaround. Performance isn't bad (I tried a query with hundreds of records and it only took a couple of seconds at most), and I was already using it for an external API call.
public ActionResult GetInfo(string term)
{
using (var dbContext = new DatabaseContext())
{
// use DbContext to get data from the database
var retrievedData = dbContext.TableName.Where(...);
var initJson = Json(retrievedData.Select(data => new {
id = data.id,
text = data.text
}));
var serializedJson = Newtonsoft.Json.JsonConvert.SerializeObject(initJson);
var deserializedJson = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedJson);
return Json(deserializedJson);
}
}

ASP MVC async Controller and HttpContext.Cache - Correct Pattern?

Given an async action method on an ASP MVC Controller and an async method that gets some data:
public async Task<ActionResult> Index()
{
var apiClient = new apiClient();
var data = await apiClient.GetDataAsync(id);
I want GetDataAsync to store the result as a Cache item, so it doesn't have to request from an external api next time.
I can sometimes get this to work by passing in a reference to the cache object, (often inexplicably null even though passed from what I thought was the starting thread. Must not be the starting thread I guess?).
var data = await apiClient.GetDataAsync(id, System.Web.HttpContext.Current.Cache);
But I seem to remember that this is not a good idea (something to do with thread safety).
What is the recommended way to handle caching in an async method? Should I move cache handling into the controllers? Seems a shame as it made sense for the cache management to happen closer to the data source.

async await with .net 4.0 - maintain static context

I have an MVC 4.0 site which is using the BCL async/await package.
To preserve HttpContext across the initial thread and the subsequent thread (after the await) I began by creating a closure with a reference to the context like so:
public async Task<ViewResult> GetCustomer(int id)
{
var ctx = HttpContext.Current;
ctx["test"] = "test";
await DoSomeLongRunningIO();
var test = ctx["test"];
//do other things with context
return View();
}
However, I need to call various services after the await. These legacy services call the HttpContext.Current directly.
So I approached this with the following code, which seemed like a simple way to ensure these services still work as expected.
public async Task<ViewResult> GetCustomer(int id)
{
var ctx = HttpContext.Current;
await DoSomeLongRunningIO();
HttpContext.Current = ctx;
//call other services which use static references to httpcontext
return View();
}
This does work, however I have been reading this answer that suggests it is a bad idea:
Is this a bad idea, and if so why is it worse than the first example?
Thanks for your time.
Are you aware that async/await in an ASP.NET app on .NET 4.0 is undefined?
If you upgrade to .NET 4.5, you'll find that HttpContext is preserved automatically for you. There's no need for closures or to set it.
Setting HttpContext.Current is a bad idea, because you're bypassing the ASP.NET safety checks that ensure there is only one thread at a time with that context.