public void Init()
        {
            if (!PubnubCommon.PAMEnabled)
            {
                EnqueueTestComplete();
                return;
            }

            receivedGrantMessage = false;

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "GrantRequestUnitTest";
            unitTest.TestCaseName = "Init";
            pubnub.PubnubUnitTest = unitTest;

            string channel = "hello_my_channel";

            EnqueueCallback(() => pubnub.GrantAccess<string>(channel, true, true, 20, ThenPublishInitializeShouldReturnGrantMessage, DummyErrorCallback));
            //Thread.Sleep(1000);

            EnqueueConditional(() => grantInitCallbackInvoked);

            EnqueueCallback(() => Assert.IsTrue(receivedGrantMessage, "WhenAClientIsPresent Grant access failed."));

            EnqueueTestComplete();
        }
 public void ThenItShouldReturnSuccessCodeAndInfoForComplexMessage2WithSsl()
 {
   Pubnub pubnub = new Pubnub(
     "demo",
     "demo",
     "",
     "",
     true
     );
   string channel = "hello_world";
   object message = new PubnubDemoObject();
   //object message = new CustomClass2();
   
   string json = JsonConvert.SerializeObject(message);
   Common common = new Common();
   
   pubnub.PubnubUnitTest = common.CreateUnitTestInstance("WhenAMessageIsPublished", "ThenItShouldReturnSuccessCodeAndInfoForComplexMessage2WithSsl");
   
   common.DeliveryStatus = false;
   common.Response = null;
   
   pubnub.Publish(channel, message, common.DisplayReturnMessage);
   //wait till the response is received from the server
   while (!common.DeliveryStatus);
   IList<object> fields = common.Response as IList<object>;
   string sent = fields[1].ToString();
   string one = fields[0].ToString();
   Assert.AreEqual("Sent", sent);
   Assert.AreEqual("1", one);
 }
        public void Init()
        {
            if (!PubnubCommon.PAMEnabled) return;

            currentUnitTestCase = "Init";
            receivedGrantMessage = false;

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "GrantRequestUnitTest";
            unitTest.TestCaseName = "Init3";
            pubnub.PubnubUnitTest = unitTest;

            grantManualEvent = new ManualResetEvent(false);
            pubnub.ChannelGroupGrantAccess<string>(channelGroupName, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback);
            Thread.Sleep(1000);
            grantManualEvent.WaitOne(310*1000);

            grantManualEvent = new ManualResetEvent(false);
            pubnub.ChannelGroupGrantAccess<string>(channelGroupName1, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback);
            Thread.Sleep(1000);
            grantManualEvent.WaitOne(310 * 1000);

            grantManualEvent = new ManualResetEvent(false);
            pubnub.ChannelGroupGrantAccess<string>(channelGroupName2, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback);
            Thread.Sleep(1000);
            grantManualEvent.WaitOne(310 * 1000);

            pubnub.EndPendingRequests(); 
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed.");
        }
        public void ThenNoExistChannelShouldReturnNotSubscribed()
        {
            receivedNotSubscribedMessage = false;
            mreUnsubscribe = new ManualResetEvent(false);

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

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "WhenUnsubscribedToAChannel";
                    unitTest.TestCaseName = "ThenNoExistChannelShouldReturnNotSubscribed";

                    pubnub.PubnubUnitTest = unitTest;

                    string channel = "hello_my_channel";

                    EnqueueCallback(() => pubnub.Unsubscribe<string>(channel, DummyMethodNoExistChannelUnsubscribeChannelUserCallback, DummyMethodNoExistChannelUnsubscribeChannelConnectCallback, DummyMethodNoExistChannelUnsubscribeChannelDisconnectCallback1, NoExistChannelErrorCallback));
                    mreUnsubscribe.WaitOne(310 * 1000);

                    EnqueueCallback(() => pubnub.EndPendingRequests());
                    EnqueueCallback(() => Assert.IsTrue(receivedNotSubscribedMessage, "WhenUnsubscribedToAChannel --> ThenNoExistChannelShouldReturnNotSubscribed Failed"));
                    EnqueueTestComplete();
                });
        }
        public void NullMessage()
        {
            Pubnub pubnub = new Pubnub(
                "demo",
                "demo",
                "",
                "",
                false
            );
            string channel = "hello_world";
            string message = null;

            Common common = new Common();
            common.DeliveryStatus = false;
            common.Response = null;

            pubnub.Publish(channel, message, common.DisplayReturnMessage);
            //wait till the response is received from the server
            while (!common.DeliveryStatus) ;
            IList<object> fields = common.Response as IList<object>;
            string sent = fields[1].ToString();
            string one = fields[0].ToString();
            Assert.AreEqual("Sent", sent);
            Assert.AreEqual("1", one);
        }
        public void Init()
        {
            if (!PubnubCommon.PAMEnabled) return;

            receivedGrantMessage = false;

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "GrantRequestUnitTest";
            unitTest.TestCaseName = "Init";
            pubnub.PubnubUnitTest = unitTest;

            string channel = "hello_my_channel";

            pubnub.GrantAccess<string>(channel, true, true, 20, ThenUnsubscribeInitializeShouldReturnGrantMessage, DummyErrorCallback);
            Thread.Sleep(1000);

            grantManualEvent.WaitOne();

            pubnub.EndPendingRequests();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedGrantMessage, "WhenUnsubscribedToAChannel Grant access failed.");
        }
Example #7
0
        public void ThenChannelLevelShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenChannelLevelShouldReturnSuccess";

            receivedAuditMessage = false;

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

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "WhenAuditIsRequested";
                    unitTest.TestCaseName = "ThenChannelLevelShouldReturnSuccess";
                    pubnub.PubnubUnitTest = unitTest;

                    string channel = "hello_my_channel";

                    if (PubnubCommon.PAMEnabled)
                    {
                        mreAudit = new ManualResetEvent(false);
                        pubnub.AuditAccess<string>(channel, AccessToChannelLevelCallback, DummyErrorCallback);
                        mreAudit.WaitOne(60 * 1000);

                        Assert.IsTrue(receivedAuditMessage, "WhenAuditIsRequested -> ThenChannelLevelShouldReturnSuccess failed.");
                    }
                    else
                    {
                        Assert.Inconclusive("PAM Not Enabled for WhenAuditIsRequested -> ThenChannelLevelShouldReturnSuccess");
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        TestComplete();
                    });
                });
        }
		public void ItShouldReturnDetailedHistory()
		{
			Pubnub pubnub = new Pubnub(
				"demo",
				"demo",
				"",
				"",
				false
				);
			string channel = "hello_world";
			string message = "Test message";
			
			Common common = new Common();
			common.DeliveryStatus = false;
			common.Response = null;
			
			//publish a test message. 
			pubnub.Publish(channel, message, common.DisplayReturnMessage);
			
			while (!common.DeliveryStatus); 
			
			pubnub.PubnubUnitTest = common.CreateUnitTestInstance("WhenDetailedHistoryIsRequested" ,"ItShouldReturnDetailedHistory");
			
			common.DeliveryStatus = false;
			common.Response = null;
			pubnub.DetailedHistory(channel, 1, common.DisplayReturnMessage);
			while (!common.DeliveryStatus);
			
			ParseResponse(common.Response, 0, 0, message);
		}
        public void ThenPresenceShouldReturnCustomUUID()
        {
            receivedCustomUUID = false;

            Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenAClientIsPresented";
            unitTest.TestCaseName = "ThenPresenceShouldReturnCustomUUID";
            pubnub.PubnubUnitTest = unitTest;

            string channel = "hello_my_channel";

            pubnub.Presence<string>(channel, ThenPresenceWithCustomUUIDShouldReturnMessage, PresenceUUIDDummyMethodForConnectCallback, DummyErrorCallback);
            Thread.Sleep(1000);
            
            //since presence expects from stimulus from sub/unsub...
            pubnub.SessionUUID = customUUID;
            pubnub.Subscribe<string>(channel, DummyMethodForSubscribeUUID, SubscribeUUIDDummyMethodForConnectCallback, DummyErrorCallback);
            Thread.Sleep(1000);
            subscribeUUIDManualEvent.WaitOne(2000);

            pubnub.Unsubscribe<string>(channel, DummyMethodForUnSubscribeUUID, UnsubscribeUUIDDummyMethodForConnectCallback, UnsubscribeUUIDDummyMethodForDisconnectCallback, DummyErrorCallback);
            Thread.Sleep(1000);
            unsubscribeUUIDManualEvent.WaitOne(2000);

            presenceUUIDManualEvent.WaitOne(310 * 1000);

            pubnub.EndPendingRequests();

            Assert.IsTrue(receivedCustomUUID, "Custom UUID not received");
        }
        public void ThenSubKeyLevelWithReadShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenSubKeyLevelWithReadShouldReturnSuccess";
            mreGrant = new ManualResetEvent(false);

            receivedGrantMessage = false;

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

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "WhenGrantIsRequested";
                    unitTest.TestCaseName = "ThenSubKeyLevelWithReadShouldReturnSuccess";
                    pubnub.PubnubUnitTest = unitTest;
                    if (PubnubCommon.PAMEnabled)
                    {
                        EnqueueCallback(() => pubnub.GrantAccess<string>("", true, false, 5, AccessToSubKeyLevelCallback, DummyErrorCallback));
                        mreGrant.WaitOne(310 * 1000);
                        EnqueueCallback(() => Assert.IsTrue(receivedGrantMessage, "WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess failed."));
                    }
                    else
                    {
                        EnqueueCallback(() => Assert.Inconclusive("PAM Not Enabled for WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess."));
                    }
                    EnqueueTestComplete();
                });
        }
    public void ThenShouldReturnUnsubscribedMessage()
    {
      Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);
      
      Common common = new Common();
      common.DeliveryStatus = false;
      common.Response = null;
      
      pubnub.PubnubUnitTest = common.CreateUnitTestInstance("WhenUnsubscribedToAChannel", "ThenShouldReturnUnsubscribedMessage");
      
      string channel = "hello_world";

      pubnub.Subscribe<string>(channel, common.DisplayReturnMessageDummy, common.DisplayReturnMessage, common.DisplayReturnMessageDummy);

      common.WaitForResponse();
      common.DeliveryStatus = false;
      common.Response = null;

      pubnub.Unsubscribe<string>(channel, common.DisplayReturnMessageDummy, common.DisplayReturnMessageDummy, common.DisplayReturnMessage, common.DisplayReturnMessageDummy);
      common.WaitForResponse();

      if (common.Response.ToString().Contains ("Unsubscribed from")) {
        Console.WriteLine("Response:" + common.Response);
		Assert.NotNull(common.Response);
      }
      else
      {
		Assert.Fail("ThenShouldReturnUnsubscribedMessage failed");
      }    
    }
        public void Receive_from_standIn()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");
            using (var sut = new PubnubHostTransceiver(cre, "hostchannel"))
            {

                var are = new AutoResetEvent(false);
                HostInput result = null;
                sut.ReceivedFromStandIn += _ =>
                                               {
                                                   result = _;
                                                   are.Set();
                                               };

                var standIn = new Pubnub(cre.PublishingKey, cre.SubscriptionKey, cre.SecretKey);
                var hi = new HostInput{CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname", StandInEndpointAddress = "endpoint"};
                standIn.publish("hostchannel", hi.Serialize(), _ => { });

                Assert.IsTrue(are.WaitOne(5000));

                Assert.AreEqual(hi.CorrelationId, result.CorrelationId);
                Assert.AreEqual(hi.Data, result.Data);
                Assert.AreEqual(hi.Portname, result.Portname);
                Assert.AreEqual(hi.StandInEndpointAddress, result.StandInEndpointAddress);
            }
        }
        public void Send_to_standIn()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");
            using(var sut = new PubnubHostTransceiver(cre, "hostchannel"))
            {
                var standIn = new Pubnub(cre.PublishingKey, cre.SubscriptionKey, cre.SecretKey);
                try
                {
                    var standInChannel = Guid.NewGuid().ToString();

                    var are = new AutoResetEvent(false);
                    ReadOnlyCollection<object> result = null;
                    standIn.subscribe(standInChannel, (ReadOnlyCollection<object> _) =>
                                              {
                                                  result = _;
                                                  are.Set();
                                              });

                    var ho = new HostOutput{CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname"};
                    sut.SendToStandIn(new Tuple<string, HostOutput>(standInChannel, ho));

                    Assert.IsTrue(are.WaitOne(5000));

                    var hoReceived = Convert.FromBase64String((string)((JValue)result[0]).Value).Deserialize() as HostOutput;
                    Assert.AreEqual(ho.CorrelationId, hoReceived.CorrelationId);
                    Assert.AreEqual(ho.Data, hoReceived.Data);
                    Assert.AreEqual(ho.Portname, hoReceived.Portname);
                }
                finally
                {
                    standIn.subscribe("standIn", _ => {});
                }
            }
        }
        public void Init()
        {
            if (!PubnubCommon.PAMEnabled)
            {
                EnqueueTestComplete();
                return;
            }

            receivedGrantMessage = false;

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

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "GrantRequestUnitTest";
                    unitTest.TestCaseName = "Init2";
                    pubnub.PubnubUnitTest = unitTest;

                    string channel = "hello_my_channel,hello_my_channel-pnpres";
                    EnqueueCallback(() => pubnub.GrantAccess<string>(channel, true, true, 20, ThenPresenceInitializeShouldReturnGrantMessage, DummyErrorCallback));
                    mreGrant.WaitOne(310 * 1000);

                    EnqueueCallback(() => Assert.IsTrue(receivedGrantMessage, "WhenAClientIsPresent Grant access failed."));
                    EnqueueTestComplete();
                });
        }
        public void Init()
        {
            if (!PubnubCommon.PAMEnabled)
            {
                Assert.Inconclusive("WhenAClientIsPresent Grant access failed.");
                return;
            }

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "GrantRequestUnitTest";
            unitTest.TestCaseName = "Init";
            pubnub.PubnubUnitTest = unitTest;

            string channel = "hello_my_channel";

            pubnub.GrantAccess<string>(channel, true, true, 20, ThenSubscriberInitializeShouldReturnGrantMessage, DummyErrorCallback);
            //Thread.Sleep(1000);

            grantManualEvent.WaitOne();

            Assert.IsTrue(receivedGrantMessage, "WhenAClientIsPresent Grant access failed.");
        }
        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 Init()
        {
            if (!PubnubCommon.PAMEnabled)
            {
                TestComplete();
                return;
            }

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

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "GrantRequestUnitTest";
                    unitTest.TestCaseName = "Init";
                    pubnub.PubnubUnitTest = unitTest;

                    string channel = "hello_my_channel,hello_my_channel1,hello_my_channel2";

                    mreGrant = new ManualResetEvent(false);
                    pubnub.GrantAccess<string>(channel, true, true, 20, ThenSubscriberInitializeShouldReturnGrantMessage, DummyErrorCallback);
                    mreGrant.WaitOne(60 * 1000); //1 minute

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            Assert.IsTrue(receivedGrantMessage, "WhenAClientIsPresent Grant access failed.");
                            TestComplete();
                        });
                });
        }
Example #18
0
 static PollWorker()
 {
     if (pubnub == null)
     {
         pubnub = new Pubnub("demo", "demo");
     }
 }
        public void ItShouldReturnDetailedHistory ()
        {
            GC.Collect ();
            Pubnub pubnub = new Pubnub (
                          Common.PublishKey,
                          Common.SubscribeKey,
                          "",
                          "",
                          false
                      );
            string channel = "hello_world_de1";
            string message = "Test Message";
      
            Common common = new Common ();
            common.DeliveryStatus = false;
            common.Response = null;

            pubnub.PubnubUnitTest = common.CreateUnitTestInstance ("WhenDetailedHistoryIsRequested", "ItShouldReturnDetailedHistory");
      
            //publish a test message. 
            pubnub.Publish (channel, message, common.DisplayReturnMessage, common.DisplayReturnMessageDummy);
      
            common.WaitForResponse ();

            common.DeliveryStatus = false;
            common.Response = null;
            Thread.Sleep (1000);
            pubnub.DetailedHistory (channel, 1, common.DisplayReturnMessage, common.DisplayReturnMessageDummy);
            common.WaitForResponse ();

            ParseResponse (common.Response, 0, 0, message);
            pubnub.EndPendingRequests ();
        }
Example #20
0
        public void ThenChannelLevelShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenChannelLevelShouldReturnSuccess";

            receivedAuditMessage = false;

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenAuditIsRequested";
            unitTest.TestCaseName = "ThenChannelLevelShouldReturnSuccess";
            pubnub.PubnubUnitTest = unitTest;

            string channel = "hello_my_channel";

            if (PubnubCommon.PAMEnabled)
            {
                auditManualEvent = new ManualResetEvent(false);
                pubnub.AuditAccess<string>(channel, AccessToChannelLevelCallback, DummyErrorCallback);
                Task.Delay(1000);

                auditManualEvent.WaitOne();

                pubnub.PubnubUnitTest = null;
                pubnub = null;
                Assert.IsTrue(receivedAuditMessage, "WhenAuditIsRequested -> ThenChannelLevelShouldReturnSuccess failed.");
            }
            else
            {
                Assert.Inconclusive("PAM Not Enabled for WhenAuditIsRequested -> ThenChannelLevelShouldReturnSuccess");
            }
        }
        public async Task<HttpResponseMessage> Post(string sessionKey, string channel)
        {
            string folderName =  "_TemporaryFiles";
            string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
            string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);

            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new MultipartFormDataStreamProvider(PATH);
                //var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
                //{

                //    //if (t.IsFaulted || t.IsCanceled)
                //    //{
                //    //    throw new HttpResponseException(HttpStatusCode.BadGateway);
                //    //}

                //    var fileInfo = streamProvider.FileData.Select(i =>
                //    {
                //        var info = new FileInfo(i.LocalFileName);
                //        return new FileDesc(info.Name, rootUrl+"/"+folderName+"/"+info.Name, info.Length);
                //    });
                //    return fileInfo;
                //});

                //return task;

                try
                {
                    // Read the form data.
                    await Request.Content.ReadAsMultipartAsync(streamProvider);
                    Pubnub pubnub = new Pubnub("demo", "demo");
                    string pubnubChannel = channel;
                    //var dbUser = unitOfWork.Users.All().FirstOrDefault(x => x.Sessionkey == sessionkey);
                    var uploader = new DropboxUploader();
                    List<string> urls = new List<string>();
                    foreach (MultipartFileData file in streamProvider.FileData)
                    {
                        //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                        //Trace.WriteLine("Server file path: " + file.LocalFileName);
                        string fileName = file.LocalFileName.Normalize();
                        var url = uploader.UploadFileToDropBox(fileName.Trim(), file.Headers.ContentDisposition.FileName.Replace("\"", ""));
                        urls.Add(url.ToString());
                        //dbUser.ProfilePicture = url;
                        pubnub.Publish(pubnubChannel, url.ToString(), (object obj) => {});
                        //break;
                    }
                    return Request.CreateResponse(HttpStatusCode.OK, urls);
                }
                catch (System.Exception e)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
            }

        }
        public void Receive_from_host()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");

            using (var sut = new PubnubStandInTransceiver(cre, "hostchannel"))
            {
                var are = new AutoResetEvent(false);
                HostOutput result = null;
                sut.ReceivedFromHost += _ =>
                                            {
                                                result = _;
                                                are.Set();
                                            };

                var sender = new Pubnub(cre.PublishingKey, cre.SubscriptionKey);
                var ho = new HostOutput {CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "portname"};
                sender.publish(sut.StandInEndpointAddress, ho.Serialize(), _ => { });

                Assert.IsTrue(are.WaitOne(5000));

                Assert.AreEqual(ho.CorrelationId, result.CorrelationId);
                Assert.AreEqual(ho.Data, result.Data);
                Assert.AreEqual(ho.Portname, result.Portname);
            }
        }
        public void ThenPresenceShouldReturnReceivedMessage()
        {
            receivedPresenceMessage = false;
            ThreadPool.QueueUserWorkItem((s) =>
                {
                    Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);
                    string channel = "my/channel";

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "WhenAClientIsPresented";
                    unitTest.TestCaseName = "ThenPresenceShouldReturnReceivedMessage";
                    pubnub.PubnubUnitTest = unitTest;

                    pubnub.Presence<string>(channel, ThenPresenceShouldReturnMessage);

                    //since presence expects from stimulus from sub/unsub...
                    pubnub.Subscribe<string>(channel, DummyMethodForSubscribe);
                    subscribeManualEvent.WaitOne(2000);

                    pubnub.Unsubscribe<string>(channel, DummyMethodForUnSubscribe);
                    unsubscribeManualEvent.WaitOne(2000);

                    pubnub.PresenceUnsubscribe<string>(channel, DummyMethodForPreUnSub);
                    presenceUnsubscribeEvent.WaitOne(2000);

                    presenceManualEvent.WaitOne(310 * 1000);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                       {
                           Assert.IsTrue(receivedPresenceMessage, "Presence message not received");
                           TestComplete();
                       });
                });
        }
        public void ThenPresenceShouldReturnCustomUUID()
        {
            receivedCustomUUID = false;

            Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenAClientIsPresented";
            unitTest.TestCaseName = "ThenPresenceShouldReturnCustomUUID";
            pubnub.PubnubUnitTest = unitTest;

            string channel = "my/channel";

            pubnub.Presence<string>(channel, ThenPresenceWithCustomUUIDShouldReturnMessage);

            //since presence expects from stimulus from sub/unsub...
            pubnub.SessionUUID = customUUID;
            pubnub.Subscribe<string>(channel, DummyMethodForSubscribeUUID);
            subscribeUUIDManualEvent.WaitOne(2000);

            pubnub.Unsubscribe<string>(channel, DummyMethodForUnSubscribeUUID);
            unsubscribeUUIDManualEvent.WaitOne(2000);

            presenceUUIDManualEvent.WaitOne(310 * 1000);

            pubnub.PresenceUnsubscribe<string>(channel, DummyMethodForPreUnSubUUID);
            presenceUnsubscribeUUIDEvent.WaitOne();

            Assert.IsTrue(receivedCustomUUID, "Custom UUID not received");
        }
        public void Init()
        {
            if (!PubnubCommon.PAMEnabled)
            {
                EnqueueTestComplete();
                return;
            }

            receivedGrantMessage = false;

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

                    PubnubUnitTest unitTest = new PubnubUnitTest();
                    unitTest.TestClassName = "GrantRequestUnitTest";
                    unitTest.TestCaseName = "Init3";
                    pubnub.PubnubUnitTest = unitTest;

                    EnqueueCallback(() => pubnub.ChannelGroupGrantAccess<string>(channelGroupName, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback));
                    grantManualEvent.WaitOne(310 * 1000);

                    EnqueueCallback(() => Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed."));
                    EnqueueCallback(() =>
                            {
                                pubnub.PubnubUnitTest = null;
                                pubnub = null;
                            }
                        );
                    EnqueueTestComplete();
                });
        }
        public void ThenSubscribeShouldReturnConnectStatus()
        {
            receivedConnectMessage = false;
            ThreadPool.QueueUserWorkItem((s) =>
                {
                    Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);

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

                    pubnub.PubnubUnitTest = unitTest;

                    string channel = "my/channel";

                    pubnub.Subscribe<string>(channel, ReceivedMessageCallbackYesConnect, ConnectStatusCallback);
                    meSubscribeYesConnect.WaitOne(310 * 1000);
                    Thread.Sleep(200);

                    pubnub.Unsubscribe<string>(channel, dummyUnsubCallback);
                    meUnsubscribe.WaitOne(310 * 1000);
                    Thread.Sleep(200);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            Assert.IsTrue(receivedConnectMessage, "WhenSubscribedToAChannel --> ThenSubscribeShouldReturnConnectStatus Failed");
                            TestComplete();
                        });
                });
        }
        public void ThenPresenceShouldReturnReceivedMessage()
        {
            receivedPresenceMessage = false;

            Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);
            
            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenAClientIsPresented";
            unitTest.TestCaseName = "ThenPresenceShouldReturnReceivedMessage";
            pubnub.PubnubUnitTest = unitTest;
            
            string channel = "my/channel";

            pubnub.Presence<string>(channel, ThenPresenceShouldReturnMessage);

            //since presence expects from stimulus from sub/unsub...
            pubnub.Subscribe<string>(channel, DummyMethodForSubscribe);
            subscribeManualEvent.WaitOne(2000);

            pubnub.Unsubscribe<string>(channel, DummyMethodForUnSubscribe);
            unsubscribeManualEvent.WaitOne(2000);

            presenceManualEvent.WaitOne(310 * 1000);

            pubnub.PresenceUnsubscribe<string>(channel, DummyMethodForPreUnSub);
            presenceUnsubscribeEvent.WaitOne();
            
            Assert.IsTrue(receivedPresenceMessage, "Presence message not received");
        }
Example #28
0
        public void ThenUnencryptPublishShouldReturnSuccessCodeAndInfo()
        {
			Debug.Log("Running ThenUnencryptPublishShouldReturnSuccessCodeAndInfo()");
            isUnencryptPublished = false;
            Pubnub pubnub = new Pubnub("demo","demo","","",false);
            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenAMessageIsPublished";
            unitTest.TestCaseName = "ThenUnencryptPublishShouldReturnSuccessCodeAndInfo";
            pubnub.PubnubUnitTest = unitTest;
            string channel = "my/channel";
            string message = messageForUnencryptPublish;

            pubnub.Publish<string>(channel, message, ReturnSuccessUnencryptPublishCodeCallback);
            mreUnencryptedPublish.WaitOne(310*1000);

            if (!isUnencryptPublished)
            {
                UUnitAssert.True(isUnencryptPublished, "Unencrypt Publish Failed");
            }
            else
            {
                pubnub.DetailedHistory<string>(channel, -1, unEncryptPublishTimetoken, -1, false, CaptureUnencryptDetailedHistoryCallback);
                mreUnencryptDetailedHistory.WaitOne(310 * 1000);
                UUnitAssert.True(isUnencryptDetailedHistory, "Unable to match the successful unencrypt Publish");
            }
        }
        public void ThenSubKeyLevelWithReadShouldReturnSuccess()
        {
            currentUnitTestCase = "ThenSubKeyLevelWithReadShouldReturnSuccess";

            receivedGrantMessage = false;

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenGrantIsRequested";
            unitTest.TestCaseName = "ThenSubKeyLevelWithReadShouldReturnSuccess";
            pubnub.PubnubUnitTest = unitTest;
            if (PubnubCommon.PAMEnabled)
                {
                    pubnub.GrantAccess<string>("", true, false, 5, AccessToSubKeyLevelCallback, DummyErrorCallback);
                    Thread.Sleep(1000);

                    grantManualEvent.WaitOne();

                    Assert.IsTrue(receivedGrantMessage, "WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess failed.");
                } else
                {
                    Assert.Ignore("PAM Not Enabled for WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess.");
                }
        }
Example #30
0
        public void ThenSubKeyLevelWithReadShouldReturnSuccess()
        {
            grantAccessCallbackInvoked = false;

            currentUnitTestCase = "ThenSubKeyLevelWithReadShouldReturnSuccess";

            receivedGrantMessage = false;

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

            PubnubUnitTest unitTest = new PubnubUnitTest();
            unitTest.TestClassName = "WhenGrantIsRequested";
            unitTest.TestCaseName = "ThenSubKeyLevelWithReadShouldReturnSuccess";
            pubnub.PubnubUnitTest = unitTest;
            if (PubnubCommon.PAMEnabled)
            {
                EnqueueCallback(() => pubnub.GrantAccess<string>("", true, false, 5, AccessToSubKeyLevelCallback, DummyErrorCallback));
                //Thread.Sleep(1000);

                EnqueueConditional(() => grantAccessCallbackInvoked);

                EnqueueCallback(() => Assert.IsTrue(receivedGrantMessage, "WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess failed."));
            }
            else
            {
                EnqueueCallback(() => Assert.Inconclusive("PAM Not Enabled for WhenGrantIsRequested -> ThenSubKeyLevelWithReadShouldReturnSuccess."));
            }
            EnqueueTestComplete();
        }
Example #31
0
        protected void ShowSettings()
        {
            DisableActions();
            if (pubnub != null)
            {
                pubnub.EndPendingRequests();
            }
            SettingsDialog settings = new SettingsDialog(this);

            settings.Modal = true;

            settings.Name = "Settings";
            bool errorFree = true;

            settings.Response += delegate(object o, ResponseArgs args) {
                if (args.ResponseId == Gtk.ResponseType.Ok)
                {
                    //string channel = this.Channel;
                    pubnub = new Pubnub("demo", "demo", "", this.Cipher, this.Ssl);
                    if (!string.IsNullOrEmpty(this.CustomUuid))
                    {
                        pubnub.SessionUUID = this.CustomUuid;
                    }
                    StringBuilder sbHead = new StringBuilder();
                    //sbHead.Append("Ch:");
                    foreach (string ch in this.Channel.Split(','))
                    {
                        sbHead.Append(ch.Trim());
                        sbHead.Append("\n");
                    }

                    entrySsl.Text    = (this.Ssl)?"On": "Off";
                    entryUuid.Text   = pubnub.SessionUUID;
                    entryCipher.Text = this.Cipher;
                    //entryServerTime.Text = this.time

                    //this.tvChannels.Buffer.Text = sbHead.ToString();

                    PubnubProxy proxy = new PubnubProxy();
                    if (!string.IsNullOrWhiteSpace(this.Server))
                    {
                        proxy.ProxyServer   = this.Server;
                        proxy.ProxyPort     = this.Port;
                        proxy.ProxyUserName = this.Username;
                        proxy.ProxyPassword = this.Password;

                        try
                        {
                            pubnub.Proxy = proxy;
                        }
                        catch (MissingFieldException mse)
                        {
                            Console.WriteLine(mse.Message);
                            errorFree = false;
                        }
                    }
                    if (errorFree)
                    {
                        EnableActions();
                        SubscribeToChannels();
                    }
                    else
                    {
                        ShowSettings();
                    }
                }
                else
                {
                    if (pubnub != null)
                    {
                        EnableActions();
                    }
                }
            };
            settings.Run();
            settings.Destroy();
        }
Example #32
0
        public static void AtUserLevel()
        {
            bool receivedAuditMessage = false;

            if (!PubnubCommon.PAMEnabled)
            {
                Assert.Ignore("PAM not enabled; CleanupGrant -> AtUserLevel.");
                return;
            }

            if (!PubnubCommon.EnableStubTest)
            {
                receivedAuditMessage = false;
                PNConfiguration config = new PNConfiguration
                {
                    PublishKey   = PubnubCommon.PublishKey,
                    SubscribeKey = PubnubCommon.SubscribeKey,
                    SecretKey    = PubnubCommon.SecretKey,
                    Uuid         = "mytestuuid",
                };

                pubnub = createPubNubInstance(config);
                ManualResetEvent auditManualEvent = new ManualResetEvent(false);
                pubnub.Audit().Async(new PNAccessManagerAuditResultExt((r, s) => {
                    try
                    {
                        Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));

                        if (r != null)
                        {
                            Console.WriteLine("PNAccessManagerAuditResult={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            if (s.StatusCode == 200 && s.Error == false)
                            {
                                if (!String.IsNullOrEmpty(r.Channel))
                                {
                                    var channels = r.Channel.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    Console.WriteLine("CleanupGrant / AtUserLevel / UserCallbackForCleanUpAccess - Channel Count = {0}", channels.Length);
                                    foreach (string channelName in channels)
                                    {
                                        if (r.AuthKeys != null)
                                        {
                                            foreach (string authKey in r.AuthKeys.Keys)
                                            {
                                                Console.WriteLine("Auth Key = " + authKey);
                                                ManualResetEvent revokeManualEvent = new ManualResetEvent(false);
                                                pubnub.Grant().Channels(new[] { channelName }).AuthKeys(new[] { authKey }).Read(false).Write(false).Manage(false)
                                                .Async(new PNAccessManagerGrantResultExt((r1, s1) =>
                                                {
                                                    try
                                                    {
                                                        Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s1));

                                                        if (r1 != null)
                                                        {
                                                            Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r1));
                                                        }
                                                    }
                                                    catch { /* ignore */ }
                                                    finally
                                                    {
                                                        revokeManualEvent.Set();
                                                    }
                                                }));
                                                revokeManualEvent.WaitOne();
                                            }
                                        }
                                    }
                                }

                                if (r.Level == "subkey")
                                {
                                    receivedAuditMessage = true;
                                }
                            }
                        }
                    }
                    catch { /* ignore */ }
                    finally
                    {
                        auditManualEvent.Set();
                    }
                }));
                auditManualEvent.WaitOne();
                pubnub.Destroy();
                pubnub = null;
                Assert.IsTrue(receivedAuditMessage, "CleanupGrant -> AtUserLevel failed.");
            }
            else
            {
                Assert.Ignore("Only for live test; CleanupGrant -> AtUserLevel.");
            }
        }
        public void ThenPubnubShouldGenerateUniqueIdentifier()
        {
            Pubnub pubnub = new Pubnub("demo", "demo", "", "", false);

            Assert.IsNotNull(pubnub.generateGUID());
        }
Example #34
0
        public void ThenRevokeAtUserLevelReturnSuccess()
        {
            server.ClearRequests();

            currentUnitTestCase = "ThenRevokeAtUserLevelReturnSuccess";

            receivedGrantMessage  = false;
            receivedRevokeMessage = false;

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

            pubnub = this.createPubNubInstance(config);

            string expectedGrant  = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":5,\"channel\":\"hello_my_channel\",\"auths\":{\"hello_my_authkey\":{\"r\":1,\"w\":1,\"m\":0}}},\"service\":\"Access Manager\",\"status\":200}";
            string expectedRevoke = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":1,\"channel\":\"hello_my_channel\",\"auths\":{\"hello_my_authkey\":{\"r\":0,\"w\":0,\"m\":0}}},\"service\":\"Access Manager\",\"status\":200}";

            server.RunOnHttps(config.Secure);
            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", authKey)
                              .WithParameter("channel", channel)
                              .WithParameter("m", "0")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "1")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "5")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "1")
                              .WithParameter("signature", "V6C3eRs_YSP7njOW1f9xAFpmCx5do_7D3oUGXxDClXw=")
                              .WithResponse(expectedGrant)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));
            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", authKey)
                              .WithParameter("channel", channel)
                              .WithParameter("m", "0")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "0")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "0")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "0")
                              .WithParameter("signature", "MJVPMrBFTV7jo8jMp_DSn9OhIi8aikd7wru8x0sz3io=")
                              .WithResponse(expectedRevoke)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            if (PubnubCommon.PAMEnabled)
            {
                grantManualEvent = new ManualResetEvent(false);
                pubnub.Grant().Channels(new string[] { channel }).AuthKeys(new string[] { authKey }).Read(true).Write(true).Manage(false).TTL(5).Async(new GrantResult());
                Thread.Sleep(1000);
                grantManualEvent.WaitOne();

                if (receivedGrantMessage)
                {
                    revokeManualEvent = new ManualResetEvent(false);
                    Console.WriteLine("WhenGrantIsRequested -> ThenRevokeAtUserLevelReturnSuccess -> Grant ok..Now trying Revoke");
                    pubnub.Grant().Channels(new string[] { channel }).AuthKeys(new string[] { authKey }).Read(false).Write(false).Manage(false).TTL(0).Async(new RevokeGrantResult());
                    Thread.Sleep(1000);
                    revokeManualEvent.WaitOne();

                    pubnub.Destroy();
                    pubnub.PubnubUnitTest = null;
                    pubnub = null;
                    Assert.IsTrue(receivedRevokeMessage, "WhenGrantIsRequested -> ThenRevokeAtUserLevelReturnSuccess -> Grant success but revoke failed.");
                }
                else
                {
                    Assert.IsTrue(receivedGrantMessage, "WhenGrantIsRequested -> ThenRevokeAtUserLevelReturnSuccess failed. -> Grant not occured, so is revoke");
                }
            }
            else
            {
                Assert.Ignore("PAM Not Enabled for WhenGrantIsRequested -> ThenRevokeAtUserLevelReturnSuccess.");
            }
        }
Example #35
0
        public void ThenMultipleAuthGrantShouldReturnSuccess()
        {
            server.ClearRequests();

            currentUnitTestCase = "ThenMultipleAuthGrantShouldReturnSuccess";

            receivedGrantMessage = false;

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

            pubnub = this.createPubNubInstance(config);

            channelBuilder = new string[multipleChannelGrantCount];
            authKeyBuilder = new string[multipleChannelGrantCount];

            for (int index = 0; index < multipleChannelGrantCount; index++)
            {
                channelBuilder[index] = String.Format("csharp-hello_my_channel-{0}", index);
                authKeyBuilder[index] = String.Format("AuthKey-csharp-hello_my_channel-{0}", index);
            }

            string expected = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":5,\"channels\":{\"csharp-hello_my_channel-0\":{\"auths\":{\"AuthKey-csharp-hello_my_channel-0\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-1\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-2\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-3\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-4\":{\"r\":1,\"w\":1,\"m\":0}}},\"csharp-hello_my_channel-1\":{\"auths\":{\"AuthKey-csharp-hello_my_channel-0\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-1\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-2\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-3\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-4\":{\"r\":1,\"w\":1,\"m\":0}}},\"csharp-hello_my_channel-2\":{\"auths\":{\"AuthKey-csharp-hello_my_channel-0\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-1\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-2\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-3\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-4\":{\"r\":1,\"w\":1,\"m\":0}}},\"csharp-hello_my_channel-3\":{\"auths\":{\"AuthKey-csharp-hello_my_channel-0\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-1\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-2\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-3\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-4\":{\"r\":1,\"w\":1,\"m\":0}}},\"csharp-hello_my_channel-4\":{\"auths\":{\"AuthKey-csharp-hello_my_channel-0\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-1\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-2\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-3\":{\"r\":1,\"w\":1,\"m\":0},\"AuthKey-csharp-hello_my_channel-4\":{\"r\":1,\"w\":1,\"m\":0}}}}},\"service\":\"Access Manager\",\"status\":200}";

            server.RunOnHttps(config.Secure);
            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", "AuthKey-csharp-hello_my_channel-0%2CAuthKey-csharp-hello_my_channel-1%2CAuthKey-csharp-hello_my_channel-2%2CAuthKey-csharp-hello_my_channel-3%2CAuthKey-csharp-hello_my_channel-4")
                              .WithParameter("channel", "csharp-hello_my_channel-0%2Ccsharp-hello_my_channel-1%2Ccsharp-hello_my_channel-2%2Ccsharp-hello_my_channel-3%2Ccsharp-hello_my_channel-4")
                              .WithParameter("m", "0")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "1")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "5")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "1")
                              .WithParameter("signature", "9_2ZxQiQeXroQqt3x728ebRN6f4hMPk7QtebCKSZl7Q=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            if (PubnubCommon.PAMEnabled)
            {
                grantManualEvent = new ManualResetEvent(false);
                pubnub.Grant().Channels(channelBuilder).AuthKeys(authKeyBuilder).Read(true).Write(true).Manage(false).TTL(5).Async(new GrantResult());
                Thread.Sleep(1000);

                grantManualEvent.WaitOne();

                pubnub.Destroy();
                pubnub.PubnubUnitTest = null;
                pubnub = null;
                Assert.IsTrue(receivedGrantMessage, "WhenGrantIsRequested -> ThenMultipleAuthGrantShouldReturnSuccess failed.");
            }
            else
            {
                Assert.Ignore("PAM Not Enabled for WhenGrantIsRequested -> ThenMultipleAuthGrantShouldReturnSuccess.");
            }
        }
Example #36
0
        public static void Init()
        {
            UnitTestLog unitLog = new Tests.UnitTestLog();

            unitLog.LogLevel = MockServer.LoggingMethod.Level.Verbose;
            server           = Server.Instance();
            MockServer.LoggingMethod.MockServerLog = unitLog;
            server.Start();

            if (!PubnubCommon.PAMEnabled)
            {
                return;
            }

            bool receivedGrantMessage = false;

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

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);
            manualResetEventWaitTimeout = (PubnubCommon.EnableStubTest) ? 1000 : 310 * 1000;

            ManualResetEvent grantManualEvent = new ManualResetEvent(false);

            string expected = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":20,\"channel\":\"hello_my_channel\",\"auths\":{\"myAuth\":{\"r\":1,\"w\":1,\"m\":1}}},\"service\":\"Access Manager\",\"status\":200}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", authKey)
                              .WithParameter("channel", "hello_my_channel")
                              .WithParameter("channel-group", "hello_my_group%2Chello_my_group1%2Chello_my_group2")
                              .WithParameter("m", "1")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "1")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "20")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "1")
                              .WithParameter("signature", "oiUrVMZSf7NEGk6M9JrvpnffmMEy7wWLgYGHwMztIlU=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Grant().AuthKeys(new [] { authKey }).ChannelGroups(new [] { channelGroupName, channelGroupName1, channelGroupName2 }).Channels(new [] { channelName }).Read(true).Write(true).Manage(true).TTL(20)
            .Async(new PNAccessManagerGrantResultExt(
                       (r, s) =>
            {
                try
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        Debug.WriteLine("PNAccessManagerGrantResult={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(r));

                        if (r.ChannelGroups != null && r.ChannelGroups.Count > 0)
                        {
                            foreach (KeyValuePair <string, Dictionary <string, PNAccessManagerKeyData> > channelGroupKP in r.ChannelGroups)
                            {
                                receivedGrantMessage = false;

                                string channelGroup = channelGroupKP.Key;
                                var read            = r.ChannelGroups[channelGroup][authKey].ReadEnabled;
                                var write           = r.ChannelGroups[channelGroup][authKey].WriteEnabled;
                                var manage          = r.ChannelGroups[channelGroup][authKey].ManageEnabled;

                                if (read && write && manage)
                                {
                                    receivedGrantMessage = true;
                                }
                                else
                                {
                                    receivedGrantMessage = false;
                                    break;
                                }
                            }
                        }
                        if (r.Channels != null && r.Channels.Count > 0)
                        {
                            foreach (KeyValuePair <string, Dictionary <string, PNAccessManagerKeyData> > channelKP in r.Channels)
                            {
                                receivedGrantMessage = false;

                                string channel = channelKP.Key;
                                var read       = r.Channels[channel][authKey].ReadEnabled;
                                var write      = r.Channels[channel][authKey].WriteEnabled;
                                var manage     = r.Channels[channel][authKey].ManageEnabled;

                                if (read && write && manage)
                                {
                                    receivedGrantMessage = true;
                                }
                                else
                                {
                                    receivedGrantMessage = false;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    }
                }
                catch { /* ignore */ }
                finally
                {
                    grantManualEvent.Set();
                }
            }));
            Thread.Sleep(1000);
            grantManualEvent.WaitOne(manualResetEventWaitTimeout);

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

            Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed.");
        }
        public static async Task ThenWithAsyncIgnoreCipherKeyUnencryptSignalListenerShouldGetMessagae()
#endif
        {
            server.ClearRequests();

            bool internalReceivedMessage = false;
            bool receivedErrorMessage    = false;

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

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

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

            server.RunOnHttps(config.Secure);

            ManualResetEvent subscribeManualEvent = new ManualResetEvent(false);

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

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

            string channel = "hello_my_channel";

            manualResetEventWaitTimeout = 310 * 1000;

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

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

                Thread.Sleep(1000);

                pubnub.RemoveListener(listenerSubCallack);
                pubnub.Destroy();
                pubnub.PubnubUnitTest = null;
                pubnub = null;
                if (receivedErrorMessage)
                {
                    internalReceivedMessage = false;
                }
                Assert.IsTrue(internalReceivedMessage, "WhenSubscribedToAChannel --> ThenWithAsyncIgnoreCipherKeyUnencryptSignalListenerShouldGetMessagae Failed");
            }
        }
Example #38
0
        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)
                            {
                                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)
                {
                    if (s.ErrorData != null)
                    {
                        Debug.WriteLine(s.ErrorData.Information);
                    }
                }
                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
                {
                    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(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
                    {
                        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(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 static async Task ThenWithAsyncUnencryptSignalShouldReturnSuccessCodeAndInfo()
#endif
        {
            server.ClearRequests();

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

            bool receivedSignalMessage = false;

            string channel = "hello_my_channel";
            string message = messageForUnencryptSignal;

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

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

            string expected = "[1,\"Sent\",\"14715278266153304\"]";

            server.AddRequest(new Request()
                              .WithMethod("POST")
                              .WithPath(String.Format("/v1/signal/{0}/{1}/{2}", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel))
                              .WithContent("{\"message\":\"%22Pubnub%20Messaging%20API%201%22\"}")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            manualResetEventWaitTimeout = 310 * 1000;

#if NET40
            PNResult <PNPublishResult> signalResult = Task.Factory.StartNew(async() => await pubnub.Signal().Channel(channel).Message(message).ExecuteAsync()).Result.Result;
#else
            PNResult <PNPublishResult> signalResult = await pubnub.Signal().Channel(channel).Message(message).ExecuteAsync();
#endif
            if (signalResult.Result != null && signalResult.Status.StatusCode == 200 && !signalResult.Status.Error &&
                signalResult.Result.Timetoken > 0)
            {
                receivedSignalMessage = true;
            }

            if (!receivedSignalMessage)
            {
                Assert.IsTrue(receivedSignalMessage, "WithAsync Unencrypt Signal Failed");
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
Example #40
0
        public static void ThenSubscribeShouldReturnReceivedMessage()
        {
            server.ClearRequests();

            bool receivedMessage = false;

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

            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" }
            })
            .Async(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" }
                })
                .Async(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");
            }
        }
Example #41
0
 public override void Signal <T>(Pubnub pubnub, PNSignalResult <T> signal)
 {
     throw new NotImplementedException();
 }
        public static void Init()
        {
            UnitTestLog unitLog = new Tests.UnitTestLog();

            unitLog.LogLevel = MockServer.LoggingMethod.Level.Verbose;
            server           = Server.Instance();
            MockServer.LoggingMethod.MockServerLog = unitLog;
            server.Start();

            if (!PubnubCommon.PAMServerSideGrant)
            {
                return;
            }

            bool   receivedGrantMessage = false;
            string channel = "hello_my_channel";

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

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            string expected = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":20,\"channel\":\"hello_my_channel\",\"auths\":{\"myAuth\":{\"r\":1,\"w\":1,\"m\":1}}},\"service\":\"Access Manager\",\"status\":200}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", authKey)
                              .WithParameter("channel", channel)
                              .WithParameter("m", "1")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "1")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "20")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "1")
                              .WithParameter("signature", "JMQKzXgfqNo-HaHuabC0gq0X6IkVMHa9AWBCg6BGN1Q=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            ManualResetEvent grantManualEvent = new ManualResetEvent(false);

            pubnub.Grant().Channels(new[] { channel }).AuthKeys(new[] { authKey }).Read(true).Write(true).Manage(true).TTL(20)
            .Execute(new PNAccessManagerGrantResultExt(
                         (r, s) =>
            {
                try
                {
                    Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    if (r != null)
                    {
                        Debug.WriteLine("PNAccessManagerGrantResult={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                        if (r.Channels != null && r.Channels.Count > 0)
                        {
                            var read  = r.Channels[channel][authKey].ReadEnabled;
                            var write = r.Channels[channel][authKey].WriteEnabled;
                            if (read && write)
                            {
                                receivedGrantMessage = true;
                            }
                        }
                    }
                }
                catch { /* ignore */ }
                finally
                {
                    grantManualEvent.Set();
                }
            }));

            if (!PubnubCommon.EnableStubTest)
            {
                Thread.Sleep(1000);
            }

            grantManualEvent.WaitOne();

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedGrantMessage, "WhenAMessageIsPublished Grant access failed.");
        }
Example #43
0
        public static void Init()
        {
            UnitTestLog unitLog = new Tests.UnitTestLog();

            unitLog.LogLevel = MockServer.LoggingMethod.Level.Verbose;
            server           = Server.Instance();
            MockServer.LoggingMethod.MockServerLog = unitLog;
            server.Start();

            if (!PubnubCommon.PAMEnabled)
            {
                return;
            }

            receivedGrantMessage = false;

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

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            string expected = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":20,\"channel\":\"hello_my_channel\",\"auths\":{\"myAuth\":{\"r\":1,\"w\":1,\"m\":1}}},\"service\":\"Access Manager\",\"status\":200}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", authKey)
                              .WithParameter("channel", "hello_my_channel%2Chello_my_channel1%2Chello_my_channel2")
                              .WithParameter("m", "1")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "1")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "20")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "1")
                              .WithParameter("signature", "hc7IKhEB7tyL6ENR3ndOOlHqPIG3RmzxwJMSGpofE6Q=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Grant().Channels(channelsGrant).AuthKeys(new [] { authKey }).Read(true).Write(true).Manage(true).TTL(20).Execute(new UTGrantResult());

            Thread.Sleep(1000);

            grantManualEvent.WaitOne();

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

            Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannel2 Grant access failed.");
        }
Example #44
0
 public override void ObjectEvent(Pubnub pubnub, PNObjectApiEventResult objectEvent)
 {
     throw new NotImplementedException();
 }
Example #45
0
        private static void CommonSubscribeShouldReturnReceivedMessageBasedOnParams(string secretKey, string cipherKey, bool ssl)
        {
            receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                SecretKey    = secretKey,
                CipherKey    = cipherKey,
                Uuid         = "mytestuuid",
                AuthKey      = authKey,
                Secure       = ssl,
                LogVerbosity = PNLogVerbosity.BODY,
                PubnubLog    = new TestLog(),
                NonSubscribeRequestTimeout = 120
            };

            server.RunOnHttps(ssl);

            SubscribeCallback listenerSubCallack = new UTSubscribeCallback();

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

            manualResetEventWaitTimeout = 310 * 1000;

            subscribeManualEvent = new ManualResetEvent(false);

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

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

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

            expected = "{}";

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

            pubnub.Subscribe <string>().Channels(new [] { channel }).QueryParam(new Dictionary <string, object> {
                { "ut", currentTestCase }
            }).Execute();

            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

            publishManualEvent   = new ManualResetEvent(false);
            subscribeManualEvent = new ManualResetEvent(false);

            publishedMessage = "Test for WhenSubscribedToAChannel ThenItShouldReturnReceivedMessage";

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

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

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/%22QoHwTga0QtOCtJRQ6sqtyateB%2FVotNt%2F50y23yXW7rpCbZdJLUAVKKbf01SpN6zghA6MqQaaHRXoYqAf84RF56C7Ky6Oi6jLqN2I5%2FlXSCw%3D%22", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            Thread.Sleep(1000);

            pubnub.Publish().Channel(channel).Message(publishedMessage).QueryParam(new Dictionary <string, object> {
                { "ut", currentTestCase }
            }).Execute(new UTPublishResult());

            publishManualEvent.WaitOne(manualResetEventWaitTimeout);

            Thread.Sleep(1000);

            pubnub.Unsubscribe <string>().Channels(new [] { channel }).QueryParam(new Dictionary <string, object> {
                { "ut", currentTestCase }
            }).Execute();

            Thread.Sleep(1000);

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

            Thread.Sleep(1000);
        }
Example #46
0
 public override void Presence(Pubnub pubnub, PNPresenceEventResult presence)
 {
 }
Example #47
0
 public Listener(Pubnub pubnub)
 {
     this.pubnub = pubnub;
 }
Example #48
0
        private static void CommonSubscribeShouldReturnEmojiMessageBasedOnParams(string secretKey, string cipherKey, bool ssl)
        {
            receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                SecretKey    = secretKey,
                CipherKey    = cipherKey,
                Uuid         = "mytestuuid",
                AuthKey      = authKey,
                Secure       = ssl,
                LogVerbosity = PNLogVerbosity.BODY,
                PubnubLog    = new TestLog(),
                NonSubscribeRequestTimeout = 120
            };

            server.RunOnHttps(ssl);

            SubscribeCallback listenerSubCallack = new UTSubscribeCallback();

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

            manualResetEventWaitTimeout = 310 * 1000;

            subscribeManualEvent = new ManualResetEvent(false);

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

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

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

            expected = "{}";

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

            pubnub.Subscribe <string>().Channels(new [] { channel }).QueryParam(new Dictionary <string, object>()
            {
                { "ut", currentTestCase }
            }).Execute();

            subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status

            publishManualEvent   = new ManualResetEvent(false);
            subscribeManualEvent = new ManualResetEvent(false);

            publishedMessage = "Text with 😜 emoji 🎉.";

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

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/%22Text%20with%20%F0%9F%98%9C%20emoji%20%F0%9F%8E%89.%22", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel))
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

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

            Thread.Sleep(1000);

            pubnub.Publish().Channel(channel).Message(publishedMessage).QueryParam(new Dictionary <string, object>()
            {
                { "ut", currentTestCase }
            }).Execute(new UTPublishResult());
            publishManualEvent.WaitOne(manualResetEventWaitTimeout);

            pubnub.Unsubscribe <string>().Channels(new [] { channel }).QueryParam(new Dictionary <string, object>()
            {
                { "ut", currentTestCase }
            }).Execute();

            Thread.Sleep(1000);

            pubnub.RemoveListener(listenerSubCallack);
            Thread.Sleep(1000);
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Thread.Sleep(1000);
        }
        public Pubnub_MessagingSpeedTest(string channelName, string cipher, bool enableSSL, Pubnub pubnub)
            : base(UITableViewStyle.Plain, null)
        {
            Channel     = channelName;
            Ssl         = enableSSL;
            Cipher      = cipher;
            this.pubnub = pubnub;

            string strSsl = "";

            if (Ssl)
            {
                strSsl = ", SSL";
            }

            string strCip = "";

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

            string head = String.Format("Ch: {0} {1} {2}", Channel, strSsl, strCip);

            bool bIphone = true;

            string hardwareVer = DeviceHardware.Version.ToString().ToLower();

            if (hardwareVer.IndexOf("ipad") >= 0)
            {
                bIphone = false;
            }

            InitArrays();

            perfHeader = new PerformanceHeader();
            secOutput  = new Section(perfHeader.View);

            sdHeader          = new SdHeader(speedTestNames, speedTestSorted);
            sdHeader.View.Tag = 101;

            graphHeader          = new GraphHeader();
            graphHeader.View.Tag = 102;

            UISegmentedControl segmentedControl = new UISegmentedControl();

            segmentedControl.HorizontalAlignment = UIControlContentHorizontalAlignment.Center;

            segmentedControl.Frame = new CGRect(10, 20, UIScreen.MainScreen.Bounds.Width - 20, 40);
            segmentedControl.InsertSegment("Graph", 0, false);
            segmentedControl.InsertSegment("SD", 1, false);
            segmentedControl.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;

            segmentedControl.AddSubview(graphHeader.View);

            segmentedControl.ValueChanged += (sender, e) => {
                var selectedSegmentId = (sender as UISegmentedControl).SelectedSegment;
                if (segmentedControl.SelectedSegment == 0)
                {
                    if (segmentedControl.ViewWithTag(101) != null)
                    {
                        segmentedControl.ViewWithTag(101).RemoveFromSuperview();
                    }
                    graphHeader.View.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
                    segmentedControl.AddSubview(graphHeader.View);
                }
                else if (segmentedControl.SelectedSegment == 1)
                {
                    if (segmentedControl.ViewWithTag(102) != null)
                    {
                        segmentedControl.ViewWithTag(102).RemoveFromSuperview();
                    }

                    sdHeader.View.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
                    segmentedControl.AddSubview(sdHeader.View);
                }
            };
            segmentedControl.SelectedSegment = 0;
            segmentedControl.ControlStyle    = UISegmentedControlStyle.Plain;
            secOutput.Add(segmentedControl);

            Section sectionSegmentedControl = new Section();

            //sectionSegmentedControl.Add(segmentedControl);

            root = new RootElement(head)
            {
                new Section("PubNub speed test"),
                secOutput,
                //sectionSegmentedControl
            };

            Root = root;
            this.Root.UnevenRows = true;
            dvc = new DialogViewController(UITableViewStyle.Plain, root, true);
            dvc.NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, delegate {
                pubnub.Destroy();
                runSpeedtest = false;
                speedTestThread.Join(1000);
                AppDelegate.navigation.PopToRootViewController(true);
            });
            dvc.TableView.ScrollEnabled   = true;
            dvc.TableView.SeparatorColor  = UIColor.Clear;
            dvc.TableView.SeparatorStyle  = UITableViewCellSeparatorStyle.None;
            dvc.TableView.BackgroundView  = null;
            dvc.TableView.BackgroundColor = UIColor.White;
            AppDelegate.navigation.PushViewController(dvc, true);

            LaunchSpeedTest();
        }
Example #50
0
 public PubnubHostTransceiver(PubnubCredentials credentials, string channel)
 {
     _transceiver = new Pubnub(credentials.PublishingKey, credentials.SubscriptionKey, credentials.SecretKey);
     _transceiver.subscribe(channel, Process_input_from_standIn);
     _channel = channel;
 }
Example #51
0
        void CallingPubnub()
        {
            Dictionary <string, string> message = new Dictionary <string, string>();

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

            Pubnub pubnub = new Pubnub(pnConfiguration);

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

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

            pubnub.AddListener(subscribeCallback);

            pubnub.Subscribe <string>()
            .Channels(new string[] {
                "my_channel"
            }).Execute();
        }
        public GetChannelMetadataOperation(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubUnitTest pubnubUnit, IPubnubLog log, EndPoint.TelemetryManager telemetryManager, Pubnub instance) : base(pubnubConfig, jsonPluggableLibrary, pubnubUnit, log, telemetryManager, instance)
        {
            config             = pubnubConfig;
            jsonLibrary        = jsonPluggableLibrary;
            unit               = pubnubUnit;
            pubnubLog          = log;
            pubnubTelemetryMgr = telemetryManager;

            if (instance != null)
            {
                if (!ChannelRequest.ContainsKey(instance.InstanceId))
                {
                    ChannelRequest.GetOrAdd(instance.InstanceId, new ConcurrentDictionary <string, HttpWebRequest>());
                }
                if (!ChannelInternetStatus.ContainsKey(instance.InstanceId))
                {
                    ChannelInternetStatus.GetOrAdd(instance.InstanceId, new ConcurrentDictionary <string, bool>());
                }
                if (!ChannelGroupInternetStatus.ContainsKey(instance.InstanceId))
                {
                    ChannelGroupInternetStatus.GetOrAdd(instance.InstanceId, new ConcurrentDictionary <string, bool>());
                }
            }
        }
Example #53
0
 // Use this for initialization
 void Start()
 {
     Pubnub pubnub = new Pubnub("demo", "demo");
 }
Example #54
0
 public QuestionWorker()
 {
     pubnub = new Pubnub("demo", "demo");
 }
Example #55
0
        public static void ThenSpaceUpdateDeleteShouldReturnEventInfo()
        {
            server.ClearRequests();

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

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

            string spaceId = "pandu-ut-sid";

            manualResetEventWaitTimeout = 310 * 1000;

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

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

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

            ManualResetEvent manualEvent = new ManualResetEvent(false);

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

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

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

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

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

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

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

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
Example #56
0
        void Destory()
        {
            Pubnub pubnub = new Pubnub(pnConfiguration);

            pubnub.Destroy();
        }