FsCheck: Generate Arbitrary of a ArrayList with its elements as Arbitraries in C# - fscheck

I am using FsCheck in C#, I want to generate Arbitrary of an ArrayList to do PropertyBasedTesting by having 100's of ArrayList. I have this ArrayList with defined Arbitraries (they cannot be changed) for each element in it -
E.g.
System.Collections.ArrayList a = new System.Collections.ArrayList();
a.Add(Gen.Choose(1, 55));
a.Add(Arb.Generate<int>());
a.Add(Arb.Generate<string>())
How do I get an Arbitrary of this ArrayList?

Based on the example linked by Mark Seemann I created a complete compiling example. It doesn't provide much extra compared to the link, but it won't risk being broken in the future.
using System.Collections;
using FsCheck;
using FsCheck.Xunit;
using Xunit;
public class ArrayListArbritary
{
public static Arbitrary<ArrayList> ArrayList() =>
(from e1 in Gen.Choose(1, 15)
from e2 in Arb.Generate<int>()
from e3 in Arb.Generate<string>()
select CreateArrayList(e1, e2, e3))
.ToArbitrary();
private static ArrayList CreateArrayList(params object[] elements) => new ArrayList(elements);
}
public class Tests
{
public Tests()
{
Arb.Register<ArrayListArbritary>();
}
[Property]
public void TestWithArrayList(ArrayList arrayList)
{
Assert.Equal(3, arrayList.Count);
}
}

Related

With json.net, is there a shortish way to manipulate all string fields?

Given an arbitrary Newtonsoft.Json.Linq.JObject, if you want to apply some function to all string values that appear in it (wherever that may be) - whether as a basic value of a property, or in an array in the json, what would be the best way to do this?
One simple way to do this is to use JContainer.DescendantsAndSelf() to find all descendants of the root JObject that are string values, then replace the value with a remapped string using JToken.Replace():
public static class JsonExtensions
{
public static JToken MapStringValues(this JContainer root, Func<string, string> func)
{
foreach (var value in root.DescendantsAndSelf().OfType<JValue>().Where(v => v.Type == JTokenType.String).ToList())
value.Replace((JValue)func((string)value.Value));
return root;
}
}
Then use it like:
jObj.MapStringValues(s => "remapped " + s);

Using HQL to query on a Map's Values

Let's say I have a map (call it myClass.mapElem<Object, Object>) like so:
Key Val
A X
B Y
C X
I want to write HQL that can query the Values such that I can get back all instances of myClass where mapElem's value is 'X' (where 'X' is a fully populated object-- I just don't want to go through each element and say x.e1 = mapElem.e1 and x.e2=... etc). I know I can do this for the keys by using where ? in index(myClass.mapElem), I just need the corresponding statement for querying the values!
Thanks in advance...
ETA: Not sure if the syntax makes a difference, but the way I am actually querying this is like so:
select myClass.something from myClass mc join myClass.mapElem me where...
You should use elements(). I tried simulating your example with the following class
#Entity
#Table(name="Dummy")
public class TestClass {
private Integer id;
private Map<String, String> myMap;
#Id
#Column(name="DummyId")
#GeneratedValue(generator="native")
#GenericGenerator(name="native", strategy = "native")
public Integer getId() {
return id;
}
#ElementCollection
public Map<String, String> getMyMap() {
return myMap;
}
public void setId(Integer id) {
this.id = id;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
}
And persisted a few instances, which constain maps of a similar structure to what you have in your example. (using < String, String > since the values in your example are strings)
The following query gives me all instances of TestClass, where the map contains a specific value
SELECT DISTINCT myClass
FROM TestClass myClass JOIN myClass.myMap myMap
WHERE ? in elements(myMap)
In my particular case, I ended up having to use an SQL query. Not ideal, but it worked.

IComparer<> and class inheritance in C#

Is there any way to implement specialized IComparer for the base class type so a child class could still use it for sorting in speciliazed collections?
Example
public class A
{
public int X;
}
public class B:A
{
public int Y;
}
public AComparer:IComparer<A>
{
int Compare(A p1, A p2)
{
//...
}
}
so following code will work:
List<A> aList = new List<A>();
aList.Sort(new AComparer());
List<B> bList = new List<B>();
bList.Sort(new AComparer()); // <- this line fails due to type cast issues
How to approach this issue to have both - inheritance of sorting and specialized collections (and do not copy IComparer classes for each of children classes?
Thanks in advance!
Firstly, note that this is fixed in .NET 4 via generic contravariance - your code would simply work. EDIT: As noted in comments, generic variance was first supported in CLR v2, but various interfaces and delegates only became covariant or contravariant in .NET 4.
However, in .NET 2 it's still fairly easy to create a converter:
public class ComparerConverter<TBase, TChild> : IComparer<TChild>
where TChild : TBase
{
private readonly IComparer<TBase> comparer;
public ComparerConverter(IComparer<TBase> comparer)
{
this.comparer = comparer;
}
public int Compare(TChild x, TChild y)
{
return comparer.Compare(x, y);
}
}
You can then use:
List<B> bList = new List<B>();
IComparer<B> bComparer = new ComparerConverter<A, B>(new AComparer());
bList.Sort(bComparer);
EDIT: There's nothing you can do without changing the way of calling it at all. You could potentially make your AComparer generic though:
public class AComparer<T> : IComparer<T> where T : A
{
int Compare(T p1, T p2)
{
// You can still access members of A here
}
}
Then you could use:
bList.Sort(new AComparer<B>());
Of course, this means making all your comparer implementations generic, and it's somewhat ugly IMO.

Elegant way to bind html radio buttons <=> Java enums <=> mysql enums in Play?

The Goal is to have a list of options (that a user can chose through radio buttons) in one place(for eg: a yaml config file). No other place should have this list hard-coded
I've done something similar to create select elements, and I think enums worked just fine. Doing radio buttons should be very similar. I've set it up so that the labels can be defined in the messages file. I'm going to try to excerpt the relevant portions from my larger auto-form-generation code (using FastTags) the best I can. It's a bit heavy for this one case but it makes sense in the larger system.
I use the tag like #{form.selector 'order.status' /}, which looks find the variable named order in the template, sees that status is declared as public Status status, and then goes to find all the values of the Status enum and generate options for them in the select element.
First, I use a FieldContext object which just contains a bunch of info that's used by the other code to determine what to generate along with some utility methods:
public class FieldContext {
public final Map<?,?> args;
public final ExecutableTemplate template;
public final int fromLine;
public Class clazz = null;
public Field field = null;
public Object object = null;
public Object value = null;
private Map<String,String> attrs = new HashMap<String,String>();
private Map<String,Boolean> printed = new HashMap<String,Boolean>();
private List<Option> options;
...
Then I have this in another helper class (its info gets added to the FieldContext):
public List<Option> determineOptions(FieldContext context) {
List<Option> options = new ArrayList<Option>();
if (context.field.getType().isEnum()) {
for (Object option : context.field.getType().getEnumConstants()) {
options.add(new Option(option.toString(), Message.get(option.toString())));
}
}
return options;
}
then the tag declaration is
public static void _selector(Map<?,?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
String field_name = args.get("arg").toString();
TagContext.current().data.put("name", field_name);
SelectHelper helper = HelperFactory.getHelper(SelectHelper.class);
try {
FieldContext context = new FieldContext(field_name, args, template, fromLine);
helper.autoconfigure(context);
TagContext.current().data.put("selected", helper.determineValue(context));
out.print("<div class=\"formutil-field formutil-selector\">");
out.print("<label for=\"" + context.getAttr("id") + "\">");
out.print(helper.findOrCreateLabel(context));
out.print("</label>");
out.print("<select");
context.printAttribute(out, "id", "name");
out.print(">");
if (context.hasOptions()) {
for (Option option : context.getOptions()) {
out.print("<option value=\"" + option.value + "\">" + option.label + "</option>");
}
}
out.print("</select>");
context.printErrorIfPresent(out);
context.printValidationHints(out);
out.println("</div>");
}
...
}

Iterate through Custom Object's Property Names and Values

I'm trying to create an export Excel/CSV function that will iterate through a custom object and first output the property names and then output the values. I want to use reflection only where necessary so I'm attempting to save the property names when I output the headers and then reuse them to print the values.
Is this possible? I'm a little weary of using reflection in a loop but is there a better way?
Psuedo Code:
Dim Cust1 = New Customer("Tom", "123 Main Street")
Dim Cust2 = New Customer("Mike", "456 Main Street")
Dim Cust3 = New Customer("Joe", "789 Main Street")
Dim CustList As New Arraylist()
CustList.Add(Cust1)
CustList.Add(Cust2)
CustList.Add(Cust3)
CSVExport(CustList, New Customer())
Function CSVExport(List As ArrayList, CustomObject as Object) As StringWriter
Dim sw as Stringwriter
dim proplist as arraylist
'output header
Foreach CustProperty as System.Reflection.PropertyInfo CustomObject.GetType().GetProperties()
proplist.add(CustProperty.Name)
sw.write(CustProperty + ",")
EndFor
'output body
'??
'?? Here I'd like to loop through PropList and List instead of using reflection
'??
Return Sw
End Function
Its all reflection regardless of whether or not you have the names stored in a list.
Do you have a degree of control over the CustomObject. You could store the info within the CustomObject and query that info instead without using reflection. For instance, this is the code I use for my basic domain objects.
public class DomainObject
{
private HashTable _values = new HashTable();
public HashTable Properties
{
get
{
return _values;
}
}
protected void SetValue<T>(string property, T value)
{
if (_values.ContainsKey(property))
{
_values[property] = value;
}
else
{
_values.Add(property, value);
}
}
protected T GetValue<T>(string property)
{
if (_values.ContainsKey(property))
{
return (T)_values[property];
}
else
{
return default(T);
}
}
}
public class TootsieRoll : DomainObject
{
public string Size
{
get { return GetValue<string>("Size"); }
set { SetValue<string>("Size",value); }
}
public string Flavor
{
get { return GetValue<string>("Flavor"); }
set { SetVlaue<string>("Flavor", value); }
}
public int Ounces
{
get { return GetValue<int>("Ounces"); }
set { SetValue<int>("Ounces", value); }
}
}
Now your CSV code would only need to access and loop through the Key=>Value pairs within the "Properties" HashTable it inherited from the DomainObject to get the names and values. But obviously this only works if you have a level of control over your objects necessry to make them inherit from the DomainObject, and it wouldnt involve 30 years of drugery to rewrite all your property accessors. If that is the case, then reflection is your way to go.
In your Pseudo Code you're already populating an arraylist using reflection. If all you want to do is loop through the ArrayList, you can have a look at the ArrayList Class MSDN entry. It shows how to implement IEnumerable to iterate your array list, e.g:
Dim obj As [Object]
For Each obj In CType(myList, IENumberable)
Console.Write(" : {0}", obj)
Next obj
That's untested as is, I'm not sure if it should be CType(myList, IENumberable) or DirectCast(myList, IENumberable).
There is another option, using Object Serialization in VB.Net, a road far less traveled (at least around our offices).

Resources