Let's turn our attention to the SignalRClient
; we created an EventHandler
, which fires every time data is received from the Hub. The BasePresenter
will be responsible for handling the data received from this EventHandler
:
#region Constructors public BasePresenter() { _webApiAccess = new WebApiAccess(); _signalREvents = new Dictionary<string, Action<string>>() { {"clients", (data) => { var list = JsonConvert.DeserializeObject<IEnumerable<string>>(data); if (ConnectedClientsUpdated != null) { ConnectedClientsUpdated(this, new ConnectedClientsUpdatedEventArgs(list.Select(x => new Client { Username = x, }))); } } }, {"chat", (data) => { if (ChatReceived != null) { ChatReceived(this, new ChatEventArgs(data)); } } }, }; } #endregion #region Protected Methods protected void HandleSignalRDataReceived(object sender, Tuple<string, string> e) { _signalREvents[e.Item1](e.Item2); } #endregion
With each Tuple
received from the SignalRClient's OnDataReceived
event, the first string will be the key matching the indexed Action<string>
in the dictionary. The other string of the Tuple
is the data string (either a serialized JSON of HashSet<string>
, or a string which represents a chat message), which is passed as the input parameter for our Action<string>
, then, out of this input parameter, we will create the correct arguments used for the specified event.
We could take things a step further and abstract a view
object into the BasePresenter
, as every presenter requires a view
, but because each view logic is independent, it is very hard to centralize this logic in one area. The need for this will come if multiple views have similar behaviors. Then we can look at abstracting these areas into the BasePresenter
.
But wait! You may have noticed that we have two types of arguments being passed into each EventHandler
. Add a new file to the Events
folder in the Chat.Common
project called ConnectedClientsUpdatedEventArgs.cs
, and implement the following:
public class ConnectedClientsUpdatedEventArgs : EventArgs { public IList<Client> ConnectedClients { private set; get; } public ConnectedClientsUpdatedEventArgs(IEnumerable<Client> connectedClients) { ConnectedClients = new List<Client>(); foreach (var client in connectedClients) { ConnectedClients.Add(client); } } }
We also need another file called ChatEventArgs.cs
. Add this to the Events
folder and implement the following:
public class ChatEventArgs : EventArgs { public string Message { private set; get; } public ChatEventArgs(string message) { Message = message; } }
This object is the wrapper for every message received for a chat message. Now we have everything ready to implement our first presenter object.
52.15.214.27