F# IEvent.create - f#

Where is it gone ?
let triggerFindNext,findNextEvent = IEvent.create<EventArgs>()
The field, constructor or member 'create' is not defined
maybe I must to add some Framework for it ?

The IEvent.create function has been deprecated. A new way of creating events is to create instance of the Event type. In the simplest case you can write just this:
let evt = new Event<EventArgs>()
// Trigger event (instead of first element of the tuple)
evt.Trigger()
// Returns IEvent<EventArgs> value (instead of second element of the tuple)
evt.Publish
This represents event using IEvent<_> value (and doesn't generate .NET compatible event if you expose it as a property) and it uses generic Handler<_> delegate from F# libraries.
(If you want to generate .NET compatible event usable from C# then you need to add CLIEvent attribute and you can use variant of Event that takes delegate as generic parameter as described in the answer already mentioned by others)
EDIT: I posted a more complete F# snippet (with nicer formatting) here: http://fssnip.net/1d

Related

FSharp GetGenericArguments().[0].Name returns T instead of actual type name

I'm having an issue trying to reflect over a generic argument in F#. I want to pass two types to a function: the first is the type I want to find implemented in another type (which is the 2nd parameter).
When I do this in C# I get the desired results. However when I do it in F# I get Type.Name = "T" instead of "SomeType". I have put together a Gist that hopefully illustrates what I'm trying to do (it's just a linqpad sample to show what I'm trying to do) in both C# and F#: https://gist.github.com/johnbfair/11263203
Why is the result of .GetGenericArguments.[0].Name = "T" instead of "MySample2" (which is what C# outputs)?
Looks like I was making the mistake of using "typedefof<>" instead of "typeof<>". Updated the gist accordingly.
To expand on the above:
When calling the function "typeImplements" I was passing in typedefof>. Unbeknownst to me typedefof doesn't include the type of the generic ('T) when interrogating the enclosing type (in this case MySample2). So if you want to get the actual type of the generic you need to use typeof>. This is the blog post that explained the difference to me: http://phosphor-escence.blogspot.com/2013/05/difference-between-typeof-and-typedefof.html
Before:
typeImplements typedefof<MySample2> typedefof<MySample1<MySample2>> |> Dump
After: typeImplements typeof<MySample2> typeof<MySample1<MySample2>> |> Dump

Looking for robust, general op_Dynamic implementation

I've not been able to find a robust, general op_Dynamic implementation: can anyone point me to one? So far searches have only turned up toys or specific purpose implementations, but I'd like to have one on hand which, say, compares in robustness to C#'s default static dynamic implementation (i.e. handle lots / all cases, cache reflection calls) (it's been a while since I've looked at C#'s static dynamic, so forgive me if my assertions about it's abilities are false).
Thanks!
There is a module FSharp.Interop.Dynamic, on nuget that should robustly handle the dynamic operator using the dlr.
It has several advantages over a lot of the snippets out there.
Performance it uses Dynamitey for the dlr call which implements caching and is a .NET Standard Library
Handles methods that return void, you'll get a binding exception if you don't discard results of those.
The dlr handles the case of calling a delegate return by a function automatically, this will also allow you to do the same with an FSharpFunc
Adds an !? prefix operator to handle invoking directly dynamic objects and functions you don't have the type at runtime.
It's open source, Apache license, you can look at the implementation and it includes unit test example cases.
You can never get fully general implementation of the ? operator. The operator can be implemented differently for various types where it may need to do something special depending on the type:
For Dictionary<T, R>, you'd want it to use the lookup function of the dictionary
For the SQL objects in my article you referenced, you want it to use specific SQL API
For unknown .NET objects, you want it to use .NET Reflection
If you're looking for an implementation that uses Reflection, then you can use one I implemented in F# binding for MonoDevelop (available on GitHub). It is reasonably complete and handles property access, method calls as well as static members. (The rest of the linked file uses it heavily to call internal members of F# compiler). It uses Reflection directly, so it is quite slow, but it is quite feature-complete.
Another alternative would be to implement the operator on top of .NET 4.0 Dynamic Language Runtime (so that it would use the same underlying API as dynamic in C# 4). I don't think there is an implementation of this somewhere out there, but here is a simple example how you can get it:
#r "Microsoft.CSharp.dll"
open System
open System.Runtime.CompilerServices
open Microsoft.CSharp.RuntimeBinder
let (?) (inst:obj) name (arg:'T) : 'R =
// Create site (representing dynamic operation for converting result to 'R
let convertSite =
CallSite<Func<CallSite, Object, 'R>>.Create //'
(Binder.Convert(CSharpBinderFlags.None, typeof<'R>, null)) //'
// Create site for the method call with single argument of type 'T
let callSite =
CallSite<Func<CallSite, Object, 'T, Object>>.Create //'
(Binder.InvokeMember
( CSharpBinderFlags.None, name, null, null,
[| CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) |]))
// Run the method and perform conversion
convertSite.Target.Invoke
(convertSite, callSite.Target.Invoke(callSite, inst, arg))
let o = box (new Random())
let a : int = o?Next(10)
This works only for instance method calls with single argument (You can find out how to do this by looking at code generated by C# compiler for dynamic invocations). I guess if you mixed the completeness (from the first one) with the approach to use DLR (in the second one), you'd get the most robust implementation you can get.
EDIT: I also posted the code to F# Snippets. Here is the version using DLR: http://fssnip.net/2U and here is the version from F# plugin (using .NET Reflection): http://fssnip.net/2V

What does [Bindable] mean in actionscript?

[Bindable]
/**
* Display output of video device.
*/
public var videoLocal : Video;
Anyone knows?
[Bindable] is a one of several meta tags that you can use in flex ActionScript code. It can be applied to properties, or methods that are marked in any scope. It cannot be used with static class members.
The key to using the [Bindable] meta tag is understanding what is going on under the hood when you use it. Essentially using data binding is a type of shorthand for adding event listeners and dispatching events.
There are two basic forms of the [Bindable] tag. The first is just [Bindable] followed by a var/property declaration. The Second is [Bindable(event="eventname")] followed by either a var/property declaration, a function/method declaration or one half of a getter/setter declaration.
I'll explain the longer notation first since the other builds on the same concept but with even more shorthand.
When you use [Bindable(event="eventname")] you are essentially telling the compiler that this var/property/function/method (call this the instance member) is 'available' to be used as the source for data binding. You are also telling it that when the value of the instance member has been invalidated/changed and it needs to be re-read that the "eventname" event will be dispatched.
In this longer form this all you are doing. You the developer are responsible for actually dispatching the "eventname" event whenever the value needs to be updated in the binding subscribers.
The real efficiency of using data binding comes on the subscribing side. The typical notation you will see in MXML is value="{instance.propertyName}" When you use the notation { } you are telling the compiler to do the following:
Create an event listener that listens to the event named in the bindable meta tag
In that event listener re-read the instance.propertyName and update this value
If you use the shorter form [Bindable], and you add the tag before a property/var, the compiler fills in the blanks and adds some additional functionality to make the property bindable. Essentially you are telling the compiler "add the events and methods you need to make this property bindable"
Now the way to think of what the compiler will do under the hood is this.
make a private version of your var
create an "event" to trigger the binding
create a getter function with scope and name of your original var that returns the private verson of the var when called.
create a setter function with scope and name of your original var that sets the private version of the var when called AND dispatches the triggering event.
In essence the compiler will do much of the work for you.
[Bindable]
public var xyz
is equivalent to
private var _xyz:String;
[Bindable(event="updateXYZValue")]
public function get xyz():String{
return _xyz;
}
public function set xyz(newxyz:String):void{
_xyz = newxyz;
dispatchEvent(new Event("updateXYZValue"));
}
The only functional differences in these is that in the first instance;
you do not know the name of the event that will be dispatched to trigger the binding
there is no way to update the underlying value without triggering the data binding
This second example also demonstrates one special case of the [Bindable] meta tag. This is that when you are applying it to a getter/setter pair defined for the same variable name you need only apply it to one or the other, it will apply to both. Typically you should set it on the getter.
You can use either notation on a function/method however if you do not specify an event the binding will never be triggered so if you are trying to bind to a function you should alway specify an event. It is also possible to specify more than one triggering event by stacking the tag. eg.
[Bindable(event="metaDataChanged")]
[Bindable(event="metaObjectUpdated")]
public function readMyMetaData():MetaDataObject{
var myMetaDataObject:MetaDataObject;
.
.
.
return myMetaDataObject;
}
This would presume that somewhere else you your class you will dispatch this metaDataChanged event or the metaObjectUpdated event when you want trigger the binding.
Also note that with this notation you can tie the binding of any instance member to any event that the instance will dispatch. Even inherited events that you yourself do not generate such as FrameEnter, OnChange, etc...
Data bindings can also be setup and destroyed during runtime. If you are interested in this take a look at the mx.binding.utils classes.
It is used in Databinding with Flex, you can read more about it here
http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_2.html
Creating properties to use as the source for data binding
When you create a property that you
want to use as the source of a data
binding expression, Flex can
automatically copy the value of the
source property to any destination
property when the source property
changes. To signal to Flex to perform
the copy, you must use the [Bindable]
data tag to register the property with
Flex.
As an addition to what Justin said, you can actually use two ways data binding in Flex with the # character. Here's an example:
<s:TextInput id="txt1" text="#{txt2.text}" />
For a working example with source code enabled you can check out this article I wrote a while back:
Two-ways data binding in Flex

How to implement custom events in F# on the compact framework?

I tried following the example given on MSDN, but my code does not compile on the compact framework. It does compile on the normal framework, though.
type StorageComponent(game) =
inherit GameComponent(game)
let title_storage_acquired_event = new Control.DelegateEvent<StorageEventHandler>()
Error message:
The type 'DelegateEvent' is not defined
Based on the hint from Brian, it looks that the types DelegateEvent<'Delegate> and Event<'Delegate, 'Args> are not supported on .NET Compact Framework. This would mean that you cannot declare an event that uses an explicitly specified delegate type.
However, you can still use the Event<'T> type which creates an event of type Handler<'T> (which is a generic delegate type representing methods with two parameters of types obj and 'T):
type StorageComponent(game) =
inherit GameComponent(game)
let titleStorageAcquiredEvent =
new Event<StorageEventArgs>()
[<CLIEvent>] // If you want to create C# compatible event
member x.TitleStorageAcquired =
titleStorageAcquiredEvent.Publish()
Assuming that the declaration of StorageEventHandler looks like this:
delegate void StorageEventHandler(object sender, StorageEventArgs args);
The example above should create more or less an equivalent code (with the only difference that it uses generic Handler<_> delegate type instead of your own StorageEventHandler).
If you take a look at the code in the CTP
C:\Program Files (x86)\FSharp-2.0.0.0\source\fsharp\FSharp.Core\event.fs
it will offer some clues (I'm guessing NETCF does not have del.DynamicInvoke). It might also offer clues as to what to do instead; I'm not sure, but hopefully someone else will chime in with a full answer.

Way to record changes to an object using F#

Is there a clever way to record changes made to an object in F#?
I have been researching F# as a way to build an object model that replicates itself over the network. One task I need to solve is how to detect changes made to objects so I can send only changes to clients
Note: I am looking for answers other than "implement INotifyPropertyChanged" or "do something that can easily be done in C#". If that is the only way to solve the problem in F# then F# is not the tool im looking for.
Why F#? Because I am not satisfied with the ways this state observer pattern is implemented in C#. Hence I am investigating if there is some elegant way to implement it in a dynamic language, starting with F#.
Instead of detecting and notifying changes as they happen, you could make your classes immutable (for example by using the standard immutable types like records and unions, or by making the object contain only immutable things). Then you could write a function that "diffs" two instances of a class, and have some agent that looks for changes on a schedule or based on some trigger and sends the diffs to the other end.
Because the data would be immutable, the agent would only need to retain a pointer to the version it last sent. The diffing function itself could either be written by hand for each class, which would allow for an efficient implementation that takes the properties of the data into account, or you could write a generic one using reflection.
An example of INotifyPropertyChanged use in F#.
type DemoCustomer() =
let mutable someValue = 0
let propertyChanged = Event<_, _>()
member this.MyProperty
with get() = someValue
and set(x) =
someValue <- x
propertyChanged.Trigger(this, PropertyChangedEventArgs("MyProperty"))
interface INotifyPropertyChanged with
[<CLIEvent>]
member this.PropertyChanged = propertyChanged.Publish
How about using the INotifyPropertyChanged interface? and raise events that cause the data to be replicated when it is changed?
I'd use a proxy library: Castle DynamicProxy, LinFu, Spring.NET, etc.
Using a proxy library you can easily implement INotifyPropertyChanged in a transparent, non-invasive way.
Can you use reflection to walk the object fields and see what changed? If they contain immutable F# data then equality checks will pick up the changes. You can then send the diffs relative to the last sent object.

Resources