//listen to the channel
        public void Listen()
        {
            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
                (pubnubObj, message) =>
            {
                //Call the notification windows from the UI thread
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    //Show the message as a WPF window message like WIN-10 toast
                    NotificationWindow ts = new NotificationWindow();
                    //Convert the message to JSON
                    JsonMsg bsObj         = JsonConvert.DeserializeObject <JsonMsg>(message.Message.ToString());
                    string messageBoxText = "Name: " + bsObj.Name + Environment.NewLine + "Description: " + bsObj.Description + Environment.NewLine + "Date: " + bsObj.Date;
                    ts.NotifText.Text     = messageBoxText;
                    ts.Show();
                }));
            },
                (pubnubObj, presence) =>
            {
                // handle incoming presence data
            },
                (pubnubObj, status) =>
            {
                // the status object returned is always related to subscribe but could contain
                // information about subscribe, heartbeat, or errors
                // use the PNOperationType to switch on different options
            });

            pubnub.AddListener(listenerSubscribeCallack);
        }
示例#2
0
        public PubNubMessageHandler(ChatOutputControl chatOutputControl)
        {
            this.chatOutputControl = chatOutputControl;

            //Configure PubNub
            PNConfiguration pnConfiguration = new PNConfiguration
            {
                PublishKey   = PublishKey,
                SubscribeKey = SubscribeKey,
                Uuid         = userId,
                Secure       = false
            };

            this.pubnub = new Pubnub(pnConfiguration);

            //Add listener to receive Publish messages and Presence events
            SubscribeCallbackExt generalSubscribeCallack = new SubscribeCallbackExt(
                (Pubnub pubnubObj, PNMessageResult <object> message) => {
                Console.WriteLine(message.Message);

                //Determine if the message publisher is the current user
                bool messageFromCurrentUser = message.Publisher.ToString() == userId;

                //Deserialize the JSON message
                EnrichedChatMessage chatMessage = JsonConvert.DeserializeObject <EnrichedChatMessage>(message.Message.ToString());

                //Verify that both the message text and extraction properties were defined in the message
                if (chatMessage.Text == null || chatMessage.Extractions == null)
                {
                    Console.WriteLine("Message arrived with an unexpected format:", message.Message);
                }
                else
                {
                    //Update the output user control with the new message text
                    chatOutputControl.NewMessage(chatMessage.Text, messageFromCurrentUser);

                    //Convert the message enrichment data into formatted JSON to be displayed
                    string formattedJsonMetadata = JsonConvert.SerializeObject(chatMessage.Extractions, Formatting.Indented);
                    chatOutputControl.UpdateMetadata(formattedJsonMetadata == "[]" ? "No additional metadata" : formattedJsonMetadata);
                }
            },
                (pubnubObj, presence) => { },
                (pubnubObj, status) => { }
                );

            pubnub.AddListener(generalSubscribeCallack);

            //Subscribe to the chat channel
            pubnub.Subscribe <string>()
            .Channels(new string[] {
                ChannelName
            })
            .Execute();
        }
示例#3
0
        void Listener()
        {
            Pubnub pubnub = new Pubnub(pnConfiguration);

            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
                (pubnubObj, message) => { },
                (pubnubObj, presence) => { },
                (pubnubObj, status) => { });

            pubnub.AddListener(listenerSubscribeCallack);

            // some time later
            pubnub.RemoveListener(listenerSubscribeCallack);
        }
示例#4
0
        public void Dispose()
        {
            if (_Disposed)
            {
                return;
            }
            //  TODO: check this - it looks dodgy
            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt((pubnubObj, message) => { }, (pubnubObj, presence) => { }, (pubnubObj, status) => { });

            _Pubnub.AddListener(listenerSubscribeCallack);
            // some time later
            _Pubnub.RemoveListener(listenerSubscribeCallack);
            _Pubnub.Destroy();
            _Disposed = true;
        }
        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            data = e.Parameter as PubnubConfigData;

            if (data != null)
            {
                config                            = new PNConfiguration();
                config.PublishKey                 = data.publishKey;
                config.SubscribeKey               = data.subscribeKey;
                config.SecretKey                  = data.secretKey;
                config.CipherKey                  = data.cipherKey;
                config.Secure                     = data.ssl;
                config.Origin                     = data.origin;
                config.Uuid                       = data.sessionUUID;
                config.AuthKey                    = data.authKey;
                config.PresenceTimeout            = data.presenceHeartbeat;
                config.SubscribeTimeout           = data.subscribeTimeout;
                config.NonSubscribeRequestTimeout = data.nonSubscribeTimeout;
                config.UseClassicHttpWebRequest   = true;

                config.PubnubLog    = new PlatformPubnubLog();
                config.LogVerbosity = PNLogVerbosity.BODY;
                pubnub   = new Pubnub(config);
                listener = new SubscribeCallbackExt(
                    (o, m) =>
                {
                    DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                },
                    (o, p) =>
                {
                    DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(p));
                },
                    (o, s) =>
                {
                    DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                });
                //pubnub.NetworkCheckMaxRetries = data.maxRetries;
                //pubnub.NetworkCheckRetryInterval = data.retryInterval;
                //pubnub.LocalClientHeartbeatInterval = data.localClientHeartbeatInterval;
                //pubnub.EnableResumeOnReconnect = data.resumeOnReconnect;
                //pubnub.PresenceHeartbeat = data.presenceHeartbeat;
                //pubnub.PresenceHeartbeatInterval = data.presenceHeartbeatInterval;
            }
        }
示例#6
0
        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            data = e.Parameter as PubnubConfigData;

            if (data != null)
            {
                config                            = new PNConfiguration();
                config.PublishKey                 = data.publishKey;
                config.SubscribeKey               = data.subscribeKey;
                config.SecretKey                  = data.secretKey;
                config.CipherKey                  = data.cipherKey;
                config.Secure                     = data.ssl;
                config.Origin                     = data.origin;
                config.Uuid                       = data.sessionUUID;
                config.AuthKey                    = data.authKey;
                config.PresenceTimeout            = data.presenceHeartbeat;
                config.SubscribeTimeout           = data.subscribeTimeout;
                config.NonSubscribeRequestTimeout = data.nonSubscribeTimeout;
                config.UseClassicHttpWebRequest   = true;

                config.PubnubLog    = new PlatformPubnubLog();
                config.LogVerbosity = PNLogVerbosity.BODY;
                pubnub   = new Pubnub(config);
                listener = new SubscribeCallbackExt(
                    async(o, m) =>
                {
                    await DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(m)).ConfigureAwait(false);
                },
                    async(o, p) =>
                {
                    await DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(p)).ConfigureAwait(false);
                },
                    async(o, s) =>
                {
                    await DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(s)).ConfigureAwait(false);
                });
            }
        }
        public static void ThenSubscriberShouldBeAbleToReceiveManyMessages()
        {
            server.ClearRequests();

            bool receivedMessage          = false;
            bool receivedErrorMessage     = false;
            int  numberOfReceivedMessages = 0;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }

            server.RunOnHttps(false);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) =>
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                if (m != null)
                {
                    Debug.WriteLine("SubscribeCallback: PNMessageResult: {0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(m.Message));
                    numberOfReceivedMessages++;
                    if (numberOfReceivedMessages >= 10)
                    {
                        receivedMessage = true;
                        subscribeManualEvent.Set();
                    }
                }
            },
                (o, p) => {
                subscribeManualEvent.Set();
            },
                (o, s) => {
                Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode));
                if (s.StatusCode != 200 || s.Error)
                {
                    receivedErrorMessage = true;
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                    subscribeManualEvent.Set();
                }
                else if (s.StatusCode == 200 && s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    receivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            manualResetEventWaitTimeout = 310 * 1000;

            string channel = "hello_my_channel";

            numberOfReceivedMessages = 0;

            string expected = "{\"t\":{\"t\":\"14839022442039237\",\"r\":7},\"m\":[]}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithParameter("heartbeat", "300")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("tt", "0")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            expected = "{}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Subscribe <string>().Channels(new [] { channel }).Execute();
            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

            if (!receivedErrorMessage)
            {
                if (receivedMessage && !PubnubCommon.EnableStubTest)
                {
                    for (int index = 0; index < 10; index++)
                    {
                        Debug.WriteLine("ThenSubscriberShouldBeAbleToReceiveManyMessages..Publishing " + index.ToString());
                        ManualResetEvent publishManualEvent = new ManualResetEvent(false);
                        pubnub.Publish().Channel(channel).Message(index.ToString())
                        .Execute(new PNPublishResultExt((r, s) =>
                        {
                            if (r != null && s.StatusCode == 200 && !s.Error)
                            {
                                receivedMessage = true;
                            }
                            publishManualEvent.Set();
                        }));
                        publishManualEvent.WaitOne(manualResetEventWaitTimeout);
                    }
                }

                pubnub.Unsubscribe <string>().Channels(new[] { channel }).Execute();

                Thread.Sleep(1000);
            }

            pubnub.RemoveListener(listenerSubCallack);
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;

            Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannel --> ThenSubscriberShouldBeAbleToReceiveManyMessages Failed");
        }
        public static void ThenMultiSubscribeShouldReturnConnectStatusSSL()
        {
            server.ClearRequests();

            bool receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = true,
                LogVerbosity = PNLogVerbosity.BODY,
                PubnubLog    = new TestLog(),
                NonSubscribeRequestTimeout = 120
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }

            server.RunOnHttps(true);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) => { },
                (o, p) => { },
                (o, s) => {
                Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode));
                if (s.StatusCode == 200 && s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    receivedMessage = true;
                }
                subscribeManualEvent.Set();
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            manualResetEventWaitTimeout = 310 * 1000;

            string channel1 = "hello_my_channel1";

            string expected = "{\"t\":{\"t\":\"14839022442039237\",\"r\":7},\"m\":[]}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel1))
                              .WithParameter("heartbeat", "300")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("tt", "0")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            expected = "{}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Subscribe <string>().Channels(new [] { channel1 }).Execute();
            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

            string channel2 = "hello_my_channel2";

            if (receivedMessage)
            {
                receivedMessage      = false;
                subscribeManualEvent = new ManualResetEvent(false);

                expected = "{\"t\":{\"t\":\"14836303477713304\",\"r\":7},\"m\":[]}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel1 + "," + channel2))
                                  .WithParameter("heartbeat", "300")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("tt", "0")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                expected = "{}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel1 + "," + channel2))
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                Thread.Sleep(1000);

                pubnub.Subscribe <string>().Channels(new [] { channel2 }).Execute();
                subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status
            }

            Thread.Sleep(1000);

            pubnub.Unsubscribe <string>().Channels(new [] { channel1, channel2 }).Execute();
            pubnub.RemoveListener(listenerSubCallack);
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;

            Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannel --> ThenMultiSubscribeShouldReturnConnectStatusSSL Failed");
        }
        private static void CommonComplexMessageSubscribeShouldReturnReceivedMessageBasedOnParams(string secretKey, string cipherKey, bool ssl, out bool receivedMessage)
        {
            if (PubnubCommon.PAMServerSideRun && string.IsNullOrEmpty(secretKey))
            {
                Assert.Ignore("Ignored for Server side run");
            }
            bool        internalReceivedMessage = false;
            bool        receivedErrorMessage    = false;
            CustomClass publishedMessage        = new CustomClass();

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                CipherKey    = cipherKey,
                Uuid         = "mytestuuid",
                Secure       = ssl
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = secretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }

            server.RunOnHttps(ssl);

            ManualResetEvent subscribeManualEvent = new ManualResetEvent(false);

            SubscribeCallback listenerSubCallack = new SubscribeCallbackExt(
                (o, m) =>
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                if (m != null)
                {
                    Debug.WriteLine("SubscribeCallback: PNMessageResult: {0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(m.Message));
                    if (pubnub.JsonPluggableLibrary.SerializeToJsonString(publishedMessage) == m.Message.ToString())
                    {
                        internalReceivedMessage = true;
                    }
                    subscribeManualEvent.Set();
                }
            },
                (o, p) => {
                subscribeManualEvent.Set();
            },
                (o, s) => {
                Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode));
                if (s.StatusCode != 200 || s.Error)
                {
                    receivedErrorMessage = true;
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                    subscribeManualEvent.Set();
                }
                else if (s.StatusCode == 200 && s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    internalReceivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            string channel = "hello_my_channel";

            manualResetEventWaitTimeout = 310 * 1000;


            string expected = "{\"t\":{\"t\":\"14836303477713304\",\"r\":7},\"m\":[]}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithParameter("auth", authKey)
                              .WithParameter("heartbeat", "300")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("tt", "0")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "zJpO1HpSZxGkOr3EALbOk-vQgjIZTZ6AU5svzNU9l_A=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithParameter("auth", authKey)
                              .WithParameter("heartbeat", "300")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("tt", "0")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            expected = "{}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Subscribe <string>().Channels(new [] { channel }).Execute();
            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status


            expected = "[1,\"Sent\",\"14836234233392078\"]";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/publish/demo-36/{0}/0/{1}/0/{2}", PubnubCommon.SubscribeKey, channel, "%7B%22foo%22%3A%22hi%21%22%2C%22bar%22%3A%5B1%2C2%2C3%2C4%2C5%5D%7D"))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/publish/demo-36/{0}/0/{1}/0/{2}", PubnubCommon.SubscribeKey, channel, "%22Zbr7pEF%2FGFGKj1rOstp0tWzA4nwJXEfj%2BezLtAr8qqE%3D%22"))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            Thread.Sleep(1000);

            if (!receivedErrorMessage)
            {
                ManualResetEvent publishManualEvent = new ManualResetEvent(false);
                pubnub.Publish().Channel(channel).Message(publishedMessage)
                .Execute(new PNPublishResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        internalReceivedMessage = true;
                    }
                    publishManualEvent.Set();
                }));

                publishManualEvent.WaitOne(manualResetEventWaitTimeout);

                pubnub.Unsubscribe <string>().Channels(new[] { channel }).Execute();

                Thread.Sleep(1000);
            }

            receivedMessage = internalReceivedMessage;
            pubnub.RemoveListener(listenerSubCallack);
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
示例#10
0
        public static void ThenSubscribeShouldReturnReceivedMessage()
        {
            server.ClearRequests();

            bool receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false,
                LogVerbosity = PNLogVerbosity.BODY,
                PubnubLog    = new TestLog(),
                NonSubscribeRequestTimeout = 120
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }

            server.RunOnHttps(false);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) => {
                if (m != null)
                {
                    Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                    if (string.Compare(publishedMessage.ToString(), m.Message.ToString(), true) == 0)
                    {
                        receivedMessage = true;
                    }
                }
                subscribeManualEvent.Set();
            },
                (o, p) => { /* Catch the presence events */ },
                (o, s) => {
                Debug.WriteLine("SubscribeCallback: PNStatus: " + s.StatusCode.ToString());
                if (s.StatusCode != 200 || s.Error)
                {
                    subscribeManualEvent.Set();
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                }
                else if (s.StatusCode == 200 && (s.Category == PNStatusCategory.PNConnectedCategory || s.Category == PNStatusCategory.PNDisconnectedCategory))
                {
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName))
                              .WithParameter("add", channelName)
                              .WithParameter("auth", config.AuthKey)
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            ManualResetEvent channelGroupManualEvent = new ManualResetEvent(false);

            pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName }).ChannelGroup(channelGroupName).QueryParam(new Dictionary <string, object> {
                { "ut", "ThenSubscribeShouldReturnReceivedMessage" }
            })
            .Execute(new PNChannelGroupsAddChannelResultExt((r, s) => {
                try
                {
                    Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    if (r != null)
                    {
                        Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                        if (s.StatusCode == 200 && s.Error == false && s.AffectedChannelGroups.Contains(channelGroupName))
                        {
                            receivedMessage = true;
                        }
                    }
                }
                catch { /* ignore */ }
                finally { channelGroupManualEvent.Set(); }
            }));
            channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;

                expected = "{\"t\":{\"t\":\"14839022442039237\",\"r\":7},\"m\":[]}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithParameter("auth", authKey)
                                  .WithParameter("channel-group", "hello_my_group")
                                  .WithParameter("heartbeat", "300")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("tt", "0")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                expected = "{}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                pubnub.Subscribe <string>().ChannelGroups(new [] { channelGroupName }).QueryParam(new Dictionary <string, object> {
                    { "ut", "ThenSubscribeShouldReturnReceivedMessage" }
                }).Execute();
                subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

                subscribeManualEvent = new ManualResetEvent(false);

                publishedMessage = "Test for WhenSubscribedToAChannelGroup ThenItShouldReturnReceivedMessage";

                expected = "[1,\"Sent\",\"14722484585147754\"]";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/%22Test%20for%20WhenSubscribedToAChannelGroup%20ThenItShouldReturnReceivedMessage%22", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channelName))
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                Thread.Sleep(1000);

                ManualResetEvent publishManualEvent = new ManualResetEvent(false);
                pubnub.Publish().Channel(channelName).Message(publishedMessage).QueryParam(new Dictionary <string, object> {
                    { "ut", "ThenSubscribeShouldReturnReceivedMessage" }
                })
                .Execute(new PNPublishResultExt((r, s) =>
                {
                    Debug.WriteLine("Publish PNStatus => Status = : " + s.StatusCode.ToString());
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        Debug.WriteLine("Publish Response: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                        publishTimetoken = r.Timetoken;
                        receivedMessage  = true;
                    }

                    publishManualEvent.Set();
                }));
                publishManualEvent.WaitOne(manualResetEventWaitTimeout);

                Thread.Sleep(1000);
                pubnub.Unsubscribe <string>().ChannelGroups(new [] { channelGroupName }).QueryParam(new Dictionary <string, object> {
                    { "ut", "ThenSubscribeShouldReturnReceivedMessage" }
                }).Execute();
                Thread.Sleep(1000);
                pubnub.RemoveListener(listenerSubCallack);
                pubnub.Destroy();
                pubnub.PubnubUnitTest = null;
                pubnub = null;

                Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed");
            }
            else
            {
                Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed");
            }
        }
示例#11
0
        public void Initialize(string userId, long lastActivity = 0)
        {
            try
            {
                //  we can only initialize if the user is registered
                if (string.IsNullOrEmpty(userId))
                {
                    return;
                }
                _UserId = userId;

                PNConfiguration config = new PNConfiguration();
                config.PublishKey   = _PublishKey;
                config.SubscribeKey = _SubscribeKey;
                config.Uuid         = _UserId;
                config.Secure       = true;

                _Pubnub = new Pubnub(config);

                SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt((pubnubObj, message) =>
                {
                    try
                    {
                        //  get the message base to determine type
                        BaseMessage m = Serializer.Deserialize <BaseMessage>(message.Message.ToString());
                        //  deserialize to actual type
                        m = (BaseMessage)Serializer.Deserialize(GetType().Assembly.GetType(m.Type), message.Message.ToString());
                        //  let listeners know
                        MessageReceived?.Invoke(this, new MessageEventArgs <BaseMessage>(m));
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.MessageReceived - Unable to deserialize message: {0}", message.Message.ToString()));
                    }
                }, (pubnubObj, presence) =>
                {
                    // handle incoming presence data
                    if (presence.Event.Equals("join"))
                    {
                        RaiseChannelJoined(presence.Channel, presence.Uuid);
                    }
                    else if (presence.Event.Equals("leave"))
                    {
                        RaiseChannelLeft(presence.Channel, presence.Uuid);
                    }
                    else if (presence.Event.Equals("state-change"))
                    {
                        //  listen for status events - eg: typing, etc
                        if ((presence.State == null) || (presence.State.Count == 0))
                        {
                            return;
                        }
                        foreach (var key in presence.State.Keys)
                        {
                            var state = (ChatState)Enum.Parse(typeof(ChatState), presence.State[key].ToString());
                            RaiseChannelState(presence.Channel, presence.Uuid, state);
                        }
                    }
                    else if (presence.Event.Equals("timeout"))
                    {
                    }
                    else if (presence.Event.Equals("interval"))
                    {
                        //  find the ids that have joined
                        if ((presence.Join != null) && (presence.Join.Length > 0))
                        {
                            foreach (var uuid in presence.Join)
                            {
                                RaiseChannelJoined(presence.Channel, uuid);
                            }
                        }
                        if ((presence.Leave != null) && (presence.Leave.Length > 0))
                        {
                            foreach (var uuid in presence.Leave)
                            {
                                RaiseChannelJoined(presence.Channel, uuid);
                            }
                        }
                    }
                    else if (presence.HereNowRefresh)
                    {
                        //  TODO: request state for channels
                        //GetState();
                    }
                }, (pubnubObj, status) =>
                {
                    if (status.Operation == PNOperationType.PNHeartbeatOperation)
                    {
                        Connected = !status.Error;
                        ConnectedChanged?.Invoke(this, new EventArgs());
                    }
                    else if ((status.Operation != PNOperationType.PNSubscribeOperation) && (status.Operation != PNOperationType.PNUnsubscribeOperation))
                    {
                        return;
                    }

                    if (status.Category == PNStatusCategory.PNConnectedCategory)
                    {
                        // this is expected for a subscribe, this means there is no error or issue whatsoever
                    }
                    else if (status.Category == PNStatusCategory.PNReconnectedCategory)
                    {
                        // this usually occurs if subscribe temporarily fails but reconnects. This means
                        // there was an error but there is no longer any issue
                    }
                    else if (status.Category == PNStatusCategory.PNDisconnectedCategory)
                    {
                        // this is the expected category for an unsubscribe. This means there
                        // was no error in unsubscribing from everything
                    }
                    else if (status.Category == PNStatusCategory.PNUnexpectedDisconnectCategory)
                    {
                        // this is usually an issue with the internet connection, this is an error, handle appropriately
                    }
                    else if (status.Category == PNStatusCategory.PNAccessDeniedCategory)
                    {
                        // this means that PAM does allow this client to subscribe to this
                        // channel and channel group configuration. This is another explicit error
                    }
                });

                _Pubnub.AddListener(listenerSubscribeCallack);

                //  create and subscribe to the lobby channel
                _Pubnub
                .Subscribe <string>()
                .Channels(new string[] { _UserId })
                .WithPresence()
                .Execute();

                Initialized = true;
                InitializedChanged?.Invoke(this, new EventArgs());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.Initialize - Exception: {0}", ex));
            }
        }
        public static void ThenShouldReturnUnsubscribedMessage()
        {
            server.RunOnHttps(false);

            bool receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            server.RunOnHttps(false);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) => { if (m != null)
                            {
                                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                            }
                },
                (o, p) => { /* Catch the presence events */ },
                (o, s) => {
                Debug.WriteLine("SubscribeCallback: PNStatus: " + s.StatusCode.ToString());
                if (s.StatusCode != 200 || s.Error)
                {
                    subscribeManualEvent.Set();
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                }
                else if (s.StatusCode == 200 && (s.Category == PNStatusCategory.PNConnectedCategory || s.Category == PNStatusCategory.PNDisconnectedCategory))
                {
                    receivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            channelGroupName = "hello_my_group";
            string channelName = "hello_my_channel";

            int manualResetEventWaitTimeout = 310 * 1000;

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName))
                              .WithParameter("add", channelName)
                              .WithParameter("auth", config.AuthKey)
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            ManualResetEvent cgManualEvent = new ManualResetEvent(false);

            pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName }).ChannelGroup(channelGroupName)
            .Execute(new PNChannelGroupsAddChannelResultExt((r, s) => {
                try
                {
                    Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    if (r != null)
                    {
                        Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                        if (s.StatusCode == 200 && s.Error == false && s.AffectedChannelGroups.Contains(channelGroupName))
                        {
                            receivedMessage = true;
                        }
                    }
                }
                catch { /* ignore */ }
                finally { cgManualEvent.Set(); }
            }));
            cgManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;
                expected        = "{\"t\":{\"t\":\"14839022442039237\",\"r\":7},\"m\":[]}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithParameter("auth", authKey)
                                  .WithParameter("channel-group", channelGroupName)
                                  .WithParameter("heartbeat", "300")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("tt", "0")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                expected = "{}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                pubnub.Subscribe <string>().ChannelGroups(new [] { channelGroupName }).Execute();
                subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

                if (receivedMessage)
                {
                    receivedMessage      = false;
                    subscribeManualEvent = new ManualResetEvent(false);

                    expected = "{\"status\": 200, \"action\": \"leave\", \"message\": \"OK\", \"service\": \"Presence\"}";

                    server.AddRequest(new Request()
                                      .WithMethod("GET")
                                      .WithPath(String.Format("/v2/presence/sub_key/{0}/channel/{1}/leave", PubnubCommon.SubscribeKey, channelGroupName))
                                      .WithResponse(expected)
                                      .WithStatusCode(System.Net.HttpStatusCode.OK));

                    pubnub.Unsubscribe <string>().ChannelGroups(new [] { channelGroupName }).Execute();
                    subscribeManualEvent.WaitOne(manualResetEventWaitTimeout);
                }

                pubnub.RemoveListener(listenerSubCallack);
                pubnub.Destroy();
                pubnub.PubnubUnitTest = null;
                pubnub = null;

                Assert.IsTrue(receivedMessage, "WhenUnsubscribedToAChannelGroup --> ThenShouldReturnUnsubscribedMessage Failed");
            }
            else
            {
                Assert.IsTrue(receivedMessage, "WhenUnsubscribedToAChannelGroup --> ThenShouldReturnUnsubscribedMessage Failed");
            }
        }
        public static void ThenMultiSubscribeShouldReturnConnectStatus()
        {
            server.ClearRequests();

            bool receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                AuthKey      = authKey,
                Secure       = false
            };

            server.RunOnHttps(false);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) => { if (m != null)
                            {
                                Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                            }
                },
                (o, p) => { /* Catch the presence events */ },
                (o, s) => {
                Console.WriteLine("SubscribeCallback: PNStatus: " + s.StatusCode.ToString());
                if (s.StatusCode != 200 || s.Error)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    if (s.ErrorData != null)
                    {
                        Console.WriteLine(s.ErrorData.Information);
                    }
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else if (s.StatusCode == 200 &&
                         (s.AffectedChannelGroups != null && s.AffectedChannelGroups.Contains(channelGroupName1) && s.AffectedChannelGroups.Contains(channelGroupName2)) &&
                         s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    receivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            manualResetEventWaitTimeout = 310 * 1000;

            channelGroupName1 = "hello_my_group1";
            channelGroupName2 = "hello_my_group2";

            string channelName1 = "hello_my_channel1";
            string channelName2 = "hello_my_channel2";

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName1))
                              .WithParameter("add", channelName1)
                              .WithParameter("auth", config.AuthKey)
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            ManualResetEvent channelGroupManualEvent = new ManualResetEvent(false);

            pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName1 }).ChannelGroup(channelGroupName1)
            .Async(new PNChannelGroupsAddChannelResultExt((r, s) => {
                try
                {
                    Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    if (r != null)
                    {
                        Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                        if (s.StatusCode == 200 && s.Error == false && (s.AffectedChannelGroups.Contains(channelGroupName1) || s.AffectedChannelGroups.Contains(channelGroupName2)))
                        {
                            receivedMessage = true;
                        }
                    }
                }
                catch { /* ignore */ }
                finally { channelGroupManualEvent.Set(); }
            }));
            channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;

                expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName2))
                                  .WithParameter("add", channelName2)
                                  .WithParameter("auth", config.AuthKey)
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                channelGroupManualEvent = new ManualResetEvent(false);
                pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName2 }).ChannelGroup(channelGroupName2)
                .Async(new PNChannelGroupsAddChannelResultExt((r, s) => {
                    try
                    {
                        Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                        if (r != null)
                        {
                            Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            if (s.StatusCode == 200 && s.Error == false && (s.AffectedChannelGroups.Contains(channelGroupName1) || s.AffectedChannelGroups.Contains(channelGroupName2)))
                            {
                                receivedMessage = true;
                            }
                        }
                    }
                    catch { /* ignore */ }
                    finally { channelGroupManualEvent.Set(); }
                }));
                channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (receivedMessage)
            {
                receivedMessage = false;

                expected = "{\"t\":{\"t\":\"14839022442039237\",\"r\":7},\"m\":[]}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithParameter("auth", config.AuthKey)
                                  .WithParameter("channel-group", "hello_my_group1,hello_my_group2")
                                  .WithParameter("heartbeat", "300")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("tt", "0")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                expected = "{}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));


                pubnub.Subscribe <string>().ChannelGroups(new [] { channelGroupName1, channelGroupName2 }).Execute();
                subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status
            }

            Thread.Sleep(1000);

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;

            Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
        }
示例#14
0
using PE.Plugins.PubnubChat.Models;

using PubnubApi;

using System;

namespace PE.Plugins.PubnubChat
{
    public enum ChatState
    {
        None,
        Waiting,
        Typing,
        InCall
    }

    public class ChatService : IChatService, IDisposable
    {
        #region Events

        public event InitializationChangedEventHandler InitializedChanged;
        public event EventHandler ConnectedChanged;
        public event EventHandler<MessageEventArgs> MessageReceived;
        public event EventHandler<PresenceEventArgs> ChannelJoined;
        public event EventHandler<PresenceEventArgs> ChannelLeft;
        public event EventHandler<PresenceEventArgs> ChannelTimeout;
        public event EventHandler<PresenceEventArgs> ChannelState;
        public event EventHandler<MessageEventArgs> PublishComplete;

        #endregion Events

        #region Fields

        private Pubnub _Pubnub;

        private readonly string _PublishKey = string.Empty;
        private readonly string _SubscribeKey = string.Empty;

        private SubscribeCallbackExt _ListenerSubscribeCallack;

        private string _UserId = string.Empty;
        private string _AuthKey = string.Empty;
        private bool _Disposed = false;

        private int _FailCount = 0;

        private string _PushData = string.Empty;

        #endregion Fields

        #region Constructors

        public ChatService(ChatConfiguration configuration)
        {
            _PublishKey = configuration.PublishKey;
            _SubscribeKey = configuration.SubscribeKey;
        }

        ~ChatService()
        {
            Dispose();
        }

        #endregion Constructors

        #region Properties

        public bool Connected { get; private set; }

        public bool Initialized { get; private set; } = false;

        #endregion Properties

        #region Init

        public void Initialize(string userId, string authKey = null, bool reset = true, string push = "")
        {
            System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.Uninitialize - Initializing Chat for user {_UserId}, Reset: {reset}");
            if (reset) _FailCount = 0;
            //  we can only initialize if the user is registered
            if (string.IsNullOrEmpty(userId)) return;
            _UserId = userId;
            _AuthKey = authKey;
            _PushData = push;

            PNConfiguration config = new PNConfiguration();
            config.PublishKey = _PublishKey;
            config.SubscribeKey = _SubscribeKey;
            config.Uuid = _UserId;
            config.Secure = true;
            config.HeartbeatNotificationOption = PNHeartbeatNotificationOption.All;
            if (!string.IsNullOrEmpty(authKey)) config.AuthKey = authKey;

            _Pubnub = new Pubnub(config);

            _ListenerSubscribeCallack = new SubscribeCallbackExt(
                (pubnub, message) => OnMessageReceived(pubnub, message),
                (pubnub, presence) => OnPresenceReceived(pubnub, presence),
                (pubnub, status) => OnStatusReceived(pubnub, status));

            _Pubnub.AddListener(_ListenerSubscribeCallack);

            //  create and subscribe to the lobby channel
            _Pubnub
                .Subscribe<string>()
                .Channels(new string[] { _UserId })
                .WithPresence()
                .Execute();

            //  add push if necessary
            if (!string.IsNullOrEmpty(_PushData))
            {
                var data = _PushData.Split(new char[] { '|' });
                if (data.Length != 2) throw new ArgumentException("Push initialization data.");

                var type = (PNPushType)Enum.Parse(typeof(PNPushType), data[0]);

                _Pubnub.AddPushNotificationsOnChannels()
                    .PushType(type)
                    .Channels(new string[] { _UserId })
                    //.DeviceId(data[1])
                    .DeviceId(data[1])
                    .Async(new AddPushChannelCallback());
                }
            Initialized = true;
            InitializedChanged?.Invoke(Initialized);
        }

        public void Uninitialize()
        {
            //  this can be called before Initialize
            if (_Pubnub == null) return;
            try
            {
                System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.Uninitialize - Uninitializing Chat for user {_UserId}");
                _Pubnub.RemoveListener(_ListenerSubscribeCallack);
                _Pubnub.Unsubscribe<string>().Channels(new string[] { _UserId }).Execute();
                //  TODO: consider removing push channel association here
                Initialized = false;
                InitializedChanged?.Invoke(Initialized);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"{ GetType().Name}.Uninitialize - Exception: { ex}");
            }
        }

        #endregion Init

        #region Callbacks

        private void OnMessageReceived(Pubnub pubnub, PNMessageResult<object> result)
        {
            try
            {
                MessageReceived?.Invoke(this, new MessageEventArgs(result.Message.ToString()));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.MessageReceived - Unable to deserialize message: { result.Message}\r\n\tException: { ex}");
            }
        }

        private void OnPresenceReceived(Pubnub pubnub, PNPresenceEventResult result)
        {
            System.Diagnostics.Debug.WriteLine($"*** { GetType().Name}.OnPresenceReceived\r\n -> Event: { result.Event}");
            {
                // handle incoming presence data 
                if (result.Event.Equals("join"))
                {
                    RaiseChannelJoined(result.Channel, result.Uuid);
                }
                else if (result.Event.Equals("leave"))
                {
                    RaiseChannelLeft(result.Channel, result.Uuid);
                }
                else if (result.Event.Equals("state-change"))
                {
                    //  listen for status events - eg: typing, etc
                    if ((result.State == null) || (result.State.Count == 0)) return;
                    foreach (var key in result.State.Keys)
                    {
                        var state = (ChatState)Enum.Parse(typeof(ChatState), result.State[key].ToString());
                        RaiseChannelState(result.Channel, result.Uuid, state);
                    }
                }
                else if (result.Event.Equals("timeout"))
                {
                }
                else if (result.Event.Equals("interval"))
                {
                    //  find the ids that have joined
                    if ((result.Join != null) && (result.Join.Length > 0))
                    {
                        foreach (var uuid in result.Join) RaiseChannelJoined(result.Channel, uuid);
                    }
                    if ((result.Leave != null) && (result.Leave.Length > 0))
                    {
                        foreach (var uuid in result.Leave) RaiseChannelJoined(result.Channel, uuid);
                    }
                }
                else if (result.HereNowRefresh)
                {
                    //  TODO: request state for channels
                    //GetState();
                }
            }
        }

        private void OnStatusReceived(Pubnub pubnub, PNStatus status)
        {
            {
                System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.OnStatusReceived\r\n -> Operation: { status.Operation}\r\n -> Category: { status.Category}\r\n -> Error: { status.Error}\r\n -> Data: { status.ErrorData}\r\n -> Status Code: { status.StatusCode}");

                if (status.Operation == PNOperationType.PNHeartbeatOperation)
                {
                    Connected = !status.Error;
                    ConnectedChanged?.Invoke(this, new EventArgs());
                }

                if ((status.Operation == PNOperationType.PNSubscribeOperation) && (status.Category == PNStatusCategory.PNUnknownCategory) && (status.StatusCode == 404))
                {
                    try
                    {
                        _FailCount++;
                        if (_FailCount > 3)
示例#15
0
        public static async Task ThenWithAsyncSendFileShouldReturnSuccess()
#endif
        {
            server.ClearRequests();

            receivedMessage = false;
            bool receivedEvent = false;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNFileEventResult eventResult)
            {
                receivedEvent = true;
                System.Diagnostics.Debug.WriteLine("FILE EVENT: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                //CipherKey = "enigma",
                Uuid   = "mytestuuid",
                Secure = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            mre = new ManualResetEvent(false);
            pubnub.Subscribe <string>().Channels(new string[] { channelName }).Execute();
            mre.WaitOne(2000);

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            mre = new ManualResetEvent(false);

            string fileId   = "";
            string fileName = "";

            receivedMessage = false;
            string targetFileUpload = @"C:\Pandu\pubnub\word_test.txt";
            Dictionary <string, object> myInternalMsg = new Dictionary <string, object>();

            myInternalMsg.Add("color", "red");
            myInternalMsg.Add("name", "John Doe");
#if NET40
            PNResult <PNFileUploadResult> sendFileResult = Task.Factory.StartNew(async() => await pubnub.SendFile().Channel(channelName).File(targetFileUpload).Message(myInternalMsg).ExecuteAsync()).Result.Result;
#else
            PNResult <PNFileUploadResult> sendFileResult = await pubnub.SendFile().Channel(channelName).File(targetFileUpload).Message(myInternalMsg).ExecuteAsync();
#endif
            if (sendFileResult.Result != null && !string.IsNullOrEmpty(sendFileResult.Result.FileId) && sendFileResult.Result.Timetoken > 0)
            {
                System.Diagnostics.Debug.WriteLine("SendFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(sendFileResult.Result));
                fileId          = sendFileResult.Result.FileId;
                fileName        = sendFileResult.Result.FileName;
                receivedMessage = true;
            }

            receivedMessage = false;
            mre             = new ManualResetEvent(false);
            pubnub.ListFiles().Channel(channelName)
            .Execute(new PNListFilesResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("ListFiles result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    receivedMessage = true;
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();


            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DownloadFile().Channel(channelName).FileId(fileId).FileName(fileName).Execute(new PNDownloadFileResultExt((result, status) =>
                {
                    if (result != null && result.FileBytes != null && result.FileBytes.Length > 0)
                    {
                        System.Diagnostics.Debug.WriteLine("DownloadFile result = " + result.FileBytes.Length);
                        receivedMessage = true;
                    }
                    mre.Set();
                }));
                mre.WaitOne();
            }

            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DeleteFile().Channel(channelName).FileId(fileId).FileName(fileName)
                .Execute(new PNDeleteFileResultExt((result, status) =>
                {
                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine("DeleteFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                        receivedMessage = true;
                    }
                    mre.Set();
                }));
                Thread.Sleep(1000);
                mre.WaitOne();
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage && receivedEvent, "WhenFileIsRequested -> ThenWithAsyncSendFileShouldReturnSuccess failed.");
        }
        public static void ThenSubscribeShouldReturnConnectStatus()
        {
            server.ClearRequests();

            bool receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(false);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) => { },
                (o, p) => { },
                (o, s) => {
                Console.WriteLine("{0} {1} {2}", s.Operation, s.Category, s.StatusCode);
                if (s.StatusCode == 200 && s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    receivedMessage = true;
                }
                subscribeManualEvent.Set();
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            string channel = "hello_my_channel";

            manualResetEventWaitTimeout = 310 * 1000;

            string expected = "{\"t\":{\"t\":\"14836303477713304\",\"r\":7},\"m\":[]}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithParameter("heartbeat", "300")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("tt", "0")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            expected = "{}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, channel))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Subscribe <string>().Channels(new [] { channel }).Execute();
            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

            Thread.Sleep(1000);
            pubnub.Unsubscribe <string>().Channels(new [] { channel }).Execute();

            Thread.Sleep(1000);

            pubnub.RemoveListener(listenerSubCallack);
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;

            Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannel --> ThenSubscribeShouldReturnConnectStatus Failed");
        }
示例#17
0
        public static void ThenUserUpdateDeleteShouldReturnEventInfo()
        {
            server.ClearRequests();

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Ignored ThenUserUpdateDeleteShouldReturnEventInfo");
                return;
            }

            bool receivedMessage     = false;
            bool receivedDeleteEvent = false;
            bool receivedUpdateEvent = false;

            string userId = "pandu-ut-uid";

            manualResetEventWaitTimeout = 310 * 1000;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNObjectApiEventResult eventResult)
            {
                System.Diagnostics.Debug.WriteLine("EVENT:" + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
                if (eventResult.Type.ToLowerInvariant() == "user")
                {
                    if (eventResult.Event.ToLowerInvariant() == "update")
                    {
                        receivedUpdateEvent = true;
                    }
                    else if (eventResult.Event.ToLowerInvariant() == "delete")
                    {
                        receivedDeleteEvent = true;
                    }
                }
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMEnabled)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            server.RunOnHttps(false);
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            ManualResetEvent manualEvent = new ManualResetEvent(false);

            pubnub.Subscribe <string>().Channels(new string[] { "pnuser-" + userId }).Execute();
            manualEvent.WaitOne(2000);

            manualEvent = new ManualResetEvent(false);
            System.Diagnostics.Debug.WriteLine("pubnub.DeleteUser() STARTED");
            pubnub.DeleteUser().Id(userId).Execute(new PNDeleteUserResultExt(
                                                       delegate(PNDeleteUserResult result, PNStatus status) { }));
            manualEvent.WaitOne(2000);

            manualEvent = new ManualResetEvent(false);
            #region "CreateUser"
            System.Diagnostics.Debug.WriteLine("pubnub.CreateUser() STARTED");
            pubnub.CreateUser().Id(userId).Name("pandu-ut-un")
            .Execute(new PNCreateUserResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                    if (userId == r.Id)
                    {
                        receivedMessage = true;
                    }
                }
                manualEvent.Set();
            }));
            #endregion
            manualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;
                manualEvent     = new ManualResetEvent(false);
                #region "UpdateUser"
                System.Diagnostics.Debug.WriteLine("pubnub.UpdateUser() STARTED");
                pubnub.UpdateUser().Id(userId).Name("pandu-ut-un-upd")
                .ProfileUrl("pandu-sample-profile-url").ExternalId("pandu-sample-ext-id")
                .Email("*****@*****.**")
                .CustomObject(new Dictionary <string, object>()
                {
                    { "color", "red" }
                })
                .Execute(new PNUpdateUserResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                        if (userId == r.Id)
                        {
                            receivedMessage = true;
                        }
                    }
                    manualEvent.Set();
                }));
                #endregion
                manualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (!receivedDeleteEvent)
            {
                manualEvent = new ManualResetEvent(false);
                System.Diagnostics.Debug.WriteLine("pubnub.DeleteUser() 2 STARTED");
                pubnub.DeleteUser().Id(userId).Execute(new PNDeleteUserResultExt(
                                                           delegate(PNDeleteUserResult result, PNStatus status) { }));
                manualEvent.WaitOne(2000);
            }

            pubnub.Unsubscribe <string>().Channels(new string[] { "pnuser-" + userId }).Execute();
            pubnub.RemoveListener(eventListener);

            Assert.IsTrue(receivedDeleteEvent && receivedUpdateEvent, "User events Failed");

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
        // Where pair like "BTC_USD"
        // TODO: change interface so SubscribeWebSocket takes (at least) a currency pair argument
        public void SubscribeWebSocket(string[] args = null)
        {
            var config = new PNConfiguration();

            config.SubscribeKey = "sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f";
            //config.AuthKey = this.ApiKey;
            //config.CipherKey = this.ApiSecret;
            var pubnub = new Pubnub(config);

            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
                (pubnubObj, message) => {
                // Handle new message stored in message.Message
                string channel = message.Channel;
                long timeToken = message.Timetoken;
                //cout("channel: {0}", channel);
                if (channel == "lightning_ticker_BTC_USD")
                {
                    var ticker = JsonConvert.DeserializeObject <BitFlyerWebsocketTicker>((string)message.Message);
                    //cout(ticker.ToString());
                }
                else if (channel == "lightning_board_BTC_USD")
                {
                    var obupdate = JsonConvert.DeserializeObject <BitFlyerOrderBookUpdate>((string)message.Message);
                    foreach (var b in obupdate.bids)
                    {
                        m_orderBook.UpdateBid(b.price, b.size);
                    }
                    foreach (var a in obupdate.asks)
                    {
                        m_orderBook.UpdateAsk(a.price, a.size);
                    }
                    FireOrderBookUpdate();
                    //cout(obupdate.ToString());
                }
            },
                (pubnubObj, presence) => {
                // handle incoming presence data
            },
                (pubnubObj, status) => {
                // the status object returned is always related to subscribe but could contain
                // information about subscribe, heartbeat, or errors
                // use the PNOperationType to switch on different options
                switch (status.Operation)
                {
                // let's combine unsubscribe and subscribe handling for ease of use
                case PNOperationType.PNSubscribeOperation:
                case PNOperationType.PNUnsubscribeOperation:
                    // note: subscribe statuses never have traditional
                    // errors, they just have categories to represent the
                    // different issues or successes that occur as part of subscribe
                    switch (status.Category)
                    {
                    case PNStatusCategory.PNConnectedCategory:
                        // this is expected for a subscribe, this means there is no error or issue whatsoever
                        break;

                    case PNStatusCategory.PNReconnectedCategory:
                        // this usually occurs if subscribe temporarily fails but reconnects. This means
                        // there was an error but there is no longer any issue
                        break;

                    case PNStatusCategory.PNDisconnectedCategory:
                        // this is the expected category for an unsubscribe. This means there
                        // was no error in unsubscribing from everything
                        break;

                    case PNStatusCategory.PNUnexpectedDisconnectCategory:
                        // this is usually an issue with the internet connection, this is an error, handle appropriately
                        break;

                    case PNStatusCategory.PNAccessDeniedCategory:
                        // this means that PAM does allow this client to subscribe to this
                        // channel and channel group configuration. This is another explicit error
                        break;

                    default:
                        // More errors can be directly specified by creating explicit cases for other
                        // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
                        break;
                    }
                    break;

                case PNOperationType.PNHeartbeatOperation:
                    // heartbeat operations can in fact have errors, so it is important to check first for an error.
                    if (status.Error)
                    {
                        // There was an error with the heartbeat operation, handle here
                    }
                    else
                    {
                        // heartbeat operation was successful
                    }
                    break;

                default:
                    // Encountered unknown status type
                    break;
                }
            });

            pubnub.AddListener(listenerSubscribeCallack);

            pubnub.Subscribe <string>()
            .Channels(new string[] {
                //"lightning_ticker_BTC_JPY",
                "lightning_ticker_BTC_USD",
                "lightning_board_BTC_USD"
            })
            .Execute();
        }
示例#19
0
        public static async Task ThenWithAsyncIgnoreCipherKeyUnencryptSignalListenerShouldGetMessagae()
#endif
        {
            server.ClearRequests();

            bool internalReceivedMessage = false;
            bool receivedErrorMessage    = false;

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Ignored ThenWithAsyncIgnoreCipherKeyUnencryptSignalListenerShouldGetMessagae");
                return;
            }

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                CipherKey    = "testcipherkey",
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }

            server.RunOnHttps(config.Secure);

            ManualResetEvent subscribeManualEvent = new ManualResetEvent(false);

            SubscribeCallback listenerSubCallack = new SubscribeCallbackExt(
                delegate(Pubnub o, PNSignalResult <object> m)
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                if (m != null)
                {
                    Debug.WriteLine(string.Format("Signal SubscribeCallback: PNMessageResult: {0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(m.Message)));
                    if (pubnub.JsonPluggableLibrary.SerializeToJsonString(messageForUnencryptSignal) == m.Message.ToString())
                    {
                        internalReceivedMessage = true;
                    }
                    subscribeManualEvent.Set();
                }
            },
                delegate(Pubnub o, PNStatus s) {
                Debug.WriteLine(string.Format("{0} {1} {2}", s.Operation, s.Category, s.StatusCode));
                if (s.StatusCode != 200 || s.Error)
                {
                    receivedErrorMessage = true;
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                    subscribeManualEvent.Set();
                }
                else if (s.StatusCode == 200 && s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    internalReceivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            string channel = "hello_my_channel";

            manualResetEventWaitTimeout = 310 * 1000;

            pubnub.Subscribe <string>().Channels(new[] { channel }).Execute();
            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for connect
            Thread.Sleep(1000);
            if (!receivedErrorMessage)
            {
                subscribeManualEvent    = new ManualResetEvent(false); //Reset to wait for message
                internalReceivedMessage = false;
#if NET40
                PNResult <PNPublishResult> signalResult = Task.Factory.StartNew(async() => await pubnub.Signal().Channel(channel).Message(messageForUnencryptSignal).ExecuteAsync()).Result.Result;
#else
                PNResult <PNPublishResult> signalResult = await pubnub.Signal().Channel(channel).Message(messageForUnencryptSignal).ExecuteAsync();
#endif
                if (signalResult.Result != null && signalResult.Status.StatusCode == 200 && !signalResult.Status.Error)
                {
                    internalReceivedMessage = true;
                }

                pubnub.Unsubscribe <string>().Channels(new[] { channel }).Execute();

                Thread.Sleep(1000);

                pubnub.RemoveListener(listenerSubCallack);
                pubnub.Destroy();
                pubnub.PubnubUnitTest = null;
                pubnub = null;
                if (receivedErrorMessage)
                {
                    internalReceivedMessage = false;
                }
                Assert.IsTrue(internalReceivedMessage, "WhenSubscribedToAChannel --> ThenWithAsyncIgnoreCipherKeyUnencryptSignalListenerShouldGetMessagae Failed");
            }
        }
示例#20
0
        public static void ThenMemberAddUpdateRemoveShouldReturnEventInfo()
        {
            server.ClearRequests();

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Ignored ThenMemberAddUpdateRemoveShouldReturnEventInfo");
                return;
            }

            bool receivedMessage     = false;
            bool receivedCreateEvent = false;
            bool receivedDeleteEvent = false;
            bool receivedUpdateEvent = false;

            string spaceId = "pandu-ut-sid";
            string userId1 = "pandu-ut-uid1";
            string userId2 = "pandu-ut-uid2";

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNObjectApiEventResult eventResult)
            {
                System.Diagnostics.Debug.WriteLine("EVENT:" + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
                if (eventResult.Type.ToLowerInvariant() == "membership")
                {
                    if (eventResult.Event.ToLowerInvariant() == "create")
                    {
                        receivedCreateEvent = true;
                    }
                    else if (eventResult.Event.ToLowerInvariant() == "update")
                    {
                        receivedUpdateEvent = true;
                    }
                    else if (eventResult.Event.ToLowerInvariant() == "delete")
                    {
                        receivedDeleteEvent = true;
                    }
                }
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMEnabled)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            server.RunOnHttps(false);
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            ManualResetEvent manualEvent = new ManualResetEvent(false);

            pubnub.Subscribe <string>().Channels(new string[] { "pnuser-" + userId1, "pnuser-" + userId2, spaceId }).Execute();
            manualEvent.WaitOne(2000);


            manualResetEventWaitTimeout = 310 * 1000;
            System.Diagnostics.Debug.WriteLine("pubnub.DeleteUser() 1 STARTED");
            manualEvent = new ManualResetEvent(false);
            pubnub.DeleteUser().Id(userId1).Execute(new PNDeleteUserResultExt(
                                                        delegate(PNDeleteUserResult result, PNStatus status) { }));
            manualEvent.WaitOne(2000);

            System.Diagnostics.Debug.WriteLine("pubnub.DeleteUser() 2 STARTED");
            manualEvent = new ManualResetEvent(false);
            pubnub.DeleteUser().Id(userId2).Execute(new PNDeleteUserResultExt(
                                                        delegate(PNDeleteUserResult result, PNStatus status) { }));
            manualEvent.WaitOne(2000);

            System.Diagnostics.Debug.WriteLine("pubnub.DeleteSpace() STARTED");
            manualEvent = new ManualResetEvent(false);
            pubnub.DeleteSpace().Id(spaceId).Execute(new PNDeleteSpaceResultExt(
                                                         delegate(PNDeleteSpaceResult result, PNStatus status) { }));
            manualEvent.WaitOne(2000);

            manualEvent     = new ManualResetEvent(false);
            receivedMessage = false;
            #region "CreateUser 1"
            System.Diagnostics.Debug.WriteLine("pubnub.CreateUser() 1 STARTED");
            pubnub.CreateUser().Id(userId1).Name("pandu-ut-un1")
            .Execute(new PNCreateUserResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                    if (userId1 == r.Id)
                    {
                        receivedMessage = true;
                    }
                }
                manualEvent.Set();
            }));
            #endregion
            manualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;
                manualEvent     = new ManualResetEvent(false);
                #region "CreateUser 2"
                System.Diagnostics.Debug.WriteLine("pubnub.CreateUser() 2 STARTED");
                pubnub.CreateUser().Id(userId2).Name("pandu-ut-un2")
                .Execute(new PNCreateUserResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                        if (userId2 == r.Id)
                        {
                            receivedMessage = true;
                        }
                    }
                    manualEvent.Set();
                }));
                #endregion
                manualEvent.WaitOne(manualResetEventWaitTimeout);
            }
            if (receivedMessage)
            {
                receivedMessage = false;
                manualEvent     = new ManualResetEvent(false);
                #region "CreateSpace"
                System.Diagnostics.Debug.WriteLine("pubnub.CreateSpace() STARTED");
                pubnub.CreateSpace().Id(spaceId).Name("pandu-ut-spname")
                .Execute(new PNCreateSpaceResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                        if (spaceId == r.Id)
                        {
                            receivedMessage = true;
                        }
                    }
                    manualEvent.Set();
                }));
                #endregion
                manualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (receivedMessage)
            {
                receivedMessage = false;
                manualEvent     = new ManualResetEvent(false);
                #region "Members Add"
                System.Diagnostics.Debug.WriteLine("pubnub.Members() ADD STARTED");
                pubnub.Members().SpaceId(spaceId)
                .Add(new List <PNMember>()
                {
                    new PNMember()
                    {
                        UserId = userId1
                    },
                    new PNMember()
                    {
                        UserId = userId2
                    }
                })
                .Execute(new PNMembersResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                        if (r.Members != null &&
                            r.Members.Find(x => x.UserId == userId1) != null &&
                            r.Members.Find(x => x.UserId == userId2) != null)
                        {
                            receivedMessage = true;
                        }
                    }
                    manualEvent.Set();
                }));
                #endregion
                manualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (receivedMessage)
            {
                receivedMessage = false;
                manualEvent     = new ManualResetEvent(false);
                #region "Members Update/Remove"
                System.Diagnostics.Debug.WriteLine("pubnub.Members() UPDATE/REMOVE STARTED");
                pubnub.Members().SpaceId(spaceId)
                .Update(new List <PNMember>()
                {
                    new PNMember()
                    {
                        UserId = userId1, Custom = new Dictionary <string, object>()
                        {
                            { "color", "green1" }
                        }
                    }
                })
                .Remove(new List <string>()
                {
                    userId2
                })
                .Execute(new PNMembersResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                        if (r.Members != null &&
                            r.Members.Find(x => x.UserId == userId1) != null)
                        {
                            receivedMessage = true;
                        }
                    }
                    manualEvent.Set();
                }));
                #endregion
                manualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            pubnub.Unsubscribe <string>().Channels(new string[] { "pnuser-" + userId1, "pnuser-" + userId2, spaceId }).Execute();
            pubnub.RemoveListener(eventListener);

            Assert.IsTrue(receivedDeleteEvent && receivedUpdateEvent && receivedCreateEvent, "Member events Failed");

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
示例#21
0
        public void AddListener(Func <MessageDTO, bool> func)
        {
            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt(
                (pubnubObj, message) =>
            {
                func(new MessageDTO(message.Message.ToString()));
            },
                (pubnubObj, presence) =>
            {
                // handle incoming presence data
            },
                (pubnubObj, status) =>
            {
                // the status object returned is always related to subscribe but could contain
                // information about subscribe, heartbeat, or errors
                // use the PNOperationType to switch on different options
                switch (status.Operation)
                {
                // let's combine unsubscribe and subscribe handling for ease of use
                case PNOperationType.PNSubscribeOperation:
                case PNOperationType.PNUnsubscribeOperation:
                    // note: subscribe statuses never have traditional
                    // errors, they just have categories to represent the
                    // different issues or successes that occur as part of subscribe
                    switch (status.Category)
                    {
                    case PNStatusCategory.PNConnectedCategory:
                        // this is expected for a subscribe, this means there is no error or issue whatsoever
                        break;

                    case PNStatusCategory.PNReconnectedCategory:
                        // this usually occurs if subscribe temporarily fails but reconnects. This means
                        // there was an error but there is no longer any issue
                        break;

                    case PNStatusCategory.PNDisconnectedCategory:
                        // this is the expected category for an unsubscribe. This means there
                        // was no error in unsubscribing from everything
                        break;

                    case PNStatusCategory.PNUnexpectedDisconnectCategory:
                        // this is usually an issue with the internet connection, this is an error, handle appropriately
                        break;

                    case PNStatusCategory.PNAccessDeniedCategory:
                        // this means that PAM does allow this client to subscribe to this
                        // channel and channel group configuration. This is another explicit error
                        break;

                    default:
                        // More errors can be directly specified by creating explicit cases for other
                        // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
                        break;
                    }
                    break;

                case PNOperationType.PNHeartbeatOperation:
                    // heartbeat operations can in fact have errors, so it is important to check first for an error.
                    if (status.Error)
                    {
                        // There was an error with the heartbeat operation, handle here
                    }
                    else
                    {
                        // heartbeat operation was successful
                    }
                    break;

                default:
                    // Encountered unknown status type
                    break;
                }
            }
                );

            pubnub.AddListener(listenerSubscribeCallack);
        }
示例#22
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.PageHomeView);

            string channelName      = Intent.GetStringExtra("Channel");
            string channelGroupName = Intent.GetStringExtra("ChannelGroup");

            bool   enableSSL = Convert.ToBoolean((Intent.GetStringExtra("SslOn")));
            string cipher    = (Intent.GetStringExtra("Cipher"));

            string ssl = "";

            if (enableSSL)
            {
                ssl = "SSL,";
            }

            if (!String.IsNullOrWhiteSpace(cipher))
            {
                cipher = " Cipher";
            }

            string head = String.Format("{0}{1}", ssl, cipher);

            pubnub = LaunchScreen.pubnub;

            config                    = pubnub.PNConfig;
            config.PubnubLog          = new LocalLog();
            config.LogVerbosity       = PNLogVerbosity.BODY;
            config.ReconnectionPolicy = PNReconnectionPolicy.LINEAR;

            listener = new SubscribeCallbackExt(
                (o, m) =>
            {
                if (m != null)
                {
                    Display(pubnub.JsonPluggableLibrary.SerializeToJsonString(m.Message));
                }
            },
                (o, p) =>
            {
                if (p != null)
                {
                    Display(p.Event);
                }
            },
                (o, s) =>
            {
                if (s != null)
                {
                    Display(s.Category + " " + s.Operation + " " + s.StatusCode);
                }
            });

            Title        = head;
            this.m_Title = this.m_DrawerTitle = this.Title;

            TextView txtSubscribedChannel = FindViewById <TextView> (Resource.Id.newChannels);

            txtSubscribedChannel.Text = channelName;
            channel = txtSubscribedChannel.Text;

            TextView txtSubscribedChannelGroup = FindViewById <TextView> (Resource.Id.newChannelGroups);

            txtSubscribedChannelGroup.Text = channelGroupName;
            channelGroup = txtSubscribedChannelGroup.Text;

            TextView txtViewLog = FindViewById <TextView> (Resource.Id.txtViewLog);

            txtViewLog.Text = "";
            try {
                this.m_Drawer                = this.FindViewById <DrawerLayout> (Resource.Id.drawer_layout);
                this.m_DrawerList            = this.FindViewById <ListView> (Resource.Id.left_drawer);
                this.m_DrawerList.Adapter    = new ArrayAdapter <string> (this, Resource.Layout.ItemMenu, Sections);
                this.m_DrawerList.ItemClick += (sender, args) => ListItemClicked(args.Position);

                this.m_Drawer.SetDrawerShadow(Resource.Drawable.drawer_shadow_dark, (int)GravityFlags.Start);
                //DrawerToggle is the animation that happens with the indicator next to the actionbar
                this.m_DrawerToggle = new MyActionBarDrawerToggle(this, this.m_Drawer,
                                                                  Resource.Drawable.ic_drawer_light,
                                                                  Resource.String.drawer_open,
                                                                  Resource.String.drawer_close);
                //Display the current fragments title and update the options menu
                this.m_DrawerToggle.DrawerClosed += (o, args) => {
                    this.ActionBar.Title = this.m_Title;
                    this.InvalidateOptionsMenu();
                };
                //Display the drawer title and update the options menu
                this.m_DrawerToggle.DrawerOpened += (o, args) => {
                    this.ActionBar.Title = this.m_DrawerTitle;
                    this.InvalidateOptionsMenu();
                };
                //Set the drawer lister to be the toggle.
                this.m_Drawer.SetDrawerListener(this.m_DrawerToggle);

                //if first time you will want to go ahead and click first item.
                this.ActionBar.SetDisplayHomeAsUpEnabled(true);
                this.ActionBar.SetHomeButtonEnabled(true);
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
示例#23
0
        void CallingPubnub()
        {
            Dictionary <string, string> message = new Dictionary <string, string>();

            message.Add("msg", "Hello World!");

            Pubnub pubnub = new Pubnub(pnConfiguration);

            SubscribeCallbackExt subscribeCallback = new SubscribeCallbackExt(
                (pubnubObj, messageResult) =>
            {
                if (messageResult != null)
                {
                    Debug.WriteLine("In Example, SusbcribeCallback received PNMessageResult");
                    Debug.WriteLine("In Example, SusbcribeCallback messsage channel = " + messageResult.Channel);
                    Debug.WriteLine("In Example, SusbcribeCallback messsage channelGroup = " + messageResult.Subscription);
                    Debug.WriteLine("In Example, SusbcribeCallback messsage publishTimetoken = " + messageResult.Timetoken);
                    Debug.WriteLine("In Example, SusbcribeCallback messsage publisher = " + messageResult.Publisher);
                    string jsonString = messageResult.Message.ToString();
                    Dictionary <string, string> msg = pubnub.JsonPluggableLibrary.DeserializeToObject <Dictionary <string, string> >(jsonString);
                    Debug.WriteLine("msg: " + msg["msg"]);

                    // MyList.Add(msg["msg"]);
                }
            },
                (pubnubObj, presencResult) =>
            {
                if (presencResult != null)
                {
                    Debug.WriteLine("In Example, SusbcribeCallback received PNPresenceEventResult");
                    Debug.WriteLine(presencResult.Channel + " " + presencResult.Occupancy + " " + presencResult.Event);
                }
            },
                (pubnubObj, statusResult) =>
            {
                if (statusResult.Category == PNStatusCategory.PNConnectedCategory)
                {
                    pubnub.Publish()
                    .Channel("my_channel")
                    .Message(message)
                    .Async(new PNPublishResultExt((publishResult, publishStatus) =>
                    {
                        if (!publishStatus.Error)
                        {
                            Debug.WriteLine(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow, publishResult.Timetoken));
                        }
                        else
                        {
                            Debug.WriteLine(publishStatus.Error);
                            Debug.WriteLine(publishStatus.ErrorData.Information);
                        }
                    }));
                }
            }
                );

            pubnub.AddListener(subscribeCallback);

            pubnub.Subscribe <string>()
            .Channels(new string[] {
                "my_channel"
            }).Execute();
        }
        public static void ThenChannelMetadataSetDeleteShouldReturnEventInfo()
        {
            server.ClearRequests();

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Ignored ThenChannelMetadataSetDeleteShouldReturnEventInfo");
                return;
            }

            bool receivedMessage     = false;
            bool receivedDeleteEvent = false;
            bool receivedUpdateEvent = false;

            string channelMetadataId = "pandu-ut-sid";

            manualResetEventWaitTimeout = 310 * 1000;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNObjectEventResult eventResult)
            {
                System.Diagnostics.Debug.WriteLine("EVENT:" + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
                if (eventResult.Type.ToLowerInvariant() == "channel")
                {
                    if (eventResult.Event.ToLowerInvariant() == "set")
                    {
                        receivedUpdateEvent = true;
                    }
                    else if (eventResult.Event.ToLowerInvariant() == "delete")
                    {
                        receivedDeleteEvent = true;
                    }
                }
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false,
                AuthKey      = "myauth"
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            server.RunOnHttps(false);
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            ManualResetEvent manualEvent = new ManualResetEvent(false);

            pubnub.Subscribe <string>().Channels(new string[] { channelMetadataId }).Execute();
            manualEvent.WaitOne(2000);

            manualEvent = new ManualResetEvent(false);
            System.Diagnostics.Debug.WriteLine("pubnub.RemoveChannelMetadata() STARTED");
            pubnub.RemoveChannelMetadata().Channel(channelMetadataId).Execute(new PNRemoveChannelMetadataResultExt(
                                                                                  delegate(PNRemoveChannelMetadataResult result, PNStatus status) { }));
            manualEvent.WaitOne(2000);

            manualEvent = new ManualResetEvent(false);
            #region "SetChannelMetadata"
            System.Diagnostics.Debug.WriteLine("pubnub.SetChannelMetadata() STARTED");
            pubnub.SetChannelMetadata().Channel(channelMetadataId).Name("pandu-ut-spname")
            .Execute(new PNSetChannelMetadataResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                    if (channelMetadataId == r.Channel)
                    {
                        receivedMessage = true;
                    }
                }
                manualEvent.Set();
            }));
            #endregion
            manualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;
                manualEvent     = new ManualResetEvent(false);
                #region "SetChannelMetadata"
                System.Diagnostics.Debug.WriteLine("pubnub.SetChannelMetadata() STARTED");
                pubnub.SetChannelMetadata().Channel(channelMetadataId).Name("pandu-ut-spname-upd")
                .Description("pandu-ut-spdesc")
                .Custom(new Dictionary <string, object>()
                {
                    { "color", "red" }
                })
                .Execute(new PNSetChannelMetadataResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        pubnub.JsonPluggableLibrary.SerializeToJsonString(r);
                        if (channelMetadataId == r.Channel)
                        {
                            receivedMessage = true;
                        }
                    }
                    manualEvent.Set();
                }));
                #endregion
                manualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (!receivedDeleteEvent)
            {
                manualEvent = new ManualResetEvent(false);
                System.Diagnostics.Debug.WriteLine("pubnub.RemoveChannelMetadata() 2 STARTED");
                pubnub.RemoveChannelMetadata().Channel(channelMetadataId).Execute(new PNRemoveChannelMetadataResultExt(
                                                                                      delegate(PNRemoveChannelMetadataResult result, PNStatus status) { }));
                manualEvent.WaitOne(2000);
            }

            Thread.Sleep(2000);

            pubnub.Unsubscribe <string>().Channels(new string[] { channelMetadataId }).Execute();
            pubnub.RemoveListener(eventListener);

            Assert.IsTrue(receivedDeleteEvent && receivedUpdateEvent, "Channel Metadata events Failed");

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
示例#25
0
        public static async Task ThenWithAsyncAddRemoveMessageActionReturnEventInfo()
#endif
        {
            server.ClearRequests();
            if (!PubnubCommon.PAMServerSideRun)
            {
                Assert.Ignore("ThenWithAsyncAddRemoveMessageActionReturnEventInfo needs Secret Key");
                return;
            }

            bool receivedMessage     = false;
            bool receivedAddEvent    = false;
            bool receivedRemoveEvent = false;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNMessageActionEventResult eventResult)
            {
                System.Diagnostics.Debug.WriteLine("EVENT:" + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
                if (eventResult.Event == "added")
                {
                    receivedAddEvent = true;
                }
                else if (eventResult.Event == "removed")
                {
                    receivedRemoveEvent = true;
                }
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            string channel = "hello_my_channel";

            manualResetEventWaitTimeout = (PubnubCommon.EnableStubTest) ? 1000 : 310 * 1000;
            long   currentMessageTimetoken = new Random().Next(Int32.MaxValue);
            long   currentActionTimetoken  = 0;
            string currentUUID             = "";

            ManualResetEvent me = new ManualResetEvent(false);

            pubnub.Subscribe <string>().Channels(new string[] { channel }).Execute();
            me.WaitOne(2000);

            System.Diagnostics.Debug.WriteLine("GetMessageActions STARTED");
#if NET40
            PNResult <PNGetMessageActionsResult> getMsgActionResult = Task.Factory.StartNew(async() => await pubnub.GetMessageActions().Channel(channel).ExecuteAsync()).Result.Result;
#else
            PNResult <PNGetMessageActionsResult> getMsgActionResult = await pubnub.GetMessageActions().Channel(channel).ExecuteAsync();
#endif
            if (getMsgActionResult.Result != null && getMsgActionResult.Status.StatusCode == 200 && !getMsgActionResult.Status.Error)
            {
                System.Diagnostics.Debug.WriteLine("GetMessageActions = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(getMsgActionResult.Result));

                if (getMsgActionResult.Result.MessageActions != null && getMsgActionResult.Result.MessageActions.Exists(x => x.MessageTimetoken == currentMessageTimetoken))
                {
                    PNMessageActionItem actionItem = getMsgActionResult.Result.MessageActions.Find(x => x.MessageTimetoken == currentMessageTimetoken);
                    currentActionTimetoken = actionItem.ActionTimetoken;
                    currentUUID            = actionItem.Uuid;
                }
            }
            Thread.Sleep(2000);

            if (currentMessageTimetoken > 0 && currentActionTimetoken > 0)
            {
                System.Diagnostics.Debug.WriteLine("RemoveMessageAction STARTED");

#if NET40
                PNResult <PNRemoveMessageActionResult> removeMsgActionResult = Task.Factory.StartNew(async() => await pubnub.RemoveMessageAction()
                                                                                                     .Channel(channel)
                                                                                                     .MessageTimetoken(currentMessageTimetoken)
                                                                                                     .ActionTimetoken(currentActionTimetoken)
                                                                                                     .Uuid(currentUUID)
                                                                                                     .ExecuteAsync()).Result.Result;
#else
                PNResult <PNRemoveMessageActionResult> removeMsgActionResult = await pubnub.RemoveMessageAction()
                                                                               .Channel(channel)
                                                                               .MessageTimetoken(currentMessageTimetoken)
                                                                               .ActionTimetoken(currentActionTimetoken)
                                                                               .Uuid(currentUUID)
                                                                               .ExecuteAsync();
#endif
                if (removeMsgActionResult.Result != null && removeMsgActionResult.Status.StatusCode == 200 && !removeMsgActionResult.Status.Error)
                {
                    System.Diagnostics.Debug.WriteLine("RemoveMessageAction = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(removeMsgActionResult.Result));
                    receivedMessage = true;
                }
            }

            System.Diagnostics.Debug.WriteLine("AddMessageAction STARTED");
#if NET40
            PNResult <PNAddMessageActionResult> addMsgActionResult = Task.Factory.StartNew(async() => await pubnub.AddMessageAction()
                                                                                           .Channel(channel)
                                                                                           .MessageTimetoken(currentMessageTimetoken)
                                                                                           .Action(new PNMessageAction {
                Type = "reaction", Value = "smily_face"
            })
                                                                                           .ExecuteAsync()).Result.Result;
#else
            PNResult <PNAddMessageActionResult> addMsgActionResult = await pubnub.AddMessageAction()
                                                                     .Channel(channel)
                                                                     .MessageTimetoken(currentMessageTimetoken)
                                                                     .Action(new PNMessageAction {
                Type = "reaction", Value = "smily_face"
            })
                                                                     .ExecuteAsync();
#endif
            if (addMsgActionResult.Result != null && addMsgActionResult.Status.StatusCode == 200 && !addMsgActionResult.Status.Error && addMsgActionResult.Result.MessageTimetoken == currentMessageTimetoken)
            {
                System.Diagnostics.Debug.WriteLine("AddMessageAction = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(addMsgActionResult.Result));
                receivedMessage        = true;
                currentActionTimetoken = addMsgActionResult.Result.ActionTimetoken;
                currentUUID            = addMsgActionResult.Result.Uuid;
            }
            Thread.Sleep(2000);

            if (receivedMessage && currentActionTimetoken > 0 && currentMessageTimetoken > 0 && !receivedRemoveEvent)
            {
                System.Diagnostics.Debug.WriteLine("RemoveMessageAction To Confirm STARTED");

#if NET40
                Task.Factory.StartNew(async() => await pubnub.RemoveMessageAction()
                                      .Channel(channel)
                                      .MessageTimetoken(currentMessageTimetoken)
                                      .ActionTimetoken(currentActionTimetoken)
                                      .Uuid(currentUUID)
                                      .ExecuteAsync());
#else
                await pubnub.RemoveMessageAction()
                .Channel(channel)
                .MessageTimetoken(currentMessageTimetoken)
                .ActionTimetoken(currentActionTimetoken)
                .Uuid(currentUUID)
                .ExecuteAsync();
#endif
            }

            Thread.Sleep(4000);

            pubnub.Unsubscribe <string>().Channels(new string[] { channel }).Execute();
            pubnub.RemoveListener(eventListener);

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedAddEvent && receivedRemoveEvent, "Message Action events Failed");
        }
示例#26
0
        public static void ThenSendFileShouldReturnSuccess()
        {
            server.ClearRequests();

            receivedMessage = false;
            bool receivedEvent = false;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNFileEventResult eventResult)
            {
                receivedEvent = true;
                System.Diagnostics.Debug.WriteLine("FILE EVENT: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                //CipherKey = "enigma",
                Uuid   = "mytestuuid",
                Secure = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            mre = new ManualResetEvent(false);
            pubnub.Subscribe <string>().Channels(new string[] { channelName }).Execute();
            mre.WaitOne(2000);

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            mre = new ManualResetEvent(false);

            string fileId   = "";
            string fileName = "";

            receivedMessage = false;
            string targetFileUpload = @"C:\Pandu\pubnub\word_test.txt";

            //string targetFileDownload = @"c:\pandu\temp\pandu_test.gif";
            pubnub.SendFile().Channel(channelName).File(targetFileUpload).CipherKey("enigma").Message("This is my sample file")
            .Execute(new PNFileUploadResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("SendFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    fileId          = result.FileId;
                    fileName        = result.FileName;
                    receivedMessage = true;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("SendFile failed = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();

            receivedMessage = false;
            mre             = new ManualResetEvent(false);
            pubnub.ListFiles().Channel(channelName)
            .Execute(new PNListFilesResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("ListFiles result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    receivedMessage = true;
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();


            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DownloadFile().Channel(channelName).FileId(fileId).FileName(fileName).Execute(new PNDownloadFileResultExt((result, status) =>
                {
                    if (result != null && result.FileBytes != null && result.FileBytes.Length > 0)
                    {
                        System.Diagnostics.Debug.WriteLine("DownloadFile result = " + result.FileBytes.Length);
                        receivedMessage = true;
                        //System.IO.File.WriteAllBytes(targetFileDownload, result.FileBytes);
                    }
                    mre.Set();
                }));
                mre.WaitOne();
            }

            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DeleteFile().Channel(channelName).FileId(fileId).FileName(fileName)
                .Execute(new PNDeleteFileResultExt((result, status) =>
                {
                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine("DeleteFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                        receivedMessage = true;
                    }
                    mre.Set();
                }));
                Thread.Sleep(1000);
                mre.WaitOne();
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage && receivedEvent, "WhenFileIsRequested -> TheSendFileShouldReturnSuccess failed.");
        }
示例#27
0
        public static async Task ThenWithAsyncUuidMetadataUpdateDeleteShouldReturnEventInfo()
#endif
        {
            server.ClearRequests();

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Ignored ThenWithAsyncUuidUpdateDeleteShouldReturnEventInfo");
                return;
            }

            bool receivedMessage     = false;
            bool receivedDeleteEvent = false;
            bool receivedUpdateEvent = false;

            string uuidMetadataId = "pandu-ut-uid";

            manualResetEventWaitTimeout = 310 * 1000;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNObjectEventResult eventResult)
            {
                System.Diagnostics.Debug.WriteLine("EVENT:" + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
                if (eventResult.Type.ToLowerInvariant() == "uuid")
                {
                    if (eventResult.Event.ToLowerInvariant() == "set")
                    {
                        receivedUpdateEvent = true;
                    }
                    else if (eventResult.Event.ToLowerInvariant() == "delete")
                    {
                        receivedDeleteEvent = true;
                    }
                }
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false,
                AuthKey      = "myauth"
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            server.RunOnHttps(false);
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            ManualResetEvent manualEvent = new ManualResetEvent(false);

            pubnub.Subscribe <string>().Channels(new string[] { uuidMetadataId }).Execute();
            manualEvent.WaitOne(2000);

            System.Diagnostics.Debug.WriteLine("pubnub.DeleteUuidMetadata() STARTED");
#if NET40
            Task.Factory.StartNew(async() => await pubnub.RemoveUuidMetadata().Uuid(uuidMetadataId).ExecuteAsync());
#else
            await pubnub.RemoveUuidMetadata().Uuid(uuidMetadataId).ExecuteAsync();
#endif

            #region "SetUuidMetadata"
            System.Diagnostics.Debug.WriteLine("pubnub.SetUuidMetadata() STARTED");
#if NET40
            PNResult <PNSetUuidMetadataResult> createUserResult = Task.Factory.StartNew(async() => await pubnub.SetUuidMetadata().Uuid(uuidMetadataId).Name("pandu-ut-un").ExecuteAsync()).Result.Result;
#else
            PNResult <PNSetUuidMetadataResult> createUserResult = await pubnub.SetUuidMetadata().Uuid(uuidMetadataId).Name("pandu-ut-un").ExecuteAsync();
#endif
            if (createUserResult.Result != null && createUserResult.Status.StatusCode == 200 && !createUserResult.Status.Error)
            {
                pubnub.JsonPluggableLibrary.SerializeToJsonString(createUserResult.Result);
                if (uuidMetadataId == createUserResult.Result.Uuid)
                {
                    receivedMessage = true;
                }
            }
            #endregion

            if (receivedMessage)
            {
                receivedMessage = false;
                #region "SetUuidMetadata"
                System.Diagnostics.Debug.WriteLine("pubnub.UpdateUser() STARTED");
#if NET40
                PNResult <PNSetUuidMetadataResult> updateUserResult = Task.Factory.StartNew(async() => await pubnub.SetUuidMetadata().Uuid(uuidMetadataId).Name("pandu-ut-un-upd")
                                                                                            .ProfileUrl("pandu-sample-profile-url").ExternalId("pandu-sample-ext-id")
                                                                                            .Email("*****@*****.**")
                                                                                            .Custom(new Dictionary <string, object>()
                {
                    { "color", "red" }
                })
                                                                                            .ExecuteAsync()).Result.Result;
#else
                PNResult <PNSetUuidMetadataResult> updateUserResult = await pubnub.SetUuidMetadata().Uuid(uuidMetadataId).Name("pandu-ut-un-upd")
                                                                      .ProfileUrl("pandu-sample-profile-url").ExternalId("pandu-sample-ext-id")
                                                                      .Email("*****@*****.**")
                                                                      .Custom(new Dictionary <string, object>()
                {
                    { "color", "red" }
                })
                                                                      .ExecuteAsync();
#endif
                if (updateUserResult.Result != null && updateUserResult.Status.StatusCode == 200 && !updateUserResult.Status.Error)
                {
                    pubnub.JsonPluggableLibrary.SerializeToJsonString(updateUserResult.Result);
                    if (uuidMetadataId == updateUserResult.Result.Uuid)
                    {
                        receivedMessage = true;
                    }
                }
                #endregion
            }

            if (!receivedDeleteEvent)
            {
                System.Diagnostics.Debug.WriteLine("pubnub.DeleteUuidMetadata() 2 STARTED");
#if NET40
                Task.Factory.StartNew(async() => await pubnub.RemoveUuidMetadata().Uuid(uuidMetadataId).ExecuteAsync());
#else
                await pubnub.RemoveUuidMetadata().Uuid(uuidMetadataId).ExecuteAsync();
#endif
            }

            Thread.Sleep(2000);

            pubnub.Unsubscribe <string>().Channels(new string[] { uuidMetadataId }).Execute();
            pubnub.RemoveListener(eventListener);

            Assert.IsTrue(receivedDeleteEvent && receivedUpdateEvent, "User events Failed");

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
示例#28
0
 }
                        System.Diagnostics.Debug.WriteLine(" -> Not found error, attempting to reinitialize");
                        //  disconnect
                        //System.Diagnostics.Debug.WriteLine(" -> -> uninitialize");
                        //Uninitialize();
                        //  reconnect
                        System.Diagnostics.Debug.WriteLine(" -> -> reinitialize");
                        Initialize(_UserId, _AuthKey, false, _PushData);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.Initialize - Exception: {0}", ex));
                    }
                }

                if (status.Category == PNStatusCategory.PNConnectedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Connected");
                    // this is expected for a subscribe, this means there is no error or issue whatsoever
                    // reset fail count
                    _FailCount = 0;
                }
                else if (status.Category == PNStatusCategory.PNReconnectedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Reconnected");
                    // this usually occurs if subscribe temporarily fails but reconnects. This means
                    // there was an error but there is no longer any issue
                }
                else if (status.Category == PNStatusCategory.PNDisconnectedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Disconnected");
                    // this is the expected category for an unsubscribe. This means there
                    // was no error in unsubscribing from everything
                }
                else if (status.Category == PNStatusCategory.PNUnexpectedDisconnectCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Unexpected disconnected");
                    // this is usually an issue with the internet connection, this is an error, handle appropriately
                }
                else if (status.Category == PNStatusCategory.PNAccessDeniedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Access Denied");
                    // this means that PAM does allow this client to subscribe to this
                    // channel and channel group configuration. This is another explicit error
                }
            }
        }

        #endregion Callbacks

        #region Operations

        public void GetHistory(long timeStamp)
        {
            try
            {
                if (!Initialized || string.IsNullOrEmpty(_UserId)) return;
                _Pubnub.History()
                    .Channel(_UserId)
                    .Start(timeStamp)
                    .Count(20)
                    .Async(new PNHistoryResultExt((result, status) =>
                    {
                        if ((result.Messages == null) || (result.Messages.Count == 0)) return;
                        foreach (var message in result.Messages)
                        {
                            //  let listeners know
                            MessageReceived?.Invoke(this, new MessageEventArgs(message.Entry.ToString()));
                        }
                    }));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.GetHistory - Exception: {0}", ex));
            }
        }

        public void Publish(string to, string message, object state)
        {
            try
            {
                if (!Initialized || string.IsNullOrEmpty(_UserId)) throw new ArgumentException("Cannot publish before initialize.");

                //  publish message
                _Pubnub.Publish()
                    .Channel(to)
                    .Message(message)
                    .Async(new PNPublishResultExt((result, status) =>
                    {
                        if (message == null) return;
                        //  get the message
                        PublishComplete?.Invoke(this, new MessageEventArgs(message)
                        {
                            State = state,
                            Success = !status.Error,
                            Timestamp = new DateTime(result.Timetoken)
                        });
                    }));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.Publish - Exception: {0}", ex));
            }
        }

        #endregion Operations

        #region Event Triggers

        private void RaiseChannelJoined(string channel, string uuid)
        {
            ChannelJoined?.Invoke(this, new PresenceEventArgs(channel, uuid));
        }

        private void RaiseChannelLeft(string channel, string uuid)
        {
            ChannelLeft?.Invoke(this, new PresenceEventArgs(channel, uuid));
        }

        private void RaiseChannelTimeout(string channel, string uuid)
        {
            ChannelTimeout?.Invoke(this, new PresenceEventArgs(channel, uuid));
        }

        private void RaiseChannelState(string channel, string uuid, ChatState state)
        {
            ChannelState?.Invoke(this, new PresenceEventArgs(channel, uuid, state));
        }

        #endregion Event Triggers

        #region Cleanup

        public void Dispose()
        {
            if (_Disposed) return;
            //  TODO: check this - it looks dodgy
            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt((pubnubObj, message) => { }, (pubnubObj, presence) => { }, (pubnubObj, status) => { });
            _Pubnub.AddListener(listenerSubscribeCallack);
            // some time later
            _Pubnub.RemoveListener(listenerSubscribeCallack);
            _Pubnub.Destroy();
            _Disposed = true;
        }

        #endregion Cleanup
    }
}


        public static void ThenUnencryptSignalListenerShouldGetMessagae()
        {
            server.ClearRequests();

            bool internalReceivedMessage = false;
            bool receivedErrorMessage    = false;

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Ignored ThenUnencryptSignalListenerShouldGetMessagae");
                return;
            }

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                SecretKey    = PubnubCommon.SecretKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(config.Secure);

            ManualResetEvent subscribeManualEvent = new ManualResetEvent(false);

            SubscribeCallback listenerSubCallack = new SubscribeCallbackExt(
                (o, m) =>
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                if (m != null)
                {
                    Debug.WriteLine(string.Format("Signal SubscribeCallback: PNMessageResult: {0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(m.Message)));
                    if (pubnub.JsonPluggableLibrary.SerializeToJsonString(messageForUnencryptSignal) == m.Message.ToString())
                    {
                        internalReceivedMessage = true;
                    }
                    subscribeManualEvent.Set();
                }
            },
                (o, s) => {
                Debug.WriteLine("{0} {1} {2}", s.Operation, s.Category, s.StatusCode);
                if (s.StatusCode != 200 || s.Error)
                {
                    receivedErrorMessage = true;
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                    subscribeManualEvent.Set();
                }
                else if (s.StatusCode == 200 && s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    internalReceivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            string channel = "hello_my_channel";

            manualResetEventWaitTimeout = 310 * 1000;

            pubnub.Subscribe <string>().Channels(new[] { channel }).Execute();
            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for connect
            Thread.Sleep(1000);
            if (!receivedErrorMessage)
            {
                subscribeManualEvent    = new ManualResetEvent(false); //Reset to wait for message
                internalReceivedMessage = false;
                ManualResetEvent signalManualEvent = new ManualResetEvent(false);
                pubnub.Signal().Channel(channel).Message(messageForUnencryptSignal)
                .Execute(new PNPublishResultExt((r, s) =>
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        internalReceivedMessage = true;
                    }
                    signalManualEvent.Set();
                }));

                signalManualEvent.WaitOne(manualResetEventWaitTimeout);

                subscribeManualEvent.WaitOne(manualResetEventWaitTimeout);

                pubnub.Unsubscribe <string>().Channels(new[] { channel }).Execute();

                Thread.Sleep(1000);

                pubnub.RemoveListener(listenerSubCallack);
                pubnub.Destroy();
                pubnub.PubnubUnitTest = null;
                pubnub = null;
                if (receivedErrorMessage)
                {
                    internalReceivedMessage = false;
                }
                Assert.IsTrue(internalReceivedMessage, "WhenSubscribedToAChannel --> ThenUnencryptSignalListenerShouldGetMessagae Failed");
            }
        }