Organized Architecture for a Cross-Platform SignalR Application

SignalR is a great tool for keeping not only your web applications synced in real-time, but with it’s easy to use APIs for clients, it is perfect for use in your mobile applications.

I have some previous posts that are going to help in designing the of an architecture for a cross-platform implementation with SignalR. Take a look at these:

In this scenario, we are going to focus on two major layers of separation within our applications, although you can always add more layers of abstraction if that is your style or preference. Our two layers are the Portable Class Library and Native Client Libraries. This example is going to be using one PCL with all of our shared code, and then individual projects for Windows Phone 8.1, Windows 8.1, Xamarin.iOS, and Xamarin.Android.

The Portable Class Library

In this architecture, we want to focus on sharing as much code as possible. This implies that the only code that should not be in our PCL is code that includes the UI (Note we are not using Xamarin.Forms), updates the UI, or accesses the device’s native features (cameras, location, etc). This would include things such as ViewModels if you’re using the MVVM pattern (this example is using MVVM Light), Models, Web Request Logic, and even our SignalR Managers.
With that in mind, here are some nuget packages to consider for your PCL:

So let’s get started with a simple BaseHubManager to manage our connections. I’m going to follow a basic Inheritance pattern for these managers so that we can share as much of our SignalR code in our Base Manager as possible.

BaseHubManager:

  public class BaseHubManager
    {
        public HubConnection Connection{ get; set; }
        public IHubProxy Proxy { get; set; }

        // The empty constructor should only be used for a basic connection with no specific Hub
        public BaseHubManager()
        {
            Connection= new HubConnection(Constants.BaseUrl);
        }

        // Connect to specific Hub
        public BaseHubManager(string hubProxy)
        {
            Connection= new HubConnection(Constants.BaseUrl);
            Connection.Headers.Add("Authorization", string.Format("Bearer {0}", App.CurrentUser.TokenInfo.AccessToken)); //add access token to authorize
            Proxy = Connection.CreateHubProxy(hubProxy);
        }

        public async Task Start()
        {
            await _connection.Start(new LongPollingTransport());
            //Add additional shared Start logic
        }

        public void Stop()
        {
             _connection.Stop();
             //Add additional shared Stop logic
        }

        public virtual async void Connect()
        {
            await this.Start();
            //Add additional shared Connect logic
        }
    }

Now that we have a solid base, we can easily spin up individual Hub managers to connect to specific Hubs. Below is an example of a HubManager that would connect to the “ChatHub” on your server.

ChatHubManager:

 public class ChatHubManager : BaseHubManager
    {
        public ObservableCollection<string> Messages{ get; set; }

        public ChatHubManager ()
            : base("ChatHub")
        {
            this.Connect();
        }
        // Send new message to ChatHub
        public async Task<string> Create(string newMessage)
        {
            //establish connection
            await this.Start();

            var message= await Proxy.Invoke<string>("Create", newMessage);

            return message;
        }

        // Get all messages from ChatHub
        public async Task<IEnumerable<string>> Get()
        {
            //establish connection
            await this.Start();

            var messages = await Proxy.Invoke<IEnumerable<string>>("Get"));

            Messages = new ObservableCollection<string>(messages);
            return messages;

        }

    }

Expanding new HubManagers like this one make it very easy to call server-side methods from our client by simply creating an instance of our Manager and calling our Invoking methods:

var manager = new ChatManager();
var messages = await manager.Get();

Now what about the other side of SignalR – Client methods? There are some things to consider. Most importantly, will your client end points update anything in the UI? This also includes updating ViewModel properties that will cause updates in the UI.
The problem is that the client end point listeners don’t stem from any sort of UI action the way that calling a server method might. Thus, it can’t run on the UI thread by itself and you would likely run into some sort of Threading Exception.

If you don’t need to update the UI at any point from your client listener, consider adding your listeners in your manager with something like this:

public ChatHubManager ()
    : base("ChatHub")
{
        this.Connect();
        Proxy.On<string>("newMessage", async data =>
        {
            //Do something that is NOT on the UI thread
        }
}

One thing that SignalR does wonderfully is give you the ability to add these listeners from anywhere. That includes from your individual client projects that reference your PCL. So, let’s look at how to add these kind of requests to our client projects so we can update our UIs.

The Individual Client Projects

Let’s use a Windows Phone 8.1 project as our example, although the same logic can be applied to any type of project. So we need to add our client listener like we did above, but we also need it to make changes to our UI, which will require tapping into our UI thread. For this case, let’s add a ChatSignalingManager to our Windows Phone project that contains a reference to our ChatHubManager in our PCL above:

 public class ChatSignalingManager
    {
        private ChatHubManager _hubManager;
        private CoreDispatcher _dispatcher;
        public ChatSignalingManager (CoreDispatcher dispatcher)
        {
            _hubManager= new ChatHubManager ();
            _dispatcher = dispatcher;
            InitializeChatEndpoints();
        }

       //Add client end points for the ChatHubManager
        private void InitializeChatEndpoints()
        {
            var newMessage = _hubManager.Proxy.On<string>("newMessage", async data =>
            {
                await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        // process your UI changes here
                    });
            });

           // Add additional end points for the ChatHub here
        }

    }

Notice the biggest difference in how we handle our end point in our client project versus our PCL. The Dispatcher. In this case, we can pass Windows CoreDispatcher to our constructor, and by calling _dispatcher.RunAsync we are able to execute our process on our UI thread to successfully run code against our UI.

Here is an example of constructing the ChatSignalingManager from the MainPage of a Windows Phone app:

public sealed partial class MainPage : Page
{

    private ChatSignalingManager _signalingManager;
    public MainPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;
        _signalingManager = new ChatSignalingManager (Dispatcher);

    }

}

Hopefully that is enough code to get you started, but feel free to ask more questions in the comments. Just remember to share as much code as possible in your PCL and use your Client Projects to handle updates to your UI and also to utilize SignalR’s flexibility and versatility.

Databinding a Windows FlipView with MVVM Light

MVVM Light is a great cross-platform MVVM Framework, and was chosen to be used in this example. However, it isn’t required to get the same results.

FlipViews were a great addition to the WIndows Control family for Windows Phone and Windows Store applications. It’s easily customized, simple to use, and can give your app a user friendly experience for anything from an image gallery, to a news reader. So let’s get to the code.

Let’s first build the model we are going to use for each of our views in our FlipView. I’m using a PCL for my Models and ViewModels and a Windows Phone 8.1 project for the xaml, but it works in the same fashion for Windows Store.

Here is our model:


public class RotatorItem
 {
     public string Title { get; set; }
     public string ImageUri { get; set; }
     public string Subtitle { get; set; }
 }

Now let’s look at a simple ViewModel with MVVM Light to hold our collection of SimpleRotatorItems.

public class LandingRotatorPageViewModel : ViewModelBase
 {
     #region Private Properties
     private ObservableCollection<RotatorItem> _rotatorItems;
     private RotatorItem _activeItem;
     #endregion

     #region Public Properties
     public ObservableCollection<RotatorItem> RotatorItems
     {
         get
         {
             return _rotatorItems;
         }
         set
         {
             Set(() => RotatorItems, ref _rotatorItems, value);
         }
     }
     public RotatorItem ActiveItem
     {
         get
         {
             return _activeItem;
         }
         set
         {
             Set(() => ActiveItem, ref _activeItem, value);
         }
     }

     #endregion
     public LandingRotatorPageViewModel()
     {
         var rotatorItems = new ObservableCollection<RotatorItem>();
         rotatorItems.Add(new RotatorItem { ImageUri = "/Assets/Logo.scale-240.png", Title = "Title 1", Subtitle = "Subtitle 1"});
         rotatorItems.Add(new RotatorItem { ImageUri = "/Assets/Logo.scale-240.png", Title = "Title 2", Subtitle = "Subtitle 2" });
         rotatorItems.Add(new RotatorItem { ImageUri = "/Assets/Logo.scale-240.png", Title = "Title 3", Subtitle = "Subtitle 3" });
         rotatorItems.Add(new RotatorItem { ImageUri = "/Assets/Logo.scale-240.png", Title = "Title 4", Subtitle = "Subtitle 4" });
         RotatorItems = rotatorItems;
         ActiveItem = rotatorItems.First();
     }
 }

Let’s go ahead now and get our markup done for our page with the FlipView:

<FlipView x:Name="SimpleFlipView" ItemsSource="{Binding RotatorItems}" Grid.Row="1" SelectionChanged="FlipView_SelectionChanged">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="200" />
                    <RowDefinition Height="120" />
                    <RowDefinition Height="80" />
                </Grid.RowDefinitions>
                <Image Source="{Binding ImageUri}" Height="150" Grid.Row="0" VerticalAlignment="Top" Margin="0,50,0,0"/>
                <TextBlock TextWrapping="Wrap" TextAlignment="Center" Grid.Row="1" Text="{Binding Title}" FontSize="30" HorizontalAlignment="Center" Margin="20"></TextBlock>
                <TextBlock TextWrapping="Wrap" TextAlignment="Center" Grid.Row="2" FontSize="20" HorizontalAlignment="Center" Margin="20">
                    <Run Text="{Binding Subtitle}"></Run>
               </TextBlock>

            </Grid>
       </DataTemplate>
   </FlipView.ItemTemplate>
</FlipView>

Last but not least, let’s make sure our ViewModel is bound to our Page in our page Class:

 public sealed partial class MainPage : Page
 {
     private LandingRotatorPageViewModel _vm;
     public MainPage()
     {
          this.InitializeComponent();

          _vm = new LandingRotatorPageViewModel();
          this.DataContext = _vm;
     }

     /// <summary>
     /// Invoked when this page is about to be displayed in a Frame.
     /// </summary>
     /// <param name="e">Event data that describes how this page was reached.
     /// This parameter is typically used to configure the page.</param>
     protected override void OnNavigatedTo(NavigationEventArgs e)
     {
     }
}

Now that the Page’s DataContext is set to our ViewModel, the binding we placed on the FlipView element ‘ItemSource=”{Binding RotatorItems}”‘ will bind our FlipView’s Items to the items we created in the constructor for our ViewModel, and will use our ItemTemplate to create our items from the fields on the RotatorItems.

Now let’s take a look at our final result:

FlipView Item
First FlipView Item bound to ViewModel
wp_ss_20150502_0002
Second FlipView Item

So there you have it. An easy solution to using the Windows FlipView Control to display content that is bound to a ViewModel.