public void ThenMultiSubscribeShouldReturnConnectStatus()
        {
            currentUnitTestCase          = "ThenMultiSubscribeShouldReturnConnectStatus";
            receivedMessage              = false;
            receivedChannelGroupMessage1 = false;
            receivedChannelGroupMessage2 = false;
            expectedCallbackResponses    = 2;
            currentCallbackResponses     = 0;

            Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);

            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();

            unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
            unitTest.TestCaseName  = "ThenMultiSubscribeShouldReturnConnectStatus";

            pubnub.PubnubUnitTest        = unitTest;
            manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 6000 : 310 * 1000;

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

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

            subscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName1 }, channelGroupName1, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            Task.Delay(1000);
            subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

            subscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName2 }, channelGroupName2, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            Task.Delay(1000);
            subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

            if (receivedChannelGroupMessage1 && receivedChannelGroupMessage2)
            {
                subscribeManualEvent = new ManualResetEvent(false);
                pubnub.Subscribe <string>("", string.Format("{0},{1}", channelGroupName1, channelGroupName2), ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
                subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                pubnub.EndPendingRequests();

                pubnub.PubnubUnitTest = null;
                pubnub = null;
                Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
            }
            else
            {
                pubnub.PubnubUnitTest = null;
                pubnub = null;
                Assert.IsTrue(receivedChannelGroupMessage1 && receivedChannelGroupMessage2, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
            }
        }
Exemplo n.º 2
0
        void channelGroupForm_ChannelGroupRequestSubmitted(object sender, EventArgs e)
        {
            string channelName      = channelGroupForm.ChannelName;
            string channelGroupName = channelGroupForm.ChannelGroupName;
            string nameSpace        = "";

            switch (channelGroupForm.ChannelGroupRequestType)
            {
            case "AddChannel":
                UpdateListBoxForDisplay("Running AddChannelsToChannelGroup()");
                pubnub.AddChannelsToChannelGroup <string>(channelName.Split(','), nameSpace, channelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                break;

            case "RemoveChannel":
                UpdateListBoxForDisplay("Running RemoveChannelsFromChannelGroup()");
                pubnub.RemoveChannelsFromChannelGroup <string>(channelName.Split(','), nameSpace, channelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                break;

            case "GetChannelList":
                UpdateListBoxForDisplay("Running GetChannelsForChannelGroup()");
                pubnub.GetChannelsForChannelGroup <string>(nameSpace, channelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                break;
            }

            channelGroupForm = null;
        }
Exemplo n.º 3
0
        public void ThenAddChannelShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenAddChannelShouldReturnSuccess";

            receivedChannelGroupMessage = false;

            ThreadPool.QueueUserWorkItem((s) =>
            {
                Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);

                PubnubUnitTest unitTest = new PubnubUnitTest();
                unitTest.TestClassName  = "WhenChannelGroupIsRequested";
                unitTest.TestCaseName   = "ThenAddChannelShouldReturnSuccess";
                pubnub.PubnubUnitTest   = unitTest;

                channelGroupManualEvent = new ManualResetEvent(false);
                string channelName      = "hello_my_channel";

                pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName }, channelGroupName, ChannelGroupCRUDCallback, DummyErrorCallback);

                channelGroupManualEvent.WaitOne(310 * 1000);

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenAddChannelShouldReturnSuccess failed.");
                    TestComplete();
                });
            });
        }
Exemplo n.º 4
0
        public void ThenShouldReturnUnsubscribedMessage()
        {
            currentUnitTestCase                  = "ThenShouldReturnUnsubscribedMessage";
            receivedMessage                      = false;
            receivedChannelGroupMessage          = false;
            receivedChannelGroupConnectedMessage = false;

            ThreadPool.QueueUserWorkItem((s) =>
            {
                Pubnub pubnub      = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
                pubnub.SessionUUID = "myuuid";

                PubnubUnitTest unitTest = new PubnubUnitTest();
                unitTest.TestClassName  = "WhenUnsubscribedToAChannelGroup";
                unitTest.TestCaseName   = "ThenShouldReturnUnsubscribedMessage";

                pubnub.PubnubUnitTest = unitTest;

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

                unsubscribeManualEvent = new ManualResetEvent(false);
                pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback);
                unsubscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
                if (receivedChannelGroupMessage)
                {
                    unsubscribeManualEvent = new ManualResetEvent(false);
                    pubnub.Subscribe <string>("", channelGroupName, DummyMethodChannelSubscribeUserCallback, DummyMethodChannelSubscribeConnectCallback, DummyErrorCallback);
                    Thread.Sleep(1000);
                    unsubscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                    if (receivedChannelGroupConnectedMessage)
                    {
                        unsubscribeManualEvent = new ManualResetEvent(false);
                        pubnub.Unsubscribe <string>("", channelGroupName, DummyMethodUnsubscribeChannelUserCallback, DummyMethodUnsubscribeChannelConnectCallback, DummyMethodUnsubscribeChannelDisconnectCallback, DummyErrorCallback);
                        unsubscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
                    }

                    pubnub.EndPendingRequests();

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        Assert.IsTrue(receivedMessage, "WhenUnsubscribedToAChannelGroup --> ThenShouldReturnUnsubscribedMessage Failed");
                        pubnub.PubnubUnitTest = null;
                        pubnub = null;
                        TestComplete();
                    });
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        Assert.IsTrue(receivedChannelGroupMessage, "WhenUnsubscribedToAChannelGroup --> ThenShouldReturnUnsubscribedMessage Failed");
                        pubnub.PubnubUnitTest = null;
                        pubnub = null;
                        TestComplete();
                    });
                }
            });
        }
        public void ThenAddChannelShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenAddChannelShouldReturnSuccess";

            receivedChannelGroupMessage = false;

            pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenChannelGroupIsRequested";
            unitTest.TestCaseName = "ThenAddChannelShouldReturnSuccess";
            pubnub.PubnubUnitTest = unitTest;

            channelGroupManualEvent = new ManualResetEvent(false);
            string channelName = "hello_my_channel";
            
            pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupCRUDCallback, DummyErrorCallback);

            channelGroupManualEvent.WaitOne(10 * 1000, false);

            pubnub.EndPendingRequests(); 
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.True(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenAddChannelShouldReturnSuccess failed.");

        }
        public void ThenAddChannelShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenAddChannelShouldReturnSuccess";

            receivedChannelGroupMessage = false;

            ThreadPool.QueueUserWorkItem((s) =>
                {
                    Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "WhenChannelGroupIsRequested";
                    unitTest.TestCaseName = "ThenAddChannelShouldReturnSuccess";
                    pubnub.PubnubUnitTest = unitTest;

                    channelGroupManualEvent = new ManualResetEvent(false);
                    string channelName = "hello_my_channel";

                    pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupCRUDCallback, DummyErrorCallback);

                    channelGroupManualEvent.WaitOne(310 * 1000);

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenAddChannelShouldReturnSuccess failed.");
                            pubnub.PubnubUnitTest = null;
                            pubnub = null;
                            TestComplete();
                        });
                });
        }
Exemplo n.º 7
0
 void HandleAddRemoveFromCgPerms(object sender, EventArgs ea)
 {
     try {
         AddRemoveFromCgEventArgs cea = ea as AddRemoveFromCgEventArgs;
         if (cea.cds == CommonDialogStates.AddToChannelGroup)
         {
             Display("Running AddChannelsToChannelGroup");
             ThreadPool.QueueUserWorkItem(o =>
                                          pubnub.AddChannelsToChannelGroup <string> (new string[] { cea.channel }, cea.channelGroup, DisplayReturnMessage, DisplayErrorMessage)
                                          );
         }
         else if (cea.cds == CommonDialogStates.RemoveFromChannelGroup)
         {
             Display("Running RemoveChannelsFromChannelGroup");
             ThreadPool.QueueUserWorkItem(o =>
                                          pubnub.RemoveChannelsFromChannelGroup <string> (new string[] { cea.channel }, cea.channelGroup, DisplayReturnMessage, DisplayErrorMessage)
                                          );
         }
         else if (cea.cds == CommonDialogStates.GetChannelGroup)
         {
             Display("Running GetChannelsForChannelGroup");
             ThreadPool.QueueUserWorkItem(o =>
                                          pubnub.GetChannelsForChannelGroup <string> (cea.channelGroup, DisplayReturnMessage, DisplayErrorMessage)
                                          );
         }
     }
     catch (Exception ex) {
         Display(ex.Message);
     } finally {
         AddRemoveFromChannelGroupDialogFragment coroutine = sender as AddRemoveFromChannelGroupDialogFragment;
         coroutine.AddRemoveFromCgPerms -= HandleAddRemoveFromCgPerms;
     }
 }
        public void ThenAddChannelShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenAddChannelShouldReturnSuccess";

            receivedChannelGroupMessage = false;

            Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false);

            PubnubUnitTest unitTest = new PubnubUnitTest();

            unitTest.TestClassName = "WhenChannelGroupIsRequested";
            unitTest.TestCaseName  = "ThenAddChannelShouldReturnSuccess";
            pubnub.PubnubUnitTest  = unitTest;

            channelGroupManualEvent = new ManualResetEvent(false);
            string channelName = "hello_my_channel";

            pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName }, channelGroupName, ChannelGroupCRUDCallback, DummyErrorCallback);
            Task.Delay(1000);

            channelGroupManualEvent.WaitOne();

            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenAddChannelShouldReturnSuccess failed.");
        }
Exemplo n.º 9
0
        public void ThenSubscribeShouldReturnReceivedMessage()
        {
            currentUnitTestCase = "ThenSubscribeShouldReturnReceivedMessage";
            receivedMessage     = false;

            ThreadPool.QueueUserWorkItem((s) =>
            {
                Pubnub pubnub      = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
                pubnub.SessionUUID = "myuuid";

                PubnubUnitTest unitTest = new PubnubUnitTest();
                unitTest.TestClassName  = "WhenSubscribedToAChannelGroup";
                unitTest.TestCaseName   = "ThenSubscribeShouldReturnReceivedMessage";

                pubnub.PubnubUnitTest = unitTest;

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

                subscribeManualEvent = new ManualResetEvent(false);
                EnqueueCallback(() => pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback));
                subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
                if (receivedChannelGroupMessage)
                {
                    subscribeManualEvent = new ManualResetEvent(false);
                    EnqueueCallback(() => pubnub.Subscribe <string>("", channelGroupName, ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback));
                    Thread.Sleep(1000);
                    pubnub.Publish <string>(channelName, "Test for WhenSubscribedToAChannelGroup ThenItShouldReturnReceivedMessage", dummyPublishCallback, DummyPublishErrorCallback);
                    manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                    mePublish.WaitOne(manualResetEventsWaitTimeout);

                    subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                    subscribeManualEvent = new ManualResetEvent(false);
                    EnqueueCallback(() => pubnub.Unsubscribe <string>("", channelGroupName, dummyUnsubscribeCallback, SubscribeConnectCallback, UnsubscribeDummyMethodForDisconnectCallback, DummySubscribeErrorCallback));

                    subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
                    EnqueueCallback(() => pubnub.EndPendingRequests());

                    EnqueueCallback(() => Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed"));
                }
                else
                {
                    EnqueueCallback(() => Assert.IsTrue(receivedChannelGroupMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed. Add channel failed."));
                }
                EnqueueCallback(() =>
                {
                    pubnub.PubnubUnitTest = null;
                    pubnub = null;
                }
                                );
                EnqueueTestComplete();
            });
        }
Exemplo n.º 10
0
        public static void ThenAddChannelShouldReturnSuccess()
        {
            server.ClearRequests();

            currentUnitTestCase         = "ThenAddChannelShouldReturnSuccess";
            receivedChannelGroupMessage = false;

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

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

            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("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "yo21VoxIksrH3Iozeaz5Zw4BX18N3vU9PLa-zVxRXsU=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            channelGroupManualEvent = new ManualResetEvent(false);

            pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName }).ChannelGroup(channelGroupName).Execute(new ChannelGroupAddChannelResult());
            Thread.Sleep(1000);

            channelGroupManualEvent.WaitOne();

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenAddChannelShouldReturnSuccess failed.");
        }
Exemplo n.º 11
0
        public void ThenSubscribeShouldReturnReceivedMessage()
        {
            currentUnitTestCase = "ThenSubscribeShouldReturnReceivedMessage";
            receivedMessage = false;
            Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
            unitTest.TestCaseName = "ThenSubscribeShouldReturnReceivedMessage";

            pubnub.PubnubUnitTest = unitTest;

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

            subscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
            if (receivedChannelGroupMessage)
            {
                subscribeManualEvent = new ManualResetEvent(false);
                pubnub.Subscribe<string>("", channelGroupName, ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
                Task.Delay(1000);
                pubnub.Publish<string>(channelName, "Test for WhenSubscribedToAChannelGroup ThenItShouldReturnReceivedMessage", dummyPublishCallback, DummyPublishErrorCallback);
                manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                mePublish.WaitOne(manualResetEventsWaitTimeout);

                subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                subscribeManualEvent = new ManualResetEvent(false);
                pubnub.Unsubscribe<string>("", channelGroupName, dummyUnsubscribeCallback, SubscribeConnectCallback, UnsubscribeDummyMethodForDisconnectCallback, DummySubscribeErrorCallback);

                subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
                pubnub.EndPendingRequests();

                pubnub.PubnubUnitTest = null;
                pubnub = null;
                Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed");
            }
            else
            {
                pubnub.PubnubUnitTest = null;
                pubnub = null;
                Assert.IsTrue(receivedChannelGroupMessage, "WhenSubscribedToAChannelGroup --> ThenItShouldReturnReceivedMessage Failed");
            }

        }
        public void ThenShouldReturnUnsubscribedMessage()
        {
            currentUnitTestCase = "ThenShouldReturnUnsubscribedMessage";
            receivedMessage = false;
            receivedChannelGroupMessage = false;
            receivedChannelGroupConnectedMessage = false;

            pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenUnsubscribedToAChannelGroup";
            unitTest.TestCaseName = "ThenShouldReturnUnsubscribedMessage";

            pubnub.PubnubUnitTest = unitTest;

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

            unsubscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            unsubscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
            if (receivedChannelGroupMessage)
            {
                unsubscribeManualEvent = new ManualResetEvent(false);
                pubnub.Subscribe<string>("", channelGroupName, DummyMethodChannelSubscribeUserCallback, DummyMethodChannelSubscribeConnectCallback, DummyErrorCallback);
                Thread.Sleep(1000);
                unsubscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                if (receivedChannelGroupConnectedMessage)
                {
                    unsubscribeManualEvent = new ManualResetEvent(false);
                    pubnub.Unsubscribe<string>("", channelGroupName, DummyMethodUnsubscribeChannelUserCallback, DummyMethodUnsubscribeChannelConnectCallback, DummyMethodUnsubscribeChannelDisconnectCallback, DummyErrorCallback);
                    unsubscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);
                }

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

                Assert.True(receivedMessage, "WhenUnsubscribedToAChannelGroup --> ThenShouldReturnUnsubscribedMessage Failed");
            }
            else
            {
                Assert.True(receivedChannelGroupMessage, "WhenUnsubscribedToAChannelGroup --> ThenShouldReturnUnsubscribedMessage Failed");
            }
        }
        public void ThenSubscribeShouldReturnConnectStatus()
        {
            currentUnitTestCase = "ThenSubscribeShouldReturnConnectStatus";
            receivedMessage     = false;
            pubnub             = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();

            unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
            unitTest.TestCaseName  = "ThenSubscribeShouldReturnConnectStatus";

            pubnub.PubnubUnitTest = unitTest;


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

            subscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout, false);

            if (receivedChannelGroupMessage)
            {
                subscribeManualEvent = new ManualResetEvent(false);
                pubnub.Subscribe <string>("", channelGroupName, ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
                Thread.Sleep(1000);

                manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout, false);

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

                Assert.True(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenSubscribeShouldReturnConnectStatus Failed");
            }
            else
            {
                Assert.True(receivedChannelGroupMessage, "WhenSubscribedToAChannelGroup --> ThenSubscribeShouldReturnConnectStatus Failed");
            }
        }
Exemplo n.º 14
0
 void HandleAddRemoveFromCgPerms(object sender, EventArgs ea)
 {
     try {
         AddRemoveFromCgEventArgs cea = ea as AddRemoveFromCgEventArgs;
         if (cea.cds == CommonDialogStates.AddToChannelGroup)
         {
             Display("Running AddChannelsToChannelGroup");
             ThreadPool.QueueUserWorkItem(o =>
                                          pubnub.AddChannelsToChannelGroup().Channels(new [] { cea.channel })
                                          .ChannelGroup(cea.channelGroup)
                                          .Async(new DemoChannelGroupAddChannel(Display))
                                          );
         }
         else if (cea.cds == CommonDialogStates.RemoveFromChannelGroup)
         {
             Display("Running RemoveChannelsFromChannelGroup");
             ThreadPool.QueueUserWorkItem(o =>
                                          pubnub.RemoveChannelsFromChannelGroup()
                                          .Channels(new [] { cea.channel })
                                          .ChannelGroup(cea.channelGroup)
                                          .Async(new DemoChannelGroupRemoveChannel(Display))
                                          );
         }
         else if (cea.cds == CommonDialogStates.GetChannelGroup)
         {
             Display("Running GetChannelsForChannelGroup");
             ThreadPool.QueueUserWorkItem(o =>
                                          pubnub.ListChannelsForChannelGroup()
                                          .ChannelGroup(cea.channelGroup)
                                          .Async(new DemoChannelGroupAllChannels(Display))
                                          );
         }
     }
     catch (Exception ex) {
         Display(ex.Message);
     } finally {
         AddRemoveFromChannelGroupDialogFragment coroutine = sender as AddRemoveFromChannelGroupDialogFragment;
         coroutine.AddRemoveFromCgPerms -= HandleAddRemoveFromCgPerms;
     }
 }
Exemplo n.º 15
0
        public void AddChannelToGroup(List <Channel> channels)
        {
            if (!Initialized || (channels == null) || (channels.Count == 0))
            {
                return;
            }

            var ids = channels.Select(c => c.Id).ToArray();

            _Pubnub
            .AddChannelsToChannelGroup()
            .ChannelGroup(_Group)
            .Channels(ids)
            .Async(new PNChannelGroupsAddChannelResultExt((result, status) =>
            {
                if (status.Error)
                {
                    //  TODO: could not add channel?? Analytics
                    System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.AddChannelToGroup - Error {0}", ids));
                }
            }));
        }
Exemplo n.º 16
0
        public IEnumerator DoTestPresenceCG(string testName)
        {
            /*  ⁃   Add CH to CG
             * ⁃   List CG
             * ⁃   Get all CGs
             * ⁃
             * ⁃   */
            pubnub = new Pubnub(CommonIntergrationTests.PublishKey,
                                CommonIntergrationTests.SubscribeKey);

            System.Random r       = new System.Random();
            string        cg      = "UnityIntegrationTest_CG_" + r.Next(100);
            string        ch      = "UnityIntegrationTest_CH_" + r.Next(100);
            string        channel = "UnityIntegrationTest_CH_" + r.Next(100);

            UnityEngine.Debug.Log(string.Format("{0} {1}: Start coroutine ", DateTime.Now.ToString(), testName));
            string uuid = "UnityIntegrationTest_UUID";

            pubnub.ChangeUUID(uuid);

            /*Subscribe CG
             * ⁃   Publish to CH
             * ⁃   Read Message on CG*/

            bool bSubConnect = false;

            string pubMessage = "TestMessageWC";
            string chToSub    = "UnityIntegrationTest_CH.*";

            bool bAddChannel = false;
            bool bGetChannel = false;

            pubnub.AddChannelsToChannelGroup <string>(new string[] { channel }, cg, (string result) => {
                //[{"status":200,"message":"OK","service":"channel-registry","error":false}]
                UnityEngine.Debug.Log(string.Format("{0}: {1} AddChannelsToChannelGroup {2}", DateTime.Now.ToString(), testName, result));
                if (result.Contains("OK") && result.Contains("\"error\":false"))
                {
                    bAddChannel = true;
                    pubnub.GetChannelsForChannelGroup(cg, (string result2) => {
                        //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                        UnityEngine.Debug.Log(string.Format("{0}: {1} GetChannelsOfChannelGroup {2}", DateTime.Now.ToString(), testName, result2));
                        if (result2.Contains(cg) && result2.Contains(channel))
                        {
                            bGetChannel = true;
                        }
                        else
                        {
                            bGetChannel = false;
                        }
                    }, this.DisplayErrorMessage);
                }
            }, this.DisplayErrorMessage);
            UnityEngine.Debug.Log(string.Format("{0}: {1} Waiting for response", DateTime.Now.ToString(), testName));

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.Subscribe <string>("", cg + "-pnpres", (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe {2}", DateTime.Now.ToString(), testName, retM));
                if (retM.Contains("join"))
                {
                    bSubConnect = true;
                }
            }, (string retConnect) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe Connected {2}", DateTime.Now.ToString(), testName, retConnect));

                pubnub.Subscribe <string>("", cg, this.DisplayReturnMessageDummy, this.DisplayReturnMessageDummy, this.DisplayErrorMessage);
            }, this.DisplayReturnMessageDummy, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*⁃   Unsub from CG*/

            bool bUnsub = false;

            pubnub.Unsubscribe <string>(chToSub, "", this.DisplayReturnMessageDummy, this.DisplayReturnMessageDummy, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Unsubscribe {2} {3}",
                                                    DateTime.Now.ToString(), testName, retM, retM.Contains("Unsubscribed")));

                if (retM.Contains("Unsubscribed"))
                {
                    bUnsub         = true;
                    string strLog2 = string.Format("{0}: {1} After wait2   {2} {3} {4} {5}",
                                                   DateTime.Now.ToString(),
                                                   testName,
                                                   bGetChannel,
                                                   bAddChannel,
                                                   bSubConnect,
                                                   bUnsub

                                                   );
                    UnityEngine.Debug.Log(strLog2);

                    if (bAddChannel
                        & bGetChannel
                        & bSubConnect
                        & bUnsub

                        )
                    {
                        IntegrationTest.Pass();
                    }
                }
            }, this.DisplayErrorMessage);

            //yield return new WaitForSeconds (CommonIntergrationTests.WaitTimeBetweenCallsLow);


            //pubnub.EndPendingRequests ();
            pubnub.CleanUp();
        }
        public void ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage()
        {
            receivedMessage = false;
            currentTestCase = "ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage";

            pubnub             = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();

            unitTest.TestClassName = "WhenSubscribedToWildcardChannel";
            unitTest.TestCaseName  = "ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage";

            pubnub.PubnubUnitTest = unitTest;

            string wildCardSubscribeChannel = "foo.*";
            string subChannelName           = "hello_my_channel";
            string commaDelimitedChannel    = string.Format("{0},{1}", subChannelName, wildCardSubscribeChannel);

            channelGroupName = "hello_my_group";
            string channelAddForGroup = "hello_my_channel1";
            string pubWildChannelName = "foo.a";

            mreSubscribe = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channelAddForGroup }, channelGroupName, ChannelGroupAddCallback, DummyErrorCallback);
            mreSubscribe.WaitOne(manualResetEventsWaitTimeout);

            mreSubscribe = new ManualResetEvent(false);

            mreSubscribeConnect = new ManualResetEvent(false);
            pubnub.Subscribe <string>(channel: commaDelimitedChannel, channelGroup: channelGroupName, subscribeCallback: ReceivedMessageCallbackWhenSubscribed, connectCallback: SubscribeDummyMethodForConnectCallback, wildcardPresenceCallback: null, errorCallback: DummyErrorCallback);
            mreSubscribeConnect.WaitOne(manualResetEventsWaitTimeout);

            mrePublish       = new ManualResetEvent(false);
            publishedMessage = "Test for cg";
            pubnub.Publish <string>(channel: channelAddForGroup, message: publishedMessage, userCallback: dummyPublishCallback, errorCallback: DummyErrorCallback);
            manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
            mrePublish.WaitOne(manualResetEventsWaitTimeout);

            if (isPublished)
            {
                Thread.Sleep(1000);
                mrePublish       = new ManualResetEvent(false);
                publishedMessage = "Test for wc";
                pubnub.Publish <string>(channel: pubWildChannelName, message: publishedMessage, userCallback: dummyPublishCallback, errorCallback: DummyErrorCallback);
                manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                mrePublish.WaitOne(manualResetEventsWaitTimeout);
            }

            if (isPublished)
            {
                Thread.Sleep(1000);
                mrePublish       = new ManualResetEvent(false);
                publishedMessage = "Test for normal ch";
                pubnub.Publish <string>(channel: subChannelName, message: publishedMessage, userCallback: dummyPublishCallback, errorCallback: DummyErrorCallback);
                manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                mrePublish.WaitOne(manualResetEventsWaitTimeout);
            }

            endOfPublish = true;
            if (isPublished)
            {
                Thread.Sleep(1000);
                mreSubscribe.WaitOne(manualResetEventsWaitTimeout);

                mreUnsubscribe = new ManualResetEvent(false);
                pubnub.Unsubscribe <string>(commaDelimitedChannel, channelGroupName, dummyUnsubscribeCallback, SubscribeDummyMethodForConnectCallback, UnsubscribeDummyMethodForDisconnectCallback, null, DummyErrorCallback);
                mreUnsubscribe.WaitOne(manualResetEventsWaitTimeout);
            }
            Assert.IsTrue(receivedMessage, "WhenSubscribedToWildcardChannel --> ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage Failed");
            pubnub.PubnubUnitTest = null;
            pubnub.EndPendingRequests();
            pubnub = null;
        }
        public void ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage()
        {
            receivedMessage = false;
            currentTestCase = "ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage";

            pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenSubscribedToWildcardChannel";
            unitTest.TestCaseName = "ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage";

            pubnub.PubnubUnitTest = unitTest;

            string wildCardSubscribeChannel = "foo.*";
            string subChannelName = "hello_my_channel";
            string commaDelimitedChannel = string.Format("{0},{1}", subChannelName, wildCardSubscribeChannel);
            channelGroupName = "hello_my_group";
            string channelAddForGroup = "hello_my_channel1";
            string pubWildChannelName = "foo.a";

            mreSubscribe = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup<string>(new string[] { channelAddForGroup }, channelGroupName, ChannelGroupAddCallback, DummyErrorCallback);
            mreSubscribe.WaitOne(manualResetEventsWaitTimeout);

            mreSubscribe = new ManualResetEvent(false);

            mreSubscribeConnect = new ManualResetEvent(false);
            pubnub.Subscribe<string>(channel: commaDelimitedChannel, channelGroup: channelGroupName, subscribeCallback: ReceivedMessageCallbackWhenSubscribed, connectCallback: SubscribeDummyMethodForConnectCallback, wildcardPresenceCallback: null, errorCallback: DummyErrorCallback);
            mreSubscribeConnect.WaitOne(manualResetEventsWaitTimeout);

            mrePublish = new ManualResetEvent(false);
            publishedMessage = "Test for cg";
            pubnub.Publish<string>(channel: channelAddForGroup, message: publishedMessage, userCallback: dummyPublishCallback, errorCallback: DummyErrorCallback);
            manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
            mrePublish.WaitOne(manualResetEventsWaitTimeout);

            if (isPublished)
            {
                Thread.Sleep(1000);
                mrePublish = new ManualResetEvent(false);
                publishedMessage = "Test for wc";
                pubnub.Publish<string>(channel: pubWildChannelName, message: publishedMessage, userCallback: dummyPublishCallback, errorCallback: DummyErrorCallback);
                manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                mrePublish.WaitOne(manualResetEventsWaitTimeout);
            }

            if (isPublished)
            {
                Thread.Sleep(1000);
                mrePublish = new ManualResetEvent(false);
                publishedMessage = "Test for normal ch";
                pubnub.Publish<string>(channel: subChannelName, message: publishedMessage, userCallback: dummyPublishCallback, errorCallback: DummyErrorCallback);
                manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                mrePublish.WaitOne(manualResetEventsWaitTimeout);
            }

            endOfPublish = true;
            if (isPublished)
            {
                Thread.Sleep(1000);
                mreSubscribe.WaitOne(manualResetEventsWaitTimeout);

                mreUnsubscribe = new ManualResetEvent(false);
                pubnub.Unsubscribe<string>(commaDelimitedChannel, channelGroupName, dummyUnsubscribeCallback, SubscribeDummyMethodForConnectCallback, UnsubscribeDummyMethodForDisconnectCallback, null, DummyErrorCallback);
                mreUnsubscribe.WaitOne(manualResetEventsWaitTimeout);
            }
            Assert.IsTrue(receivedMessage, "WhenSubscribedToWildcardChannel --> ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage Failed");
            pubnub.PubnubUnitTest = null;
            pubnub.EndPendingRequests();
            pubnub = null;

        }
        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");
            }
        }
Exemplo n.º 20
0
        public IEnumerator DoCGCHAddListRemoveSubscribeStateHereNowUnsub(bool ssl, string testName, bool asObject, bool withCipher, object message, string expectedStringResponse, bool matchExpectedStringResponse)
        {
            /*  ⁃   Add CH to CG
             * ⁃   List CG
             * ⁃   Get all CGs
             * ⁃
             * ⁃   */
            pubnub = new Pubnub(CommonIntergrationTests.PublishKey,
                                CommonIntergrationTests.SubscribeKey);

            System.Random r       = new System.Random();
            string        cg      = "UnityIntegrationTest_CG_" + r.Next(100);
            string        ch      = "UnityIntegrationTest_CH_" + r.Next(100);
            string        channel = "UnityIntegrationTest_CH_" + r.Next(100);

            UnityEngine.Debug.Log(string.Format("{0} {1}: Start coroutine ", DateTime.Now.ToString(), testName));
            bool   bAddChannel = false;
            bool   bGetChannel = false;
            bool   bGetAllCG   = true;
            string uuid        = "UnityIntegrationTest_UUID";

            pubnub.ChangeUUID(uuid);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channel }, cg, (string result) => {
                //[{"status":200,"message":"OK","service":"channel-registry","error":false}]
                UnityEngine.Debug.Log(string.Format("{0}: {1} AddChannelsToChannelGroup {2}", DateTime.Now.ToString(), testName, result));
                if (result.Contains("OK") && result.Contains("\"error\":false"))
                {
                    bAddChannel = true;
                    pubnub.GetChannelsForChannelGroup(cg, (string result2) => {
                        //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                        UnityEngine.Debug.Log(string.Format("{0}: {1} GetChannelsOfChannelGroup {2}", DateTime.Now.ToString(), testName, result2));
                        if (result2.Contains(cg) && result2.Contains(channel))
                        {
                            bGetChannel = true;
                        }
                        else
                        {
                            bGetChannel = false;
                        }
                    }, this.DisplayErrorMessage);
                }
            }, this.DisplayErrorMessage);
            UnityEngine.Debug.Log(string.Format("{0}: {1} Waiting for response", DateTime.Now.ToString(), testName));

            string strLog = string.Format("{0}: {1} After wait {2} {3}",
                                          DateTime.Now.ToString(),
                                          testName,
                                          bAddChannel,
                                          bGetChannel);

            UnityEngine.Debug.Log(strLog);
            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*Subscribe CG
             * ⁃   Publish to CH
             * ⁃   Read Message on CG*/

            bool   bSubConnected = false;
            bool   bSubMessage   = true;
            bool   bSubMessage2  = false;
            bool   bSubPublished = false;
            string pubMessage    = "TestMessage";

            pubnub.Subscribe <string>(ch, cg, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe {2}", DateTime.Now.ToString(), testName, retM));
                if (retM.Contains(pubMessage) && retM.Contains(channel) && retM.Contains(cg))
                {
                    bSubMessage = true;
                }
                if (retM.Contains(pubMessage) && retM.Contains(ch) && !retM.Contains(cg))
                {
                    bSubMessage2 = true;
                }
            }, (string retConnect) => {
                bSubConnected = true;
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe Connected {2}", DateTime.Now.ToString(), testName, retConnect));
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.Publish(ch, pubMessage, (string pub) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Published CH {2}", DateTime.Now.ToString(), testName, pub));
            }, this.DisplayErrorMessage);

            /*
             * ⁃   Set State of CG
             * ⁃   Get State of CG
             */
            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            bool   bSetState = false;
            bool   bGetState = true;
            string state     = "{\"k\":\"v\"}";

            pubnub.SetUserState <string>(ch, cg, "", state, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} SetUserState {2} {3} {4}",
                                                    DateTime.Now.ToString(), testName, retM, retM.Contains(state), retM.Contains(ch)));
                if (retM.Contains(state) && retM.Contains(cg))
                {
                    bSetState = true;
                }
            }, this.DisplayErrorMessage);


            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*
             * ⁃   Run Here Now CG with State
             * ⁃   Run Here Now CG without State
             */
            bool bHereNow = false;

            pubnub.HereNow(ch, cg, true, false, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} HereNow {2}",
                                                    DateTime.Now.ToString(), testName, retM));
                if (retM.Contains(uuid))
                {
                    bHereNow = true;
                }
                ;
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            bool bHereNowState = false;

            pubnub.HereNow(ch, cg, true, true, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} HereNowWithState {2}",
                                                    DateTime.Now.ToString(), testName, retM));
                if (retM.Contains(uuid) && retM.Contains(state))
                {
                    bHereNowState = true;
                }
                ;
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*
             * ⁃   Del State of CG
             *
             */
            bool bSetUserState2 = true;
            bool bGetUserState2 = true;

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*
             * ⁃   Remove CH from CG
             * ⁃   List CG
             */


            /*⁃   Unsub from CG*/

            bool bUnsub = false;

            pubnub.Unsubscribe <string>(ch, cg, this.DisplayReturnMessageDummy, this.DisplayReturnMessageDummy, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Unsubscribe {2} {3} {4}",
                                                    DateTime.Now.ToString(), testName, retM, retM.Contains("Unsubscribed"), retM.Contains(cg)));

                if (retM.Contains("Unsubscribed") && retM.Contains(cg))
                {
                    bUnsub = true;
                }
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*bool bRemoveCh = false;
             * pubnub.RemoveChannelsFromChannelGroup<string>(new string[]{channel}, cg, (string retM)=>{
             *  UnityEngine.Debug.Log (string.Format ("{0}: {1} RemoveChannelsFromChannelGroup {2}",
             *      DateTime.Now.ToString (), testName, retM));
             *  if(retM.Contains("OK") && retM.Contains("\"error\":false")){
             *      bRemoveCh = true;
             *  }
             * },  this.DisplayErrorMessage);*/

            bool bRemoveCh    = true;
            bool bGetChannel2 = true;

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            string strLog2 = string.Format("{0}: {1} After wait2   {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15}",
                                           DateTime.Now.ToString(),
                                           testName,
                                           bAddChannel,
                                           bGetChannel,
                                           bGetAllCG,
                                           bSubMessage,
                                           bGetState,
                                           bSetState,
                                           bHereNowState,
                                           bHereNow,
                                           bUnsub,
                                           bSetUserState2,
                                           bGetUserState2,
                                           bRemoveCh,
                                           bGetChannel2,
                                           bSubMessage2
                                           );

            UnityEngine.Debug.Log(strLog2);

            if (bAddChannel
                & bGetAllCG
                & bGetChannel
                & bGetState
                & bSetState
                & bSubMessage
                & bHereNowState
                & bHereNow
                & bUnsub
                & bSetUserState2
                & bGetUserState2
                & bRemoveCh
                & bGetChannel2
                & bSubMessage2
                )
            {
                IntegrationTest.Pass();
            }
            pubnub.EndPendingRequests();
            pubnub.CleanUp();
        }
Exemplo n.º 21
0
        void ProcessPubnubRequest(string requestType)
        {
            CheckUserInputs();
            channel      = txtChannel.Text;
            channelGroup = txtChannelGroup.Text.Trim();

            bool   storeInHistory = chkStoreInHistory.Checked;
            string pamAuthKey     = txtPAMAuthKey.Text.Trim();

            UpdateTimer.Enabled = true;

            switch (requestType.ToLower())
            {
            case "presence":
                if (channelGroup == "")
                {
                    pubnub.Presence <string>(channel, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayErrorMessage);
                }
                else
                {
                    pubnub.Presence <string>(channel, channelGroup, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayErrorMessage);
                }
                break;

            case "subscribe":
                if (channelGroup == "")
                {
                    pubnub.Subscribe <string>(channel, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayErrorMessage);
                }
                else
                {
                    pubnub.Subscribe <string>(channel, channelGroup, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayErrorMessage);
                }
                break;

            case "detailedhistory":
                pubnub.DetailedHistory <string>(channel, 10, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "publish":
                if (radNormalPublish.Checked)
                {
                    string messageToBePublished = txtPublishMessage.Text;
                    pubnub.Publish <string>(channel, messageToBePublished, storeInHistory, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radToastPublish.Checked)
                {
                    MpnsToastNotification toast = new MpnsToastNotification();
                    //toast.type = "toast";
                    toast.text1 = "hardcode message";
                    Dictionary <string, object> dicToast = new Dictionary <string, object>();
                    dicToast.Add("pn_mpns", toast);

                    pubnub.EnableDebugForPushPublish = true;
                    pubnub.Publish <string>(channel, dicToast, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radFlipTilePublish.Checked)
                {
                    pubnub.PushRemoteImageDomainUri.Add(new Uri("http://cdn.flaticon.com"));

                    MpnsFlipTileNotification tile = new MpnsFlipTileNotification();
                    tile.title                 = "front title";
                    tile.count                 = 6;
                    tile.back_title            = "back title";
                    tile.back_content          = "back message";
                    tile.back_background_image = "Assets/Tiles/pubnub3.png";
                    tile.background_image      = "http://cdn.flaticon.com/png/256/37985.png";
                    Dictionary <string, object> dicTile = new Dictionary <string, object>();
                    dicTile.Add("pn_mpns", tile);

                    pubnub.EnableDebugForPushPublish = true;
                    pubnub.Publish <string>(channel, dicTile, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radCycleTilePublish.Checked)
                {
                    MpnsCycleTileNotification tile = new MpnsCycleTileNotification();
                    tile.title  = "front title";
                    tile.count  = 2;
                    tile.images = new string[] { "Assets/Tiles/pubnub1.png", "Assets/Tiles/pubnub2.png", "Assets/Tiles/pubnub3.png", "Assets/Tiles/pubnub4.png" };

                    Dictionary <string, object> dicTile = new Dictionary <string, object>();
                    dicTile.Add("pn_mpns", tile);

                    pubnub.EnableDebugForPushPublish = true;
                    pubnub.Publish <string>(channel, dicTile, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radIconicTilePublish.Checked)
                {
                    MpnsIconicTileNotification tile = new MpnsIconicTileNotification();
                    tile.title          = "front title";
                    tile.count          = 2;
                    tile.wide_content_1 = "my wide content";

                    Dictionary <string, object> dicTile = new Dictionary <string, object>();
                    dicTile.Add("pn_mpns", tile);

                    pubnub.EnableDebugForPushPublish = true;
                    pubnub.Publish <string>(channel, dicTile, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                txtPublishMessage.Text = "";
                lblErrorMessage.Text   = "";
                break;

            case "unsubscribe":
                if (channelGroup == "")
                {
                    pubnub.Unsubscribe <string>(channel, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayDisconnectCallbackMessage, DisplayErrorMessage);
                }
                else
                {
                    pubnub.Unsubscribe <string>(channel, channelGroup, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayDisconnectCallbackMessage, DisplayErrorMessage);
                }
                break;

            case "presenceunsubscribe":
                if (channelGroup == "")
                {
                    pubnub.PresenceUnsubscribe <string>(channel, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayDisconnectCallbackMessage, DisplayErrorMessage);
                }
                else
                {
                    pubnub.PresenceUnsubscribe <string>(channel, channelGroup, DisplayUserCallbackMessage, DisplayConnectCallbackMessage, DisplayDisconnectCallbackMessage, DisplayErrorMessage);
                }
                break;

            case "herenow":
                bool showUUID2         = chbShowUUIDList2.Checked;
                bool includeUserState2 = chbShowUserState2.Checked;
                pubnub.HereNow <string>(channel, showUUID2, includeUserState2, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "globalherenow":
                bool showUUID         = chbShowUUIDList.Checked;
                bool includeUserState = chbShowUserState.Checked;
                pubnub.GlobalHereNow <string>(showUUID, includeUserState, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "wherenow":
                pubnub.WhereNow <string>(uuid, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "time":
                pubnub.Time <string>(DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "grantaccess":
                pubnub.GrantAccess <string>(channel, pamAuthKey, true, true, 60, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "revokeaccess":
                pubnub.GrantAccess <string>(channel, pamAuthKey, false, false, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "auditaccess":
                pubnub.AuditAccess <string>(channel, pamAuthKey, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "disablenetwork":
                pubnub.EnableSimulateNetworkFailForTestingOnly();
                break;

            case "enablenetwork":
                pubnub.DisableSimulateNetworkFailForTestingOnly();
                break;

            case "disconnectandretry":
                pubnub.TerminateCurrentSubscriberRequest();
                break;

            case "getuserstate":
                string getUserStateUUID = txtGetUserStateUUID.Text;
                pubnub.GetUserState <string>(channel, getUserStateUUID, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "jsonsetuserstate":
                string jsonUserState = txtJsonUserState.Text;
                pubnub.SetUserState <string>(channel, jsonUserState, DisplayUserCallbackMessage, DisplayErrorMessage);
                break;

            case "setuserstate":
                string key1   = txtKey1.Text;
                string value1 = txtValue1.Text;

                int    valueInt;
                double valueDouble;

                if (Int32.TryParse(value1, out valueInt))
                {
                    pubnub.SetUserState <string>(channel, new KeyValuePair <string, object>(key1, valueInt), DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (Double.TryParse(value1, out valueDouble))
                {
                    pubnub.SetUserState <string>(channel, new KeyValuePair <string, object>(key1, valueDouble), DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else
                {
                    pubnub.SetUserState <string>(channel, new KeyValuePair <string, object>(key1, value1), DisplayUserCallbackMessage, DisplayErrorMessage);
                }

                break;

            case "channelgroup":
                string userChannelGroupName = txtChannelGroupName.Text;
                if (radChannelGroupGet.Checked)
                {
                    pubnub.GetChannelsForChannelGroup <string>(userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radChannelGroupAdd.Checked)
                {
                    string userChannelGroupAddChannel = txtChannelGroupAddChannels.Text;
                    pubnub.AddChannelsToChannelGroup <string>(new string[] { userChannelGroupAddChannel }, userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radChannelGroupRemove.Checked)
                {
                    string userChannelGroupRemoveChannel = txtChannelGroupRemoveChannels.Text;
                    pubnub.RemoveChannelsFromChannelGroup <string>(new string[] { userChannelGroupRemoveChannel }, userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radChannelGroupGrant.Checked)
                {
                    pubnub.ChannelGroupGrantAccess <string>(userChannelGroupName, true, true, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radChannelGroupAudit.Checked)
                {
                    pubnub.ChannelGroupAuditAccess <string>(userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                else if (radChannelGroupRevoke.Checked)
                {
                    pubnub.ChannelGroupGrantAccess <string>(userChannelGroupName, false, false, DisplayUserCallbackMessage, DisplayErrorMessage);
                }
                break;

            default:
                break;
            }
        }
        public IEnumerator DoTestSubscribeWithTimetoken(bool ssl, string testName, bool asObject, bool withCipher, object message, string expectedStringResponse, bool matchExpectedStringResponse)
        {
            /*  ⁃   Add CH to CG
             * ⁃   List CG
             * ⁃   Get all CGs
             * ⁃
             * ⁃   */
            pubnub = new Pubnub(CommonIntergrationTests.PublishKey,
                                CommonIntergrationTests.SubscribeKey);

            System.Random r       = new System.Random();
            string        cg      = "UnityIntegrationTest_CG_" + r.Next(100);
            string        ch      = "UnityIntegrationTest_CH_" + r.Next(100);
            string        channel = "UnityIntegrationTest_CH_" + r.Next(100);

            UnityEngine.Debug.Log(string.Format("{0} {1}: Start coroutine ", DateTime.Now.ToString(), testName));
            bool   bAddChannel = false;
            bool   bGetChannel = false;
            bool   bGetAllCG   = true;
            string uuid        = "UnityIntegrationTest_UUID";

            pubnub.ChangeUUID(uuid);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channel }, cg, (string result) => {
                //[{"status":200,"message":"OK","service":"channel-registry","error":false}]
                UnityEngine.Debug.Log(string.Format("{0}: {1} AddChannelsToChannelGroup {2}", DateTime.Now.ToString(), testName, result));
                if (result.Contains("OK") && result.Contains("\"error\":false"))
                {
                    bAddChannel = true;
                    pubnub.GetChannelsForChannelGroup(cg, (string result2) => {
                        //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                        UnityEngine.Debug.Log(string.Format("{0}: {1} GetChannelsOfChannelGroup {2}", DateTime.Now.ToString(), testName, result2));
                        if (result2.Contains(cg) && result2.Contains(channel))
                        {
                            bGetChannel = true;
                        }
                        else
                        {
                            bGetChannel = false;
                        }
                    }, this.DisplayErrorMessage);
                }
            }, this.DisplayErrorMessage);
            UnityEngine.Debug.Log(string.Format("{0}: {1} Waiting for response", DateTime.Now.ToString(), testName));

            string strLog = string.Format("{0}: {1} After wait {2} {3}",
                                          DateTime.Now.ToString(),
                                          testName,
                                          bAddChannel,
                                          bGetChannel);

            UnityEngine.Debug.Log(strLog);
            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            string tt = "";

            pubnub.Time <string>((string str) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1}Time {2}", DateTime.Now.ToString(), testName, str));
                object[] obj = pubnub.JsonPluggableLibrary.DeserializeToObject(str) as object[];
                tt           = obj[0].ToString();
                UnityEngine.Debug.Log(string.Format("{0}: {1} Time tt {2}", DateTime.Now.ToString(), testName, tt));
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*Subscribe CG
             * ⁃   Publish to CH
             * ⁃   Read Message on CG*/

            bool   bSubMessage = false;
            string pubMessage  = "TestMessageTT";

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.Publish(channel, pubMessage, (string pub) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Published CH {2}", DateTime.Now.ToString(), testName, pub));
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.Subscribe <string>(ch, cg, tt, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe {2}", DateTime.Now.ToString(), testName, retM));
                if (retM.Contains(pubMessage) && retM.Contains(channel) && retM.Contains(cg))
                {
                    bSubMessage = true;
                }
            }, (string retConnect) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe Connected {2}", DateTime.Now.ToString(), testName, retConnect));
            }, this.DisplayReturnMessageDummy, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            /*⁃   Unsub from CG*/

            bool bUnsub = false;

            pubnub.Unsubscribe <string>(ch, cg, this.DisplayReturnMessageDummy, this.DisplayReturnMessageDummy, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Unsubscribe {2} {3} {4}",
                                                    DateTime.Now.ToString(), testName, retM, retM.Contains("Unsubscribed"), retM.Contains(cg)));

                if (retM.Contains("Unsubscribed") && retM.Contains(cg))
                {
                    bUnsub = true;
                }
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            bool bRemoveCh = true;

            /*pubnub.RemoveChannelsFromChannelGroup<string>(new string[]{channel}, cg, (string retM)=>{
             *  UnityEngine.Debug.Log (string.Format ("{0}: {1} RemoveChannelsFromChannelGroup {2}",
             *      DateTime.Now.ToString (), testName, retM));
             *  if(retM.Contains("OK") && retM.Contains("\"error\":false")){
             *      bRemoveCh = true;
             *  }
             * },  this.DisplayErrorMessage);
             *
             * yield return new WaitForSeconds (CommonIntergrationTests.WaitTimeBetweenCallsLow);  */

            string strLog2 = string.Format("{0}: {1} After wait2   {2} {3} {4} {5} {6} {7}",
                                           DateTime.Now.ToString(),
                                           testName,
                                           bAddChannel,
                                           bGetChannel,
                                           bGetAllCG,
                                           bSubMessage,
                                           bUnsub,
                                           bRemoveCh
                                           );

            UnityEngine.Debug.Log(strLog2);

            if (bAddChannel
                & bGetAllCG
                & bGetChannel
                & bSubMessage
                & bUnsub
                & bRemoveCh
                )
            {
                IntegrationTest.Pass();
            }
            pubnub.EndPendingRequests();
            pubnub.CleanUp();
        }
        public void ThenSubscribeShouldReturnConnectStatus()
        {
            currentUnitTestCase = "ThenSubscribeShouldReturnConnectStatus";
            receivedMessage = false;

            ThreadPool.QueueUserWorkItem((s) =>
                {
                    Pubnub pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
                    pubnub.SessionUUID = "myuuid";

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
                    unitTest.TestCaseName = "ThenSubscribeShouldReturnConnectStatus";

                    pubnub.PubnubUnitTest = unitTest;

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

                    subscribeManualEvent = new ManualResetEvent(false);
                    EnqueueCallback(() => pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName }, channelGroupName, ChannelGroupAddCallback, DummySubscribeErrorCallback));
                    subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                    if (receivedChannelGroupMessage)
                    {
                        subscribeManualEvent = new ManualResetEvent(false);
                        EnqueueCallback(() => pubnub.Subscribe<string>("", channelGroupName, ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback));
                        Thread.Sleep(1000);

                        manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 1000 : 310 * 1000;
                        subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

                        EnqueueCallback(() => pubnub.EndPendingRequests());

                        EnqueueCallback(() => Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenSubscribeShouldReturnConnectStatus Failed"));
                    }
                    else
                    {
                        EnqueueCallback(() => Assert.IsTrue(receivedChannelGroupMessage, "WhenSubscribedToAChannelGroup --> ThenSubscribeShouldReturnConnectStatus Failed"));
                    }
                    EnqueueCallback(() =>
                            {
                                pubnub.PubnubUnitTest = null;
                                pubnub = null;
                            }
                        );
                    EnqueueTestComplete();
                });
        }
Exemplo n.º 24
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");
            }
        }
Exemplo n.º 25
0
        private void btnChannelGroup_Click(object sender, RoutedEventArgs e)
        {
            CheckUserInputs();
            channelGroup = txtChannelGroup.Text.Trim();

            if (authKey.Trim() != "")
            {
                pubnub.AuthenticationKey = authKey;
            }

            ChannelGroupDialog channelGroupPopup = new ChannelGroupDialog();

            channelGroupPopup.txtChannelGroupName.Text = channelGroup;
            channelGroupPopup.Show();

            channelGroupPopup.Closed += (obj, args) =>
            {
                if (channelGroupPopup.DialogResult == true)
                {
                    string userChannelGroupName = channelGroupPopup.txtChannelGroupName.Text.Trim();
                    if (channelGroupPopup.radChannelGroupGet.IsChecked.Value)
                    {
                        Console.WriteLine("Running GetChannelsForChannelGroup()");
                        pubnub.GetChannelsForChannelGroup <string>(userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radChannelGroupAdd.IsChecked.Value)
                    {
                        Console.WriteLine("Running AddChannelsToChannelGroup()");
                        string userChannelGroupAddChannel = channelGroupPopup.txtChannelGroupAddChannels.Text;
                        pubnub.AddChannelsToChannelGroup <string>(new string[] { userChannelGroupAddChannel }, userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radChannelGroupRemove.IsChecked.Value)
                    {
                        Console.WriteLine("Running RemoveChannelsFromChannelGroup()");
                        string userChannelGroupRemoveChannel = channelGroupPopup.txtChannelGroupRemoveChannels.Text;
                        pubnub.RemoveChannelsFromChannelGroup <string>(new string[] { userChannelGroupRemoveChannel }, userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radChannelGroupGrant.IsChecked.Value)
                    {
                        Console.WriteLine("Running ChannelGroupGrantAccess()");
                        pubnub.ChannelGroupGrantAccess <string>(userChannelGroupName, true, true, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radChannelGroupAudit.IsChecked.Value)
                    {
                        Console.WriteLine("Running ChannelGroupAuditAccess()");
                        pubnub.ChannelGroupAuditAccess <string>(userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radChannelGroupRevoke.IsChecked.Value)
                    {
                        Console.WriteLine("Running ChannelGroupRevokeAccess()");
                        pubnub.ChannelGroupGrantAccess <string>(userChannelGroupName, false, false, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }

                    else if (channelGroupPopup.radPresenceChannelGroupGrant.IsChecked.Value)
                    {
                        Console.WriteLine("Running ChannelGroupGrantPresenceAccess()");
                        pubnub.ChannelGroupGrantPresenceAccess <string>(userChannelGroupName, true, true, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radPresenceChannelGroupAudit.IsChecked.Value)
                    {
                        Console.WriteLine("Running ChannelGroupAuditPresenceAccess()");
                        pubnub.ChannelGroupAuditPresenceAccess <string>(userChannelGroupName, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                    else if (channelGroupPopup.radPresenceChannelGroupRevoke.IsChecked.Value)
                    {
                        Console.WriteLine("Running ChannelGroup Revoke PresenceAccess()");
                        pubnub.ChannelGroupGrantPresenceAccess <string>(userChannelGroupName, false, false, DisplayUserCallbackMessage, DisplayErrorMessage);
                    }
                }
            };
        }
Exemplo n.º 26
0
        private void btnChannelGroup_Click(object sender, RoutedEventArgs e)
        {
            channelGroup = txtChannelGroup.Text;

            this.IsEnabled = false;
            Border border = new Border();

            border.BorderBrush     = new SolidColorBrush(Colors.Black);
            border.BorderThickness = new Thickness(5.0);

            StackPanel channelGroupStackPanel = new StackPanel();

            channelGroupStackPanel.Background = new SolidColorBrush(Colors.Blue);
            channelGroupStackPanel.Width      = 400;
            channelGroupStackPanel.Height     = 440;

            Popup channelGroupPopup = new Popup();

            channelGroupPopup.Height = 420;
            channelGroupPopup.Width  = 300;

            channelGroupPopup.HorizontalOffset = 10;
            channelGroupPopup.VerticalOffset   = 100;

            ChannelGroupUserControl control = new ChannelGroupUserControl();

            control.txtChannelGroup.Text = channelGroup;
            control.txtChannelName.Text  = "ch1";

            channelGroupStackPanel.Children.Add(control);
            border.Child = channelGroupStackPanel;

            channelGroupPopup.Child  = border;
            channelGroupPopup.IsOpen = true;

            control.btnOK.Click += (s, args) =>
            {
                channelGroupPopup.IsOpen = false;
                string msg = "";
                string userChannelGroup = control.txtChannelGroup.Text;;
                string userChannelName  = control.txtChannelName.Text;

                if (control.radGetChannelsOfChannelGroup.IsChecked.Value)
                {
                    msg = "Running GetChannelsForChannelGroup";
                    pubnub.GetChannelsForChannelGroup <string>(userChannelGroup, PubnubCallbackResult, PubnubDisplayErrorMessage);
                }

                if (control.radAddChannelToChannelGroup.IsChecked.Value)
                {
                    msg = "Running AddChannelsToChannelGroup";
                    pubnub.AddChannelsToChannelGroup <string>(new string[] { userChannelName }, userChannelGroup, PubnubCallbackResult, PubnubDisplayErrorMessage);
                }

                if (control.radRemoveChannelFromChannelGroup.IsChecked.Value)
                {
                    msg = "Running RemoveChannelsFromChannelGroup";
                    pubnub.RemoveChannelsFromChannelGroup <string>(new string[] { userChannelName }, userChannelGroup, PubnubCallbackResult, PubnubDisplayErrorMessage);
                }

                TextBlock textBlock = new TextBlock();
                textBlock.Text = msg;
                messageStackPanel.Children.Add(textBlock);
                scrollViewerResult.UpdateLayout();
                scrollViewerResult.ScrollToVerticalOffset(scrollViewerResult.ExtentHeight);
                channelGroupPopup = null;
                this.IsEnabled    = true;
            };
            control.btnCancel.Click += (s, args) =>
            {
                channelGroupPopup.IsOpen = false;
                channelGroupPopup        = null;
                this.IsEnabled           = true;
            };
        }
        public IEnumerator DoRemoveCGAndRemoveAllCG(bool ssl, string testName, bool asObject, bool withCipher, object message, string expectedStringResponse, bool matchExpectedStringResponse)
        {
            /*  ⁃   Add CH to CG
             * ⁃   List CG
             * ⁃   Get all CGs
             * ⁃
             * ⁃   */
            pubnub = new Pubnub(CommonIntergrationTests.PublishKey,
                                CommonIntergrationTests.SubscribeKey);

            System.Random r       = new System.Random();
            string        cg      = "UnityIntegrationTest_CG_" + r.Next(100);
            string        ch      = "UnityIntegrationTest_CH_" + r.Next(100);
            string        channel = "UnityIntegrationTest_CH_" + r.Next(100);

            UnityEngine.Debug.Log(string.Format("{0} {1}: Start coroutine ", DateTime.Now.ToString(), testName));
            bool   bAddChannel = false;
            bool   bGetChannel = false;
            bool   bGetAllCG   = true;
            string uuid        = "UnityIntegrationTest_UUID";

            pubnub.ChangeUUID(uuid);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channel, ch }, cg, (string result) => {
                //[{"status":200,"message":"OK","service":"channel-registry","error":false}]
                UnityEngine.Debug.Log(string.Format("{0}: {1} AddChannelsToChannelGroup {2}", DateTime.Now.ToString(), testName, result));
                if (result.Contains("OK") && result.Contains("\"error\":false"))
                {
                    bAddChannel = true;
                    pubnub.GetChannelsForChannelGroup(cg, (string result2) => {
                        //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                        UnityEngine.Debug.Log(string.Format("{0}: {1} GetChannelsOfChannelGroup {2}", DateTime.Now.ToString(), testName, result2));
                        if (result2.Contains(cg) && result2.Contains(channel))
                        {
                            bGetChannel = true;
                        }
                        else
                        {
                            bGetChannel = false;
                        }
                    }, this.DisplayErrorMessage);
                }
            }, this.DisplayErrorMessage);
            UnityEngine.Debug.Log(string.Format("{0}: {1} Waiting for response", DateTime.Now.ToString(), testName));
            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            string strLog = string.Format("{0}: {1} After wait {2} {3}",
                                          DateTime.Now.ToString(),
                                          testName,
                                          bAddChannel,
                                          bGetChannel);

            UnityEngine.Debug.Log(strLog);
            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            bool bRemoveCh = false;

            pubnub.RemoveChannelsFromChannelGroup <string>(new string[] { channel }, cg, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} RemoveChannelsFromChannelGroup {2}",
                                                    DateTime.Now.ToString(), testName, retM));
                if (retM.Contains("OK") && retM.Contains("\"error\":false"))
                {
                    bRemoveCh = true;
                }
            }, this.DisplayErrorMessage);

            bool bGetChannel2 = false;

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.GetChannelsForChannelGroup(cg, (string result2) => {
                //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                UnityEngine.Debug.Log(string.Format("{0}: {1} GetChannelsOfChannelGroup2 {2}", DateTime.Now.ToString(), testName, result2));
                if (result2.Contains(cg) && !result2.Contains(channel))
                {
                    bGetChannel2 = true;
                }
                else
                {
                    bGetChannel2 = false;
                }
            }, this.DisplayErrorMessage);

            bool bRemoveAll = false;

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.RemoveChannelGroup(cg, (string retM) => {
                //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                UnityEngine.Debug.Log(string.Format("{0}: {1} RemoveChannelGroup {2}", DateTime.Now.ToString(), testName, retM));
                if (retM.Contains("OK") && retM.Contains("\"error\":false"))
                {
                    bRemoveAll = true;
                }
                else
                {
                    bRemoveAll = false;
                }
            }, this.DisplayErrorMessage);

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            string strLog2 = string.Format("{0}: {1} After wait2   {2} {3} {4} {5} {6} {7}",
                                           DateTime.Now.ToString(),
                                           testName,
                                           bAddChannel,
                                           bGetChannel,
                                           bGetAllCG,
                                           bRemoveCh,
                                           bGetChannel2,
                                           bRemoveAll
                                           );

            UnityEngine.Debug.Log(strLog2);

            if (bAddChannel
                & bGetAllCG
                & bGetChannel
                & bRemoveCh
                & bGetChannel2
                & bRemoveAll
                )
            {
                IntegrationTest.Pass();
            }
            pubnub.EndPendingRequests();
            pubnub.CleanUp();
        }
Exemplo n.º 28
0
        public void ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage()
        {
            server.ClearRequests();

            receivedMessage = false;
            currentTestCase = "ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage";

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

            server.RunOnHttps(false);

            SubscribeCallback listenerSubCallack = new UTSubscribeCallback();

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

            string wildCardSubscribeChannel = "foo.*";
            string subChannelName           = "hello_my_channel";

            string[] commaDelimitedChannel = new string[] { subChannelName, wildCardSubscribeChannel };
            channelGroupName = "hello_my_group";
            string channelAddForGroup = "hello_my_channel1";
            string pubWildChannelName = "foo.a";

            manualResetEventWaitTimeout = 310 * 1000;

            channelGroupManualEvent = new ManualResetEvent(false);

            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", channelAddForGroup)
                              .WithParameter("auth", config.AuthKey)
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.AddChannelsToChannelGroup().Channels(new string[] { channelAddForGroup }).ChannelGroup(channelGroupName).Async(new ChannelGroupAddChannelResult());
            channelGroupManualEvent.WaitOne();

            subscribeManualEvent = new ManualResetEvent(false);

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

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, "foo.%2A,hello_my_channel"))
                              .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, "foo.%2A,hello_my_channel"))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Subscribe <string>().Channels(commaDelimitedChannel).ChannelGroups(new string[] { channelGroupName }).Execute();

            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout);

            publishManualEvent = new ManualResetEvent(false);

            publishedMessage = "Test for cg";

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

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

            Thread.Sleep(1000);

            pubnub.Publish().Channel(channelAddForGroup).Message(publishedMessage).Async(new UTPublishResult());

            publishManualEvent.WaitOne(manualResetEventWaitTimeout);
            Console.WriteLine("publishManualEvent.WaitOne DONE");


            if (receivedMessage)
            {
                receivedMessage = false;

                subscribeManualEvent = new ManualResetEvent(false);

                Thread.Sleep(1000);
                publishManualEvent = new ManualResetEvent(false);
                publishedMessage   = "Test for wc";

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

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

                Thread.Sleep(1000);

                pubnub.Publish().Channel(pubWildChannelName).Message(publishedMessage).Async(new UTPublishResult());

                publishManualEvent.WaitOne(manualResetEventWaitTimeout);
                Console.WriteLine("publishManualEvent.WaitOne DONE");
            }

            if (receivedMessage)
            {
                receivedMessage = false;

                publishManualEvent = new ManualResetEvent(false);
                publishedMessage   = "Test for normal ch";

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

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

                Thread.Sleep(1000);

                pubnub.Publish().Channel(subChannelName).Message(publishedMessage).Async(new UTPublishResult());

                publishManualEvent.WaitOne(manualResetEventWaitTimeout);
                Console.WriteLine("publishManualEvent.WaitOne DONE");
            }

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

            Thread.Sleep(1000);

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

            Assert.IsTrue(receivedMessage, "WhenSubscribedToWildcardChannel --> ChannelAndChannelGroupAndWildcardChannelSubscribeShouldReturnReceivedMessage Failed");
        }
        public void ThenMultiSubscribeShouldReturnConnectStatus()
        {
            server.ClearRequests();

            currentTestCase = "ThenMultiSubscribeShouldReturnConnectStatus";
            receivedMessage = false;

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

            server.RunOnHttps(false);

            SubscribeCallback listenerSubCallack = new UTSubscribeCallback();

            pubnub = this.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";

            channelGroupManualEvent = new ManualResetEvent(false);

            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));

            pubnub.AddChannelsToChannelGroup().Channels(new string[] { channelName1 }).ChannelGroup(channelGroupName1).Async(new ChannelGroupAddChannelResult());
            channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;

                channelGroupManualEvent = new ManualResetEvent(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));

                pubnub.AddChannelsToChannelGroup().Channels(new string[] { channelName2 }).ChannelGroup(channelGroupName2).Async(new ChannelGroupAddChannelResult());
                channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (receivedMessage)
            {
                receivedMessage      = false;
                subscribeManualEvent = new ManualResetEvent(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 string[] { 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");
        }
Exemplo n.º 30
0
        public static async Task ThenWithAsyncAddChannelShouldReturnSuccess()
#endif
        {
            server.ClearRequests();

            currentUnitTestCase         = "ThenAddChannelShouldReturnSuccess";
            receivedChannelGroupMessage = false;

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

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

            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("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "yo21VoxIksrH3Iozeaz5Zw4BX18N3vU9PLa-zVxRXsU=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            channelGroupManualEvent = new ManualResetEvent(false);

#if NET40
            PNResult <PNChannelGroupsAddChannelResult> cgAddResult = Task.Factory.StartNew(async() => await pubnub.AddChannelsToChannelGroup().Channels(new[] { channelName }).ChannelGroup(channelGroupName).ExecuteAsync()).Result.Result;
#else
            PNResult <PNChannelGroupsAddChannelResult> cgAddResult = await pubnub.AddChannelsToChannelGroup().Channels(new[] { channelName }).ChannelGroup(channelGroupName).ExecuteAsync();
#endif
            Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(cgAddResult.Status));

            if (cgAddResult.Result != null)
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(cgAddResult.Result));
                if (cgAddResult.Status.StatusCode == 200 && !cgAddResult.Status.Error)
                {
                    receivedChannelGroupMessage = true;
                }
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenWithAsyncAddChannelShouldReturnSuccess failed.");
        }
        private void btnChannelGroup_Click(object sender, RoutedEventArgs e)
        {
            channelGroup = txtChannelGroup.Text;

            this.IsEnabled = false;
            Border border = new Border();

            border.BorderBrush     = new SolidColorBrush(Colors.Black);
            border.BorderThickness = new Thickness(5.0);

            StackPanel channelGroupStackPanel = new StackPanel();

            channelGroupStackPanel.Background = new SolidColorBrush(Colors.Blue);
            channelGroupStackPanel.Width      = 400;
            channelGroupStackPanel.Height     = 600;

            Popup channelGroupPopup = new Popup();

            channelGroupPopup.Height = 300;
            channelGroupPopup.Width  = 300;

            channelGroupPopup.HorizontalOffset = 10;
            channelGroupPopup.VerticalOffset   = 100;

            ChannelGroupUserControl control = new ChannelGroupUserControl();

            TextBox txtPAMChannelGroup = control.FindName("txtChannelGroup") as TextBox;

            if (txtPAMChannelGroup != null)
            {
                txtPAMChannelGroup.Text = channelGroup;
            }
            TextBox txtChannelName = control.FindName("txtChannelName") as TextBox;

            if (txtChannelName != null)
            {
                txtChannelName.Text = "ch1";
            }

            channelGroupStackPanel.Children.Add(control);
            border.Child = channelGroupStackPanel;

            channelGroupPopup.Child  = border;
            channelGroupPopup.IsOpen = true;

            channelGroupPopup.Closed += (senderPopup, argsPopup) =>
            {
                if (control.IsOKButtonEntered)
                {
                    string userChannelGroup = "";
                    string userChannelName  = "";

                    txtPAMChannelGroup = control.FindName("txtChannelGroup") as TextBox;
                    if (txtPAMChannelGroup != null)
                    {
                        userChannelGroup = txtPAMChannelGroup.Text;

                        txtChannelName = control.FindName("txtChannelName") as TextBox;
                        if (txtChannelName != null)
                        {
                            userChannelName = txtChannelName.Text;
                        }
                        RadioButton radGetChannelsOfChannelGroup = control.FindName("radGetChannelsOfChannelGroup") as RadioButton;
                        if (radGetChannelsOfChannelGroup != null && radGetChannelsOfChannelGroup.IsChecked.Value)
                        {
                            DisplayMessageInTextBox("Running GetChannelsForChannelGroup:");
                            pubnub.ListChannelsForChannelGroup()
                            .ChannelGroup(userChannelGroup)
                            .Async(new PNChannelGroupsAllChannelsResultExt((r, s) =>
                            {
                                DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            }));
                        }

                        RadioButton radAddChannelToChannelGroup = control.FindName("radAddChannelToChannelGroup") as RadioButton;
                        if (radAddChannelToChannelGroup != null && radAddChannelToChannelGroup.IsChecked.Value)
                        {
                            DisplayMessageInTextBox("Running AddChannelsToChannelGroup:");
                            pubnub.AddChannelsToChannelGroup()
                            .Channels(new string[] { userChannelName })
                            .ChannelGroup(userChannelGroup)
                            .Async(new PNChannelGroupsAddChannelResultExt((r, s) =>
                            {
                                DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            }));
                        }

                        RadioButton radRemoveChannelFromChannelGroup = control.FindName("radRemoveChannelFromChannelGroup") as RadioButton;
                        if (radRemoveChannelFromChannelGroup != null && radRemoveChannelFromChannelGroup.IsChecked.Value)
                        {
                            DisplayMessageInTextBox("Running RemoveChannelsFromChannelGroup:");
                            pubnub.RemoveChannelsFromChannelGroup()
                            .Channels(new string[] { userChannelName })
                            .ChannelGroup(userChannelGroup)
                            .Async(new PNChannelGroupsRemoveChannelResultExt((r, s) =>
                            {
                                DisplayMessageInTextBox(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            }));
                        }
                    }
                }
                channelGroupPopup = null;
                this.IsEnabled    = true;
            };
        }
Exemplo n.º 32
0
        static public void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            PubnubProxy proxy = null;
            
            Console.WriteLine("HINT: TO TEST RE-CONNECT AND CATCH-UP,");
            Console.WriteLine("      DISCONNECT YOUR MACHINE FROM NETWORK/INTERNET AND ");
            Console.WriteLine("      RE-CONNECT YOUR MACHINE AFTER SOMETIME.");
            Console.WriteLine();
            Console.WriteLine("      IF NO NETWORK BEFORE MAX RE-TRY CONNECT,");
            Console.WriteLine("      NETWORK ERROR MESSAGE WILL BE SENT");
            Console.WriteLine();

            Console.WriteLine("Enter Pubnub Origin. Default Origin = pubsub.pubnub.com"); //TODO
            Console.WriteLine("If you want to accept default value, press ENTER.");
            string origin = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (origin.Trim() == "")
            {
                origin = "pubsub.pubnub.com";
                Console.WriteLine("Default Origin selected");
            }
            else
            {
                Console.WriteLine("Pubnub Origin Provided");
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Enable SSL? ENTER Y for Yes, else N");
            string enableSSL = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (enableSSL.Trim().ToLower() == "y")
            {
                Console.WriteLine("SSL Enabled");
            }
            else
            {
                Console.WriteLine("SSL NOT Enabled");
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("ENTER cipher key for encryption feature.");
            Console.WriteLine("If you don't want to avail at this time, press ENTER.");
            string cipherKey = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (cipherKey.Trim().Length > 0)
            {
                Console.WriteLine("Cipher key provided.");
            }
            else
            {
                Console.WriteLine("No Cipher key provided");
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("ENTER subscribe key.");
            Console.WriteLine("If you want to accept default demo subscribe key, press ENTER.");
            string subscribeKey = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (subscribeKey.Trim().Length > 0)
            {
                Console.WriteLine("Subscribe key provided.");
            }
            else
            {
                Console.WriteLine("Default demo subscribe key provided");
                subscribeKey = "demo";
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("ENTER publish key.");
            Console.WriteLine("If you want to accept default demo publish key, press ENTER.");
            string publishKey = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (publishKey.Trim().Length > 0)
            {
                Console.WriteLine("Publish key provided.");
            }
            else
            {
                Console.WriteLine("Default demo publish key provided");
                publishKey = "demo";
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("ENTER secret key.");
            Console.WriteLine("If you don't want to avail at this time, press ENTER.");
            string secretKey = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (secretKey.Trim().Length > 0)
            {
                Console.WriteLine("Secret key provided.");
            }
            else
            {
                Console.WriteLine("Default demo Secret key provided");
                secretKey = "demo";
            }
            Console.ResetColor();
            Console.WriteLine();

            pubnub = new Pubnub(publishKey, subscribeKey, secretKey, cipherKey,
                (enableSSL.Trim().ToLower() == "y") ? true : false);

            pubnub.Origin = origin;

            Console.WriteLine("Use Custom Session UUID? ENTER Y for Yes, else N");
            string enableCustomUUID = Console.ReadLine();
            if (enableCustomUUID.Trim().ToLower() == "y")
            {
                Console.WriteLine("ENTER Session UUID.");
                string sessionUUID = Console.ReadLine();
                pubnub.SessionUUID = sessionUUID;
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Accepted Custom Session UUID.");
                Console.ResetColor();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Default Session UUID opted.");
                Console.ResetColor();
            }
            Console.WriteLine();

            Console.WriteLine("By default Resume On Reconnect is enabled. Do you want to disable it? ENTER Y for Yes, else N");
            string disableResumeOnReconnect = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (disableResumeOnReconnect.Trim().ToLower() == "y")
            {
                Console.WriteLine("Resume On Reconnect Disabled");
                pubnub.EnableResumeOnReconnect = false;
            }
            else
            {
                Console.WriteLine("Resume On Reconnect Enabled by default");
                pubnub.EnableResumeOnReconnect = true;
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Subscribe Timeout = 310 seconds (default). Enter the value to change, else press ENTER");
            string subscribeTimeoutEntry = Console.ReadLine();
            int subscribeTimeout;
            Int32.TryParse(subscribeTimeoutEntry, out subscribeTimeout);
            Console.ForegroundColor = ConsoleColor.Blue;
            if (subscribeTimeout > 0)
            {
                Console.WriteLine("Subscribe Timeout = {0}",subscribeTimeout);
                pubnub.SubscribeTimeout = subscribeTimeout;
            }
            else
            {
                Console.WriteLine("Subscribe Timeout = {0} (default)", pubnub.SubscribeTimeout);
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Non Subscribe Timeout = 15 seconds (default). Enter the value to change, else press ENTER");
            string nonSubscribeTimeoutEntry = Console.ReadLine();
            int nonSubscribeTimeout;
            Int32.TryParse(nonSubscribeTimeoutEntry, out nonSubscribeTimeout);
            Console.ForegroundColor = ConsoleColor.Blue;
            if (nonSubscribeTimeout > 0)
            {
                Console.WriteLine("Non Subscribe Timeout = {0}", nonSubscribeTimeout);
                pubnub.NonSubscribeTimeout = nonSubscribeTimeout;
            }
            else
            {
                Console.WriteLine("Non Subscribe Timeout = {0} (default)", pubnub.NonSubscribeTimeout);
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Network Check MAX retries = 50 (default). Enter the value to change, else press ENTER");
            string networkCheckMaxRetriesEntry = Console.ReadLine();
            int networkCheckMaxRetries;
            Int32.TryParse(networkCheckMaxRetriesEntry, out networkCheckMaxRetries);
            Console.ForegroundColor = ConsoleColor.Blue;
            if (networkCheckMaxRetries > 0)
            {
                Console.WriteLine("Network Check MAX retries = {0}", networkCheckMaxRetries);
                pubnub.NetworkCheckMaxRetries = networkCheckMaxRetries;
            }
            else
            {
                Console.WriteLine("Network Check MAX retries = {0} (default)", pubnub.NetworkCheckMaxRetries);
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Network Check Retry Interval = 10 seconds (default). Enter the value to change, else press ENTER");
            string networkCheckRetryIntervalEntry = Console.ReadLine();
            int networkCheckRetryInterval;
            Int32.TryParse(networkCheckRetryIntervalEntry, out networkCheckRetryInterval);
            Console.ForegroundColor = ConsoleColor.Blue;
            if (networkCheckRetryInterval > 0)
            {
                Console.WriteLine("Network Check Retry Interval = {0} seconds", networkCheckRetryInterval);
                pubnub.NetworkCheckRetryInterval = networkCheckRetryInterval;
            }
            else
            {
                Console.WriteLine("Network Check Retry Interval = {0} seconds (default)", pubnub.NetworkCheckRetryInterval);
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Local Client Heartbeat Interval = 15 seconds (default). Enter the value to change, else press ENTER");
            string heartbeatIntervalEntry = Console.ReadLine();
            int localClientHeartbeatInterval;
            Int32.TryParse(heartbeatIntervalEntry, out localClientHeartbeatInterval);
            Console.ForegroundColor = ConsoleColor.Blue;
            if (localClientHeartbeatInterval > 0)
            {
                Console.WriteLine("Heartbeat Interval = {0} seconds", localClientHeartbeatInterval);
                pubnub.LocalClientHeartbeatInterval = localClientHeartbeatInterval;
            }
            else
            {
                Console.WriteLine("Heartbeat Interval = {0} seconds (default)", pubnub.LocalClientHeartbeatInterval);
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("HTTP Proxy Server with NTLM authentication(IP + username/pwd) exists? ENTER Y for Yes, else N");
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("NOTE: Pubnub example is being tested with CCProxy 7.3 Demo version");
            Console.ResetColor();
            string enableProxy = Console.ReadLine();
            if (enableProxy.Trim().ToLower() == "y")
            {
                bool proxyAccepted = false;
                while (!proxyAccepted)
                {
                    Console.WriteLine("ENTER proxy server name or IP.");
                    string proxyServer = Console.ReadLine();
                    Console.WriteLine("ENTER port number of proxy server.");
                    string proxyPort = Console.ReadLine();
                    int port;
                    Int32.TryParse(proxyPort, out port);
                    Console.WriteLine("ENTER user name for proxy server authentication.");
                    string proxyUsername = Console.ReadLine();
                    Console.WriteLine("ENTER password for proxy server authentication.");
                    string proxyPassword = Console.ReadLine();
                    
                    proxy = new PubnubProxy();
                    proxy.ProxyServer = proxyServer;
                    proxy.ProxyPort = port;
                    proxy.ProxyUserName = proxyUsername;
                    proxy.ProxyPassword = proxyPassword;
                    Console.ForegroundColor = ConsoleColor.Blue;
                    try
                    {
                        pubnub.Proxy = proxy;
                        proxyAccepted = true;
                        Console.WriteLine("Proxy details accepted");
                        Console.ResetColor();
                    }
                    catch (MissingFieldException mse)
                    {
                        Console.WriteLine(mse.Message);
                        Console.WriteLine("Please RE-ENTER Proxy Server details.");
                    }
                    Console.ResetColor();
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("No Proxy");
                Console.ResetColor();
            }
            Console.WriteLine();

            Console.WriteLine("Enter Auth Key. If you don't want to use Auth Key, Press ENTER Key");
            authKey = Console.ReadLine();
            pubnub.AuthenticationKey = authKey;

            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine(string.Format("Auth Key = {0}", authKey));
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Display ErrorCallback messages? Enter Y for Yes, Else N for No.");
            Console.WriteLine("Default = N  ");
            string displayErrMessage = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (displayErrMessage.Trim().ToLower() == "y" )
            {
                showErrorMessageSegments = true;
                Console.WriteLine("ErrorCallback messages will  be displayed");
            }
            else
            {
                showErrorMessageSegments = false;
                Console.WriteLine("ErrorCallback messages will NOT be displayed.");
            }
            Console.ResetColor();
            Console.WriteLine();

            Console.WriteLine("Display Debug Info in ErrorCallback messages? Enter Y for Yes, Else N for No.");
            Console.WriteLine("Default = Y  ");
            string debugMessage = Console.ReadLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            if (debugMessage.Trim().ToLower() == "n")
            {
                showDebugMessages = false;
                Console.WriteLine("ErrorCallback messages will NOT  be displayed");
            }
            else
            {
                showDebugMessages = true;
                Console.WriteLine("Debug messages will be displayed.");
            }
            Console.ResetColor();
            Console.WriteLine();


            bool exitFlag = false;
            string channel="";
            string channelGroup = "";
            int currentUserChoice = 0;
            string userinput = "";
            Console.WriteLine("");
            while (!exitFlag)
            {
                if (currentUserChoice < 1 || (currentUserChoice > 40 && currentUserChoice != 99))
                {
                    Console.WriteLine("ENTER 1 FOR Subscribe channel/channelgroup");
                    Console.WriteLine("ENTER 2 FOR Publish");
                    Console.WriteLine("ENTER 3 FOR Presence channel/channelgroup");
                    Console.WriteLine("ENTER 4 FOR Detailed History");
                    Console.WriteLine("ENTER 5 FOR Here_Now");
                    Console.WriteLine("ENTER 6 FOR Unsubscribe");
                    Console.WriteLine("ENTER 7 FOR Presence-Unsubscribe");
                    Console.WriteLine("ENTER 8 FOR Time");
                    Console.WriteLine("ENTER 9 FOR Disconnect/Reconnect existing Subscriber(s) (when internet is available)");
                    Console.WriteLine("ENTER 10 TO Disable Network Connection (no internet)");
                    Console.WriteLine("ENTER 11 TO Enable Network Connection (yes internet)");
                    Console.WriteLine("ENTER 12 FOR Grant Access to channel/ChannelGroup");
                    Console.WriteLine("ENTER 13 FOR Audit Access to channel/ChannelGroup");
                    Console.WriteLine("ENTER 14 FOR Revoke Access to channel/ChannelGroup");
                    Console.WriteLine("ENTER 15 FOR Grant Access to Presence Channel/ChannelGroup");
                    Console.WriteLine("ENTER 16 FOR Audit Access to Presence Channel/ChannelGroup");
                    Console.WriteLine("ENTER 17 FOR Revoke Access to Presence Channel/ChannelGroup");
                    Console.WriteLine("ENTER 18 FOR Change/Update Auth Key (Current value = {0})", pubnub.AuthenticationKey);
                    Console.WriteLine("ENTER 19 TO Simulate Machine Sleep Mode");
                    Console.WriteLine("ENTER 20 TO Simulate Machine Awake Mode");
                    Console.WriteLine("ENTER 21 TO Set Presence Heartbeat (Current value = {0} sec)", pubnub.PresenceHeartbeat);
                    Console.WriteLine("ENTER 22 TO Set Presence Heartbeat Interval (Current value = {0} sec)", pubnub.PresenceHeartbeatInterval);
                    Console.WriteLine("Enter 23 TO Set User State by Add/Modify Key-Pair");
                    Console.WriteLine("Enter 24 TO Set User State by Deleting existing Key-Pair");
                    Console.WriteLine("Enter 25 TO Set User State with direct json string");
                    Console.WriteLine("Enter 26 TO Get User State");
                    Console.WriteLine("Enter 27 FOR WhereNow");
                    Console.WriteLine("Enter 28 FOR GlobalHere_Now");
                    Console.WriteLine("Enter 29 TO change UUID. (Current value = {0})", pubnub.SessionUUID);
                    Console.WriteLine("Enter 38 FOR Channel Group - Add channel(s)");
                    Console.WriteLine("Enter 39 FOR Channel Group - Remove channel/group/namespace");
                    Console.WriteLine("Enter 40 FOR Channel Group - Get channel(s)/namespace(s)");
                    Console.WriteLine("ENTER 99 FOR EXIT OR QUIT");

                    userinput = Console.ReadLine();
                }
                switch (userinput)
                {
                    case "99":
                        exitFlag = true;
                        pubnub.EndPendingRequests();
                        break;
                    case "1":
                        Console.WriteLine("Enter CHANNEL name for subscribe. Use comma to enter multiple channels.");
                        Console.WriteLine("NOTE: If you want to consider only Channel Group(s), just hit ENTER");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter CHANNEL GROUP name for subscribe. Use comma to enter multiple channel groups.");
                        Console.WriteLine("To denote a namespaced CHANNEL GROUP, use the colon (:) character with the format namespace:channelgroup.");
                        Console.WriteLine("NOTE: If you want to consider only Channel(s), assuming you already entered , just hit ENTER");
                        channelGroup = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel Group= {0}", channelGroup));
                        Console.ResetColor();
                        Console.WriteLine();

                        if (channel.Length <= 0 && channelGroup.Length <= 0)
                        {
                            Console.WriteLine("To run subscribe(), atleast provide either channel name or channel group name or both");
                        }
                        else
                        {
                            Console.WriteLine("Running subscribe()");
                            pubnub.Subscribe<string>(channel, channelGroup, DisplaySubscribeReturnMessage, DisplaySubscribeConnectStatusMessage, DisplayErrorMessage);
                        }
                        break;
                    case "2":
                        Console.WriteLine("Enter CHANNEL name for publish.");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();

                        if (channel == "")
                        {
                            Console.WriteLine("Invalid CHANNEL name");
                            break;
                        }
                        Console.WriteLine("Store In History? Enter Y for Yes or N for No. To accept default(Y), just press ENTER");
                        string storeInHistory = Console.ReadLine();
                        bool store = true;
                        if (storeInHistory.ToLower() == "n")
                        {
                            store = false;
                        }

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Store In History = {0}", storeInHistory));
                        Console.ResetColor();




                        Console.WriteLine("Direct JSON String? Enter Y for Yes or N for No. To accept default(N), just press ENTER");
                        string directJson = Console.ReadLine();
                        bool jsonPublish = false;
                        if (directJson.ToLower() == "y")
                        {
                            jsonPublish = true;
                            pubnub.EnableJsonEncodingForPublish = false;
                        }
                        else
                        {
                            pubnub.EnableJsonEncodingForPublish = true;
                        }

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Direct JSON String = {0}", jsonPublish));
                        Console.ResetColor();



                        /* TO TEST SMALL TEXT PUBLISH ONLY */
                        Console.WriteLine("Enter the message for publish and press ENTER key to submit");
                        //string publishMsg = Console.ReadLine();

                        /* UNCOMMENT THE FOLLOWING CODE BLOCK TO TEST LARGE TEXT PUBLISH ONLY */
                        #region Code To Test Large Text Publish
                        ConsoleKeyInfo enteredKey;
                        StringBuilder publishBuilder = new StringBuilder();
                        do
                        {
                            enteredKey = Console.ReadKey(); //This logic is being used to capture > 2K input in console window
                            if (enteredKey.Key != ConsoleKey.Enter)
                            {
                                publishBuilder.Append(enteredKey.KeyChar);
                            }
                        } while (enteredKey.Key != ConsoleKey.Enter);
                        string publishMsg = publishBuilder.ToString();
                        #endregion
                        
                        Console.WriteLine("Running publish()");

                        double doubleData;
                        int intData;
                        if (int.TryParse(publishMsg, out intData)) //capture numeric data
                        {
                            pubnub.Publish<string>(channel, intData, store, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else if (double.TryParse(publishMsg, out doubleData)) //capture numeric data
                        {
                            pubnub.Publish<string>(channel, doubleData, store, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            //check whether any numeric is sent in double quotes
                            if (publishMsg.IndexOf("\"") == 0 && publishMsg.LastIndexOf("\"") == publishMsg.Length - 1)
                            {
                                string strMsg = publishMsg.Substring(1, publishMsg.Length - 2);
                                if (int.TryParse(strMsg, out intData))
                                {
                                    pubnub.Publish<string>(channel, strMsg, store, DisplayReturnMessage, DisplayErrorMessage);
                                }
                                else if (double.TryParse(strMsg, out doubleData))
                                {
                                    pubnub.Publish<string>(channel, strMsg, store, DisplayReturnMessage, DisplayErrorMessage);
                                }
                                else
                                {
                                    pubnub.Publish<string>(channel, publishMsg, store, DisplayReturnMessage, DisplayErrorMessage);
                                }
                            }
                            else
                            {
                                pubnub.Publish<string>(channel, publishMsg, store, DisplayReturnMessage, DisplayErrorMessage);
                            }
                        }
                        break;
                    case "3":
                        Console.WriteLine("Enter CHANNEL name for presence. Use comma to enter multiple channels.");
                        Console.WriteLine("NOTE: If you want to consider only Presence Channel Group(s), just hit ENTER");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Presence Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter CHANNEL GROUP name for presence. Use comma to enter multiple channel groups.");
                        Console.WriteLine("To denote a namespaced CHANNEL GROUP, use the colon (:) character with the format namespace:channelgroup.");
                        Console.WriteLine("NOTE: If you want to consider only Presence Channel(s), assuming you already entered, just hit ENTER");
                        channelGroup = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Presence Channel Group= {0}", channelGroup));
                        Console.ResetColor();
                        Console.WriteLine();

                        if (channel.Length <= 0 && channelGroup.Length <= 0)
                        {
                            Console.WriteLine("To run presence(), atleast provide either channel name or channel group name or both");
                        }
                        else
                        {
                            Console.WriteLine("Running presence()");
                            pubnub.Presence<string>(channel, channelGroup, DisplaySubscribeReturnMessage, DisplaySubscribeConnectStatusMessage, DisplayErrorMessage);
                        }
                        break;
                    case "4":
                        Console.WriteLine("Enter CHANNEL name for Detailed History");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running detailed history()");
                        pubnub.DetailedHistory<string>(channel, 100, DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "5":
                        bool showUUID = true;
                        bool includeUserState = false;

                        Console.WriteLine("Enter CHANNEL name for HereNow");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Show UUID List? Y or N? Default is Y. Press N for No Else press ENTER");
                        string userChoiceShowUUID = Console.ReadLine();
                        if (userChoiceShowUUID.ToLower() == "n")
                        {
                            showUUID = false;
                        }
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Show UUID = {0}",showUUID));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Include User State? Y or N? Default is N. Press Y for Yes Else press ENTER");
                        string userChoiceIncludeUserState = Console.ReadLine();
                        if (userChoiceIncludeUserState.ToLower() == "y")
                        {
                            includeUserState = true;
                        }
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Include User State = {0}", includeUserState));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running Here_Now()");
                        pubnub.HereNow<string>(channel, showUUID, includeUserState, DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "6":
                        Console.WriteLine("Enter CHANNEL name for Unsubscribe. Use comma to enter multiple channels.");
                        Console.WriteLine("NOTE: If you want to consider only Channel Group, just hit ENTER");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter channel group name");
                        Console.WriteLine("NOTE: If you want to consider only Channel, just hit ENTER");
                        channelGroup = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.ResetColor();

                        if (channel.Length <= 0 && channelGroup.Length <= 0)
                        {
                            Console.WriteLine("To run unsubscribe(), atleast provide either channel name or channel group name or both");
                        }
                        else
                        {
                            Console.WriteLine("Running unsubscribe()");
                            pubnub.Unsubscribe<string>(channel, channelGroup, DisplayReturnMessage, DisplaySubscribeConnectStatusMessage, DisplaySubscribeDisconnectStatusMessage, DisplayErrorMessage);
                        }
                        break;
                    case "7":
                        Console.WriteLine("Enter CHANNEL name for Presence Unsubscribe. Use comma to enter multiple channels.");
                        channel = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter channel group name for Presence Unsubscribe");
                        Console.WriteLine("NOTE: If you want to consider only Channel, just hit ENTER");
                        channelGroup = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.ResetColor();

                        if (channel.Length <= 0 && channelGroup.Length <= 0)
                        {
                            Console.WriteLine("To run presence-unsubscribe(), atleast provide either channel name or channel group name or both");
                        }
                        else
                        {
                            Console.WriteLine("Running presence-unsubscribe()");
                            pubnub.PresenceUnsubscribe<string>(channel, channelGroup, DisplayReturnMessage, DisplayPresenceConnectStatusMessage, DisplayPresenceDisconnectStatusMessage, DisplayErrorMessage);
                        }
                        break;
                    case "8":
                        Console.WriteLine("Running time()");
                        pubnub.Time<string>(DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "9":
                        Console.WriteLine("Running Disconnect/auto-Reconnect Subscriber Request Connection");
                        pubnub.TerminateCurrentSubscriberRequest();
                        break;
                    case "10":
                        Console.WriteLine("Disabling Network Connection (no internet)");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Initiating Simulation of Internet non-availability");
                        Console.WriteLine("Until Choice=11 is entered, no operations will occur");
                        Console.WriteLine("NOTE: Publish from other pubnub clients can occur and those will be ");
                        Console.WriteLine("      captured upon choice=11 is entered provided resume on reconnect is enabled.");
                        Console.ResetColor();
                        pubnub.EnableSimulateNetworkFailForTestingOnly();
                        break;
                    case "11":
                        Console.WriteLine("Enabling Network Connection (yes internet)");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Stopping Simulation of Internet non-availability");  
                        Console.ResetColor();
                        pubnub.DisableSimulateNetworkFailForTestingOnly();
                        break;
                    case "12":
                        Console.WriteLine("Enter CHANNEL name for PAM Grant. For Presence, Select Option 15.");
                        Console.WriteLine("To enter CHANNEL GROUP name, just hit ENTER");
                        channel = Console.ReadLine();

                        if (channel.Trim().Length <= 0)
                        {
                            channel = "";
                            Console.WriteLine("Enter CHANNEL GROUP name for PAM Grant.");
                            channelGroup = Console.ReadLine();
                        }
                        if (channel.Trim().Length <= 0 && channelGroup.Trim().Length <= 0)
                        {
                            Console.WriteLine("Channel or ChannelGroup not provided. Please try again.");
                            break;
                        }
                        Console.WriteLine("Enter the auth_key for PAM Grant (optional)");
                        Console.WriteLine("Press Enter Key if there is no auth_key at this time.");
                        string authGrant = Console.ReadLine();
                        
                        Console.WriteLine("Read Access? Enter Y for Yes (default), N for No.");
                        string readAccess = Console.ReadLine();
                        bool read = (readAccess.ToLower() == "n") ? false : true;

                        bool write = false;
                        if (channel.Trim().Length > 0)
                        {
                            Console.WriteLine("Write Access? Enter Y for Yes (default), N for No.");
                            string writeAccess = Console.ReadLine();
                            write = (writeAccess.ToLower() == "n") ? false : true;
                        }

                        bool manage=false;
                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine("Manage Access? Enter Y for Yes (default), N for No.");
                            string manageAccess = Console.ReadLine();
                            manage = (manageAccess.ToLower() == "n") ? false : true;
                        }
                        Console.WriteLine("How many minutes do you want to allow Grant Access? Enter the number of minutes.");
                        Console.WriteLine("Default = 1440 minutes (24 hours). Press ENTER now to accept default value.");
                        int grantTimeLimitInMinutes;
                        string grantTimeLimit = Console.ReadLine();
                        if (string.IsNullOrEmpty(grantTimeLimit.Trim()))
                        {
                            grantTimeLimitInMinutes = 1440;
                        }
                        else
                        {
                            Int32.TryParse(grantTimeLimit, out grantTimeLimitInMinutes);
                            if (grantTimeLimitInMinutes < 0) grantTimeLimitInMinutes = 1440;
                        }

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.WriteLine(string.Format("auth_key = {0}", authGrant));
                        Console.WriteLine(string.Format("Read Access = {0}", read.ToString()));
                        if (channel.Trim().Length > 0)
                        {
                            Console.WriteLine(string.Format("Write Access = {0}", write.ToString()));
                        }
                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine(string.Format("Manage Access = {0}", manage.ToString()));
                        }
                        Console.WriteLine(string.Format("Grant Access Time Limit = {0}", grantTimeLimitInMinutes.ToString()));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running PamGrant()");
                        if (channel.Trim().Length > 0)
                        {
                            pubnub.GrantAccess<string>(channel, authGrant, read, write, grantTimeLimitInMinutes, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.ChannelGroupGrantAccess<string>(channelGroup, authGrant, read, manage, grantTimeLimitInMinutes, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "13":
                        Console.WriteLine("Enter CHANNEL name for PAM Audit");
                        Console.WriteLine("To enter CHANNEL GROUP name, just hit ENTER");
                        channel = Console.ReadLine();

                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine("Enter CHANNEL GROUP name for PAM Audit.");
                            channelGroup = Console.ReadLine();
                        }
                        if (channel.Trim().Length <= 0 && channelGroup.Trim().Length <= 0)
                        {
                            Console.WriteLine("Channel or ChannelGroup not provided. Please try again.");
                            break;
                        }

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", channel));
                        Console.ResetColor();
                        Console.WriteLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter the auth_key for PAM Audit (optional)");
                        Console.WriteLine("Press Enter Key if there is no auth_key at this time.");
                        string authAudit = Console.ReadLine();
                        
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("auth_key = {0}", authAudit));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running PamAudit()");
                        if (channel.Trim().Length > 0)
                        {
                            pubnub.AuditAccess<string>(channel, authAudit, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.ChannelGroupAuditAccess<string>(channelGroup, authAudit, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "14":
                        Console.WriteLine("Enter CHANNEL name for PAM Revoke");
                        Console.WriteLine("To enter CHANNEL GROUP name, just hit ENTER");
                        channel = Console.ReadLine();
                        
                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine("Enter CHANNEL GROUP name for PAM Revoke.");
                            channelGroup = Console.ReadLine();
                        }
                        if (channel.Trim().Length <= 0 && channelGroup.Trim().Length <= 0)
                        {
                            channel = "";
                            Console.WriteLine("Channel or ChannelGroup not provided. Please try again.");
                            break;
                        }
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter the auth_key for PAM Revoke (optional)");
                        Console.WriteLine("Press Enter Key if there is no auth_key at this time.");
                        string authRevoke = Console.ReadLine();
                        
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("auth_key = {0}", authRevoke));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running PamRevoke()");
                        if (channel.Trim().Length > 0)
                        {
                            pubnub.GrantAccess<string>(channel, authRevoke, false, false, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.ChannelGroupGrantAccess<string>(channelGroup, authRevoke, false, false, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "15":
                        Console.WriteLine("Enter CHANNEL name for PAM Grant Presence.");
                        Console.WriteLine("To enter CHANNEL GROUP name, just hit ENTER");
                        channel = Console.ReadLine();

                        if (channel.Trim().Length <= 0)
                        {
                            channel = "";
                            Console.WriteLine("Enter CHANNEL GROUP name for PAM Grant Presence.");
                            channelGroup = Console.ReadLine();
                        }
                        if (channel.Trim().Length <= 0 && channelGroup.Trim().Length <= 0)
                        {
                            Console.WriteLine("Channel or ChannelGroup not provided. Please try again.");
                            break;
                        }
                        
                        Console.WriteLine("Enter the auth_key for PAM Grant Presence (optional)");
                        Console.WriteLine("Press Enter Key if there is no auth_key at this time.");
                        string authGrantPresence = Console.ReadLine();
                        
                        Console.WriteLine("Read Access? Enter Y for Yes (default), N for No.");
                        string readPresenceAccess = Console.ReadLine();
                        bool readPresence = (readPresenceAccess.ToLower() == "n") ? false : true;

                        bool writePresence = false;
                        if (channel.Trim().Length > 0)
                        {
                            Console.WriteLine("Write Access? Enter Y for Yes (default), N for No.");
                            string writePresenceAccess = Console.ReadLine();
                            writePresence = (writePresenceAccess.ToLower() == "n") ? false : true;
                        }

                        bool managePresence=false;
                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine("Manage Access? Enter Y for Yes (default), N for No.");
                            string manageAccess = Console.ReadLine();
                            managePresence = (manageAccess.ToLower() == "n") ? false : true;
                        }

                        Console.WriteLine("How many minutes do you want to allow Grant Presence Access? Enter the number of minutes.");
                        Console.WriteLine("Default = 1440 minutes (24 hours). Press ENTER now to accept default value.");
                        int grantPresenceTimeLimitInMinutes;
                        string grantPresenceTimeLimit = Console.ReadLine();
                        if (string.IsNullOrEmpty(grantPresenceTimeLimit.Trim()))
                        {
                            grantPresenceTimeLimitInMinutes = 1440;
                        }
                        else
                        {
                            Int32.TryParse(grantPresenceTimeLimit, out grantPresenceTimeLimitInMinutes);
                            if (grantPresenceTimeLimitInMinutes < 0) grantPresenceTimeLimitInMinutes = 1440;
                        }

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", channel));
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.WriteLine(string.Format("auth_key = {0}", authGrantPresence));
                        Console.WriteLine(string.Format("Read Access = {0}", readPresence.ToString()));
                        if (channel.Trim().Length > 0)
                        {
                            Console.WriteLine(string.Format("Write Access = {0}", writePresence.ToString()));
                        }
                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine(string.Format("Manage Access = {0}", managePresence.ToString()));
                        }
                        Console.WriteLine(string.Format("Grant Access Time Limit = {0}", grantPresenceTimeLimitInMinutes.ToString()));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running PAM GrantPresenceAccess()");
                        if (channel.Trim().Length > 0)
                        {
                            pubnub.GrantPresenceAccess<string>(channel, authGrantPresence, readPresence, writePresence, grantPresenceTimeLimitInMinutes, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.ChannelGroupGrantPresenceAccess<string>(channelGroup, authGrantPresence, readPresence, managePresence, grantPresenceTimeLimitInMinutes, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "16":
                        Console.WriteLine("Enter CHANNEL name for PAM Presence Audit");
                        Console.WriteLine("To enter CHANNEL GROUP name, just hit ENTER");
                        channel = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine("Enter CHANNEL GROUP name for PAM Presence Audit.");
                            channelGroup = Console.ReadLine();
                            
                            Console.ForegroundColor = ConsoleColor.Blue;
                            Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                            Console.ResetColor();
                            Console.WriteLine();

                        }
                        if (channel.Trim().Length <= 0 && channelGroup.Trim().Length <= 0)
                        {
                            Console.WriteLine("Channel or ChannelGroup not provided. Please try again.");
                            break;
                        }

                        Console.WriteLine("Enter the auth_key for PAM Presence Audit (optional)");
                        Console.WriteLine("Press Enter Key if there is no auth_key at this time.");
                        string authPresenceAudit = Console.ReadLine();
                        
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("auth_key = {0}", authPresenceAudit));
                        Console.ResetColor();
                        Console.WriteLine();


                        Console.WriteLine("Running PAM Presence Audit()");
                        if (channel.Trim().Length > 0)
                        {
                            pubnub.AuditPresenceAccess<string>(channel, authPresenceAudit, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.ChannelGroupAuditPresenceAccess<string>(channelGroup, authPresenceAudit, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "17":
                        Console.WriteLine("Enter CHANNEL name for PAM Presence Revoke");
                        Console.WriteLine("To enter CHANNEL GROUP name, just hit ENTER");
                        channel = Console.ReadLine();

                        if (channel.Trim().Length <= 0)
                        {
                            Console.WriteLine("Enter CHANNEL GROUP name for PAM Revoke.");
                            channelGroup = Console.ReadLine();
                        }
                        if (channel.Trim().Length <= 0 && channelGroup.Trim().Length <= 0)
                        {
                            channel = "";
                            Console.WriteLine("Channel or ChannelGroup not provided. Please try again.");
                            break;
                        }
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", channel));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", channelGroup));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Enter the auth_key for PAM Presence Revoke (optional)");
                        Console.WriteLine("Press Enter Key if there is no auth_key at this time.");
                        string authPresenceRevoke = Console.ReadLine();
                        
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("auth_key = {0}", authPresenceRevoke));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running PAM Presence Revoke()");
                        if (channel.Trim().Length > 0)
                        {
                            pubnub.GrantPresenceAccess<string>(channel, authPresenceRevoke, false, false, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.ChannelGroupGrantPresenceAccess<string>(channelGroup, authPresenceRevoke, false, false, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "18":
                        Console.WriteLine("Enter Auth Key (applies to all subscribed channels).");
                        Console.WriteLine("If you don't want to use Auth Key, Press ENTER Key");
                        authKey = Console.ReadLine();
                        pubnub.AuthenticationKey = authKey;

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Auth Key = {0}", authKey));
                        Console.ResetColor();
                        Console.WriteLine();

                        break;
                    case "19":
                        Console.WriteLine("Enabling simulation of Sleep/Suspend Mode");  
                        pubnub.EnableMachineSleepModeForTestingOnly();
                        Console.ForegroundColor = ConsoleColor.Red;  
                        Console.WriteLine("Machine Sleep Mode simulation activated");
                        Console.ResetColor();  
                        break;
                    case "20":
                        Console.WriteLine("Disabling simulation of Sleep/Suspend Mode");  
                        pubnub.DisableMachineSleepModeForTestingOnly();
                        Console.ForegroundColor = ConsoleColor.Red;  
                        Console.WriteLine("Simulation going to awake mode");  
                        Console.ResetColor();  
                        break;
                    case "21":
                        Console.WriteLine("Enter Presence Heartbeat in seconds");
                        string pnHeartbeatInput = Console.ReadLine();
                        Int32.TryParse(pnHeartbeatInput, out presenceHeartbeat);
                        pubnub.PresenceHeartbeat = presenceHeartbeat;
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Presence Heartbeat = {0}", presenceHeartbeat));
                        Console.ResetColor();
                        break;
                    case "22":
                        Console.WriteLine("Enter Presence Heartbeat Interval in seconds");
                        Console.WriteLine("NOTE: Ensure that it is less than Presence Heartbeat-3 seconds");
                        string pnHeartbeatIntervalInput = Console.ReadLine();
                        Int32.TryParse(pnHeartbeatIntervalInput, out presenceHeartbeatInterval);
                        pubnub.PresenceHeartbeatInterval = presenceHeartbeatInterval;
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Presence Heartbeat Interval = {0}", presenceHeartbeatInterval));
                        Console.ResetColor();
                        break;
                    case "23":
                        Console.WriteLine("Enter channel name");
                        Console.WriteLine("NOTE: If you want to consider only Channel Group, just hit ENTER");
                        string userStateChannel = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", userStateChannel));
                        Console.ResetColor();

                        Console.WriteLine("Enter channel group name");
                        Console.WriteLine("NOTE: If you want to consider only Channel, just hit ENTER");
                        string userStateChannelGroup = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", userStateChannelGroup));
                        Console.ResetColor();

                        Console.WriteLine("User State will be accepted as dictionary key:value pair");

                        Console.WriteLine("Enter key. ");
                        string keyUserState = Console.ReadLine();
                        if (string.IsNullOrEmpty(keyUserState.Trim()))
                        {
                            Console.WriteLine("dictionary key:value pair entry completed.");
                            break;
                        }
                        Console.WriteLine("Enter value");
                        string valueUserState = Console.ReadLine();

                        int valueInt;
                        double valueDouble;
                        //string currentUserState = "";
                        if (Int32.TryParse(valueUserState, out valueInt))
                        {
                            pubnub.SetUserState<string>(userStateChannel, userStateChannelGroup, new KeyValuePair<string, object>(keyUserState, valueInt), DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else if (Double.TryParse(valueUserState, out valueDouble))
                        {
                            pubnub.SetUserState<string>(userStateChannel, userStateChannelGroup, new KeyValuePair<string, object>(keyUserState, valueDouble), DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.SetUserState<string>(userStateChannel, userStateChannelGroup, new KeyValuePair<string, object>(keyUserState, valueUserState), DisplayReturnMessage, DisplayErrorMessage);
                        }

                        break;
                    case "24":
                        Console.WriteLine("Enter channel name");
                        Console.WriteLine("NOTE: If you want to consider only Channel Group, just hit ENTER");
                        string deleteChannelUserState = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", deleteChannelUserState));
                        Console.ResetColor();

                        Console.WriteLine("Enter channel group name");
                        Console.WriteLine("NOTE: If you want to consider only Channel, just hit ENTER");
                        string deleteChannelGroupUserState = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", deleteChannelGroupUserState));
                        Console.ResetColor();

                        Console.WriteLine("Enter key of the User State Key-Value pair to be deleted");
                        string deleteKeyUserState = Console.ReadLine();
                        pubnub.SetUserState<string>(deleteChannelUserState, deleteChannelGroupUserState, new KeyValuePair<string, object>(deleteKeyUserState, null), DisplayReturnMessage, DisplayErrorMessage);

                        break;
                    case "25":
                        Console.WriteLine("Enter channel name");
                        Console.WriteLine("NOTE: If you want to consider only Channel Group, just hit ENTER");
                        string setUserStateChannel = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", setUserStateChannel));
                        Console.ResetColor();

                        Console.WriteLine("Enter channel group name");
                        Console.WriteLine("NOTE: If you want to consider only Channel, just hit ENTER");
                        string setUserStateChannelGroup = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", setUserStateChannelGroup));
                        Console.ResetColor();

                        Console.WriteLine("Enter user state in json format (Eg. {\"key1\":\"value1\",\"key2\":\"value2\"}");
                        string jsonUserState = Console.ReadLine();

                        if (jsonUserState.Trim() == "")
                        {
                            Console.WriteLine("Invalid User State");
                            break;
                        }
                        Console.WriteLine("Enter UUID. (Optional. Press ENTER to skip it)");
                        string uuid = Console.ReadLine();
                        if (string.IsNullOrEmpty(uuid))
                        {
                            pubnub.SetUserState<string>(setUserStateChannel, setUserStateChannelGroup, jsonUserState, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.SetUserState<string>(setUserStateChannel, setUserStateChannelGroup, uuid, jsonUserState, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "26":
                        Console.WriteLine("Enter channel name");
                        Console.WriteLine("NOTE: If you want to consider only Channel Group, just hit ENTER");
                        string getUserStateChannel2 = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}", getUserStateChannel2));
                        Console.ResetColor();

                        Console.WriteLine("Enter channel group name");
                        Console.WriteLine("NOTE: If you want to consider only Channel, just hit ENTER");
                        string setUserStateChannelGroup2 = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("ChannelGroup = {0}", setUserStateChannelGroup2));
                        Console.ResetColor();

                        Console.WriteLine("Enter UUID. (Optional. Press ENTER to skip it)");
                        string uuid2 = Console.ReadLine();
                        if (string.IsNullOrEmpty(uuid2))
                        {
                            pubnub.GetUserState<string>(getUserStateChannel2, setUserStateChannelGroup2, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        else
                        {
                            pubnub.GetUserState<string>(getUserStateChannel2, setUserStateChannelGroup2, uuid2, DisplayReturnMessage, DisplayErrorMessage);
                        }
                        break;
                    case "27":
                        Console.WriteLine("Enter uuid for WhereNow. To consider SessionUUID, just press ENTER");
                        string whereNowUuid = Console.ReadLine();

                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("uuid = {0}", whereNowUuid));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running Where_Now()");
                        pubnub.WhereNow<string>(whereNowUuid, DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "28":
                        bool globalHereNowShowUUID = true;
                        bool globalHereNowIncludeUserState = false;

                        Console.WriteLine("Show UUID List? Y or N? Default is Y. Press N for No Else press ENTER");
                        string userChoiceGlobalHereNowShowUUID = Console.ReadLine();
                        if (userChoiceGlobalHereNowShowUUID.ToLower() == "n")
                        {
                            globalHereNowShowUUID = false;
                        }
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Show UUID = {0}", globalHereNowShowUUID));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Include User State? Y or N? Default is N. Press Y for Yes Else press ENTER");
                        string userChoiceGlobalHereNowIncludeUserState = Console.ReadLine();
                        if (userChoiceGlobalHereNowIncludeUserState.ToLower() == "y")
                        {
                            globalHereNowIncludeUserState = true;
                        }
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Include User State = {0}", globalHereNowIncludeUserState));
                        Console.ResetColor();
                        Console.WriteLine();

                        Console.WriteLine("Running Global HereNow()");
                        pubnub.GlobalHereNow<string>(globalHereNowShowUUID, globalHereNowIncludeUserState,DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "29":
                        Console.WriteLine("ENTER UUID.");
                        string sessionUUID = Console.ReadLine();
                        pubnub.ChangeUUID(sessionUUID);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine("UUID = {0}",pubnub.SessionUUID);
                        Console.ResetColor();
                        break;
                    case "38":
                        Console.WriteLine("Enter namespace");
                        string addChannelGroupNamespace = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("namespace = {0}", addChannelGroupNamespace));
                        Console.ResetColor();
                        
                        Console.WriteLine("Enter channel group name");
                        string addChannelGroupName = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("channel group name = {0}", addChannelGroupName));
                        Console.ResetColor();
                        

                        Console.WriteLine("Enter CHANNEL name. Use comma to enter multiple channels.");
                        channel = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();
                        pubnub.AddChannelsToChannelGroup<string>(channel.Split(','), addChannelGroupNamespace, addChannelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "39":
                        Console.WriteLine("Enter namespace");
                        string removeChannelGroupNamespace = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("namespace = {0}", removeChannelGroupNamespace));
                        Console.ResetColor();

                        if (removeChannelGroupNamespace.Trim().Length > 0)
                        {
                            Console.WriteLine("Do you want to remove the namespace and all its group names and all its channels? Default is No. Enter Y for Yes, Else just hit ENTER key");
                            string removeExistingNamespace = Console.ReadLine();
                            if (removeExistingNamespace.ToLower() == "y")
                            {
                                pubnub.RemoveChannelGroupNameSpace<string>(removeChannelGroupNamespace, DisplayReturnMessage, DisplayErrorMessage);
                                break;
                            }
                        }

                        Console.WriteLine("Enter channel group name");
                        string removeChannelGroupName = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("channel group name = {0}", removeChannelGroupName));
                        Console.ResetColor();

                        if (removeChannelGroupName.Trim().Length <= 0)
                        {
                            Console.WriteLine("Channel group not provided. Try again");
                            break;
                        }
                        Console.WriteLine("Do you want to remove the channel group and all its channels? Default is No. Enter Y for Yes, Else just hit ENTER key");
                        string removeExistingGroup = Console.ReadLine();
                        if (removeExistingGroup.ToLower() == "y")
                        {
                            pubnub.RemoveChannelGroup<string>(removeChannelGroupNamespace, removeChannelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                            break;
                        }
                        
                        Console.WriteLine("Enter CHANNEL name. Use comma to enter multiple channels.");
                        channel = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("Channel = {0}",channel));
                        Console.ResetColor();
                        Console.WriteLine();
                        pubnub.RemoveChannelsFromChannelGroup<string>(channel.Split(','), removeChannelGroupNamespace, removeChannelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    case "40":
                        Console.WriteLine("Do you want to get all existing namespaces? Default is No. Enter Y for Yes, Else just hit ENTER key");
                        string getExistingNamespace = Console.ReadLine();
                        if (getExistingNamespace.ToLower() == "y")
                        {
                            pubnub.GetAllChannelGroupNamespaces<string>(DisplayReturnMessage, DisplayErrorMessage);
                            break;
                        }

                        Console.WriteLine("Enter namespace");
                        string channelGroupNamespace = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("namespace = {0}", channelGroupNamespace));
                        Console.ResetColor();

                        if (channelGroupNamespace.Trim().Length > 0)
                        {
                            Console.WriteLine("Do you want to get all existing channel group names for the provided namespace? Default is No. Enter Y for Yes, Else just hit ENTER key");
                            string getExistingGroupNames = Console.ReadLine();
                            if (getExistingGroupNames.ToLower() == "y")
                            {
                                pubnub.GetAllChannelGroups<string>(channelGroupNamespace, DisplayReturnMessage, DisplayErrorMessage);
                                break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Do you want to get all existing channel group names? Default is No. Enter Y for Yes, Else just hit ENTER key");
                            string getExistingGroupNames = Console.ReadLine();
                            if (getExistingGroupNames.ToLower() == "y")
                            {
                                pubnub.GetAllChannelGroups<string>(DisplayReturnMessage, DisplayErrorMessage);
                                break;
                            }
                        }
                        
                        Console.WriteLine("Enter channel group name");
                        string channelGroupName = Console.ReadLine();
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine(string.Format("channel group name = {0}", channelGroupName));
                        Console.ResetColor();

                        pubnub.GetChannelsForChannelGroup<string>(channelGroupNamespace, channelGroupName, DisplayReturnMessage, DisplayErrorMessage);
                        break;
                    default:
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("INVALID CHOICE. ENTER 99 FOR EXIT OR QUIT");
                        Console.ResetColor();
                        break;
                }
                if (!exitFlag)
                {
                    userinput = Console.ReadLine();
                    Int32.TryParse(userinput, out currentUserChoice);
                }
            }

            Console.WriteLine("\nPress any key to exit.\n\n");
            Console.ReadLine();

        }
        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");
        }
        public void ThenMultiSubscribeShouldReturnConnectStatus()
        {
            currentUnitTestCase = "ThenMultiSubscribeShouldReturnConnectStatus";
            receivedMessage = false;
            receivedChannelGroupMessage1 = false;
            receivedChannelGroupMessage2 = false;
            expectedCallbackResponses = 2;
            currentCallbackResponses = 0;

            pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, "", "", false);
            pubnub.SessionUUID = "myuuid";

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenSubscribedToAChannelGroup";
            unitTest.TestCaseName = "ThenMultiSubscribeShouldReturnConnectStatus";

            pubnub.PubnubUnitTest = unitTest;
            manualResetEventsWaitTimeout = (unitTest.EnableStubTest) ? 6000 : 310 * 1000;

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

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

            subscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName1 }, channelGroupName1, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            Thread.Sleep(1000);
            subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

            subscribeManualEvent = new ManualResetEvent(false);
            pubnub.AddChannelsToChannelGroup<string>(new string[] { channelName2 }, channelGroupName2, ChannelGroupAddCallback, DummySubscribeErrorCallback);
            Thread.Sleep(1000);
            subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

            if (receivedChannelGroupMessage1 && receivedChannelGroupMessage2)
            {
                subscribeManualEvent = new ManualResetEvent(false);
                pubnub.Subscribe<string>("", string.Format("{0},{1}", channelGroupName1, channelGroupName2), ReceivedMessageCallbackWhenSubscribed, SubscribeConnectCallback, DummySubscribeErrorCallback);
                subscribeManualEvent.WaitOne(manualResetEventsWaitTimeout);

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

                Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
            }
            else
            {
                Assert.IsTrue(receivedChannelGroupMessage1 && receivedChannelGroupMessage2, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
            }
        }
Exemplo n.º 35
0
        public IEnumerator DoSubscribeSetStateDelStateCG(bool ssl, string testName, bool asObject, bool withCipher, object message, string expectedStringResponse, bool matchExpectedStringResponse)
        {
            /*  ⁃   Add CH to CG
             * ⁃   List CG
             * ⁃   Get all CGs
             * ⁃
             * ⁃   */
            pubnub = new Pubnub(CommonIntergrationTests.PublishKey,
                                CommonIntergrationTests.SubscribeKey);

            System.Random r       = new System.Random();
            string        cg      = "UnityIntegrationTest_CG_" + r.Next(100);
            string        ch      = "UnityIntegrationTest_CH_" + r.Next(100);
            string        channel = "UnityIntegrationTest_CH_" + r.Next(100);

            UnityEngine.Debug.Log(string.Format("{0} {1}: Start coroutine ", DateTime.Now.ToString(), testName));
            bool   bAddChannel = false;
            string uuid        = "UnityIntegrationTest_UUID";

            pubnub.ChangeUUID(uuid);
            pubnub.AddChannelsToChannelGroup <string>(new string[] { channel, ch }, cg, (string result) => {
                //[{"status":200,"message":"OK","service":"channel-registry","error":false}]
                UnityEngine.Debug.Log(string.Format("{0}: {1} AddChannelsToChannelGroup {2}", DateTime.Now.ToString(), testName, result));
                if (result.Contains("OK") && result.Contains("\"error\":false"))
                {
                    bAddChannel = true;
                }
            }, this.DisplayErrorMessage);
            UnityEngine.Debug.Log(string.Format("{0}: {1} Waiting for response", DateTime.Now.ToString(), testName));

            string strLog = string.Format("{0}: {1} After wait {2}",
                                          DateTime.Now.ToString(),
                                          testName,
                                          bAddChannel
                                          );

            UnityEngine.Debug.Log(strLog);
            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));


            bool   bSubConnected = false;
            bool   bSetState     = false;
            bool   bGetState     = true;
            string state         = "{\"k\":\"v\"}";

            pubnub.Subscribe <string>(ch, cg, (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe {2}", DateTime.Now.ToString(), testName, retM));
            }, (string retConnect) => {
                bSubConnected = true;
                UnityEngine.Debug.Log(string.Format("{0}: {1} Subscribe Connected {2}", DateTime.Now.ToString(), testName, retConnect));

                pubnub.SetUserState <string>(ch, cg, "", state, (string retM) => {
                    UnityEngine.Debug.Log(string.Format("{0}: {1} SetUserState {2} {3} {4}",
                                                        DateTime.Now.ToString(), testName, retM, retM.Contains(state), retM.Contains(ch)));
                    if (retM.Contains(state) && retM.Contains(cg))
                    {
                        bSetState = true;
                    }
                }, this.DisplayErrorMessage);
            }, this.DisplayErrorMessage);


            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            bool bSetUserState2 = true;
            bool bGetUserState2 = true;

            pubnub.SetUserState(ch, cg, uuid, new KeyValuePair <string, object>("k", ""), (string retM) => {
                UnityEngine.Debug.Log(string.Format("{0}: {1} SetUserState2 {2} {3} {4}",
                                                    DateTime.Now.ToString(), testName, retM, retM.Contains(state), retM.Contains(channel)));
                if (!retM.Contains(state) && retM.Contains(cg))
                {
                    bSetUserState2 = true;
                    pubnub.GetUserState(ch, cg, (string pub) => {
                        UnityEngine.Debug.Log(string.Format("{0}: {1} GetUserState2 {2}", DateTime.Now.ToString(), testName, pub));
                        if (!pub.Contains(state) && pub.Contains(cg))
                        {
                            bGetUserState2 = true;
                        }
                    }, this.DisplayErrorMessage);
                }
            }, this.DisplayErrorMessage);


            bool bRemoveAll = false;

            yield return(new WaitForSeconds(CommonIntergrationTests.WaitTimeBetweenCallsLow));

            pubnub.RemoveChannelGroup(cg, (string retM) => {
                //[{"status":200,"payload":{"channels":["UnityIntegrationTests_30","a","c","ch","tj"],"group":"cg"},"service":"channel-registry","error":false}]

                UnityEngine.Debug.Log(string.Format("{0}: {1} RemoveChannelGroup {2}", DateTime.Now.ToString(), testName, retM));
                if (retM.Contains("OK") && retM.Contains("\"error\":false"))
                {
                    bRemoveAll = true;
                }
                else
                {
                    bRemoveAll = false;
                }
            }, this.DisplayErrorMessage);


            string strLog2 = string.Format("{0}: {1} After wait2   {2} {3} {4} {5} {6}",
                                           DateTime.Now.ToString(),
                                           testName,
                                           bAddChannel,
                                           bSetUserState2,
                                           bGetUserState2,
                                           bRemoveAll,
                                           bSetState
                                           );

            UnityEngine.Debug.Log(strLog2);

            if (bAddChannel
                & bRemoveAll
                & bSetState
                & bSetUserState2
                & bGetUserState2
                )
            {
                IntegrationTest.Pass();
            }
            pubnub.EndPendingRequests();
            pubnub.CleanUp();
        }