AppEvents - Do stuff when things happen (WP7)

Posted by on

Open Source

Ever wanted an easy way for apps to track certain events then run code based off what events the user has triggered? Well now you can with AppEvents!

So AppEvents is a Windows Phone 7 library to manage events for a user across multiple sessions. In this example I will use it with CodeTrack to prompt the user to rate the app after they have added 3 repos.

Lets get started, App.xaml.cs (this code can be put anywhere in the app but I felt this was better to be done at the start of the app)

public App()
{
    ...
    EventClient.New()
        .Add(RuleSet.When("rate-app",
            el => el.Any(e => e.Name == "addrepo" && e.Occurrrences.Count > 2))
            .Do(r => AskToRate())
        );
}

Now lets break that down, first we have the New() function being called, this creates the instance (and sets the Current singleton in the EventClient class). It also uses the default JsonEventStorageProvider to store the EventStore data, this can be overwritten with a type parameter on the new function:

EventClient.New<MyCustomEventStoreage>()

Now this is where the RuleSets are added to the client using RuleSet.When() The first parameter of this function is a name of the rule. This is mainly to keep track of the rule and make sure we don’t run it twice. The second parameter is a Func<UserEventList, bool> which means we can create lamba expressions to be run against the UserEventList object, this expression tells the RuleSet when it should fire its Do Action.

    .Add(RuleSet.When("rate-app",
        el =&gt; el.Any(e =&gt; e.Name == "addrepo" &amp;&amp; e.Occurrrences.Count &gt; 2))
        .Do(r =&gt; AskToRate())
    );

So where do I get it?

The last part to this is firing off the events this part is very simple.

    EventClient.Current.Fire("addrepo");

And thats pretty much it, the library then does the rest

The library also allows for manual checking of events if for instance you fire an event on a page but want the RuleSet to be executed on a different page. To do this we simply add a false optional parameter to the Fire method to stop it running the RuleSets with the event. We can also manually run rules, either singly by the RuleSet name or all the rules in the list. We can also set the EventClient to not save the EventStore using the provider each time (and just have it saved later for performance).

EventClient.Current.Fire("addrepo", false);
EventClient.Current.Fire("addrepo", false, false);
EventClient.Current.RunRule("rate-app");
EventClient.Current.RunRules();
EventClient.Current.SaveEventStore();

So where do I get it?

The project if on GitHub for your forking, issues and discussions.AppEvents on Github.

Windows Mobile 6: Legacy

I have also made a Windows Mobile 6 version of this library but haven't actively tested it too much, if you feel like giving it a go be sure to let me know how you go.