/// <summary> /// Updates the Connected property when the connection state changes /// </summary> private static void ConnectionStateChanged(object sender, ConnectionState state) { if (state == ConnectionState.Disconnected && Online) { DependencyService.Get <Toast>().Show("De socket verbinding wordt hersteld"); pusher.ConnectAsync(); } else if (state == ConnectionState.Connected && !Online) { DependencyService.Get <Toast>().Show("De socket verbinding wordt verbroken"); pusher.DisconnectAsync(); } }
public async Task TestPusherEventsAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options { RaiseAllEventsOnPusher = true }); var events = new List <IIncomingEvent>(); pusher.GetEventSubscription <ConnectionEstablishedEventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.DataObject.SocketId, "a"); Assert.AreEqual(evt.EventName, "pusher:connection_established"); events.Add(evt); }; await pusher.ConnectAsync(); Assert.AreEqual(1, events.Count); events.Clear(); pusher.GetEventSubscription <SubscriptionSucceededEventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, "foo"); Assert.AreEqual(evt.EventName, "pusher_internal:subscription_succeeded"); events.Add(evt); }; await pusher.SubscribeToChannelAsync("foo"); Assert.AreEqual(1, events.Count); }
// Pusher Initiation / Connection private static async Task InitPusher() { _pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new HttpAuthorizer("http://localhost:8888/auth/" + HttpUtility.UrlEncode(_name)) }); _pusher.ConnectionStateChanged += _pusher_ConnectionStateChanged; _pusher.Error += _pusher_Error; // Setup private channel _chatChannel = _pusher.SubscribeAsync("private-channel").Result; _chatChannel.Subscribed += ChatChannel_Subscribed; // Inline binding! _chatChannel.Bind("client-my-event", (dynamic data) => { Console.WriteLine("[" + data.name + "] " + data.message); }); // Setup presence channel _presenceChannel = (PresenceChannel)_pusher.SubscribeAsync("presence-channel").Result; _presenceChannel.Subscribed += PresenceChannel_Subscribed; _presenceChannel.MemberAdded += PresenceChannel_MemberAdded; _presenceChannel.MemberRemoved += PresenceChannel_MemberRemoved; await _pusher.ConnectAsync(); }
static void Main(string[] args) { Console.WriteLine("Ingrese el nombre del usuario."); var usernameInput = Console.ReadLine(); using (HttpClient client = new HttpClient()) { string url = "http://localhost:64952/Auth/Login"; var dataModel = new LoginRequest(); dataModel.username = usernameInput; var data = JsonConvert.SerializeObject(dataModel); StringContent requestData = new StringContent(data); var response = client.PostAsync(url, requestData).Result; var userDataJson = response.Content.ReadAsStringAsync().Result; var userData = JsonConvert.DeserializeObject <User>(userDataJson); // Obtener la lista de rooms var _pusher = new Pusher("04016b8df0172af7d6fd"); _pusher.ConnectionStateChanged += _pusher_ConnectionStateChanged; _pusher.Error += _pusher_Error; _pusher.ConnectAsync(); } }
private async Task InitialisePusher() { if (pusher == null) { pusher = new Pusher(PUSHER_KEY, new PusherOptions() { Cluster = PUSHER_CLUSTER, Encrypted = true }); pusher.Error += OnPusherOnError; pusher.ConnectionStateChanged += PusherOnConnectionStateChanged; pusher.Connected += PusherOnConnected; try { channel = await pusher.SubscribeAsync(PUSHER_CHANNEL_NAME); } catch (Exception e) { Debug.LogError($"{e.GetType()} - {e.Message}\n{e.StackTrace}"); } channel.Subscribed += OnChannelOnSubscribed; await pusher.ConnectAsync(); } }
private async Task InitialisePusher() { //Environment.SetEnvironmentVariable("PREFER_DNS_IN_ADVANCE", "true"); if (_pusher == null && (APP_KEY != "APP_KEY") && (APP_CLUSTER != "APP_CLUSTER")) { _pusher = new Pusher(APP_KEY, new PusherOptions() { Cluster = APP_CLUSTER, Encrypted = true }); _pusher.Error += OnPusherOnError; _pusher.ConnectionStateChanged += PusherOnConnectionStateChanged; _pusher.Connected += PusherOnConnected; _channel = await _pusher.SubscribeAsync("my-channel"); _channel.Subscribed += OnChannelOnSubscribed; await _pusher.ConnectAsync(); } else { Debug.LogError("APP_KEY and APP_CLUSTER must be correctly set. Find how to set it at https://dashboard.pusher.com"); } }
private async Task StartPusherAsync() { var smintIoSettingsDatabaseModel = await _smintIoSettingsDatabaseProvider.GetSmintIoSettingsDatabaseModelAsync(); smintIoSettingsDatabaseModel.ValidateForPusher(); var pusherAuthEndpoint = $"https://{smintIoSettingsDatabaseModel.TenantId}.clapi.smint.io/consumer/v1/notifications/pusher/auth"; var tokenDatabaseModel = await _smintIoTokenDatabaseProvider.GetTokenDatabaseModelAsync(); tokenDatabaseModel.ValidateForPusher(); var authorizer = new HttpAuthorizer(pusherAuthEndpoint, tokenDatabaseModel.AccessToken); _pusher = new Pusher("32f31c26a83e09dc401b", new PusherOptions() { Cluster = "eu", Authorizer = authorizer }); _pusher.ConnectionStateChanged += ConnectionStateChanged; _pusher.Error += PusherError; var connectionState = await _pusher.ConnectAsync(); if (connectionState == ConnectionState.Connected) { await SubscribeToPusherChannelAsync((int)smintIoSettingsDatabaseModel.ChannelId); } }
protected override async Task Run() { _pusher.ConnectionStateChanged += (_, state) => { _logger.Information("Pusher connection state changed: {PusherConnectionState}", state); }; _pusher.Subscribed += (_, channel) => { _logger.Information("Pusher subscribed to channel: {PusherChannelName}", channel.Name); }; await _pusher.ConnectAsync(); await Task.WhenAll( _pusher.SubscribeAsync("sim-data"), _pusher.SubscribeAsync("temporal"), _pusher.SubscribeAsync("ticker") ); _pusher.BindAll(GlobalHandler); _pusher.Bind("sim-data", WrapHandler(SimDataHandler)); _pusher.Bind("temporal-message", WrapHandler(TemporalHandler)); _pusher.Bind("ticker-message", WrapHandler(TickerHandler)); _pusher.Bind("game-data", WrapHandler(GameDataHandler)); // Wait forever await SubscribeLoop(); }
public async Task TriggerNotSubscribedErrorTestAsync() { // Arrange ChannelTypes channelType = ChannelTypes.Private; Pusher localPusher = PusherFactory.GetPusher(channelType: ChannelTypes.Presence, saveTo: _clients); string testEventName = "client-pusher-event-test"; PusherEvent pusherEvent = CreatePusherEvent(channelType, testEventName); await localPusher.ConnectAsync().ConfigureAwait(false); Channel localChannel = await localPusher.SubscribeAsync(pusherEvent.ChannelName).ConfigureAwait(false); TriggerEventException exception = null; // Act await localPusher.UnsubscribeAllAsync().ConfigureAwait(false); try { await localChannel.TriggerAsync(testEventName, pusherEvent.Data); } catch (TriggerEventException error) { exception = error; } // Assert Assert.IsNotNull(exception, $"Expected a {nameof(TriggerEventException)}"); Assert.AreEqual(ErrorCodes.TriggerEventNotSubscribedError, exception.PusherCode); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); var infoTb = FindViewById <EditText>(Resource.Id.infoTb); pusher = new Pusher("dc777df44df8be24ae85", new Handler(Looper.MainLooper)); pusher.ConnectAsync(15000, ConnectionTimeoutAction.CloseConnection, 20000, NetworkUnavailableAction.Ignore); pusher.Connected += (sender) => { RunOnUiThread(() => { infoTb.AppendLine("Connected!"); channel = pusher.Subscribe("my-channel"); channel.Bind("my-event", (obj) => { var car = Pusher.ParseMessageToObject(obj.message.Value as string, new Car()); infoTb.AppendLine($"{car.Name}, {car.Color}, {car.Make}"); }); }); }; pusher.ConnectionStateChanged += (s, state) => { switch (state) { case ConnectionState.Disconnected: channel.Unbind("my-event"); break; } }; }
private async Task InitialisePusher() { //Environment.SetEnvironmentVariable("PREFER_DNS_IN_ADVANCE", "true"); if (_pusher == null && (APP_KEY != "APP_KEY") && (APP_CLUSTER != "APP_CLUSTER")) { _pusher = new Pusher(APP_KEY, new PusherOptions() { Cluster = APP_CLUSTER, Encrypted = true }); _pusher.Error += OnPusherOnError; _pusher.ConnectionStateChanged += PusherOnConnectionStateChanged; _pusher.Connected += PusherOnConnected; _channel = await _pusher.SubscribeAsync(GameMaster.Instance.game.getPin()); _channel.Subscribed += OnChannelOnSubscribed; await _pusher.ConnectAsync(); } else { Debug.LogError("APP_KEY and APP_CLUSTER must be correctly set."); } }
public async Task TriggerClientEventAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Connect await pusher.ConnectAsync().ConfigureAwait(false); // Subscribe Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false); // Trigger event channel.Trigger("client-chat-event", new ChatMessage { Name = "Joe", Message = "Hello from Joe!", }); #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task ConnectThenSubscribePublicChannelAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Connect await pusher.ConnectAsync().ConfigureAwait(false); // Subscribe try { Channel channel = await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false); Assert.AreEqual(true, channel.IsSubscribed); } catch (Exception) { // Handle error } #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task ConnectedAndDisconnectedDelegatesAsync() { Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Cluster = Config.Cluster, Encrypted = true, }); void OnConnected(object sender) { Console.WriteLine("Connected: " + ((Pusher)sender).SocketID); } void OnDisconnected(object sender) { Console.WriteLine("Disconnected: " + ((Pusher)sender).SocketID); } pusher.Connected += OnConnected; pusher.Disconnected += OnDisconnected; await pusher.ConnectAsync().ConfigureAwait(false); await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task ConnectThenSubscribePrivateChannelAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Connect await pusher.ConnectAsync().ConfigureAwait(false); try { // Subscribe Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false); Assert.AreEqual(true, channel.IsSubscribed); } catch (ChannelUnauthorizedException) { // Handle client unauthorized error } catch (Exception) { // Handle other errors } #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task TestMissingAuthenticatorThrowsExceptionAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234"); await pusher.ConnectAsync(); Assert.ThrowsException <AggregateException>(() => pusher.SubscribeToChannelAsync("private-foo").Wait()); }
public async Task PusherSubscribedDelegateAsync() { #region Code snippet // Lists all current presence channel members void ListMembers(GenericPresenceChannel <ChatMember> channel) { Dictionary <string, ChatMember> members = channel.GetMembers(); foreach (var member in members) { Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}"); } } // Subscribed event handler void SubscribedHandler(object sender, Channel channel) { if (channel is GenericPresenceChannel <ChatMember> presenceChannel) { ListMembers(presenceChannel); } else if (channel.Name == "private-chat-channel-1") { // Trigger event channel.Trigger("client-chat-event", new ChatMessage { Name = "Joe", Message = "Hello from Joe!", }); } } // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Add subcribed event handler pusher.Subscribed += SubscribedHandler; // Create subscriptions await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false); await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false); await pusher.SubscribePresenceAsync <ChatMember>("presence-channel-1").ConfigureAwait(false); // Connect await pusher.ConnectAsync().ConfigureAwait(false); #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
public async void Connect() { _pusher = new Pusher("6f6586ea2b39f7d8e6e1", new PusherOptions() { Cluster = "eu" }); _pusher.ConnectionStateChanged += pusher_ConnectionStateChanged; _pusher.Error += pusher_Error; await _pusher.ConnectAsync(); }
public async Task PusherEventEmitterPrivateEncryptedChannelTestAsync() { // Arrange byte[] encryptionKey = GenerateEncryptionMasterKey(); var pusherServer = new PusherServer.Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherServer.PusherOptions { Cluster = Config.Cluster, EncryptionMasterKey = encryptionKey, }); ChannelTypes channelType = ChannelTypes.PrivateEncrypted; Pusher localPusher = PusherFactory.GetPusher(channelType: ChannelTypes.Presence, saveTo: _clients, encryptionKey: encryptionKey); string testEventName = "private-encrypted-event-test"; AutoResetEvent globalEventReceived = new AutoResetEvent(false); AutoResetEvent channelEventReceived = new AutoResetEvent(false); PusherEvent globalEvent = null; PusherEvent channelEvent = null; PusherEvent pusherEvent = CreatePusherEvent(channelType, testEventName); await localPusher.ConnectAsync().ConfigureAwait(false); Channel localChannel = await localPusher.SubscribeAsync(pusherEvent.ChannelName).ConfigureAwait(false); void GeneralListener(string eventName, PusherEvent eventData) { if (eventName == testEventName) { globalEvent = eventData; globalEventReceived.Set(); } } void Listener(PusherEvent eventData) { channelEvent = eventData; channelEventReceived.Set(); } EventTestData data = new EventTestData { TextField = ExpectedTextField, IntegerField = ExpectedIntegerField, }; // Act localPusher.BindAll(GeneralListener); localChannel.Bind(testEventName, Listener); await pusherServer.TriggerAsync(pusherEvent.ChannelName, testEventName, data).ConfigureAwait(false); // Assert Assert.IsTrue(globalEventReceived.WaitOne(TimeSpan.FromSeconds(5))); Assert.IsTrue(channelEventReceived.WaitOne(TimeSpan.FromSeconds(5))); AssertPusherEventsAreEqual(channelType, pusherEvent, globalEvent); AssertPusherEventsAreEqual(channelType, pusherEvent, channelEvent); }
public async Task PusherShouldSuccessfullyConnectTwiceWhenGivenAValidAppKeyAsync() { // Once Pusher pusher = await ConnectTestAsync().ConfigureAwait(false); Assert.IsNotNull(pusher); // Twice await pusher.ConnectAsync().ConfigureAwait(false); Assert.AreEqual(ConnectionState.Connected, pusher.State); }
public static async Task DisposePusherClientAsync(Pusher pusher) { if (pusher != null) { ((IPusher)pusher).PusherOptions.ClientTimeout = TimeSpan.FromSeconds(30); await pusher.UnsubscribeAllAsync().ConfigureAwait(false); await pusher.ConnectAsync().ConfigureAwait(false); await pusher.DisconnectAsync().ConfigureAwait(false); } }
public async Task ConstructionOfAPublicChannelOnlySubscriberAsync() { Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Cluster = Config.Cluster, Encrypted = true, }); await pusher.ConnectAsync().ConfigureAwait(false); await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task SubscribeThenConnectPresenceChannelAsync() { #region Code snippet // Create client Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new FakeAuthoriser(), Cluster = Config.Cluster, }); pusher.Error += ErrorHandler; // Lists all current presence channel members void ListMembers(GenericPresenceChannel <ChatMember> channel) { Dictionary <string, ChatMember> members = channel.GetMembers(); foreach (var member in members) { Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}"); } } // MemberAdded event handler void ChatMemberAdded(object sender, KeyValuePair <string, ChatMember> member) { Trace.TraceInformation($"Member {member.Value.Name} has joined"); ListMembers(sender as GenericPresenceChannel <ChatMember>); } // MemberRemoved event handler void ChatMemberRemoved(object sender, KeyValuePair <string, ChatMember> member) { Trace.TraceInformation($"Member {member.Value.Name} has left"); ListMembers(sender as GenericPresenceChannel <ChatMember>); } // Subscribe GenericPresenceChannel <ChatMember> memberChannel = await pusher.SubscribePresenceAsync <ChatMember>("presence-channel-1").ConfigureAwait(false); memberChannel.MemberAdded += ChatMemberAdded; memberChannel.MemberRemoved += ChatMemberRemoved; Assert.AreEqual(false, memberChannel.IsSubscribed); // Connect await pusher.ConnectAsync().ConfigureAwait(false); #endregion Code snippet await pusher.DisconnectAsync().ConfigureAwait(false); }
private static async Task SubscribeMultipleChannelsTestAsync(bool connectBeforeSubscribing, Pusher pusher, IList <string> channelNames) { // Arrange var subscribedEvent = new AutoResetEvent(false); int subscribedCount = 0; pusher.Subscribed += (sender, channelName) => { subscribedCount++; if (subscribedCount == channelNames.Count) { subscribedEvent.Set(); } }; // Act if (connectBeforeSubscribing) { await pusher.ConnectAsync().ConfigureAwait(false); foreach (string channelName in channelNames) { await pusher.SubscribeAsync(channelName).ConfigureAwait(false); } } else { foreach (string channelName in channelNames) { await pusher.SubscribeAsync(channelName).ConfigureAwait(false); } AssertIsDisconnected(pusher, channelNames); await pusher.ConnectAsync().ConfigureAwait(false); } // Assert Assert.IsTrue(subscribedEvent.WaitOne(TimeSpan.FromSeconds(5))); AssertIsSubscribed(pusher, channelNames); }
public async Task ConstructionOfAnAuthorizedChannelSubscriberAsync() { Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new HttpAuthorizer("http://localhost:8888/auth/Jane"), Cluster = Config.Cluster, Encrypted = true, }); await pusher.ConnectAsync().ConfigureAwait(false); await pusher.DisconnectAsync().ConfigureAwait(false); }
public async Task SpecifyingAClientTimeoutAsync() { Pusher pusher = new Pusher(Config.AppKey, new PusherOptions { Authorizer = new HttpAuthorizer("http://localhost:8888/auth/Jane"), Cluster = Config.Cluster, Encrypted = true, ClientTimeout = TimeSpan.FromSeconds(20), }); await pusher.ConnectAsync().ConfigureAwait(false); await pusher.DisconnectAsync().ConfigureAwait(false); }
private async void BeginPusherEventReceptionSession() { // The previous Extended Execution must be closed before a new one can be requested. // This code is redundant here because the sample doesn't allow a new extended // execution to begin until the previous one ends, but we leave it here for illustration. EndPusherEventReceptionSession(); var newSession = new ExtendedExecutionSession(); newSession.Reason = ExtendedExecutionReason.Unspecified; newSession.Description = "Checking for Pusher events"; newSession.Revoked += PusherEventReceptionSessionRevoked; ExtendedExecutionResult result = await newSession.RequestExtensionAsync(); switch (result) { case ExtendedExecutionResult.Allowed: Debug.WriteLine("Extended execution was allowed"); foreach (PusherEventConfig config in EventConfigs) { var pusher = new Pusher(config.AppKey, new PusherOptions() { Cluster = config.AppCluster }); pusher.ConnectionStateChanged += PusherConnectionStateChanged; pusher.Error += PusherError; ConnectionState connectionState = await pusher.ConnectAsync(); Channel myChannel = await pusher.SubscribeAsync(config.ChannelName); myChannel.Bind(config.EventName, async(PusherClient.PusherEvent eventData) => { await OnPusherEventReceptionAsync(config, eventData); }); } pusherEventReceptionSession = newSession; break; default: case ExtendedExecutionResult.Denied: Debug.WriteLine("Extended execution was denied"); newSession.Dispose(); break; } }
// Pusher Initiation / Connection private async void InitPusher() { _pusher = new Pusher("625e6f2e093b6e564050", new PusherOptions() { Encrypted = true, Cluster = "ap1" }); // Setup private channel _tableChannel = _pusher.SubscribeAsync("mobile").Result; // Inline binding! _tableChannel.Bind("changeStateTable-event", (dynamic data) => { UpdateTables(); }); await _pusher.ConnectAsync(); }
private async Task InitPusher() { var options = new PusherOptions { Cluster = "us2", Encrypted = true }; _pusher = new Pusher(ConfigurationManager.AppSettings["pusher_app_key"], options); _pusher.ConnectionStateChanged += _pusher_ConnectionStateChanged; _pusher.Error += _pusher_Error; _channel = _pusher.SubscribeAsync(ConfigurationManager.AppSettings["pusher_channel"]).Result; _channel.Subscribed += ChatChannel_Subscribed; _channel.Bind("lista-contratados", (dynamic data) => { setarContratados(JsonConvert.DeserializeObject(data.data.ToString())); }); _channel.Bind("lista-demitidos", (dynamic data) => { setarDemitidos(JsonConvert.DeserializeObject(data.data.ToString())); }); await _pusher.ConnectAsync(); }
private async Task DynamicEventEmitterTestAsync(ChannelTypes channelType) { // Arrange Pusher localPusher = PusherFactory.GetPusher(channelType: ChannelTypes.Presence, saveTo: _clients); string testEventName = "client-dynamic-event-test"; AutoResetEvent globalEventReceived = new AutoResetEvent(false); AutoResetEvent channelEventReceived = new AutoResetEvent(false); dynamic globalEvent = null; dynamic channelEvent = null; dynamic dynamicEventData = CreateDynamicEventData(); string channelName = ChannelNameFactory.CreateUniqueChannelName(channelType: channelType); await localPusher.ConnectAsync().ConfigureAwait(false); Channel remoteChannel = await _remoteClient.SubscribeAsync(channelName).ConfigureAwait(false); Channel localChannel = await localPusher.SubscribeAsync(channelName).ConfigureAwait(false); void GeneralListener(string eventName, dynamic eventData) { if (eventName == testEventName) { globalEvent = eventData; globalEventReceived.Set(); } } void Listener(dynamic eventData) { channelEvent = eventData; channelEventReceived.Set(); } // Act localPusher.BindAll(GeneralListener); localChannel.Bind(testEventName, Listener); remoteChannel.Trigger(testEventName, dynamicEventData); // Assert Assert.IsTrue(globalEventReceived.WaitOne(TimeSpan.FromSeconds(5))); Assert.IsTrue(channelEventReceived.WaitOne(TimeSpan.FromSeconds(5))); ValidateDynamicEvent(channelName, testEventName, globalEvent); ValidateDynamicEvent(channelName, testEventName, channelEvent); }
private async void ConnectAsync() { var options = new Options {Scheme = WebServiceScheme.Secure}; if (AuthenticationRequired) { options.Authenticator = new Authenticator(AuthenticationUrl, new Dictionary<string, string> { {"channel", Channel} }); } var synchronizationContext = SynchronizationContext.Current; _pusher = new Pusher(new WebSocketConnectionFactory(), AppKey, options); _pusher.Logger = _logger; _pusher.ExceptionOccured += (sender, args) => synchronizationContext.Post( x => _logger.Debug("Exception occured: {0}", args.Exception.Message), null); _logger.Debug("Connecting..."); await _pusher.ConnectAsync(); _logger.Debug("Connected!"); _logger.Debug("Subscribing to {0}!", Channel); var channel = await _pusher.SubscribeToChannelAsync(Channel); channel.GetEventSubscription<SubscriptionSucceededEventArgs>().EventEmitted += async (sender, evt) => { synchronizationContext.Post(async channelName => { var d = new MessageDialog(string.Format("Subscribed to {0}!", channelName)); await d.ShowAsync(); }, evt.Channel); }; }
public async Task TestRaiseAllEventsOnPusherAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options { RaiseAllEventsOnPusher = false }); await pusher.ConnectAsync(); var eventsOnPusher = 0; pusher.EventEmitted += (sender, evt) => eventsOnPusher++; var eventsOnChannel = 0; var channel = await pusher.SubscribeToChannelAsync("foo"); channel.EventEmitted += (sender, evt) => eventsOnChannel++; // the subscribe successful event is raised on channel, but it is raised before we can hook up the event Assert.AreEqual(0, eventsOnChannel); // RaiseAllEventsOnPusher = false prevents the subscribe successful event from being raised on pusher Assert.AreEqual(0, eventsOnPusher); }
public async Task TestMissingAuthenticatorThrowsExceptionAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234"); await pusher.ConnectAsync(); Assert.ThrowsException<AggregateException>(() => pusher.SubscribeToChannelAsync("private-foo").Wait()); }
public async Task TestChannelTypesAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options() { Authenticator = new FakeAuthenticator() }); await pusher.ConnectAsync(); var privateChannel = await pusher.SubscribeToChannelAsync("private-foo"); var presenceChannel = await pusher.SubscribeToChannelAsync("presence-foo"); var normalChannel = await pusher.SubscribeToChannelAsync("foo"); Assert.AreEqual(typeof(PrivateChannel), privateChannel.GetType()); Assert.AreEqual(typeof(PresenceChannel), presenceChannel.GetType()); Assert.AreEqual(typeof(Channel), normalChannel.GetType()); }
public async Task TestEventContractAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options() { Authenticator = new FakeAuthenticator() }); pusher.AddContract(EventContract.Create<FakeEvent>("fooHappened")); await pusher.ConnectAsync(); var sentEvent = new IncomingEvent<FakeEvent> { Channel = "foo", DataObject = new FakeEvent {Id = 1, Text = "foo"}, EventName = "fooHappened" }; var channel = await pusher.SubscribeToChannelAsync("foo"); var eventsReceived = 0; channel.GetEventSubscription<FakeEvent>().EventEmitted += (sender, receivedEvent) => { Assert.AreEqual(sentEvent.DataObject.Id, receivedEvent.DataObject.Id); Assert.AreEqual(sentEvent.DataObject.Text, receivedEvent.DataObject.Text); Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName); Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel); eventsReceived++; }; channel.EventEmitted += (sender, receivedEvent) => { Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName); Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel); eventsReceived++; Assert.AreEqual(typeof(IncomingEvent<FakeEvent>), receivedEvent.GetType()); }; factory.LastCreated.SendData(JsonConvert.SerializeObject(sentEvent)); Assert.AreEqual(2, eventsReceived); }
public async Task TestPusherEventsAsync() { var factory = new FakeConnectionFactory(); var pusher = new Pusher(factory, "abcd1234", new Options { RaiseAllEventsOnPusher = true }); var events = new List<IIncomingEvent>(); pusher.GetEventSubscription<ConnectionEstablishedEventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.DataObject.SocketId, "a"); Assert.AreEqual(evt.EventName, "pusher:connection_established"); events.Add(evt); }; await pusher.ConnectAsync(); Assert.AreEqual(1, events.Count); events.Clear(); pusher.GetEventSubscription<SubscriptionSucceededEventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, "foo"); Assert.AreEqual(evt.EventName, "pusher_internal:subscription_succeeded"); events.Add(evt); }; await pusher.SubscribeToChannelAsync("foo"); Assert.AreEqual(1, events.Count); }