Can not fake guid properties using FakeO - c#

I am trying to use the library called FakeO (https://github.com/rally25rs/FakeO)
It works fine except when there is a Guid property. Anyone have an idea what I maybe doing wrong ?
Exceptin I get is : Object of type 'System.Int32' cannot be converted to type 'System.Guid'.
here is the code
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Get a single instance of an object");
var gud = Guid.NewGuid();
var obj1 = FakeO.Create.Fake<SampleClass>(
s => s.UniqueId = FakeO.Data.Random<Guid>(),
s => s.Id = FakeO.Number.Next(),
s => s.PhoneNumber = FakeO.Phone.Number(),
s => s.SomeString = FakeO.String.Random(50));
Console.WriteLine(obj1.ToString() + "\n");
IEnumerable<SampleClass> obj2 = FakeO.Create.Fake<SampleClass>(10, s => s.Id = FakeO.Number.Next(),
s => s.PhoneNumber = FakeO.Phone.Number(),
s => s.SomeString = FakeO.String.Random(50));
foreach (var obj in obj2)
Console.WriteLine(obj.ToString());
Console.ReadKey();
}
}
public class SampleClass
{
public int Id { get; set; }
public string SomeString { get; set; }
public string PhoneNumber { get; set; }
public Guid UniqueId { get; set; }
public override string ToString()
{
var output = "ID={0},SomeString ={1},PhoneNumber = {2}";
return String.Format(output, Id, SomeString, PhoneNumber);
}
}

Guid is value type, and the author did not handle unsupported ValueType properly. He returns 0 for all unsupported value types in the Data.Random method, which is not quite nice for any struct type. According to this StackOverflow question, the last lines of Data.Random should be fixed to
if(t.IsValueType)
{
return Activator.CreateInstance(t);
}
return null;
This will return default value for struct type, which is empty Guid in case of Guid type I believe. If you want to support Guid type, you can add it in Data.Random method just before the final check of ValueType:
if (t == typeof(Guid))
return Guid.NewGuid();
I did not test my solution, but it should do.

It looks like you should be using:
FakeO.Distinct.Guid()

Related

Predicate Problems For List Selection in C#

I have a curried typed-Lambda expression that I hoped would perform a selection and derive a unique element. Sadly there is a run-time exception.
Here is the code:
Entities relation = queryType(
"test-instances",
(new KeyValuePair<String, String>("cycle-id", testSetID))
);
Entity target = (relation.entities.ToList<Entity>()).Find(
//select entity with field 'name'
e => (e.fields.Find(
//and with non-epsillon value
f => !(f.values.Find(
//of value 'targetValue'
v => (v.value.Equals(targetValue))
).value.Equals(""))
)).name.Equals("name")
);
The definition for queryType():
private Entities queryType(String entitiesType, params KeyValuePair<String, String>[] values)
{
addStandardHeaders();
String query = parsePredicate(values);
Task<HttpResponseMessage> filterTask = client.GetAsync(client.BaseAddress + RESTapi.ALMentitiesQuery(domain, project, entitiesType, query));
Task.WaitAny(filterTask);
//Callback:
HttpResponseMessage result = filterTask.Result;
if (result.IsSuccessStatusCode)
{
updateCookies(client.BaseAddress + RESTapi.ALMentitiesQuery(domain, project, entitiesType, query));
mainHeaders.Clear();
Task<Stream> output = result.Content.ReadAsStreamAsync();
Task.WaitAny(output);
//Callback:
return (Entities)fromJSON(output.Result, typeof(Entities));
}
else
{
Exception exception = getException(result);
throw new HttpException(exception.Title);
return null;
}
}
The function parsePredicate() takes pairs () and encodes them into a predicate of a language the server understands.
The exception is that in the inner-most function; the bound-variable v is applied as null. e to f works though and the data-model I'm using is sound.
Any thoughts?
Here is the class for Entities:
public class Entities
{
public List<Entity> entities{get;set;}
public long totalResults{get;set;}
public Entities(){entities = new List<Entity>();}
}
public class Entity
{
public List<Field> fields { get; set; }
public Entity() { fields = new List<Field>(); }
}
public class Field
{
public String name { get; set; }
public List<Value> values { get; set; }
public Field() { values = new List<Value>(); }
}
public class Value
{
public String value{get;set;}
}

How to dynamically get a property value in which is in another property with Linq where statement

I have found some direction for this problem but have not found anything which I can apply to this problem.
I want to filter lists of different types by stated properties they hold. I can use linq to dynamically filter a List by Test.id but I cant manage to filter a List through MyClass.Name
I have these classes.
public class Test
{
public int Id { get; set; }
public MyClass myclass { get; set; }
}
public class MyClass
{
public string Name { get; set; }
}
This is what I'm trying to do.
static void Main(string[] args)
{
var source = new List<Test> {
new Test { Id = 1,myclass = new MyClass() { Name = "bob" } },
new Test { Id = 2,myclass= new MyClass() { Name = "joe" } } };
var x = myFilter(source,"Name", "bob");
Console.WriteLine(x.Count());
}
public static IEnumerable<T> myFilter<T>(List<T> source, string propertyName, string searchString)
{
// get the myclass property then the stated property(Name) value within it
searchString = searchString.ToLower();
return source.Where(s => (s.GetType().GetProperty("myclass")
.GetType().GetProperty(propertyName)
.GetValue(s.GetType().GetProperty("myclass"),null).ToString() ?? " ")
.ToLower().Contains(searchString));
}
The count return 0 when I am expecting 1. for Test.MyClass.Name = "bob"
Is there a solution for this or is there a better way to do it besides reflection?
Thanks
you need to use the PropertyType of the returned myclass property:
public static IEnumerable<T> myFilter<T>(List<T> source, string propertyName, string searchString)
{
// get the myclass property then the stated property(Name) value within it
searchString = searchString.ToLower();
return source.Where(s => (s.GetType().GetProperty("myclass")
.PropertyType.GetProperty(propertyName)
.GetValue(s.GetType().GetProperty("myclass").GetValue(s)).ToString() ?? " ")
.ToLower().Contains(searchString));
}
You should be able to use the following:
var count = source.Count(test =>
string.Compare(test.myClass.Name, "Bob",
StringComparison.CurrentCultureIgnoreCase) == 0);
This will compare the string value of the Name Property and only count where the name is equal to "bob" and it will ignore the case.
If you want to return the Test object instead then you can use the following
var results = source.Where(test =>
string.Compare(test.myClass.Name, "Bob",
StringComparison.CurrentCultureIgnoreCase) == 0);

Getting property description attribute

Existing code (simplified)
I have this function
public static string[] GetFieldNames<T>(IEnumerable<T> items)
where T : class
{
var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types
return properties.Select(p => p.Name).ToArray();
}
So if say I have this class
class MyClass {
public string Name { get; set; }
[Description("The value")]
public int Value { get; set; }
}
I can have code like this
List<MyClass> items = ...; // Populate items somehow
string[] fieldNames = GetFieldNames(items); // This returns ["Name", "Value"]
That works fine.
The problem
I need to get the Description (if it exists), so that GetFieldNames(items) returns ["Name", "The value"]
How do I modify the GetFieldNames() function to read the Description attribute if it exists?
(Please note that this function has been simplified, the real function is much more complex, so please avoid changing the logic)
This should work for you:
return properties.Select(p =>
Attribute.IsDefined(p, typeof(DescriptionAttribute)) ?
(Attribute.GetCustomAttribute(p, typeof(DescriptionAttribute)) as DescriptionAttribute).Description:
p.Name
).ToArray();
NOTE: just add using System.Reflection as GetCustomAttribute is an extension method in .Net 4.5
public static Tuple<string,string>[] GetFieldNames<T>(IEnumerable<T> items) where T : class
{
var result =
typeof (T).GetProperties()
.Where(p => SystemTypes.Contains(p.PropertyType) &&p.GetCustomAttribute<DescriptionAttribute>() != null)
.Select(
p =>
new Tuple<string, string>(p.Name,
p.GetCustomAttribute<DescriptionAttribute>().Description));
return result.ToArray();
}
for earlier version of .Net framework we can use this extension method:
public static class Extension
{
public static T GetCustomAttribute<T>(this System.Reflection.MemberInfo mi) where T : Attribute
{
return mi.GetCustomAttributes(typeof (T),true).FirstOrDefault() as T;
}
}
This is a generic function you can make use of, if the fieldName has description tag attribute it return the value otherwise it return null.
public string GetDescription<T>(string fieldName)
{
string result;
FieldInfo fi = typeof(T).GetField(fieldName.ToString());
if (fi != null)
{
try
{
object[] descriptionAttrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
DescriptionAttribute description = (DescriptionAttribute)descriptionAttrs[0];
result = (description.Description);
}
catch
{
result = null;
}
}
else
{
result = null;
}
return result;
}
Example:
class MyClass {
public string Name { get; set; }
[Description("The age description")]
public int Age { get; set; }
}
string ageDescription = GetDescription<MyClass>(nameof(Age));
console.log(ageDescription) // OUTPUT: The age description
I am using Description attribute a lot so I wrote Nuget for this purpose.
With it you could just call:
typeof(TestClass).GetPropertyDescription("PropertyName");
It also allows to take DescriptionAttribute from class, field, enum and method.
use GetCustomAttributes Method
static void attributecheck()
{
var props = typeof(Product).GetProperties();
foreach (var propertyInfo in props)
{
var att = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (att.Length >0)
{
}
}
}

How to get class and property names and values from undeclared type

If I have these two classes:
public class A
{
public int Id { get; set; }
}
public class B
{
public string Name { get; set; }
}
Can I use a generic method like this:
public void InitMethod(object classProperty)
To pass in data like this:
var a = new A() { Id = 1 };
var b = new B() { Name = "John" };
InitMethod(a.Id);
InitMethod(b.Name);
And get the following information from within the method:
Class name (ex: "A", "B")
Property name (ex: "Id", "Name")
Property value (ex: 1, "John")
Sort of, although it may be more trouble than it is worth.
ASP.Net MVC frequently uses expressions to get at property info in a strongly-typed fashion. The expression doesn't necessarily get evaluated; instead, it is parsed for its metadata.
This isn't specific to MVC; I mention it to cite an established pattern in a Microsoft framework.
Here's a sample that gets a property name and value from an expression:
// the type being evaluated
public class Foo
{
public string Bar {
get;
set;
}
}
// method in an evaluator class
public TProperty EvaluateProperty<TProperty>( Expression<Func<Foo, TProperty>> expression ) {
string propertyToGetName = ( (MemberExpression)expression.Body ).Member.Name;
// do something with the property name
// and/or evaluate the expression and get the value of the property
return expression.Compile()( null );
}
You call it like this (note the expressions being passed):
var foo = new Foo { Bar = "baz" };
string val = EvaluateProperty( o => foo.Bar );
foo = new Foo { Bar = "123456" };
val = EvaluateProperty( o => foo.Bar );
In this example you need to pass object to InitMethod not property of that object, maybe it will be OK.
class Program
{
static void Main(string[] args)
{
InitMethod(new A() { Id = 100 });
InitMethod(new B() { Name = "Test Name" });
Console.ReadLine();
}
public static void InitMethod(object obj)
{
if (obj != null)
{
Console.WriteLine("Class {0}", obj.GetType().Name);
foreach (var p in obj.GetType().GetProperties())
{
Console.WriteLine("Property {0} type {1} value {2}", p.Name, p.GetValue(obj, null).GetType().Name, p.GetValue(obj, null));
}
}
}
}

Adding an object to a dictionary... but testing for partial uniqueness

I have the following object and I want a dictionary to conditionally determine if there is a duplicate. For example, in one dictionary I only care about two properties being unique for my key. In a second dictionary, I want all the properties being unique for the key.
Question 1:
What interfaces should I override to accomplish this? (e.g. GetHashCode, IEqualityComparer, equals operator)
Question 2:
What should I do if I change a property that ultimately changes the value of the key? This is probably more relevant if I do an Dictionary since .NET framwork somehow handles this for me, but I never thought about it.
Code
public class EventData : IEqualityComparer<EventData>
{
public string ComputerName { get; set; }
public Guid? CategoryName { get; set; }
public string LogName { get; set; }
public int EventID { get; set; }
public long? EventUniqueTracker { get; set; }
public DateTime LastQueryDate { get; set; }
public DateTime? DateOfRecord { get; set; }
//public int QueryCount { get; set; }
public int QueryCount = 0 ;//
public string zData { get; set; }
public EventData(string computerName, Guid? categoryName, string logName, int eventID, long? eventUniqueTracker, int queryCount)
{
ComputerName = computerName;
CategoryName = categoryName;
LogName = logName;
EventID = eventID;
EventUniqueTracker = eventUniqueTracker;
LastQueryDate = DateTime.Now;
QueryCount = queryCount;
}
public EventData()
{
}
public override int GetHashCode()
{
return GetHashCode(HashType.ZCompCatLogEventAllData);
}
public object GetString(HashType hType)
{
switch (hType)
{
case HashType.AComputerName:
return ComputerName;
break;
case HashType.BCompAndCat:
return new { A = ComputerName, B = CategoryName };
break;
case HashType.CCompCatLog:
return new { A = ComputerName, B = CategoryName, C = LogName };
break;
case HashType.DCompCatLogEvent:
return new { A = ComputerName, B = CategoryName, C = LogName, D = EventID };
break;
case HashType.ECompCatLogEventUserDefined1:
case HashType.FCompCatLogEventUserDefined2:
case HashType.ZCompCatLogEventAllData:
return new { A = ComputerName, B = CategoryName, C = LogName, D = EventID, E = EventUniqueTracker };
default:
break;
}
return new object { };
}
public int GetHashCode(HashType hType)
{
return GetString(hType).GetHashCode();
return 1;
}
public override string ToString()
{
return ComputerName + " " + CategoryName + " " + LogName + " " + EventID + " " + EventUniqueTracker;
}
public bool Equals(EventData x, EventData y)
{
return x.ComputerName == y.ComputerName &&
x.CategoryName == y.CategoryName &&
x.LogName == y.LogName &&
x.EventID == y.EventID &&
x.EventUniqueTracker == y.EventUniqueTracker;
}
public int GetHashCode(EventData obj)
{
EventData ci = (EventData)obj;
// http://stackoverflow.com/a/263416/328397
return new { A = ci.ComputerName, B = ci.CategoryName, C = ci.LogName, D = ci.EventID, E = ci.EventUniqueTracker }.GetHashCode();
}
}
It sounds like you should be implementing IEqualityComparer<EventData> - but not within EventData itself. Create two separate implementations - one for the first notion of equality, and one for the second. Then create your dictionaries as:
var first = new Dictionary<EventData, string>(new PartialDataEqualityComparer());
var second = new Dictionary<EventData, string>(new FullDataEqualityComparer());
Or perhaps you want to treat the second case as the "natural" equality for EventData, in which case you could make EventData implement IEquatable<EventData> and not specify a comparer when creating the second dictionary.
Basically, you implement IEquatable<T> to say "an instance of this type is capable of comparing itself against an instance of T" whereas you implement IEqualityComparer<T> to say "an instance of this type is capable of comparing any two instances of T".
What should I do if I change a property that ultimately changes the value of the key?
You're stuffed, basically. You won't (or at least probably won't) be able to find that key again in your dictionary. You should avoid this as carefully as you possibly can. Personally I usually find that classes which are good candidates for dictionary keys are also good candidates for immutability.

Categories