"You should only initialize MvxBindingSingletonCache once" error when have several test classes - mvvmcross

I run into a strange exception. In my test project, I use Moq, xUnit, and MvvmCross.Tests.
When I run my tests from one class - everything works just fine. When I run tests from 2 classes I get MvvmCross.Exceptions.MvxException.
I have 2 identical (initialization is identical) classes VitalsDataTests and GetReimbursedTests:
public class VitalsDataTests : MvxIoCSupportingTest
{
public VitalsDataTests()
{
base.Setup();
}
protected MockDispatcher MockDispatcher
{
get;
private set;
}
protected override void AdditionalSetup()
{
MockDispatcher = new MockDispatcher();
Ioc.RegisterSingleton<IMvxViewDispatcher>(MockDispatcher);
Ioc.RegisterSingleton<IMvxMainThreadDispatcher>(MockDispatcher);
Ioc.RegisterSingleton<IMvxMainThreadAsyncDispatcher>(MockDispatcher);
}
...
}
Here is my MockDispatcher:
public class MockDispatcher
: MvxMainThreadDispatcher
, IMvxViewDispatcher
{
public readonly List<MvxViewModelRequest> Requests;
public readonly List<MvxPresentationHint> Hints;
public MockDispatcher()
{
if (Hints == null) Hints = new List<MvxPresentationHint>();
if (Requests == null) Requests = new List<MvxViewModelRequest>();
}
public override bool IsOnMainThread { get; }
public Task<bool> ChangePresentation(MvxPresentationHint hint)
{
Hints.Add(hint);
return Task.FromResult(true);
}
public async Task ExecuteOnMainThreadAsync(Action action, bool maskExceptions = true)
{
await Task.Run(action);
}
public async Task ExecuteOnMainThreadAsync(Func<Task> action, bool maskExceptions = true)
{
await Task.Run(action);
}
public override bool RequestMainThreadAction(Action action, bool maskExceptions = true)
{
action();
return true;
}
public Task<bool> ShowViewModel(MvxViewModelRequest request)
{
Requests.Add(request);
return Task.FromResult(true);
}
}
What I tried:
Clearing MvxSingleton and MvxBindingSingletonCache singletons in the constructor of each class before I call base.Setup():
MvxSingleton.ClearAllSingletons();
MvxBindingSingletonCache.ClearAllSingletons();
Not sure what I'm doing wrong.
thank you for your help.

I was able to solve this error by adding XUnit Collection Attribute for each test class, like this:
[Collection("ViewModels")]
public class GetReimbursedTests : BaseTest
{
...
}

Related

MySql Entity Framework error when using SaveChangesAsync ASP.NET Core

I'm gettting an error when I try to use SaveChangesAsync with MySql EntityFramewok in a ASP.NET Core environment in dev mode in VS Code. Everything else works fine. No problems when using SaveChanges() either, without the async. Wonder if anyone else has this issue.
The error looks like this:
InvalidOperationException: Connection must be valid and open to commit transaction
MySql.Data.MySqlClient.MySqlTransaction.Commit()
The piece of code in the controller looks like this:
[HttpPut("/api/strategy/{id}")]
public async Task<IActionResult> UpdateStrategy(int id, [FromBody] StrategyResource newStrategy)
{
if(!ModelState.IsValid)
return BadRequest(ModelState);
mapper.Map<StrategyResource, Strategy>(newStrategy, strategyInDb );
context.SaveChanges(); // works fine
//await context.SaveChangesAsync(); gives ERROR
var res = mapper.Map<Strategy, StrategyResource>(strategyInDb );
return Ok(res);
}
Context initialization in the constructor of the controller (nothing special really)
private readonly JTradeContext context;
private readonly IMapper mapper;
public TradesController(JTradeContext context, IMapper mapper)
{
this.mapper = mapper;
this.context = context;
}
Context is initially added to services int the start up class
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<JTradeContext>();
}
And finally the context class itself
public class JTradeContext:DbContext
{
public DbSet<Trade> Trades { get; set; }
public DbSet<WebClient> WebClients { get; set; }
public DbSet<Strategy> Strategies { get; set; }
public DbSet<Portfolio> Portfolios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("my connection string here");
}
}

Castle Windsor Property Injection does not work with dynamic parameters

We want to use NserviceBus Saga's and in order to do that you need parameterless constructors for your saga. The only other way to inject our concerns is to use property injection which does not appear to work. Any help and guidance would be greatly appreciated.
I have posted sample code below that show's the issue.
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For<ClassWithDynamicProperty>()
.DynamicParameters((r, k) =>{ k["testString"] = "test"; }) );
container.Register(
Component.For<TestClassWithPropertyInjection>());
container.Register(
Component.For<TestClassWithConstructorInjection>());
var class1 = container.Resolve<TestClassWithConstructorInjection>();
var class2 = container.Resolve<TestClassWithPropertyInjection>();
Debug.Assert(class1.DynamicClass == null);
Debug.Assert(class2.ClassWithDynamicProperty == null);
}
}
internal class TestClassWithPropertyInjection
{
public TestClassWithPropertyInjection()
{
}
public ClassWithDynamicProperty ClassWithDynamicProperty { get; set; }
}
internal class TestClassWithConstructorInjection
{
private readonly ClassWithDynamicProperty _classWithDynamicProperty;
public TestClassWithConstructorInjection(ClassWithDynamicProperty classWithDynamicProperty)
{
_classWithDynamicProperty = classWithDynamicProperty;
}
public ClassWithDynamicProperty DynamicClass { get { return _classWithDynamicProperty; } }
}
public class ClassWithDynamicProperty
{
public string TestString { get; private set; }
public ClassWithDynamicProperty(string testString)
{
TestString = testString;
}
}

Castle.MicroKernel.ComponentNotFoundException with TypedFactoryFacility

I am having some problem resolving ITcpServer when using TypedFactoryFacility. It seems that Windsor does not find a suitable component to be returned from factory for the interface. What is specific to my case is that the interface ITcpServer is non-generic while classes implementing it are both generic.
The following code throws when run:
Unhandled Exception: Castle.MicroKernel.ComponentNotFoundException: No
component for supporting the service
ConsoleApplication1.StandardTcpServer`1 was found at
Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type
service, IDictionary arguments, IReleasePolicy policy) at
Castle.Facilities.TypedFactory.TypedFactoryComponentResolver.Resolve(IKernelInternal
kernel, IReleasePolicy scope) at
Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Resolve(IInvocation
invocation) at
Castle.Facilities.TypedFactory.Internal.TypedFactoryInterceptor.Intercept(IInvocation
invocation) at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.ITcpServerFactoryProxy.Create[T](String serverType,
T something)
The code:
class Program
{
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container.Install(new MyWindsorInstaller());
var f = container.Resolve<ITcpServerFactory>();
var tcpServer = f.Create("standard", "something");
tcpServer.Start();
}
}
public class MyWindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<ITcpServer>().ImplementedBy(typeof(LibUvTcpServer<>)),
Component.For<ITcpServer>().ImplementedBy(typeof(StandardTcpServer<>)),
Component.For<ITcpServerFactory>().AsFactory(c => c.SelectedWith(new TcpServerComponentSelector()))
);
}
}
public class TcpServerComponentSelector : DefaultTypedFactoryComponentSelector
{
protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
{
var serverType = (string)arguments.First();
return serverType == "standard" ? typeof (StandardTcpServer<>) : typeof(LibUvTcpServer<>);
}
}
public interface ITcpServerFactory
{
ITcpServer Create<T>(string serverType, T something);
}
public class StandardTcpServer<T> : ITcpServer
{
public void Start()
{
Console.WriteLine("Started...");
}
}
public class LibUvTcpServer<T> : ITcpServer
{
private readonly T something;
public LibUvTcpServer(T something)
{
this.something = something;
}
public void Start()
{
Console.WriteLine("Started...");
}
}
public interface ITcpServer
{
void Start();
}
Any help in solving the problem would be appreciated.
Change the following:
protected override Type GetComponentType(System.Reflection.MethodInfo method, object[] arguments)
{
var serverType = (string)arguments.First();
if (serverType == "standard")
{
return typeof(StandardTcpServer<>).MakeGenericType(arguments[1].GetType());
}
else
{
return typeof(LibUvTcpServer<>).MakeGenericType(arguments[1].GetType());
}
}
and the registration:
Component.For<ITcpServer>().Forward(typeof(LibUvTcpServer<>)).ImplementedBy(typeof(LibUvTcpServer<>)),
Component.For<ITcpServer>().Forward(typeof(StandardTcpServer<>)).ImplementedBy(typeof(StandardTcpServer<>)),
or if you only need to resolve through the factory:
Component.For(typeof(LibUvTcpServer<>)),
Component.For(typeof(StandardTcpServer<>)),
Good luck,
Marwijn.

Jersey unmarshal JSON: Last element null does not work

I am using Jersey to parse the following JSON:
{"response":{"status":"OK","campaigns":[{"id":12345,"state":"active","code":null}]}}
But I get the following error message:
java.lang.IllegalArgumentException: No more parsing elements.
If I switch the position of the fields code and state so that the resulting JSON looks like
{"response":{"status":"OK","campaigns":[{"id":12345,"code":null,"state":"active"}]}}
everything works fine. Also if I change the code-field in the first JSON to a non-null value like "code":"test", Jersey can parse this without any problems. I tried other more complex examples always getting the above mentioned error message when leaving the last field of any element of an array null.
I think I am doing something wrong, because I could not find any others having the similar problem. I already tried to implement a CustomJAXBContextResolver using other JSON notations like natural but nothing worked for me.
Any ideas?
Here are my binding classes:
#XmlRootElement
public class LoadEntityResponse {
public LoadEntityResponse() {
}
private Response response;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
and
public class Response {
public Response() {
}
private String status;
private String error;
private String error_id;
private Campaign[] campaigns;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_id() {
return error_id;
}
public void setError_id(String error_id) {
this.error_id = error_id;
}
public Campaign[] getCampaigns() {
return campaigns;
}
public void setCampaigns(Campaign[] campaigns) {
this.campaigns = campaigns;
}
}
and finally
public class Campaign{
public Campaign() {
}
protected int id;
protected String code;
protected String state;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Solved: Using JacksonJsonProvider now:
...
DefaultClientConfig config = new DefaultClientConfig();
config.getClasses().add(JacksonJsonProvider.class);
...
that´s all!
You can also use Jackson POJO support that comes with jersey-json but there is a need to do some configuration, see POJO support in Jersey User Guide.
Try using Genson http://code.google.com/p/genson/.
To enable it on client side use the following code:
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(GensonJsonConverter.class);
cli = Client.create(config);
EDIT: on server side there is no configuration needed, when the jar is in your classpath json support is automatically enabled.

Entity Framework type case generic in predicate

I am working on updating to a more manageable repository pattern in my MVC 4 project that uses Entity Framework code first. I've integrated a generic base repository class that will do basic CRUD operations so I don't have to implement these in each repository I create. I have ran into an issue where my All method needs to filter there query by a deleted flag if the entity is a type of TrackableEntity. Since the Entity is generic in the base repository I am attempting to cast is to a type of TrackableEntity in the where which just results in the following error message.
The 'TypeAs' expression with an input of type 'NameSpace.Models.ClientFormField' and a check of type 'NameSpace.Models.TrackableEntity' is not supported. Only entity types and complex types are supported in LINQ to Entities queries.
This error makes complete since and I understand why the code I have is not working but I am trying to find a way to filter out deleted items without having to override this method in all of my repositories. The code I have for my All method is below.
public virtual IEnumerable<T> All()
{
if (typeof(T).IsSubclassOf(typeof(TrackableEntity)))
return dbSet.Where(e => !(e as TrackableEntity).IsDeleted).ToList();
return dbSet.ToList();
}
I know that I can do the following
public virtual IEnumerable<T> All(Expression<Func<T, bool>> predicate = null)
{
if (predicate != null)
return dbSet.Where(predicate).IsDeleted).ToList();
return dbSet.ToList();
}
And then add this to all of my repositories
public override IEnumerable<CaseType> All(Expression<Func<CaseType,bool>> predicate = null)
{
if (predicate == null)
predicate = e => !e.IsDeleted;
return base.All(predicate);
}
The problem I have with this is that I am duplicating code, this is basically a copy and paste into all of my repositories which defeats the purpose of changing to this new repository pattern. I made the switch to end duplicated code in my repositories.
Here is an example of one of my entities.
public class CaseType : TrackableEntity, IValidatableObject
{
public int Id { get; set; }
public string Name { get; set; }
public bool InUse { get; set; }
public bool IsValid { get { return !this.Validate(null).Any(); } }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (String.IsNullOrEmpty(Name))
yield return new ValidationResult("Case Type name cannot be blank", new[] { "Name" });
//Finish Validation Rules
}
}
And the TrackableEntity
public abstract class TrackableEntity
{
public bool Active { get; set; }
public bool IsDeleted { get; set; }
public virtual User CreatedBy { get; set; }
public virtual User ModifiedBy { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
Any help on this would be much appreciated.
I finally got a solution working that I am happy with. I ended up making 2 generic repositories. One that is the base repository which deals with all of the calls to the database for my BaseEntity which all entities inherit from. Then I made my 2nd generic repo which is inherits BaesEntity and overrides a few methods to handle the needs of my TrackableEntities. In the end this does what I want by handling the filtering of soft deleted items from within the repo and also gives me more flexibility with the TrackableEntity.
BaseRepository -
public class BaseRepository<T> : IBaseRepository<T> where T : BaseEntity
{
private readonly IAppDb _db;
private readonly IDbSet<T> _dbSet;
public BaseRepository(IAppDb db)
{
_db = db;
_dbSet = Lwdb.Set<T>();
}
protected IAppDb Lwdb
{
get { return _db; }
}
#region IBaseRepository<T> Members
public virtual T GetById(int id)
{
return _dbSet.Find(id);
}
public virtual T Add(T entity)
{
_dbSet.Add(entity);
_db.Commit();
return entity;
}
public virtual bool Any(Expression<Func<T, bool>> expression)
{
return _dbSet.Any(expression);
}
public virtual void Delete(T entity)
{
_dbSet.Remove(entity);
_db.Commit();
}
public virtual IEnumerable<T> All()
{
return _dbSet.ToList();
}
public virtual T Update(T entity, bool attachOnly = false)
{
_dbSet.Attach(entity);
_db.SetModified(entity);
if (!attachOnly) _db.Commit();
return entity;
}
#endregion
protected User GetCurrentUser()
{
return
_db.Set<User>().Find(HttpContext.Current != null ? ((User) HttpContext.Current.Session["User"]).Id : 1);
}
BaseTrackableEntityRepository -
public class BaseTrackableEntityRepository<T> : BaseRepository<T>, IBaseTrackableEntityRepository<T>
where T : TrackableEntity
{
private readonly IAppDb _db;
private readonly IDbSet<T> _teDB;
public BaseTrackableEntityRepository(IAppDb db)
: base(db)
{
_db = db;
_teDB = _db.Set<T>();
}
#region IBaseTrackableEntityRepository<T> Members
public virtual T SetDeleteFlag(int id)
{
var entity = _teDB.Find(id);
if (entity == null) return null; //throw exception
entity.IsDeleted = true;
entity.DateModified = DateTime.Now;
entity.ModifiedBy = GetCurrentUser();
return Update(entity);
}
public override IEnumerable<T> All()
{
return _teDB.Where(e => !e.IsDeleted).ToList();
}
public override T Add(T entity)
{
var curUser = GetCurrentUser();
entity.CreatedBy = curUser;
entity.ModifiedBy = curUser;
entity.DateCreated = DateTime.Now;
entity.DateModified = DateTime.Now;
entity.Active = true;
entity.IsDeleted = false;
_teDB.Add(entity);
_db.Commit();
return entity;
}
public override T Update(T entity, bool attachOnly = false)
{
InsertTeData(ref entity);
entity.ModifiedBy = GetCurrentUser();
entity.DateModified = DateTime.Now;
_teDB.Attach(entity);
_db.SetModified(entity);
if (!attachOnly) _db.Commit();
return entity;
}
public virtual T SetStatus(int id, bool status)
{
var entity = _teDB.Find(id);
if (entity == null) return null;
entity.Active = status;
return Update(entity);
}
#endregion
private void InsertTeData(ref T entity)
{
if (entity == null || entity == null) return;
var dbEntity = GetById(entity.Id);
if (dbEntity == null) return;
_db.Detach(dbEntity);
entity.CreatedBy = dbEntity.CreatedBy;
entity.DateCreated = dbEntity.DateCreated;
entity.ModifiedBy = dbEntity.ModifiedBy;
entity.DateModified = dbEntity.DateModified;
}