public PollResponse PollEvents(long eventBufferVersion, string consumerName)
        {
            var events = new List <IEvent>();

            while (true)
            {
                for (int i = 0; i < this.eventsToPushMaxCount; i++)
                {
                    IEvent e;
                    if (!this.messageQueue.TryDequeue(out e))
                    {
                        break;
                    }

                    events.Add(e);
                }

                if (events.Count > 0)
                {
                    break;
                }

                Thread.Sleep(1);
            }

            return(PollResponse.CreateInMemoryResponse(false, true, this.streamType, events, events.Count, events.Count + this.messageQueue.Count));
        }
Exemple #2
0
        public PollResponse PollEvents(long eventBufferVersion, string consumerName)
        {
            this.serverStatus.Add(new ServerStatus(eventBufferVersion));

            PollResponse clientResponse;

            while (!this.clientResponse.TryTake(out clientResponse))
            {
                Thread.Sleep(1);
            }

            lock (this)
            {
                if (clientResponse.ProducerVersion > eventBufferVersion &&
                    clientResponse.NewRawEvents.Max(x => x.EventCollectionVersion) > eventBufferVersion)
                {
                    clientResponse = PollResponse.CreateSerializedResponse(false, true, clientResponse.StreamType,
                                                                           clientResponse.NewRawEvents.Where(x => x.EventCollectionVersion > eventBufferVersion).ToList(), eventBufferVersion, clientResponse.ProducerVersion);
                }
                else
                {
                    clientResponse = PollResponse.CreateSerializedResponse(false, false, clientResponse.StreamType, new List <NewRawEvent>(), 0, 0);
                }

                return(clientResponse);
            }
        }
Exemple #3
0
        public async Task Run(Subscription subscription, CancellationToken cancellationToken)
        {
            var query    = _epcisQueries.Single(x => x.Name == subscription.QueryName);
            var response = new PollResponse();


            try
            {
                var pendingRequests = await _subscriptionManager.GetPendingRequestIds(subscription.Id.Value, cancellationToken);

                if (pendingRequests.Any())
                {
                    var parameters = subscription.Parameters.Append(new Model.Queries.QueryParameter {
                        Name = "EQ_requestId", Values = pendingRequests.Select(x => x.ToString()).ToArray()
                    });
                    response = await query.Handle(parameters.ToArray(), cancellationToken);
                }

                response.QueryName      = query.Name;
                response.SubscriptionId = subscription.SubscriptionId;

                await SendSubscriptionResults(subscription, response, cancellationToken);

                await _subscriptionManager.AcknowledgePendingRequests(subscription.Id.Value, pendingRequests, cancellationToken);

                await _subscriptionManager.RegisterSubscriptionTrigger(subscription.Id.Value, SubscriptionResult.Success, default, cancellationToken);
Exemple #4
0
        public void ProcessPollResponse(PollResponse aspPollResponse)
        {
            switch (aspPollResponse.DeliveryNotification)
            {
            case PollResponse.EDeliveryNotification.Negative:
            {
                try
                {
                    var ship = getByMobileNum(aspPollResponse.Mobile);
                    ChangeShipStatus(ShipStatus.Error, ship);
                    break;
                }
                catch (Exception ex)
                {
                    //cancelar transaccion: no se pudo determinar para que barco corresponde el error
                    // mandar cuerpo del mensaje
                    break;
                }
            }

            case PollResponse.EDeliveryNotification.Positive:
            {
                var ship = getByMobileNum(aspPollResponse.Mobile);

                log.Info("La solicitud se envio correctamente al equipo, aguardar respuesta");
                break;
            }

            default:
                throw new NotImplementedException();
            }
        }
        private async void OnSelectAnswer(object sender, EventArgs e)
        {
            var selectedQuestion = GetSelectedQuestion();

            Debug.Assert(selectedQuestion != null);
            Debug.Assert(string.IsNullOrEmpty(userName) == false);

            int pos = answerGroup.Children.IndexOf((Button)sender);

            if (response == null)
            {
                response = new PollResponse {
                    Name           = userName,
                    ResponseIndex  = pos,
                    PollQuestionId = selectedQuestion.Id
                };
            }
            else
            {
                Debug.Assert(response.Name == userName);
                Debug.Assert(response.PollQuestionId == selectedQuestion.Id);
                response.ResponseIndex = pos;
            }
            await service.AddOrUpdatePollResponseAsync(response);

            SetSelectedAnswer();
        }
        public XDocument Format(PollResponse response)
        {
            var formatted      = WithAttributes("EPCISQueryDocument", EpcisNamespaces.Query);
            var resultName     = string.Empty;
            var typeOfResponse = response.Entities.GetType().GenericTypeArguments[0];

            if (typeOfResponse == typeof(EpcisEvent))
            {
                resultName = "EventList";
            }
            if (typeOfResponse == typeof(MasterData))
            {
                resultName = "VocabularyList";
            }

            formatted.Root.Add(
                new XElement("EPCISBody",
                             new XElement(XName.Get("QueryResults", EpcisNamespaces.Query),
                                          new XElement("queryName", response.QueryName),
                                          !string.IsNullOrEmpty(response.SubscriptionId) ? new XElement("subscriptionID", response.SubscriptionId) : null,
                                          new XElement("resultBody", new XElement(resultName, response.Entities.Select(XmlEventFormatter.Format)))
                                          )
                             )
                );

            return(formatted);
        }
Exemple #7
0
        public IEnumerable <PollResponse> GetPollResponses(int pollId)
        {
            string strSql = "SELECT a.PollAnswerID, a.DisplayText,COUNT(r.UserID) AS Votes FROM " + Config.ForumTablePrefix + "POLLANSWERS AS a LEFT OUTER JOIN " +
                            Config.ForumTablePrefix + "POLLRESPONSE AS r ON a.PollAnswerID = r.PollAnswerID WHERE a.PollId=@PollId " +
                            "GROUP BY a.PollID, a.DisplayText, a.PollAnswerID,a.SortOrder " +
                            "ORDER BY a.SortOrder";
            List <PollResponse> responses = new List <PollResponse>();

            using (SqlDataReader rdr = SqlHelper.ExecuteReader(SqlHelper.ConnString, CommandType.Text, strSql, new SqlParameter("@PollID", SqlDbType.Int)
            {
                Value = pollId
            }))
            {
                while (rdr.Read())
                {
                    PollResponse response = new PollResponse
                    {
                        Id     = rdr.GetInt32(0),
                        Answer = rdr.GetString(1),
                        Votes  = rdr.GetInt32(2)
                    };
                    responses.Add(response);
                }
            }
            return(responses);
        }
 /// <summary>
 /// Loads the data from the file, interpreting control codes as it reads
 /// </summary>
 /// <param name="data">The data file stream.</param>
 public void LoadData(byte[] data)
 {
     try
     {
         PollResponse response = new PollResponse(this.controller, data);
         this.controller.SensorData.PollResponses.Add(response);
         if (response.DataType == "GP")
         {
             this.controller.Gps.GpsList.Add(new GPSCoordinate(response));
         }
         else if (response.DataType == "TC")
         {
             this.controller.TcWindow.Set_Data(response.Time, response.Data);
         }
         else if (response.DataType == "GT")
         {
             this.controller.TimeOfDayConverter.SetBaseTime(response.Time, response.Data);
         }
         else if (response.DataType == "CF")
         {
             this.controller.Config = response.Data2;
             this.controller.MainWindow.PopulateSelectionWindow();
         }
     }
     catch (Exception e)
     {
         return;
     }
 }
        public override XDocument FormatInternal(PollResponse response)
        {
            var formatted = CreateResponse("EPCISQueryDocument");
            var resultName = "EventList";
            var resultList = default(IEnumerable<XElement>);

            if (response.EventList.Any())
            {
                resultName = "EventList";
                resultList = XmlEntityFormatter.FormatEvents(response.EventList);
            }
            else if (response.MasterdataList.Any())
            {
                resultName = "VocabularyList";
                resultList = XmlEntityFormatter.FormatMasterData(response.MasterdataList);
            }

            formatted.Root.Add(
                new XElement("EPCISBody",
                    new XElement(XName.Get("QueryResults", EpcisNamespaces.Query),
                        new XElement("queryName", response.QueryName),
                        !string.IsNullOrEmpty(response.SubscriptionId) ? new XElement("subscriptionID", response.SubscriptionId) : null,
                        new XElement("resultsBody", new XElement(resultName, resultList))
                    )
                )
            );

            return formatted;
        }
        public void TestAbuseNotification()
        {
            byte[] input    = File.ReadAllBytes("AbuseNotification.xml");
            var    response = new PollResponse(input);

            Assert.AreEqual("1301", response.Code);
            Assert.AreEqual("Command completed successfully; ack to dequeue", response.Message);

            Assert.AreEqual("Domain Activity Notification", response.Body);

            Assert.AreEqual("EPP-12345C-8BF-4CAA-A944-2F0EFCD37D9E", response.ClientTransactionId);
            Assert.AreEqual("1254234", response.ServerTransactionId);

            var notification = new AbuseNotification(File.ReadAllText("AbuseNotification.xml"));

            Assert.AreEqual("phished.co.uk", notification.DomainName);
            Assert.AreEqual("phished.co.uk", notification.Key);
            Assert.AreEqual("phishing", notification.Activity);
            Assert.AreEqual("Netcraft", notification.Source);
            Assert.AreEqual("www.youve.been.phished.co.uk", notification.HostName);
            Assert.AreEqual("http://www.youve.been.phished.co.uk/give/us/your/money.htm", notification.Url);
            Assert.IsNotNull(notification.Date);
            Assert.AreEqual(new DateTime(2011, 3, 1, 11, 44, 1), notification.Date.Value);
            Assert.AreEqual("213.135.134.24", notification.Ip);
            Assert.AreEqual("ns0.crooked.dealings.net", notification.Nameserver);
            Assert.AreEqual("*****@*****.**", notification.DnsAdmin);
            Assert.AreEqual("paypal", notification.Target);
            Assert.IsNotNull(notification.WholeDomain);
            Assert.AreEqual(YesNoFlag.Y, notification.WholeDomain);
        }
        protected override XDocument FormatInternal(PollResponse response)
        {
            var formatted      = CreateResponse("EPCISQueryDocument");
            var resultName     = "EventList";
            var typeOfResponse = response.Entities.GetType().GenericTypeArguments[0];

            if (typeOfResponse == typeof(EpcisEvent))
            {
                resultName = "EventList";
            }
            if (typeOfResponse == typeof(EpcisMasterData))
            {
                resultName = "VocabularyList";
            }

            formatted.Root.Add(
                new XElement("EPCISBody",
                             new XElement(XName.Get("QueryResults", EpcisNamespaces.Query),
                                          new XElement("queryName", response.QueryName),
                                          !string.IsNullOrEmpty(response.SubscriptionId) ? new XElement("subscriptionID", response.SubscriptionId) : null,
                                          new XElement("resultsBody", new XElement(resultName, XmlEntityFormatter.Format(response.Entities)))
                                          )
                             )
                );

            return(formatted);
        }
Exemple #12
0
        /*private void RunTest1()
         * {
         * var transport = new TcpTransport();
         *
         * var service = new Service(transport);
         *
         * service.Connect();
         * service.Read(); //<-- gets the greeting
         * service.Login("a3406310", "a3406310");
         * service.GetAgreement();
         * service.Logout();
         *
         * }*/

        /*private void RunTest()
         * {
         *  var service = new Service();
         *
         *  service.Connect();
         *  service.Read();//<-- gets the greeting
         *
         *  service.Login("a3406310", "a3406310");
         *
         *  //service.GetGreeting();
         *  //service.GetAgreement();
         *
         *  Console.WriteLine("Create Contact");
         *
         *  const string adminContactId = "111111";
         *
         *  var response = service.CreateContact(adminContactId, "Pepe Antonio", "Example Inc.", "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA", "+1.6478913606", "333", "+1.6478913607", "CCT", "*****@*****.**");
         *
         *  PrintResponse(response);
         *
         *  Console.WriteLine("Transfer Domain");
         *
         *  response = service.TransferDomain("testdomain.ca",null, adminContactId, null);
         *
         *  PrintResponse(response);
         *
         *  Console.WriteLine("Check Domain");
         *
         *  response = service.CheckDomain("testdomain.ca");
         *
         *  Console.WriteLine("Create Domain");
         *
         *  response = service.CreateDomain("testdomain.ca",adminContactId,adminContactId,2);
         *
         *  PrintResponse(response);
         *
         *  service.Disconnect();
         *
         * }*/

        /* public void TestGreeting(Service service)
         * {
         * service.Connect();
         * service.GetGreeting();
         * }*/

        /* private void RunTest2()
         * {
         * var transport = new TcpTransport();
         *
         * transport.Connect();
         *
         * var loging = new Login("", "", "");
         *
         * var response = service.Execute(loging);
         *
         * PrintResponse(response);
         *
         * var obj = new DomainCheck("test.ca");
         *
         * response = obj);
         *
         * PrintResponse(response);
         *
         *
         * }*/

        private void TestPollResponse1()
        {
            var eppResponse =
                new PollResponse(ToBytes(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?>
<epp xmlns=""urn:ietf:params:xml:ns:epp-1.0"">
    <response>
        <result code=""1301"">
            <msg>Command completed successfully; ack to dequeue</msg>
        </result>
        <msgQ id=""2710"" count=""2"">
            <qDate>2011-04-27T17:43:02.0Z</qDate>
            <msg lang=""en"">Domain 3406310x2-2.ca has been transferred to another Registrar.</msg>
        </msgQ>
        <resData>
            <poll:extData xmlns:poll=""urn:ietf:params:xml:ns:poll-1.0"">
                <poll:msgID>3027</poll:msgID>
                <poll:domainName>3406310x2-2.ca</poll:domainName>
            </poll:extData>
        </resData>
        <trID>
            <clTRID>95e1fc7a-b5b8-488f-84cb-9e94d4102832</clTRID>
            <svTRID>CIRA-000003594172-0000000002</svTRID>
        </trID>
    </response>
</epp>
"));

            PrintResponse(eppResponse);
        }
        /// <remarks>
        /// Timeout implementation inspired by: http://stackoverflow.com/questions/5018921/implement-c-sharp-timeout
        /// </remarks>
        public PollResponse PollEvents(long consumerVersion, string consumerName)
        {
            var ecv = this.eventCollectionVersion;

            var newEvents = new List <NewRawEvent>();

            // last received version could be somehow less than 0. I found once that was -1,
            // and was always pushing "0 events", as the signal r tracing showed (27/10/2015)
            if (consumerVersion < 0)
            {
                consumerVersion = 0;
            }

            // the consumer says that is more updated than the source. That is an error. Maybe the publisher did not started yet!
            if (ecv < consumerVersion)
            {
                return(PollResponse.CreateSerializedResponse(true, false, this.streamType, newEvents, consumerVersion, ecv));
            }

            bool newEventsWereFound = false;
            var  stopwatch          = Stopwatch.StartNew();

            while (!this.stopping && stopwatch.Elapsed < this.longPollingTimeout)
            {
                if (ecv == consumerVersion)
                {
                    // consumer is up to date, and now is waiting until something happens!
                    Thread.Sleep(1);
                    ecv = this.eventCollectionVersion; // I Forgot to update!
                }
                // weird error, but is crash proof. Once i had an error where in an infinite loop there was an error saying: Pushing 0 events to....
                // A Charly le paso. Sucede que limpio la base de datos y justo queria entregar un evento y no devolvia nada.
                else if (ecv > consumerVersion)
                {
                    newEvents = this.dao.FindEvents(consumerVersion, eventsToPushMaxCount);

                    if (newEvents.Count > 0)
                    {
                        newEventsWereFound = true;
                        this.log.Trace($"{this.SourceName} publisher is pushing {newEvents.Count} event/s to {consumerName}");
                        break;
                    }
                    else
                    {
                        // Lo que le paso a charly.
                        newEventsWereFound = false;
                        //this.log.Error($"There is an error in the event store or a racy condition. The consumer [{consumerName}] version is {consumerVersion} and the local event collection version should be {this.eventCollectionVersion} but it is not.");
                        this.bus.Publish(new FatalErrorOcurred(new FatalErrorException($"There is an error in the event store or a racy condition. The consumer [{consumerName}] version is {consumerVersion} and the local event collection version should be {this.eventCollectionVersion} but it is not.")));
                        break;
                    }
                }
                else
                {
                    // bizzare, but helpful to avoid infinite loops
                    break;
                }
            }

            return(PollResponse.CreateSerializedResponse(false, newEventsWereFound, this.streamType, newEvents, consumerVersion, ecv));
        }
Exemple #14
0
        public PollResponse PollEvents(long eventBufferVersion, string consumerName)
        {
            this.consumerEventCollectionVersion = eventBufferVersion < 0 ? 0 : eventBufferVersion;

            PollResponse clientResponse;

            while (!this.producerResponse.TryTake(out clientResponse))
            {
                Thread.Sleep(1);
            }

            if (!clientResponse.ErrorDetected &&
                clientResponse.NewEventsWereFound &&
                clientResponse.ConsumerVersion == this.consumerEventCollectionVersion && // only updates if versions are equall. Nasty errors ocurred while trying to synchronize.
                clientResponse.ProducerVersion > eventBufferVersion &&
                clientResponse.NewRawEvents.Max(x => x.EventCollectionVersion) > eventBufferVersion)
            {
                clientResponse = PollResponse.CreateSerializedResponse(false, true, clientResponse.StreamType,
                                                                       clientResponse.NewRawEvents.Where(x => x.EventCollectionVersion > eventBufferVersion).ToList(), eventBufferVersion, clientResponse.ProducerVersion);
            }
            else
            {
                clientResponse = PollResponse.CreateSerializedResponse(false, false, clientResponse.StreamType, new List <SerializedEvent>(), 0, 0);
            }

            return(clientResponse);
        }
        public async Task DeletePollResponseAsync(PollResponse response)
        {
            await InitializeAsync();

            await responseTable.DeleteAsync(response);

            await SynchronizeResponsesAsync(response.PollQuestionId);
        }
Exemple #16
0
        public static bool TryUpdateConsumer(string consumerName, PollResponse response, out ServerStatus status)
        {
            if (childContainers.ContainsKey(consumerName))
            {
                return(mainPublisher.TryUpdateConsumer(consumerName, response, out status));
            }

            throw new KeyNotFoundException($"The microservice [consumer] {consumerName} does not exist!");
        }
        public Task AddOrUpdatePollResponseAsync(PollResponse response)
        {
            Initialize();

            if (string.IsNullOrEmpty(response.Id))
            {
                return(responseTable.InsertAsync(response));
            }
            return(responseTable.UpdateAsync(response));
        }
        public override void Given()
        {
            ExpectedResponse  = new PollResponse();
            Mediator          = new Mock <IMediator>();
            Request           = new PollRequest();
            CancellationToken = new CancellationTokenSource().Token;
            Controller        = new EpcisSoapQueryController(Mediator.Object);

            Mediator.Setup(x => x.Send(Request, CancellationToken)).Returns(() => Task.FromResult(ExpectedResponse));
        }
Exemple #19
0
        public void TestPollNoMsgsResponse1()
        {
            byte[] input    = File.ReadAllBytes("PollNoMsgsResponse1.xml");
            var    response = new PollResponse(input);

            Assert.AreEqual("1300", response.Code);
            Assert.AreEqual("Command completed successfully; no messages", response.Message);

            Assert.AreEqual("ABC-12345", response.ClientTransactionId);
            Assert.AreEqual("54322-XYZ", response.ServerTransactionId);
        }
        public async Task AddOrUpdatePollResponseAsync(PollResponse response)
        {
            await InitializeAsync();

            if (string.IsNullOrEmpty(response.Id))
            {
                await responseTable.InsertAsync(response);
            }
            await responseTable.UpdateAsync(response);

            await SynchronizeResponsesAsync(response.PollQuestionId);
        }
        public override void Given()
        {
            base.Given();

            Response = new PollResponse {
                MasterdataList = new List <EpcisMasterData> {
                    new EpcisMasterData {
                        Id = "testMD", Type = "cbv:test:masterdata"
                    }
                }, QueryName = "TestQuery", SubscriptionId = "TestSubscription"
            };
        }
Exemple #22
0
 private static XElement Format(IEpcisResponse entity, CancellationToken cancellationToken)
 {
     return(entity switch
     {
         GetStandardVersionResponse standardVersion => FormatGetStandardVersionResponse(standardVersion),
         GetVendorVersionResponse vendorVersion => FormatGetVendorVersionResponse(vendorVersion),
         ExceptionResponse exception => FormatInternal(exception),
         GetQueryNamesResponse queryNames => FormatGetQueryNamesResponse(queryNames),
         GetSubscriptionIdsResponse subscriptionIds => FormatGetSubscriptionIdsResponse(subscriptionIds),
         PollResponse poll => FormatPollResponse(poll, cancellationToken),
         _ => throw new NotImplementedException($"Unable to format '{entity.GetType()}'")
     });
Exemple #23
0
        public void TestPollMsgsResponse1()
        {
            byte[] input    = File.ReadAllBytes("PollMsgsResponse1.xml");
            var    response = new PollResponse(input);

            Assert.AreEqual("1301", response.Code);
            Assert.AreEqual("Command completed successfully; ack to dequeue", response.Message);

            Assert.AreEqual("Contact deleted notification", response.Body);

            Assert.AreEqual("ABC-12345", response.ClientTransactionId);
            Assert.AreEqual("54322-XYZ", response.ServerTransactionId);
        }
Exemple #24
0
        public ServerStatus UpdateServer(PollResponse response)
        {
            this.clientResponse.Add(response);

            ServerStatus status;

            while (!this.serverStatus.TryTake(out status))
            {
                Thread.Sleep(1);
            }

            return(status);
        }
Exemple #25
0
        public IActionResult SendResponse([FromBody] PollResponseViewModel request)
        {
            var pollResponse = new PollResponse
            {
                UserId   = request.UserId,
                PollId   = request.PollId,
                Response = request.Response
            };

            _context.Add(pollResponse);
            _context.SaveChanges();
            return(NoContent());
        }
Exemple #26
0
        private async Task Listener2(object parameter)
        {
            CancellationToken cancellationToken = (CancellationToken)parameter;

            QueueStream queue = new QueueStream("localhost:50000", "Demo.Test.Listener", null);

            PollRequest pollRequest = new()
            {
                Queue       = "Order.Test.OutQ.Listener",
                WaitTimeout = 1000,
                MaxItems    = 100,
                AutoAck     = false
            };

            var messagesToAck = new ConcurrentBag <Message>();

            do
            {
                PollResponse response = await queue.Poll(pollRequest);

                if (!response.HasMessages)
                {
                    continue;
                }

                Logger.Technical().Debug($"{response.Messages.Count()} message(s) received from the PollResponse.").Log();

                Parallel.ForEach(response.Messages, async msg =>
                {
                    try
                    {
                        Assert.Equal(1, msg.Tags.Count());

                        Assert.True(Guid.TryParse(Encoding.UTF8.GetString(msg.Body), out var guid));
                        await Task.Delay(100);

                        msg.Ack();
                        Interlocked.Increment(ref touched);
                    }
                    catch (Exception ex)
                    {
                        Logger.Technical().Exception(ex).Log();
                        msg.NAck();
                    }
                });
            } while (!cancellationToken.IsCancellationRequested);

            queue.Close();
        }
    }
        public void TestMpackPollResponseWriteRead()
        {
            // Arrange
            var response = Message.Create(null, null, null, PollResponse.Create());
            var stream   = new MemoryStream();

            // Act
            response.Encode(stream, CodecId.Mpack);
            byte[] buf      = Interop.MessageDecodeEncode(CodecId.Mpack, 1, stream.GetBuffer(), stream.Length, buffer, buffer.Length);
            var    returned = Serializable.Decode <Message>(new MemoryStream(buf), CodecId.Mpack);

            // Assert
            Assert.IsTrue(response.Equals(returned));
        }
        public PollResponse PollEvents(Guid streamId, long consumerVersion, string consumerName)
        {
            var ecv = this.store.CurrentEventCollectionVersion;

            var newEvents = new SerializedEvent[0];

            // last received version could be somehow less than 0. I found once that was -1,
            // and was always pushing "0 events", as the signal r tracing showed (27/10/2015)
            if (consumerVersion < 0)
            {
                consumerVersion = 0;
            }

            // the consumer says that is more updated than the source. That is an error. Maybe the publisher did not started yet!
            if (ecv < consumerVersion)
            {
                return(PollResponse.CreateSerializedResponse(true, false, this.streamType, newEvents, consumerVersion, ecv));
            }

            bool newEventsWereFound = false;
            var  errorDetected      = false;
            var  stopwatch          = Stopwatch.StartNew();

            while (!this.stopping && stopwatch.Elapsed < this.longPollingTimeout)
            {
                if (ecv == consumerVersion)
                {
                    // consumer is up to date, and now is waiting until something happens!
                    Thread.Sleep(1);
                    ecv = this.store.CurrentEventCollectionVersion; // I Forgot to update!
                }
                // weird error, but is crash proof. Once i had an error where in an infinite loop there was an error saying: Pushing 0 events to....
                // A Charly le paso. Sucede que limpio la base de datos y justo queria entregar un evento y no devolvia nada.
                else if (ecv > consumerVersion)
                {
                    newEvents = this.store.FindEventsForConsumer(consumerVersion, ecv, streamId, this.eventsToPushMaxCount, consumerName);

                    newEventsWereFound = true;
                    this.log.Trace($"{this.streamType} publisher is pushing {newEvents.Length} event/s to {consumerName}");
                    break;
                }
                else
                {
                    // bizzare, but helpful to avoid infinite loops
                    break;
                }
            }

            return(PollResponse.CreateSerializedResponse(errorDetected, newEventsWereFound, this.streamType, newEvents, consumerVersion, ecv));
        }
Exemple #29
0
        public void TestPollInfoXmlGetAttributes()
        {
            string xml =
                @"<roar tick=""135510457230"">
				<info>
					<poll status=""ok""/>
				</info>
			</roar>"            ;

            System.Xml.XmlElement nn = RoarExtensions.CreateXmlElement(xml);

            PollResponse poll_response = (new Roar.DataConversion.Responses.Info.Poll()).Build(nn);

            Assert.IsNotNull(poll_response);
        }
        private ServerStatus TrySync(PollResponse payload)
        {
            HttpResponseMessage response;

            using (var client = this.CreateHttpClient())
            {
                response = client.PostAsJsonAsync(this.serverUrl, payload).Result;
            }
            if (response.IsSuccessStatusCode)
            {
                return(response.Content.ReadAsAsync <ServerStatus>().Result);
            }

            throw new HttpRequestException($"The attempt to make a request to {serverUrl} got a status code of {(int)response.StatusCode}.");
        }
        public IActionResult ProcessPrinterStatus([FromBody] PollRequest pollRequest)
        {
            if (pollRequest == null)
            {
                return(BadRequest("sadfasfasasdsdafasdf"));
            }

            // todo: if job is in progress, skip checking db to save time and return
            var pollResponse = new PollResponse {
                mediaTypes = new List <string>()
            };

            pollResponse.mediaTypes.AddRange(Document.GetOutputTypesFromType("text/vnd.star.markup"));
            pollResponse.jobReady = true;
            return(Ok(pollResponse.ToJson()));
        }
Exemple #32
0
        /// <summary>
        /// Sets the graph point.
        /// </summary>
        /// <param name="i">The point index.</param>
        /// <param name="response">The response from the microcontroller.</param>
        private void SetGraphPoint(int i, PollResponse response)
        {
            if (!this.UpdateGraphPlots.IsAlive)
            {
                return;
            }

            if (this.chartsSensorGraphs[i].InvokeRequired)
            {
                SetResponseCallbackGraph d = new SetResponseCallbackGraph(this.SetGraphPoint);
                this.Invoke(d, new object[] { i, response });
            }
            else
            {
                if (response.ConvertData() != null)
                {
                    foreach (Series series in this.chartsSensorGraphs[i].Series)
                    {
                        while ((series.Points.Count > 0) && ((series.Points[series.Points.Count - 1].XValue - series.Points[0].XValue) > LiveGraphLength))
                        {
                            series.Points.RemoveAt(0);
                        }

                        series.Points.Add(new DataPoint((double)response.Time, response.ConvertData()));
                        this.CreateDataPointToolTip(series.Points[series.Points.Count - 1], this.controller.SensorController.ReturnUnit(i));
                        this.chartsSensorGraphs[i].ChartAreas[0].AxisX.Maximum = response.Time;
                    }

                    this.chartsSensorGraphs[i].Width = (this.chartsSensorGraphs[i].Series[0].Points.Count * 10) + 170;
                    this.labelsSensorGraphsValues[i].Text = "Value: " + response.ConvertData();
                }
            }
        }
        /// <summary>
        /// This both polls and receives data from the elm 327.
        /// It will timeout after 300 ms and send a new command.
        /// </summary>
        private void BeginReceiving()
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

            while (true)
            {
                try
                {
                    byte[] buffer = this.controller.Serial.DataReceived();

                    if (buffer == null)
                    {
                        continue;
                    }

                    while (buffer.Contains((byte)PollResponse.StartTag))
                    {
                        if (buffer.Length < 2)
                        {
                            break;
                        }

                        int index = Array.IndexOf(buffer, (byte)PollResponse.StartTag);

                        byte length = buffer[index + 1];

                        if (buffer.Length < length + 2)
                        {
                            break;
                        }

                        byte[] data = new byte[length + 2];
                        Array.Copy(buffer, index, data, 0, length + 2);
                        PollResponse response = new PollResponse(this.controller, data);
                        this.controller.SensorData.PollResponses.Add(response);
                        if (response.DataType == "MK")
                        {
                            this.controller.MainWindow.AddGraphHighlight(response.Time);
                        }

                        if (response.DataType == "TC")
                        {
                            this.controller.TcWindow.Set_Data(response.Time, response.Data);
                        }

                        this.controller.MainWindow.GraphQueue.Enqueue(response);
                        data = new byte[buffer.Length - length - 2];
                        Array.Copy(buffer, index + length + 2, data, 0, buffer.Length - length - 2 - index);
                        buffer = data;
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Exemple #34
0
        private void TestPollResponse2()
        {
            var eppResponse =
                new PollResponse(ToBytes(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?>
<epp xmlns=""urn:ietf:params:xml:ns:epp-1.0"">
    <response>
        <result code=""1000"">
            <msg>Command completed successfully</msg>
        </result>
        <msgQ id=""2710"" count=""1""/>
        <trID>
            <clTRID>98487317-76e2-4869-99d7-833bc71ad708</clTRID>
            <svTRID>CIRA-000003594172-0000000003</svTRID>
        </trID>
    </response>
</epp>
"));

            PrintResponse(eppResponse);
        }
Exemple #35
0
        /*private void RunTest1()
       {
           var transport = new TcpTransport();

           var service = new Service(transport);

           service.Connect();
           service.Read(); //<-- gets the greeting
           service.Login("a3406310", "a3406310");
           service.GetAgreement();
           service.Logout();

       }*/

        /*private void RunTest()
        {
            var service = new Service();

            service.Connect();
            service.Read();//<-- gets the greeting

            service.Login("a3406310", "a3406310");

            //service.GetGreeting();
            //service.GetAgreement();

            Console.WriteLine("Create Contact");

            const string adminContactId = "111111";

            var response = service.CreateContact(adminContactId, "Pepe Antonio", "Example Inc.", "Toronto", "301 La Fanfan Ave.", "ON", "M5V 3T1", "CA", "+1.6478913606", "333", "+1.6478913607", "CCT", "*****@*****.**");

            PrintResponse(response);

            Console.WriteLine("Transfer Domain");

            response = service.TransferDomain("testdomain.ca",null, adminContactId, null);

            PrintResponse(response);

            Console.WriteLine("Check Domain");

            response = service.CheckDomain("testdomain.ca");
            
            Console.WriteLine("Create Domain");

            response = service.CreateDomain("testdomain.ca",adminContactId,adminContactId,2);

            PrintResponse(response);

            service.Disconnect();

        }*/

        /* public void TestGreeting(Service service)
       {
           service.Connect();
           service.GetGreeting();
       }*/

        /* private void RunTest2()
       {
           var transport = new TcpTransport();

           transport.Connect();

           var loging = new Login("", "", "");

           var response = service.Execute(loging);

           PrintResponse(response);

           var obj = new DomainCheck("test.ca");

           response = obj);

           PrintResponse(response);


       }*/

        private void TestPollResponse1()
        {
            var eppResponse =
                new PollResponse(ToBytes(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?>
<epp xmlns=""urn:ietf:params:xml:ns:epp-1.0"">
    <response>
        <result code=""1301"">
            <msg>Command completed successfully; ack to dequeue</msg>
        </result>
        <msgQ id=""2710"" count=""2"">
            <qDate>2011-04-27T17:43:02.0Z</qDate>
            <msg lang=""en"">Domain 3406310x2-2.ca has been transferred to another Registrar.</msg>
        </msgQ>
        <resData>
            <poll:extData xmlns:poll=""urn:ietf:params:xml:ns:poll-1.0"">
                <poll:msgID>3027</poll:msgID>
                <poll:domainName>3406310x2-2.ca</poll:domainName>
            </poll:extData>
        </resData>
        <trID>
            <clTRID>95e1fc7a-b5b8-488f-84cb-9e94d4102832</clTRID>
            <svTRID>CIRA-000003594172-0000000002</svTRID>
        </trID>
    </response>
</epp>
"));
            PrintResponse(eppResponse);
        }