No Empty<T> method in Array class? - .net-core

Error pic
Why compiler tells me it doesn't exist? I have last SDK installed and netcoreapp3.1 as targeted framework.
public SomeDefinedType[] GetRecords()
{
return new System.Array.Empty<SomeDefinedType>();
}

Array.Empty() is a function that returns an empty array, not a type. It can't be used with new. Just return the function's result:
public SomeDefinedType[] GetRecords()
{
return System.Array.Empty<SomeDefinedType>();
}

Related

RegisterGenericDecorator ignores condition

Conditions:
Autofac: 4.9.1
.NET Framework: 4.7.2
I have a generic command handler:
public interface ICommand<TResult> : IValidatableObject
{
}
public interface ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>, IValidatableObject
{
TResult Handle(TCommand command);
}
I have a decorator that I want to use for multiple, but not all, implementations of the ICommandHandler (I am going to use a custom attribute to differentiate handlers):
public sealed class LoggingDecorator<TCommand, TResult> : ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>, IValidatableObject
{
private readonly ICommandHandler<TCommand, TResult> _handler;
public LoggingDecorator(ICommandHandler<TCommand, TResult> handler)
{
_handler = handler;
}
public TResult Handle(TCommand command)
{
var test = 0;
return _handler.Handle(command);
}
}
I am trying to register them with AutoFac as follows:
builder.RegisterAssemblyTypes(ThisAssembly)
.AsClosedTypesOf(typeof(ICommandHandler<,>))
.AsImplementedInterfaces();
builder.RegisterGenericDecorator(
decoratorType: typeof(LoggingDecorator<,>),
serviceType: typeof(ICommandHandler<,>),
condition: _decoratorContext =>
{
return false; // true;
});
Seems like the condition is ignored, the decorator is "assigned" to all handlers always.
Have I mis-configured the registration in AutoFac? Or did I miss something else?
How to achieve that the decorator is not registered if the condition returns 'false' in RegisterGenericDecorator method ?
Autofac 4.9.1 is a pretty old version now (3+ yrs). I know that some behaviour around decorator conditions was fixed in v6.0.0; see this issue where upgrading fixed someone's problem that sounds similar to yours.
I'd suggest upgrading to the latest version; if upgrading doesn't fix it, put together a minimal repro and raise an issue on our github repo.

Unit Test UserManager<IdentityUser> in asp.net core

My application is an ASP.NET Core 1.0 Web API. I would like to test the following method (snipped):
public async Task<bool> GetClientsAsync()
{
foreach (var user in await this.clientAdapter.Users().ToListAsync())
{
return true;
}
return false;
}
Normally the clientAdapter is calling UserManager<IdentityUser>'s property Users. So the code for the "real" clientAdapterlooks like that:
public IQueryable<IdentityUser> Users()
{
return this.userManager.Users;
}
Now when I am testing the clientAdapter looks like the following:
private readonly List<IdentityUser> clientList;
public TestClientAdapter(){
this.clientList= this.CreateClientList();
}
public IQueryable<IdentityUser> Users()
{
return this.userList.AsQueryable();
}
The return type of the method Users() has to be IQueryable<IdentityUser> since thats the return value of the original class UserManager<IdentityUser>. Now if I execute the test I am getting the following error, as soon as it hit's the foreach loop (the problem is the ToListAsync() call):
System.NotSupportedException: "Store does not implement IQueryableUserStore<TUser>."
If I change the loop from
foreach (var user in await this.clientAdapter.Users().ToListAsync())
{
return true;
}
to
foreach (var user in this.clientAdapter.Users().ToList())
{
return true;
}
Everything works fine.
My Problem:
I am not not able to mock the UserManager since the UserManager needs a UserStore which needs a DBContext which I dont know how to mock. And even if it was possbile to mock the DBContext, I think this would turn my unit test into an integration test and I dont want that. Plus it's probably not worth the effort. So I cannot just work with a mocked Usermanager and get the data from it.
My Question:
Is it possible to make the unit test pass, without changing the method I want to test?
EDIT
#CodeCaster:
The injected clientAdapter now looks like the following (snipped):
public class TestClientAdapter: IClientAdapter, IQueryableUserStore<IdentityUser>
{
private readonly List<IdentityUser> clientList
private UserManager<IdentityUser> testUserManager;
public TestClientAdapter: ()
{
clientList= this.CreateclientList();
this.testUserManager = new UserManager<IdentityUser>(this, null, null, null, null, null, null, null, null);
}
public IQueryable<IdentityUser> Users()
{
return this.testUserManager.Users;
}
IQueryable<IdentityUser> IQueryableUserStore<IdentityUser>.Users
{
get
{
return this.clientList.AsQueryable();
}
}
Now Iam getting another Exception:
"System.InvalidOperationException" in System.Private.CoreLib.ni.dll"
ToListAsync (among of other async methods like AnyAsync, etc.) is not a standard Linq2SQL (aka IQueryable<T>) extension method from System.Linq.*.
It's part of EntityFramework and as such it assumes certain preconditions, hence it can't work with a queryable List. Basically it's a wrapper around query.AsAsyncEnumerable() and AsAsyncEnumerable checks for the existence of IAsyncEnumerable<TSource> and/or IAsyncEnumerableAccessor<TSource> and if not there throws the invalid operation exception.
There are two things you can do...
Use EF Core InMemoryDatabase for an integration test, which was made for integration tests
Refactor your code so IQueryable<T> doesn't leak outside of your repository or command/query handlers
Technically it may be possible to create an list which implements AsAsyncEnumerable<T> but I haven't tried it and most likely not working with list.AsQueryable() since it wraps the list somewhere below...
Let the clientAdapter you inject for tests also implement IQueryableUserStore<TUser>, as the UserManager casts it to that, and if that fails, throws the mentioned exception.

Use std::map with pointer

i try to use std::map as property in my class. I use Visual Studio 2012, and my class is like:
public ref class MyClass
{
std::map<std::wstring,MyType> * mpMyMap;
MyClass()
{
mpMyMap = new std::map<std::wstring,MyType>();
}
~MyClass()
{
delete mpMyMap;
}
Get(std::wstring name)
{
return mpMyMap[name];
}
}
At return mpMyMap[name]; I get error, what there is no operator[] for this type. What should I do?
the bracket operator is on the map, not on the pointer of a map...
Try : return (*mpMyMap)[name];
The correct syntax is
MyType Get(std::wstring name)
{
return (*mpMyMap)[name];
}
You could also make the map an instance member instead of a pointer
std::map<std::wstring,MyType> mMyMap;
then your original code in Get would work and you'd get rid of memory management in the constructor and the destructor of MyClass.
Use
return (*mpMyMap)[name];
or
return mpMyMap->operator[]( name );
P.S. What is this
public ref class MyClass
//^^^^^^^^^^
Also, add return type for Get (MyType in your case)
mpMyMap is a pointer (for which I can see no reason), so you need to dereference it:
return (*mpMyMap)[name];
If mpMyMap must be a dynamically allocated remember to delete it in the destructor and either prevent copying of MyClass or implement copy constructor and assignment operator.
Note Get() is missing a return type (which should be either MyType or MyType&). Make the argument to Get() a const std::wstring& to avoid unnecessary copying and const as Get() does not modify it.
Since mpMyMap is pointer first variant is
Get(std::wstring name)
{
return (*mpMyMap)[name];
}
And second
Get(std::wstring name)
{
return mpMyMap->operator[](name);
}
And Get should have return-type.

Response.AsJson doen't work when calling it from a function in NancyFx

The extension methods:
Response.AsJson
Response.AsXml
works fine when calling it from the constractor like:
public class TweetModule : NancyModule
{
public TweetModule()
: base("/")
{
Post["/{action}.json/"] = parameters =>
{
return Reponse.Asjson(new {output:parameters.action}); // OK
}
}
}
But when I call it from a function like this:
public class TweetModule : NancyModule
{
public TweetModule()
: base("/")
{
Post["/{action}.{format}/"] = parameters =>
{
return GetResponse( parameters.action,parameters.format); // Error
}
}
public Response GetResponse(string action,string format)
{
if (format == "json")
return Response.AsJson(new {output:action}); // error
else
return Response.AsXml(new {output:action}); // error
}
}
I get this exception:
<>f__AnonymousType0`1[System.String] cannot be serialized because it
does not have a parameterless constructor.
any advice?
Na that works just fine. The problem is that your captured parameter is called {fortmat} and you then pass along parameters.format which is never captured due to the typo
And I have to point out that your code won't even compile since function is not a valid keyword in C#, I just assumed that you actual meant it to say public instead.
Hope this helps

flexunit: Parametrized tests

I am trying to run a parametrized tests... Was trying to implement it like it explained here:
http://docs.flexunit.org/index.php?title=Parameterized_Test_Styles
Here is what my test case looking
import org.flexunit.runners.Parameterized;
[RunWith("org.flexunit.runners.Parameterized")]
public class ArrayBasedStackTests
{
[Paremeters]
public static var stackProvider:Array = [new ArrayBasedStack(), new LinkedListBasedStack()] ;
private var _stack:IStack;
public function ArrayBasedStackTests(param:IStack)
{
_stack = param;
}
[Before]
public function setUp():void
{
}
[After]
public function tearDown():void
{
}
[Test ( description = "Checks isEmpty method of the stack. For empty stack", dataProvider="stackProvider" )]
public function isEmptyStackPositiveTest():void
{
var stack:IStack = _stack;
assertEquals( true, stack.isEmpty() );
}
But this code throws following initializing Error:
Error: Custom runner class org.flexunit.runners.Parameterized should
be linked into project and implement IRunner. Further it needs to have
a constructor which either just accepts the class, or the class and a
builder.
Need help to fix it
UPDATE
I've updated the code so it looks like this
[RunWith("org.flexunit.runners.Parameterized")]
public class ArrayBasedStackTests
{
private var foo:Parameterized;
[Parameters]
public static function stacks():Array
{
return [ [new ArrayBasedStack()], [new LinkedListBasedStack()] ] ;
}
[Before]
public function setUp():void
{
}
[After]
public function tearDown():void
{
}
[Test ( description = "Checks isEmpty method of the stack. For empty stack", dataProvider="stacks")]
public function isEmptyStackPositiveTest(stack:IStack):void
{
assertEquals( true, _stack.isEmpty() );
}
It works. But the result is a bit strange. I have 4 test executed instead of 2. (I have 2 items in data provider, so cant get why do I have 4 tests).
Output
http://screencast.com/t/G8DHbcjDUkJ
The [Parameters] meta-data specifies that the parameters are passed to the constructor of the test - so the test class is called for each parameter. You also have the dataProvider set for the specific test method, so the test method is also called once for each parameter. Two calls for the test, and two calls to the method, ends up running four tests.
The solution is to either use [Parameters] meta-tag which specifies the data to use for the whole test class, or use the dataProvider for each test method, but not both with the same data at the same time.
You're missing the static reference to Paramaterized, as shown here:
import org.flexunit.runners.Parameterized;
[RunWith("org.flexunit.runners.Parameterized")]
public class MyTestNGTest
{
private var foo:Parameterized;
...
Basically, that error means that the [Runner] defined isn't available at runtime, which occurs if there is no static reference in the class to cause it to get linked in.
In FlexUnit 4.5.1, this approach changed to using [Rule]'s like so:
public class MyTestNGTest
{
[Rule]
public function paramaterizedRule:ParamaterizedRule = new ParamaterizedRule();
...
}
However, I can't seem to see an actual implementation of IMethodRule for paramaterized tests (that example is fictional).

Resources