Mariano Ravinale's Blog

Sharing Experiences

Archive for the ‘Silverlight’ Category

Working with MvvmLight and Ninject cool extensions

with one comment

Today I would like to share some cool stuff that you can do with MvvmLight and Ninject extensions,

Other objective of this article is to show how to implement in a very quick way(easy steps) the AOP IANPC Interception (actions to be executed before or after the execution of every call to a method in our code) provided by Ninject Extensions(DI/Ioc) applied in the implementation of the interface INotifyPropertyChange as a simple atribute.

in other words :

We are going to change this code:

      public class SomeViewModel : ViewModelBase {

           private ObservableCollection<Item> _listCollection;
           public ObservableCollection<Item> ListCollection {
               get {
                   return _listCollection;
               set {
                   _listCollection = value;

To this code:

       public class SomeViewModel : AutoNotifyViewModelBase {

           public virtual ObservableCollection<Item> ListCollection { get; set; }


A little of history and motivation first:

I’ve been doing some experiments with AOP, and then I saw a really nice article in code project about using Aspects applied to INotifyPropertyChanged (INPC), but I didn’t see a Ninject implementation so as always I’ve started to google about it.

What I saw was a gret article of Jonas Follesoe talking about using dynamic proxy for automatic INPC with Ninject I really recomend to read that post and download the project.

Reading article you can see that Ian Davis, the owner of interseption-extension for Ninject, contacted Jonas, and then he made his own adaptation of automatic INPC(IANPC) another great article

After couple week I had some free time and I wanted to see the source, of Ian davis project, and realised that the code of the IANPC was already inside, so I’ve started to make it work for share with you.

Let’s start to see the implementation:

First step is download the assemblies that we need:

Get Silverlight Ninject asemblies from GitHub.

Get Common Service locator from codeplex.

Ones that we finished to add all references to the project, let’s get to work!

In this example we are going to fill a List(Flick Behavior) with some mock items and add some effects.

Add a new Class named IocContainer.cs


Add the binding for each instance that you need in your project, as an example I’ve made some bindings for the main instance that I need to use:

public class IocContainer : NinjectModule {

       public override void Load() {






Add the Ioc Initialization into the app, Adding The Bootstrapper

    public class Bootstrapper
        private static IKernel Container { get; set; }

        public static void Initialize()
            Container = new StandardKernel(new DynamicProxy2Module(), new IocContainer());
            ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(Container));

        public static void ShutDown()

The normal implementation of this would be something like this:

var kernel = new StandardKernel(new IocContainer());

But we need to create proxies in order to do the Interception to our virtual members, that’s way we’ve added the new instance of DynamicProxy2Module, and way we need the reference to Castle.Core assembly.

Let’s do the last and important part of IANPC , the atribute NotifyOfChanges 🙂


public virtualObservableCollection<Item> ListCollection { get; set; }

But we need to implement the Interface IAutoNotifyPropertyChanged from Ninject.Extensions.Interseption in our view model otherwise it won’t work, but in MvvmLight we have a ViewModelBase with a diferent contract implementation instead to use OnPropertyChanged MvvmLight uses RaisePropertyChanged shit!!, I’ve been forced to create a new class, AutoNotifyViewModelBase that implements IAutoNotifyPropertyChanged and mvvm methods.

Implement the interface IAutoNotifyPropertyChanged in this case is already implmented in AutoNotifyViewModelBase .

public class MainViewModel : AutoNotifyViewModelBase {

       public virtual ObservableCollection<Item> ListCollection { get; set; }


So far we have develop all things required to retrieve data from a service and fill our List Collection, we have the infrastructure using Ninject Ioc, and the interception IANPC Atributes cool right.

May the code be with you!

Mariano Ravinale.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License


Written by @mravinale

febrero 18, 2011 at 8:15 pm

Publicado en Silverlight

Flick Behavior – Using a SL Listbox control as you do on WP7

with 3 comments

Working with Windows Phone 7, I get used to handle the ListBox control using that flickering efect with my mouse, then I’ve started to seek on the web for some control in Silverlight that imitates the same behavior, and I’ve found the Sasha Barber’s web,  who built a Creating A Scrollable Control Surface In WPF with a nice efect and a very cool way to do the maths and calculate the speed and distance.

So I’ve started to make it work in Silverlight as a user control, the first drop worked, but I made it using a ScrollViewer and ItemsControl, as this example:

<Grid x:Name=”LayoutRoot”>
ScrollViewer x:Name=”MyScrollViewer”Margin=”0″Background=”White”


            <ItemsControl x:Name="itemsControl"
                ItemTemplate="{StaticResource ItemTemplate}"
                ItemsSource="{Binding DataSource, ElementName=userControl}" />


but I didn’t like it, because the listbox it is more popular, and it has already a ScrollViewer and the ItemsPresenter as a Template, but it was ok, so far I’ve learned that the key is handle the MouseLeftbuttonDown , MouseLeftButtonUp and Mousemove events, to do the Maths.

So now what I’ve got to do is create a behavior for the ListBox, navigate inside the template, and get attached to the events mentionated before.

yap,but how can I find the ItemsPresenter within the ListBox?,the answer would be with the findByType<T> method, inspired by the XamlQuery library, with some magic to make it portable 😉

protected IEnumerable<DependencyObject> FindByType<T>(DependencyObject control) where T : class {
  var childrenCount = VisualTreeHelper.GetChildrenCount(control);
  for (var index = 0; index < childrenCount; index++) {
      var child = VisualTreeHelper.GetChild(control, index);
      if (child is T) yield return child;
      foreach (var desc inFindByType<T>(child)) {
        if (desc is T) yield return desc;

And now let’s find the scrollViewer and the ItemsPresenter inside the ListBox.

MyScrollViewer = FindByType<ScrollViewer>(AssociatedObject).ToList().First() as ScrollViewer;
MyItemPresenter = FindByType<ItemsPresenter>(AssociatedObject).ToList().First() as ItemsPresenter;

Yea!, so far so good, now I’ve got the main controls for the LisBox, and now let’s try to do the same that I did with the user control. but the problem was that the MouseLeftButtonDown didn’t work beacuse the event was toked by it’s parent in this case Listbox for the  SelectionChanged event so the trick is to add handlers:

                           new MouseButtonEventHandler(ItemPresenter_MouseLeftButtonDown), true);
                           new MouseButtonEventHandler(ItemPresenter_MouseLeftButtonUp), true);

Ok, now lets handle the events: first let’s track the mouse position, and calculate the desviation between the last point that it has been captured, and the current,so the follow event will be in charge of that:

private void AssociatedObject_MouseMove(object sender, MouseEventArgs e) {

   if (IsMouseCaptured ) {
      CurrentPoint = new Point(e.GetPosition(AssociatedObject).X,
      var delta = new Point(ScrollStartPoint.X - CurrentPoint.X,
                            ScrollStartPoint.Y - CurrentPoint.Y);

      ScrollTarget.X = ScrollStartOffset.X + delta.X / Speed;
      ScrollTarget.Y = ScrollStartOffset.Y + delta.Y / Speed;


And now let’s take a look to the events in charge to do the capture of the mouse clicks and points:

private void ItemPresenter_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {

    ScrollStartPoint = new Point(e.GetPosition(AssociatedObject).X,
    ScrollStartOffset.X = MyScrollViewer.HorizontalOffset;
    ScrollStartOffset.Y = MyScrollViewer.VerticalOffset;

    IsMouseCaptured = !IsMouseCaptured;


private void ItemPresenter_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {

    IsMouseCaptured = !IsMouseCaptured;

Take a look to this video Introducing the behavior.

if you are interested to see how it works take a look to this video

remember to visit Michael’s page for see how to create sample datasource

you’re free to grab the code and see how it was built, whith this post I’ve tried to share with you the journey making this component, and I really hope, that you may find this control useful and you may improve it for your own needs.

See it in action and download In expression Blend Gallery!

may the code be with you.

Mariano Ravinale

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License

Written by @mravinale

noviembre 14, 2010 at 2:40 am

Publicado en Silverlight

Using Ria Services Soap and Windows Phone 7

with 4 comments

I remember last year or so at this time, I began to glimpse Ria Services, from that preview so far Ria Services grew strongly and became something more just than a framework for creating applications RAD (Rapid Application Development) for Silverlight.

Ria Services initially was conceived  to expose our business logic as a service, taking as a model our data access layer of EF, and get our domain in a client-side context to work with Silverlight in a dynamic manner, facilitating thus the development and access to data.

However for large scale applications we may have other requirements, such as: Exposing our services in a way that they can be consumed from other systems, or decouple the business logic from the services, to make it interchangeable or use other tools like workflow in the same, and/or perhaps also to decouple the data access layer to use other ORM than EF .

For both problems there are solutions that Ria Services team has implemented in order to continue using the facilities that it has given us working on Silverlight.
For now we will focus on the first problem, the interaction with other systems in the next article I`ll deal with the decoupling between layers.

With a friend we’ve share a vision of using RIA Services for an application that could access these services from external system in this case Windows 7 Phone!!!.

Make sure we have the latest version of Ria Services:

1. First of all we need to create a Web application in Asp.Net as Empty.

2. In this case, we can designate it as “SoapRiaService”.

3. Add a database where we will test our Employee table .

4. Then select Entity Framework 4 new item and write it the database conection name, you could use “SoapTestDbEntities”.

5. For this test and for now we will take the Employees table to create our mapping


6. Ok, we already have our entity Employee in our ORM. Now we need to do a solution build.

7. As a next step we need to create our domain service and get the interface for the basic CRUD operations in order to make it accessible to our client.
To achieve this we need to add a new component called Domain Service Class that is our Ria Service. In this case we may call it “EmployeeDomainService”.

8.  When we add a Domain Services class  using the wizard we can choose the entity that we need to apply the editing operations from the context of EF.
Choose properties enabling editing metadata generation, which will allow us to access the properties of validation of the entity, and also choose to expose an endpoint of Odate (REST)

9. For each method we add the decorator [invoke] in that way we generate the corresponding proxy methods in the client.

10) The Namespace and DomainServiceNameClass, give us a clue to find out the generated WCF service. The service address is:
1. http:// [host: port] / Services / [namespace] – [DomainServiceNameClass]. svc (the ‘.’ are replaced by ‘–’ )
2. Example: http://localhost:37390/Services/SoapRiaService-EmployeeDomainService.svc

11. Now we need to add the endpoint to access the SOAP services, if we do not want a REST enpoint , just remove the OData endpoint.

12. Having all the logic and configuration ready in our application we need to make sure to add the library Microsoft.ServiceModel.DomainServices.Hosting.dll address shown below.
But you have this path, be sure to install or reinstall WCF Silverlight RIA Services V1.0 for 4 and Visual Studio 2010

13. After adding the library and compiled the project, we just need to try it (F5) to be host in the IIS test server and then we can see our service at the following address:


14. If we want to see the WSDL Contract http://localhost:37390/Services/SoapRiaService-EmployeeDomainService.svc?wsdl

15. Now we’ve ready our service, to create our application in Windows Phone 7, first download the developer tools once installed create a new Windows project Panorama Phone Application (COOL!). use “WP7SoapRiaService” to name it, if you want.

16. Once created the application we’ll need to add a service reference as an address setting http://localhost:37390/Services/SoapRiaService-EmployeeDomainService.svc, then click on GO,at this time you should now see our service and operations exposed by Ria Services, rename the namespace to “EmployeeService” for example.

17. Let see the proxy classes that were created after giving Ok double clicking on the service reference.

18. Well now as a next step we could add the Reactive eXtensions(RX) reference ,
to control the asynchronous call to our Web Service, yap Reactive Extensions now comes within the Windows SDK Phone 7!!!.

19. Once you add the reference add the following code, on my last post I’ve explained RX, and I just added a spinner property to control the visibility:

20. Add a Spinner and bind it to the Visibility property, to control its visibility depending the data in our collection.

21. Run the application, and done you have the application ready!!

The first time when you execute this test you should be patience, because it could take a little longer time until you get the information from the server.

I Hope this post could be useful 😀

Project Download.

May the Code be with you!!!

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License

Written by @mravinale

septiembre 24, 2010 at 4:44 am

Reactive Extensions en Silverlight(RX)

leave a comment »

Si bien, la idea inicial era ir haciendo los post de forma incremental y que evolucione desde los patrones de diseño, hacia patrones mas avanzados como mvc, mvp hasta llegar a mvvm y empezar con Silverlight,  crei que es importante hablar de Rx ya que nos ayudara enormemente en Silverlight, y como estamos en el browser desde el lado cliente, seguramente habra muchas llamadas asyncronicas, es ahi donde Rx entra en juego.

podriamos definir a Rx(Reactive extensions) como una libreria para aplicaciones que necesiten hacer llamadas asincronicas y orientadas a eventos utilizando colecciones del tipo Observable.

En la pagina principal explica un poco el significado de esta nueva herramienta, que nos ayudará mucho a controlar y orquestar programaticamente estos eventos y llamadas.

Pagina principal, introduccion y Video Chanel 9.


Bien si se fijan en la pagina principal dice:

“Rx is a superset of the standard LINQ sequence operators that exposes asynchronous and event-based computations as push-based, observable collections via the new .NET 4.0 interfaces IObservable<T> and IObserver<T>.  These are the mathematical dual of the familiar IEnumerable<T> and IEnumerator<T> interfaces for pull-based, enumerable collections in the .NET Framework.”

Creo que este parrafo explica rapidamente de que se trata Rx. A mi entender lo que trata de expresar es que Rx es un conjunto de operaciones que utiliza los eventos a los que se suscribe como punto de entrada para llenar collecciones del tipo observable para que de esta manera nos avise cuando podemos empezar a consumir los datos como si estos estuvieran en una collecion o dispare el consumo de estos de forma automatica.

Pero volviendo a Silverlight podemos encontrarle gran utilidad si utilizamos el patron mvvm, ya que tenemos un binding entre la vista y el ViewModel por lo tanto nos ayudara a simplificar y automatizar el proceso de llamado al  servidor en busqueda de datos, por ejemplo, que es mas o menos lo que esta en el codigo de abajo.

En este caso lo que hice es crear una clase con patron Singleton como Clase y utilizarla como Modelo , para poderla reutilizar, y una llamada a un servicio para poder obtener datos,  en este caso,consumiremos los nombres de unas personas.

public class ServicePeopleModel{

        private static volatile ServicePeopleModel instance;
        private static object keyLock = new Object();

        public static ServicePeopleModel CurrentInstance {
            get {
                if (instance == null) {
                    lock (keyLock) {
                        instance = new ServicePeopleModel();
                return instance;

        /// <summary>
        /// Gets the remote people data.
        /// </summary>
        /// <returns></returns>
        public IObservable<Person> GetPeople() {

            SLPeopleServiceClient client = new SLPeopleServiceClient();

            var observable =
             //first we are going to listen the event, 
             //when is ready to fill our collection
             (from response in Observable.FromEvent
             <GetPeopleCompletedEventArgs>(client, "GetPeopleCompleted")
            //when the data arrives and the collection is ready,
            //I need to transform this data.
             from people in ConvertItems
            //and when it is ready return observable
            //collection, -and stay tuned
            //when all the operations
            //are done, because i'm gonna call you, 
            //says the observable collection.
            select people).ObserveOnDispatcher();
            //let's call the service

            return observable;


        /// <summary>
        /// Converts the items.
        /// </summary>
        public IEnumerable<Person> ConvertItems(List<String> response){
            var people = new List<Person>();
            response.ForEach(person => people.Add(
                new Person() {Name = person})
            return people;

public class Person {

    public string Name { get; set; }


Ok, ya hemos visto como hariamos nuestro modelo para pedir los datos a nuestro servicio, transformar los datosy devolver una coleccion con todos los datos, listos para utilizar.
Pero nos falta bindear estos datos contra la vista, para automatizar la tarea, de forma que cuando vengan los datos la vista lo muestre estos datos sin que tengamos que intervenir.

//On The PeopleViewModel

public class PeopleViewModel: ViewModelBase {

    /// <summary>
    /// Initializes a new instance of the PeopleViewModelclass.
    /// </summary>
    public PeopleViewModel() {
        var client = Observable.Empty<Person>();
        //we've suscribed to a changed event and we 
        //want to select the first person to show it on the view
        PeopleCollection.CollectionChanged += (s, e) => {
           SelectedPersonProperty = PeopleCollection[0].Name;

        //let's the magic starts
        client = ServicePeopleModel.CurrentInstance.GetPeople();

        //and suscribe us to the service result
        client.Subscribe((item) => {

     /// <summary>
     /// Gets or sets SelectedPersonProperty 
     /// </summary>
     public string SelectedPersonProperty {
         get {
             return _selectedPersonProperty ;
         set {
             if (_selectedPersonProperty == value) return;
                 _selectedPersonProperty = value;
             RaisePropertyChanged("SelectedPersonProperty ");
       /// <summary>
        /// Gets or sets the PeopleCollection.
        /// </summary>
        /// <value>PeopleCollection.</value>
        public ObservableCollection<Person> PeopleCollection{
            get {
                if(_popleCollection == null){
                    _peopleCollection = new ObservableCollection<Person>();
                return _peopleCollection;
            set {
                if (_peopleCollection == value) return;
                _peopleCollection= value;

Sin embargo si ven la pagina de ejemplos podran ver mushisimas mas aplicaciones de este framework, que a mi parecer es excelente tratando de unir el observer pattern y el Iterator, de forma sencilla y con altos beneficios en cantidad y calidad de codigo.

tengo otra aplicacion parecida hecha con Rx que posteare mas adelante, creo que vale la pena bajarselo y probarlo e irle toamndo la mano, creo que despues se va volviendo natural y uno le comienza a ver mas aplicaciones.

Dejo algunos links:

Para los amantes y expertos javascript (@cortezcristian) 😉

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Written by @mravinale

agosto 16, 2010 at 4:45 am