Suppose a mapping using AutoMapper like bellow:
mapItem.ForMember(to => to.SomeProperty, from =>
{
from.Condition(x => ((FromType)x.SourceValue).OtherProperty == "something");
from.MapFrom(x => x.MyProperty);
});
What's difference of substitute Condition by PreCondition:
from.PreCondition(x => ((FromType)x.SourceValue).OtherProperty == "something");
What's the practical difference between this two methods?
The diference is that PreCondition is executed before acessing the source value and also the Condition predicate, so in this case, before get the value from MyProperty the PreCondition predicate will run, and then the value from property is evaluated and finally Condition is executed.
In the following code you can see this
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Person, PersonViewModel>()
.ForMember(p => p.Name, c =>
{
c.Condition(new Func<Person, bool>(person =>
{
Console.WriteLine("Condition");
return true;
}));
c.PreCondition(new Func<Person, bool>(person =>
{
Console.WriteLine("PreCondition");
return true;
}));
c.MapFrom(p => p.Name);
});
});
Mapper.Instance.Map<PersonViewModel>(new Person() { Name = "Alberto" });
}
}
class Person
{
public long Id { get; set; }
private string _name;
public string Name
{
get
{
Console.WriteLine("Getting value");
return _name;
}
set { _name = value; }
}
}
class PersonViewModel
{
public string Name { get; set; }
}
The output from this program is:
PreCondition
Getting value
Condition
Because the Condition method contains a overload that receives a ResolutionContext instance, that have a property called SourceValue, the Condition evaluate the property value from source, to set the SourceValue property on ResolutionContext object.
ATTENTION:
This behavior work properly until version <= 4.2.1 and >= 5.2.0.
The versions between 5.1.1 and 5.0.2, the behavior is not working properly anymore.
The output in those versions is:
Condition
PreCondition
Getting value
Related
I'm writing an extension method in order to do translation with Automapper.
I have some classes :
public class TranslatableClass : ITranslatable<TranslationClass>
{
public string Id { get; set; }
public string Label { get; set; }
public string Description { get; set; }
public List<TranslationClass> Translations { get; set; }
public string OtherEntityId { get; set; }
public string OtherEntityLabel { get; set; }
public List<OtherEntityTranslation> OtherEntityTranslations { get; set; }
}
public class TranslationClass : ITranslation
{
public Guid LanguageId { get; set; }
public string Label { get; set; }
public string Description { get; set; }
}
public class TranslatedClass
{
public string Id { get; set; }
public string Label { get; set; }
public string Description { get; set; }
public string OtherEntityLabel { get; set; }
}
public class OtherEntityTranslation : ITranslation
{
public string Label { get; set; }
public Guid LanguageId { get; set; }
}
I'd like to get an extension method like this one :
cfg.CreateMap<TranslatableClass, TranslatedClass>()
.ForMember(t => t.OtherEntityLabel, opt => opt.MapFromTranslation(t => t.OtherEntityTranslations, oet => oet.Label));
And my extension method looks like this one
public static void MapFromTranslation<TSource, TDestination, TMember, TTranslation>(this IMemberConfigurationExpression<TSource, TDestination, TMember> opt, Func<TSource, IEnumerable<TTranslation>> getTranslations, Func<TTranslation, string> getValue)
where TTranslation : ITranslation
{
opt.MapFrom((src, _, _, context) =>
{
string result = null; // here is the pain point ; I'd like to get the value as if I was automapper
if (context.Options.Items.TryGetValue(LANGUAGE, out object contextLanguage) && contextLanguage is Guid languageId)
{
var translations = getTranslations(src);
var translation = translations.FirstOrDefault(t => t.LanguageId == languageId);
if (translation != null)
{
result = getValue(translation);
}
}
return result;
});
}
The issue I'm facing is I can't find a nice way to get the default behavior of AutoMapper when I don't have a translation. In this implementation, if I don't find a translation for my language, the value will be null while it should be the value of the source object (which is the default value).
I try to put PreCondition before the MapFrom but that doesn't map the property so I get null too.
I can try to get the value from the source object with reflexion but I will lose all the capabilities of Automapper like naming convention and other stuffs.
public static void MapFromTranslation<TSource, TDestination, TMember, TTranslation>(this IMemberConfigurationExpression<TSource, TDestination, TMember> opt, Func<TSource, IEnumerable<TTranslation>> getTranslations, Func<TTranslation, string> getValue)
where TTranslation : ITranslation
{
var destinationMember = opt.DestinationMember as PropertyInfo;
var source = typeof(TSource);
var sourceProperty = source.GetProperty(destinationMember.Name);
if (sourceProperty != null)
{
opt.MapFrom((src, _, _, context) =>
{
string result = sourceProperty.GetValue(src) as string; // Get value from source as if it was the mapper
if (context.Options.Items.TryGetValue(LANGUAGE, out object contextLanguage) && contextLanguage is Guid languageId)
{
var translations = getTranslations(src);
if (translations != null)
{
var translation = translations.FirstOrDefault(t => t.LanguageId == languageId);
if (translation != null)
{
var value = getValue(translation);
if (!String.IsNullOrWhiteSpace(value))
{
result = value;
}
}
}
}
return result;
});
}
else
{
throw new Exception($"Can't map property {opt.DestinationMember.Name} from {source.Name}");
}
}
Let's re-define configuration without using extension method, trying to simplify things. Following mapping example, we can implement custom IValueResolver
cfg.CreateMap<TranslatableClass, TranslatedClass>()
.ForMember(dest => dest.OtherEntityLabel, opt => opt.MapFrom<CustomResolver>();
Implementing IValueResolver<TranslatableClass, TranslatedClass, string> interface:
public class CustomResolver: IValueResolver<TranslatableClass, TranslatedClass, string>
{
public string Resolve(TranslatableClass source, TranslatedClass destination, string member, ResolutionContext context)
{
string result = source.Label; /* needed effect! */
/* can we simplify this condition? */
if (context.Options.Items.TryGetValue(source.OtherEntityLabel, out object contextLanguage)
&& contextLanguage is Guid languageId)
{
var translations = source.OtherEntityTranslations;
var translation = translations.FirstOrDefault(t => t.LanguageId == languageId);
if (translation != null)
{
result = translation.Label;
};
}
return result;
}
}
Here comes same logic from
MapFromTranslation<TSource, TDestination, TMember, ... extension method provided below, let's put that logic right - we map TSource as TranslatableClass to TDestination as TranslatedClass.
Also, I believe that if (context.Options.Items.TryGetValue(...)) should be removed for simplicity too (are we trying to get languageId here?)
So, by using Custom Value Resolvers feature we can simplify mapper configuration and refactor for test coverage or debugging needs.
Update
I do want to use this extensions method on 50 others entity and I
won't write custom resolver for each one
Using Expressions instead of reflection should help to implement 'generic solution'. Solution is to define a cache of mapping expressions to access TSource and TDestination properties.
public static class MappingCache<TFirst, TSecond>
{
static MappingCache()
{
var first = Expression.Parameter(typeof(TFirst), "first");
var second = Expression.Parameter(typeof(TSecond), "second");
var secondSetExpression = MappingCache.GetSetExpression(second, first);
var blockExpression = Expression.Block(first, second, secondSetExpression, first);
Map = Expression.Lambda<Func<TFirst, TSecond, TFirst>>(blockExpression, first, second).Compile();
}
public static Func<TFirst, TSecond, TFirst> Map { get; private set; }
}
Next, let's try to define generic lambda-expressions for both
Func<TTranslation, string> getValue and getTranslations(...
e.g.:
public static Expression GetSetExpression(ParameterExpression sourceExpression, params ParameterExpression[] destinationExpressions)
{
/** AutoMapper also can be used here */
/* compile here all (source)=>(destination) expressions */
var destination = destinationExpressions
.Select(parameter => new
{
Parameter = parameter,
Property = parameter.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(property => IsWritable(property) && IsOfType(property, sourceExpression.Type))
})
.FirstOrDefault(parameter => parameter.Property != null);
if (destination == null)
{
throw new InvalidOperationException(string.Format("No writable property of type {0} found in types {1}.", sourceExpression.Type.FullName, string.Join(", ", destinationExpressions.Select(parameter => parameter.Type.FullName))));
}
/* Here is the generic version of mapping code! */
return Expression.IfThen(
Expression.Not(Expression.Equal(destination.Parameter, Expression.Constant(null))),
Expression.Call(destination.Parameter, destination.Property.GetSetMethod(), sourceExpression));
}
Next goes IsWritable(PropertyInfo property) that is used to check validate properties, try to implement convention-based property filtering (names, attributes, etc.) here
public static bool IsWritable(PropertyInfo property)
{
/* eliminating reflection code from extension method */
return property.CanWrite && !property.GetIndexParameters().Any();
}
Next IsOfType(PropertyInfo... and IsSubclassOf methods, - define simple rules of proper TSource->TDestination ways of mapping...
public static bool IsOfType(PropertyInfo property, Type type)
{
/* here AutoMapper could be used too, making filtering needed destination entities by following some convention */
return property.PropertyType == type || IsSubclassOf(type, property.PropertyType) || property.PropertyType.IsAssignableFrom(type);
}
public static bool IsSubclassOf(Type type, Type otherType)
{
return type.IsSubclassOf(otherType);
}
}
Trying to implement convention based mapping approach:
public static void MapFromTranslation<TSource, TDestination, TMember, TTranslation>(this IMemberConfigurationExpression<TSource, TDestination, TMember> opt, Expression<Func<TSource, TDestination, TMember, TTranslation>> mapping )
where TTranslation : ITranslation
Wiring around the Expression<Func<TSource,TDestination,TMember, TTranslation> mapping and the MappingCache<TSource,TDestination,TMember, TTranslation>.Map is the next step. Our lambda expression represents the property transformation intent generically (mapping,conversion,validating,navigating, etc...), and when compiled lambda called with parameters passed, we get the result of such transformation.
Expression:
MappingCache<TSource,TDestination,TMember, TTranslation>.GetSetExpression(first, second, third, proxy...
Function:
var result = MappingCache<TSource,TDestination,TMember, TTranslation>.Map(first,second,third,...
Keeping statically compiled lambda-delegates abstractions open, we can cover every needed mapping aspect with proper tests, - seems like the generic approach that could be used to address the question
Access default map function in MapFrom to fallback
(c) Dapper.Mapper + Tests
Ultimately I want to have an internal interface with a setter and a public one with a getter. The code that replicates this scenario is roughed below:
[TestMethod]
public void TestMethod3()
{
var fake1 = A.Fake<IInterface1>(a => a.Implements(typeof(IInterface2)));
string backingString = null;
IInterface2 fake2 = (IInterface2)fake1;
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("set_Property"))
.Invokes((string param) => { backingString = param; });
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString); //doesn't work
A.CallTo(fake2)
.Where(a => a.Method.Name.Equals("set_Property"))
.Invokes((string param) => { backingString = param; });
A.CallTo(fake2)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString); //doesn't work
fake1.Property = "asdf";
Assert.AreEqual("asdf", fake1.Property); //fails -> fake1.Property is null
Assert.AreEqual(fake1.Property, fake2.Property); //fails -> fake2.Property is null
}
}
public interface IInterface1
{
string Property { get; set; }
}
public interface IInterface2
{
string Property { get; }
}
I could get as far as using backingString to store the setter, but when setting up the getter it doesn't work as I wanted it to.
I also tried something in the line of A.CallTo(() => fake1.Property).Returns(backingString) to no avail.
Would appreciate assistance of them experts :)
When you set up your
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString);
(and similarly for fake2),
the value of backingString is null, so that's what's returned later on when you access the Property getter.
In order to return the value of backingString at the time the Property getter is called, you want ReturnsLazily.
Make this change in each place and the tests pass:
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().ReturnsLazily(() => backingString);
I have the following ugly code:
if (msg == null ||
msg.Content == null ||
msg.Content.AccountMarketMessage == null ||
msg.Content.AccountMarketMessage.Account == null ||
msg.Content.AccountMarketMessage.Account.sObject == null) return;
Is there a way to chain check for null values in C#, so that I don't have to check each individual level?
One of the proposals in C# 6 would be to add a new Null Propogation operator.
This will (hopefully) allow you to write:
var obj = msg?.Content?.AccountMarketMessage?.Account?.sObject;
if (obj == null) return;
Unfortunately, there is nothing in the language at this point that handles this.
There is not currently such a thing, but it may be coming to .NET very soon. There is a well-known User Voice thread on the subject. And as noted in this article, the Visual Studio team has recently announced that:
We are seriously considering this feature for C# and VB, and will be
prototyping it in coming months.
Edit: and as noted in Reed Copsey's answer above, it is now a planned addition for C# 6. There are better details on the Codeplex pages he linked.
There is no built-in support for this, but you can use an extension method for that:
public static bool IsNull<T>(this T source, string path)
{
var props = path.Split('.');
var type = source.GetType();
var currentObject = type.GetProperty(props[0]).GetValue(source);
if (currentObject == null) return true;
foreach (var prop in props.Skip(1))
{
currentObject = currentObject.GetType()
.GetProperty(prop)
.GetValue(currentObject);
if (currentObject == null) return true;
}
return false;
}
Then call it:
if ( !msg.IsNull("Content.AccountMarketMessage.Account.sObject") ) return;
You need monads and Monadic null checking. Could have a look at Monads.Net package. It can help with simplifying null tests and getting values from deep navigation properties
Something like
var sObject = person.With(p=>p.Content).With(w=>w.AccountMarketMessage ).With(p=>p.Account).With(p=>p.Object);
If you wanted a default value then
var sObject = person.With(p=>p.Content).With(w=>w.AccountMarketMessage).With(p=>p.Account).Return(p=>p.Object, "default value");
You can lazily evaluate the values using lambda expressions. This is overkill for a simple null check, but can be useful for chaining more complex expressions in a "fluent" manner.
Example
// a type that has many descendents
var nested = new Nested();
// setup an evaluation chain
var isNull =
NullCheck.Check( () => nested )
.ThenCheck( () => nested.Child )
.ThenCheck( () => nested.Child.Child )
.ThenCheck( () => nested.Child.Child.Child )
.ThenCheck( () => nested.Child.Child.Child.Child );
// handle the results
Console.WriteLine( isNull.IsNull ? "null" : "not null" );
Code
This is a full example (albeit draft-quality code) that can be pasted into a console app or LINQPad.
public class Nested
{
public Nested Child
{
get;
set;
}
}
public class NullCheck
{
public bool IsNull { get; private set; }
// continues the chain
public NullCheck ThenCheck( Func<object> test )
{
if( !IsNull )
{
// only evaluate if the last state was "not null"
this.IsNull = test() == null;
}
return this;
}
// starts the chain (convenience method to avoid explicit instantiation)
public static NullCheck Check( Func<object> test )
{
return new NullCheck { IsNull = test() == null };
}
}
private void Main()
{
// test 1
var nested = new Nested();
var isNull =
NullCheck.Check( () => nested )
.ThenCheck( () => nested.Child )
.ThenCheck( () => nested.Child.Child )
.ThenCheck( () => nested.Child.Child.Child )
.ThenCheck( () => nested.Child.Child.Child.Child );
Console.WriteLine( isNull.IsNull ? "null" : "not null" );
// test 2
nested = new Nested { Child = new Nested() };
isNull = NullCheck.Check( () => nested ).ThenCheck( () => nested.Child );
Console.WriteLine( isNull.IsNull ? "null" : "not null" );
// test 3
nested = new Nested { Child = new Nested() };
isNull = NullCheck.Check( () => nested ).ThenCheck( () => nested.Child ).ThenCheck( () => nested.Child.Child );
Console.WriteLine( isNull.IsNull ? "null" : "not null" );
}
Again: you probably shouldn't use this in lieu of simple null checks due to the complexity it introduces, but it's an interesting pattern.
.NET Fiddle
As stated there is a plan to have c# 6.0 implement the ? operator to facilitate this process somewhat. If you cannot wait, I would suggest using a lambda expression and a simple helper function to solve this.
public E NestedProperty<T,E>(T Parent, Func<T,E> Path, E IfNullOrEmpty = default(E))
{
try
{
return Path(Parent);
}
catch
{
return IfNullOrEmpty;
}
}
This could be used int value = NestedProperty<First,int>(blank,f => f.Second.Third.id); as shown in the demo below
program
public class Program
{
public void Main()
{
First blank = new First();
First populated = new First(true);
//where a value exists
int value = NestedProperty<First,int>(blank,f => f.Second.Third.id);
Console.WriteLine(value);//0
//where no value exists
value = NestedProperty<First,int>(populated,f => f.Second.Third.id);
Console.WriteLine(value);//1
//where no value exists and a default was used
value = NestedProperty<First,int>(blank,f => f.Second.Third.id,-1);
Console.WriteLine(value);//-1
}
public E NestedProperty<T,E>(T Parent, Func<T,E> Path, E IfNullOrEmpty = default(E))
{
try
{
return Path(Parent);
}
catch
{
return IfNullOrEmpty;
}
}
}
simple demo structure
public class First
{
public Second Second { get; set; }
public int id { get; set; }
public First(){}
public First(bool init)
{
this.id = 1;
this.Second = new Second();
}
}
public class Second
{
public Third Third { get; set; }
public int id { get; set; }
public Second()
{
this.id = 1;
this.Third = new Third();
}
}
public class Third
{
public int id { get; set; }
public Third()
{
this.id = 1;
}
}
Since 3.5 (maybe earlier), You could write very simple extension method
public static TResult DefaultOrValue<T, TResult> (this T source,
Func<T, TResult> property) where T : class
{
return source == null ? default(TResult) : property(source);
}
You may name this method even shortier and then use like this
var instance = new First {SecondInstance = new Second
{ThirdInstance = new Third {Value = 5}}};
var val =
instance .DefaultOrValue(x => x.SecondInstance)
.DefaultOrValue(x => x.ThirdInstance)
.DefaultOrValue(x => x.Value);
Console.WriteLine(val);
Console.ReadLine();
so source classes are:
public class Third
{
public int Value;
}
public class First
{
public Second SecondInstance;
}
public class Second
{
public Third ThirdInstance;
}
I have an object lets call it ObjectA
and that object has 10 properties and those are all strings.
var myObject = new {Property1="",Property2="",Property3="",Property4="",...}
is there anyway to check to see whether all these properties are null or empty?
So any built-in method that would return true or false?
If any single of them is not null or empty then the return would be false. If all of them are empty it should return true.
The idea is I do not want to write 10 if statement to control if those properties are empty or null.
Thanks
You can do it using Reflection
bool IsAnyNullOrEmpty(object myObject)
{
foreach(PropertyInfo pi in myObject.GetType().GetProperties())
{
if(pi.PropertyType == typeof(string))
{
string value = (string)pi.GetValue(myObject);
if(string.IsNullOrEmpty(value))
{
return true;
}
}
}
return false;
}
Matthew Watson suggested an alternative using LINQ:
return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => (string)pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value));
I suppose you want to make sure that all properties are filled in.
A better option is probably by putting this validation in the constructor of your class and throw exceptions if validation fails. That way you cannot create a class that is invalid; catch exceptions and handle them accordingly.
Fluent validation is a nice framework (http://fluentvalidation.codeplex.com) for doing the validation. Example:
public class CustomerValidator: AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Property1).NotNull();
RuleFor(customer => customer.Property2).NotNull();
RuleFor(customer => customer.Property3).NotNull();
}
}
public class Customer
{
public Customer(string property1, string property2, string property3)
{
Property1 = property1;
Property2 = property2;
Property3 = property3;
new CustomerValidator().ValidateAndThrow();
}
public string Property1 {get; set;}
public string Property2 {get; set;}
public string Property3 {get; set;}
}
Usage:
try
{
var customer = new Customer("string1", "string", null);
// logic here
} catch (ValidationException ex)
{
// A validation error occured
}
PS - Using reflection for this kind of thing just makes your code harder to read. Using validation as shown above makes it explicitly clear what your rules are; and you can easily extend them with other rules.
The following code returns if any property is not null.
return myObject.GetType()
.GetProperties() //get all properties on object
.Select(pi => pi.GetValue(myObject)) //get value for the property
.Any(value => value != null); // Check if one of the values is not null, if so it returns true.
Here you go
var instOfA = new ObjectA();
bool isAnyPropEmpty = instOfA.GetType().GetProperties()
.Where(p => p.GetValue(instOfA) is string) // selecting only string props
.Any(p => string.IsNullOrWhiteSpace((p.GetValue(instOfA) as string)));
and here's the class
class ObjectA
{
public string A { get; set; }
public string B { get; set; }
}
A slightly different way of expressing the linq to see if all string properties of an object are non null and non empty:
public static bool AllStringPropertyValuesAreNonEmpty(object myObject)
{
var allStringPropertyValues =
from property in myObject.GetType().GetProperties()
where property.PropertyType == typeof(string) && property.CanRead
select (string) property.GetValue(myObject);
return allStringPropertyValues.All(value => !string.IsNullOrEmpty(value));
}
Note if you've got a data structural hierarchy and you want to test everything in that hierarchy, then you can use a recursive method. Here's a quick example:
static bool AnyNullOrEmpty(object obj) {
return obj == null
|| obj.ToString() == ""
|| obj.GetType().GetProperties().Any(prop => AnyNullOrEmpty(prop.GetValue(obj)));
}
To only check if all properties are null:
bool allPropertiesNull = !myObject.GetType().GetProperties().Any(prop => prop == null);
you can use reflection and extension methods to do this.
using System.Reflection;
public static class ExtensionMethods
{
public static bool StringPropertiesEmpty(this object value)
{
foreach (PropertyInfo objProp in value.GetType().GetProperties())
{
if (objProp.CanRead)
{
object val = objProp.GetValue(value, null);
if (val.GetType() == typeof(string))
{
if (val == "" || val == null)
{
return true;
}
}
}
}
return false;
}
}
then use it on any object with string properties
test obj = new test();
if (obj.StringPropertiesEmpty() == true)
{
// some of these string properties are empty or null
}
No, I don't think there is a method to do exactly that.
You'd be best writing a simple method that takes your object and returns true or false.
Alternatively, if the properties are all the same, and you just want to parse through them and find a single null or empty, perhaps some sort of collection of strings would work for you?
You can try the following query :
if the object is "referenceKey" (where few properties may be null )
referenceKey.GetType().GetProperties().Where(x => x.GetValue(referenceKey) == null)
I need to count the properties where the value is set to not Null, so I have used the following query :
var countProvidedReferenceKeys = referenceKey.GetType().GetProperties().Where(x => x.GetValue(referenceKey) != null).Count();
This is a simple example on how I update a value in the database:
var context = new dbEntities();
var car = context.CarTable.Where(p => p.id == id).FirstOrDefault();
car.Make = "Volvo";
context.SaveChanges();
However, what I need to do now is to get the property by name instead. So this is what I in theory would like to do:
var context = new dbEntities();
var car = context.CarTable.Where(p => p.id == id).FirstOrDefault();
**car["Make"] = "Volvo";**
context.SaveChanges();
Is this possible in EF?
I wouldn't use reflection since that would be slow.
You can use expression trees, especially if you cache the expressions. Check this link for an article about it. I would write a wrapper around the code in the article which takes an object and a propertyname (string), creates/caches the func using the code in the article (or retrieves it from the cache), and executes the func.
The main question is really why do you need this?
The best way is still car.Make = "Volvo";.
If string-name is strongly needed, you can use Reflection:
var property = typeof (Car).GetProperty("Make");
property.SetValue(car, "BMW", null);
Here are 2 drawbacks:
Slow.
Compiler cannot check the string.
The other way - you can use indexer and switch:
public class Car
{
public string Make { get; set; }
public string this[String name]
{
set
{
switch (name)
{
case "Make":
Make = value;
break;
...
}
}
}
}
And then just car["Make"] = "Volvo";
It's faster, but a typ-problem occurs: you have to parse strings or operate with objects.
public class Car
{
public string Make { get; set; }
public object this[string name]
{
get
{
var property = this.GetType().GetProperties().FirstOrDefault(p => p.Name.Equals(name));
if (property != null)
{
return property.GetValue(this, null);
}
return null;
}
set
{
var property = this.GetType().GetProperties().FirstOrDefault(p => p.Name.Equals(name));
if (property != null)
{
property.SetValue(this, value, null);
}
}
}
}