Automapper MapExpression - No coercion operator is defined - automapper

I'm having difficulties creating a new ObjectMapper for Automapper (7.0.1)
I'm trying to create an Object mapper that take a source value and assign it to an object property so I can create a map between an int to a specific type of object.
So here is my MapExpression
public Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap,
PropertyMap propertyMap, Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
var property = Property(destExpression, "Value");
return Assign(property, Convert(sourceExpression, property.Type));
}
sourceExpression DebugView
$resolvedValue
destExpression DebugView
.If ($dest == null) {
.Default(Prextra.Domain.SelectLists.SYS.StateSelectListItem) } .Else {
$typeMapDestination.State }
I don't know what I'm doing wrong, but I get this exception, so I guess it tries to assign the Int32 value to the object instead of the property?
InvalidOperationException: No coercion operator is defined between
types 'System.Int32' and
'Prextra.Domain.SelectLists.SYS.StateSelectListItem'

Related

The JUnit Assume.assumeNotNull throws nullpointer instead of skipping test

I have this junit (using JUnit 4.12) test in groovy that should only be executed if getenv != null:
import org.junit.Assume
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
...
#Test
public void skipWhenNull() throws Exception {
def getenv = System.getenv("bogos")
if( getenv == null) {
println "Its null!"
}
Assume.assumeNotNull(getenv);
println "Test executing!"
}
But when I run the test it prints: Its null! and then throws a NullPointer exception (in the line: Assume.assumeNotNull(getenv); ). Is the point of: Assume.assumeNotNull(expr) not that it will skip the test when expr evaluates to null instead of throwing a Nullpointer?
I thought this might be a bug, but I think this is rather a consequence of Groovy's dynamic type system in its default behavior. Assume.assumeNotNull(Object... objects) method uses varargs parameters. It means that in case of passing a non-array element compiler wraps it within an array of expected type.
String getenv = System.getenv("bogos");
Assume.assumeNotNull(getenv); // --> Assume.assumeNotNull(new Object[] { getenv });
This is what Java's static compiler does. So in case of getenv == null we end up with:
Assume.assumeNotNull(new Object[] { null });
A non-empty array that contains a single null element. On the other hand, if we specify a variable with an array type and we assign a null value to it, calling the same method will cause NullPointerException, just like in the following example:
String[] array = null;
Assume.assumeNotNull(array); // --> throws NPE
This is at least what happens in Java. Now, why it fails in Groovy unit test? Groovy is a dynamically typed language by default, so it behaves quite differently in this area. It seems like Groovy's type system applies null value to the method type without wrapping it within an array, so in case of passing a null to a method that expects e.g. Object... objects we always get objects == null instead of objects == new Object[] { null }.
I started questioning myself if this is a bug or not. From one perspective I would expect dynamic Groovy to behave in the same way that statically compiled code behaves. But on the other hand in a dynamically typed system, this distinction is acceptable (and maybe even desirable), because dynamic type system infers the type at the runtime. It sees null so it thinks that we intend to assign null value to a variable of type Object[].
Solution
There are two ways you can solve this problem.
1. Enable static compilation
If you don't use Groovy's dynamic and metaprogramming features in your test case you can easily annotate it with #groovy.transform.CompileStatic annotation to generate a bytecode that is more similar to Java's bytecode. For instance, this is what the bytecode of your method in the dynamic Groovy looks like:
#Test
public void skipWhenNull() throws Exception {
CallSite[] var1 = $getCallSiteArray();
Object getenv = var1[4].call(System.class, "bogos");
if (ScriptBytecodeAdapter.compareEqual(getenv, (Object)null)) {
var1[5].callCurrent(this, "Its null!");
}
var1[6].call(Assume.class, getenv);
var1[7].callCurrent(this, "Test executing!");
}
And here is the same method but annotated with #CompileStatic from the bytecode perspective:
#Test
public void skipWhenNull() throws Exception {
String getenv = System.getenv("bogos");
Object var10000;
if (getenv == null) {
DefaultGroovyMethods.println(this, "Its null!");
var10000 = null;
}
Assume.assumeNotNull(new Object[]{getenv});
var10000 = null;
DefaultGroovyMethods.println(this, "Test executing!");
var10000 = null;
}
2. Wrap getenv with an array
Alternatively, you can make more explicit call to Assume.assumeNotNull method. If you replace:
Assume.assumeNotNull(getenv);
with:
Assume.assumeNotNull([getenv] as Object[]);
then you will wrap parameter explicitly with Object[] array and you will prevent from passing an array object that is represented by null, but a single element array holding null value instead.

Azure Functions : With a TableResult, how do I see a property?

I am successfully retrieving a Table Row on Azure:
TableOperation operation = TableOperation.Retrieve<MyEntity>(partitionKey, rowkey);
TableResult result = table.Execute(operation);
if (result.Result != null)
{
}
I need to look at the Result to see if MyEntity.MyProperty == true
I cannot get to view the actual MyEntity result e.g.
log.Info(result.Result); returns Submission#0+MyEntity
log.Info(result.Result.MyProperty) : object does not contain a definition for MyProperty and no extension method MyProperty accepting a first argument of type 'object' could be found
With a TableResult, how do I see a property?
Just cast result.Result to your entity class:
((MyEntity)result.Result).MyProperty

Groovy coercing List to Map doesn't throw ClassCastException or what is ArrayList1_groovyProxy?

I was writing code where I tried to cast an Object to a Map.
Map a = object as Map
I could alternatively use
Map a = (Map) object
and the whole question would be irrelevant as this throws a ClassCastException if the object is of type List, but by using the former I encountered an interesting thing.
If the object is a List, i.e. object = [], groovy type coercion will behave different from what I expected.
My expectation was to get a ClassCastException, but instead I got a resulting object. But this object seems odd. It is an instance of List and an instance of Map and using .toString() on it resulted in the output of a List, not a Map ([a,b]). Also it is not possible to set a value on the map with a['c'] = 'c'. This results in a java.lang.IllegalArgumentException: argument type mismatch.
Map a = ['a', 'b'] as Map
println(a)
println(a instanceof List)
println(a instanceof Map)
println(a.getClass())
results in the following output:
[a, b]
true
true
class ArrayList1_groovyProxy
I tried to google to find out what this ArrayList1_groovyProxy is, but couldn't find anything.
It still doesn't make sense to me, that the coercion returns an object that obviously is not really what it should be and also seems kind of broken, instead of just throwing a ClassCastException.
Can anyone explain to me the reasoning behind that behavior instead of throwing the exception and explain the use of ArrayList1_groovyProxy? Or is this just a bug in groovy?
The as operator calls the asType method with the provided type as the argument to the method.
You can see the default implementation for asType in DefaultGroovyMethods.
Since Map is an interface, it will eventually call ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, obj), which returns a dynamic proxy that implements Map.
/**
* Converts a given object to a type. This method is used through
* the "as" operator and is overloadable as any other operator.
*
* #param obj the object to convert
* #param type the goal type
* #return the resulting object
* #since 1.0
*/
#SuppressWarnings("unchecked")
public static <T> T asType(Object obj, Class<T> type) {
if (String.class == type) {
return (T) InvokerHelper.toString(obj);
}
// fall back to cast
try {
return (T) DefaultTypeTransformation.castToType(obj, type);
}
catch (GroovyCastException e) {
MetaClass mc = InvokerHelper.getMetaClass(obj);
if (mc instanceof ExpandoMetaClass) {
ExpandoMetaClass emc = (ExpandoMetaClass) mc;
Object mixedIn = emc.castToMixedType(obj, type);
if (mixedIn != null)
return (T) mixedIn;
}
if (type.isInterface()) {
try {
List<Class> interfaces = new ArrayList<Class>();
interfaces.add(type);
return (T) ProxyGenerator.INSTANCE.instantiateDelegate(interfaces, obj);
} catch (GroovyRuntimeException cause) {
// ignore
}
}
throw e;
}
As to why Groovy goes to such great lengths to coerce types--it's basically the nature of Groovy: making Java coding easier. You can construct an object by passing a Map to its constructor, or even coerce a Map instance to a particular type; so why not let every object be coerced back into a Map via the as operator?

How can I cast a object which is instantiated by reflection to its real type?

Recently I'm developing a tiny framework for myself,
and I met this problem:
How can I do things like follow:
void object CreateDictionary(Type dictionaryType)
{
object dict = dictionaryType.GetConstructor(new Type[] {}).Invoke(new object[] {});
// Cast dict to its real type here so that I can add key-value-pairs to it.
...
}
The dictionaryType is the type of some kind of Dictionary, and is got via reflection.
I have no idea about the full type because I don't know the generic attributes until runtime.
I've also tried changing the declaration object dict to var dict, but it does not work either.
You cannot do this. But, you know that this is some kind of Dictionary, so you can cast it to IDictionary and use methods of IDictionary.
object CreateDictionary(Type dictionaryType)
{
object dict = dictionaryType.GetConstructor(new Type[] {}).Invoke(new object[] {});
var idictionary = (IDictionary)dict;
idictionary.Add(key, value);
}
If your all this dictionaries is inherited from one class, you can cast it to this class and use methods of this class.
By the way, it is simpler to get instance of Type through:
object obj = Activator.CreateInstance(type);
OK, I managed to solve this problem at last.
Finally I noticed that what I want to do is not about casting,
but calling method.
Maybe there are better solutions than mine.
Anyway, I'd like to share my solution.
First, create an extension class for object (this is weird though):
public static class ReflectionHelper
{
public static object InvokeInstanceMethod(this object invoker, string methodName, params object[] parameters)
{
MethodInfo[] methods = invoker.GetType().GetMethods();
foreach (MethodInfo method in methods)
{
ParameterInfo[] paramInfos = method.GetParameters();
if (method.Name == methodName && paramInfos.Length == parameters.Length)
{
for (int i = 0; i < parameters.Length; i++)
{
if (!paramInfos[i].ParameterType.IsAssignableFrom(parameters[i].GetType()))
{
throw new MissingMethodException();
}
}
return method.Invoke(invoker, parameters);
}
}
throw new MissingMethodException();
}
}
This extension method allows me to call methods like this:
anyInstance.InvokeInstanceMethod("MethodName", param1, param2, ...);
Because all types, excluding Object itself, are derived from Object, this method can be cal on any instance of any type.
Then I use this method:
object dict = dictionaryType.CreateInstance(); // The method CreateInstance() is also an extension
dict.InvokeInstanceMethod("Add", key, val);

Adding different object types to a c# 4.0 collection

I have a function that returns objects of different types based on the parameter passed to this function.
Is it possible to add these different object types to a collection based on some identifier in C# 4.0?
Usually we do something like this
List or List
but i want one collection which can add object of any type.
Instead of just making a List<object> like other posters are recommending, you may want to define an interface eg IListableObject that contains a few methods that your objects need to implement. This will make any code using these objects much easier to write and will guard against unwanted objects getting into the collection down the line.
Yes, it is called object. Eg:
var objlist = new List<object>();
objlist.Add(1);
objlist.Add(true);
objlist.Add("hello");
You could use object[], List<object>, ArrayList, IEnumerable, ... but if those types have a common base type it would be better to stick to a strongly typed collection.
Really your collection should be as specific as you can make it. When you say
objects of different types
Do these objects have anything in common? Do they implement a common interface?
If so you you can specialise the list on that interface List<IMyInterface>
Otherwise List<object> will do what you want.
Update
No, not really.
I'm sorry but I'm going to question your design.
If you have a collection of different objects, how do you decide how to use one of the objects?
You're going to have a large switch statement switching on the type of the object, then you cast to a specific object and use it.
You also have have a similar switch statement in your factory method that creates the object.
One of the benefits of Object Orientation is that if you design your objects correctly then you don't need to do these large "If it's this object do this.Method(), if it's that object do that.OtherMethod()".
Can I ask, why are you putting different objects into the same collection? What's the benefit to you?
If you want a collection which can add objects of any type then List<object> is the most appropriate type.
Collections in earlier versions of C# (not generics) can contain any kind of objects. If they're value type, they will be boxed into object.
When you need to use them, you can just cast it to the original type.
You may use List<Type> to hold the type information, if that's what you want. And Type[], Hashtable, etc. are also fine. You can use typeof operator to get the type or use Object.GetType().
Also check out Dynamic type.
http://msdn.microsoft.com/en-us/library/dd264736.aspx
It will basically do the same thing.
My Suggestion:
public class ParamValue
{
object value = null;
public ParamValue(object val)
{
value = val;
}
public string AsString()
{
return value.ToString();
}
public int AsInt()
{
return int.Parse(value.ToString());
}
public int? AsNullableInt()
{
int n;
if (int.TryParse(value.ToString(), out n))
{
return n;
}
return null;
}
public bool AsBool()
{
return bool.Parse(value.ToString());
}
public bool? AsNullableBool()
{
bool b;
if (bool.TryParse(value.ToString(), out b))
{
return b;
}
return null;
}
}
public class Params
{
Dictionary<string, object> paramCol = new Dictionary<string, object>();
public void Add(string paramName, object value)
{
paramCol.Add(paramName, value);
}
public ParamValue this[string paramName]
{
get
{
object v;
if (paramCol.TryGetValue(paramName, out v))
{
return new ParamValue(v);
}
return null;
}
}
}
Use param class as a collectio to your values, you can convert the return to every type you want.
You could use a Tuple of Genric Types
public Tuple<T, T> MySuperMethod()
{
int number = 1;
string text = "Batman";
return new Tuple<int, string>(number, text);
}
The .NET Framework directly supports tuples with one to seven
elements. In addition, you can create tuples of eight or more elements
by nesting tuple objects in the Rest property of a Tuple object.
https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.100).aspx

Resources