SortedList porting to Silverlight - silverlight

It looks SortedList is excluded.. What do you think most appropriate out of existing collections? (to keep the same fast access and changes)
Can silverlight Dictionary be permanently sorted?
Best regards
VLK

I ported both the Wintellect Power Collections and the C5 Generic Collections to Silverlight. I made them available here - http://jaykimble.net/powercollections-and-c5-collections-for-silverlight4.aspx.
I did this mostly because this question peaked my interest. Feel free to use them in any type of project you would like to use them with.

To answer your question: No. The dictionary does not guarantee ordered items by key.
However the List<T> supports the BinarySearch method. This can help you acheive similar goals of the SortedList.
The documentation has a nice example of how that is basically acheived. See:-
List<T>.BinarySearch Method (T)

You might take a look at Wintellect's Power Collections. This library is free under the EPL. I think the OrderedMultiDictionary will do the trick for you. You should be able to compile this under Silverlight. I have not used this for a couple of years but did use this library (and Richter's threading library) for a WPF project.
Edit:
After playing around with this it looks like you will need to do a little work to get the power collections to work in Silverlight.

My workaround for not having silverlight was to create a generic list with a KeyValuePair type and then ordering the list.
List<KeyValuePair<int, string>> sampleList = new List<KeyValuePair<int, string>>();
//Assuming you have a set of objects in an array or list
foreach(var item in items)
{
sampleList.Add(new KeyValuePair<int, string>>(item.ID, item.Description))
}
sampleList = sampleList.OrderBy(data => data.Key).ToList();
The effect is the same as using a sorted list.

Related

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

WPF Tree Diagram Library?

Is there any reliable and free WPF library to create simple tree diagrams dynamically? I mean, all I want is something that would allow me to do that kind of pseudo-code:
Item item1 = new Item("Level 1");
Item item11 = new Item("Level 1.1");
Item item12 = new Item("Level 1.2");
Item item111 = new Item("Level 1.1.1");
item11.AddChild(item111);
item1.AddChild(item11);
item1.AddChild(item12);
And then to generate automatically the correspoding diagram:
Thank you.
I found this diagram solution and tinkered a bit in order to adapt it to my needs.
I'm kinda surprised there's no library to do so. Still looking for it :)
I've found this one pretty easy to use:
https://www.codeproject.com/Articles/29518/A-Graph-Tree-Drawing-Control-for-WPF
You can find an example how to use it in the downloaded zip file here:
SilverTreeContainer.zip\TreeContainer\TreeContainerTest\winTreeContainerTest.xaml
Later, I also found this article interesting:
How to easily draw graphs in WPF?
This is for Graph drawing in general, not specialized for Trees; but I've found the above link here as well (top rated answer, option 6)

WCF - Is it better to use IList / IDictionary instead of an Array?

What gives more performance?
Use normal arrays like string[]
Or is it better to use IList or IDictionary instead?
I would think the performance is identical - in the end, when the message is serialized into XML and sent across the wire, the XSD's capability of representing a list of elements is used, no matter which approach you use in your C# code.

Circular Linked List in Cocoa

Is there something similar to a circular linked list available in Cocoa?
I know that an NSArray is ordered - but I don't think I can use 'nextItem' or 'previousItem' - correct? Furthermore, I need the nextItem of the last item to be the first item.
I could add my own nextItem and previousItem methods, but I'm surprised if Apple haven't implemented something suitable already. I can't find it though if they have.
While you can certainly use a category to add the behavior to NSArray (as #darren suggests), it's possible that you might actually need a true circular buffer. If that's the case, check out the CHDataStructures framework. Besides a CHCircularBufferStack, there's also a CHCircularBufferQueue and a CHCircularBufferDeque.
I'm not aware of any such circular list data structure. Your idea about implementing it manually seems like a good idea. I would use a category:
#implementation NSArray (myCircularList)
-(id)nextItem;
-(id)previousItem;

How can I edit immutable objects in WPF without duplicating code?

We have lots of immutable value objects in our domain model, one example of this is a position, defined by a latitude, longitude & height.
/// <remarks>When I grow up I want to be an F# record.</remarks>
public class Position
{
public double Latitude
{
get;
private set;
}
// snip
public Position(double latitude, double longitude, double height)
{
Latitude = latitude;
// snip
}
}
The obvious way to allow editing of a position is to build a ViewModel which has getters and setters, as well as a ToPosition() method to extract the validated immutable position instance. While this solution would be ok, it would result in a lot of duplicated code, especially XAML.
The value objects in question consist of between three and five properties which are usually some variant of X, Y, Z & some auxiliary stuff. Given this, I had considered creating three ViewModels to handle the various possibilities, where each ViewModel would need to expose properties for the value of each property as well as a description to display for each label (eg. "Latitude").
Going further, it seems like I could simplify it to one general ViewModel that can deal with N properties and hook everything up using reflection. Something like a property grid, but for immutable objects. One issue with a property grid is that I want to be able to change the look so I can have labels and textboxes such as:
Latitude: [ 32 ] <- TextBox
Longitude: [ 115 ]
Height: [ 12 ]
Or put it in a DataGrid such as:
Latitude | Longitude | Height
32 115 12
So my question is:
Can you think of an elegant way to solve this problem? Are there any libraries that do this or articles about something similar?
I'm mainly looking for:
Code duplication to be minimized
Easy to add new value object types
Possible to extend with some kind of validation
Custom Type Descriptors could be used to solve this problem. Before you bind to a Position, your type descriptor could kick in, and provide get and set methods to temporarily build the values. When the changes are committed, it could build the immutable object.
It might look something like this:
DataContext = new Mutable(position,
dictionary => new Position(dictionary["lattitude"], ...)
);
Your bindings can still look like this:
<TextBox Text="{Binding Path=Lattitude}" />
Because the Mutable object will 'pretend' to have properties like Lattitude thanks to its TypeDescriptor.
Alternatively you might use a converter in your bindings and come up with some kind of convention.
Your Mutable class would take the current immutable object, and a Func<IDictionary, object> that allows you to create the new immutable object once editing completes. Your Mutable class would make use of the type descriptor, which would create PropertyDescriptors that create the new immutable object upon being set.
For an example of how to use type descriptors, see here:
http://www.paulstovell.com/editable-object-adapter
Edit: if you want to limit how often your immutable objects are created, you might also look at BindingGroups and IEditableObject, which your Mutable can also implement.
I found this old question while researching my possible options in the same situation. I figured I should update it in case anyone else stumbles on to it:
Another option (not available when Paul offered his solution since .Net 4 wasn't out yet) is to use the same strategy, but instead of implementing it using CustomTypeDescriptors, use a combination of generics, dynamic objects and reflection to achieve the same effect.
In this case, you define a class
class Mutable<ImmutableType> : DynamicObject
{
//...
}
It's constructor takes an instance of the immutable type and a delegate that constructs a new instance of it out of a dictionary, just like in Paul's answer. The difference here, however, is that you override the TryGetMember and TrySetMember to populate an internal dictionary that you're eventually going to use as the argument for the constructor-delegate. You use reflection in order to verify that the only properties that you're accepting are those that are actually implemented in ImmutableType.
Performance wise, I wager that Paul's answer is faster, and doesn't involve dynamic objects, which are known to put C# developers into fits. But the implementation for this solution is also a little simpler, because Type Descriptors are a bit arcane.
Here's the requested proof-of-concept / example implementation:
https://bitbucket.org/jwrush/mutable-generic-example
Can you think of an elegant way to solve this problem?
Honestly, you just dance around the problem, but don't mention the problem itself ;).
If I correctly guess your problem, then the combination of MultiBinding and IMultiValueConverter should do the trick.
HTH.
P.S. BTW, you have immutable class instances, not value objects. With value objects (which are described by struct keyword) you would dance much more no matter if there were setters or not :).

Resources