public async Task <ActionResult> PostPoll(PollRequest request)
        {
            if (request.Answers.Count == 0 || string.IsNullOrEmpty(request.Name))
            {
                return(BadRequest("Some fields are left empty!"));
            }

            Member member = GetAuthenticatedMember();

            Poll poll = new Poll
            {
                Creator = member,
                Answers = request.Answers
                          .Select(a => new PollAnswer {
                    Answer = a.Answer
                })
                          .ToList(),
                Name         = request.Name,
                Participants = request.Participants.Select(p => new PollParticipant()
                {
                    MemberID = p.MemberID
                }).ToList()
            };

            _context.Polls.Add(poll);
            await _context.SaveChangesAsync();

            return(Ok(poll));
        }
Beispiel #2
0
        public async Task Strawpoll(string title, params string[] options)
        {
            try
            {
                var poll = new Strawpoll();

                var obj = new PollRequest()
                {
                    Title   = title,
                    Options = new List <string>()
                    {
                        options[0], options[1]
                    },
                    Multi    = false,
                    Dupcheck = DupCheck.Normal,
                    Captcha  = false
                };

                var p = await poll.CreatePollAsync(obj);

                //var pp = await poll.GetPollAsync(p.Id);

                await ReplyAsync(p.Id.ToString());
            }
            catch (Exception ex)
            {
                await ReplyAsync("error: " + ex.Message.ToString());
            }
        }
        public void CreatePollRequest_ResultsInWaitStillRunning_Test()
        {
            var request = new PollRequest <string>();
            var task    = request.WaitAsync();

            Assert.False(task.IsCompleted);
        }
        //syncSubscriptions

        internal NetNotification GetSyncMessage(string queueName, NetMessage message)
        {
            NetNotification receivedMessage             = null;
            HandoverSyncObject <NetNotification> synObj = null;

            lock (syncSubscriptions)
            {
                if (syncSubscriptions.ContainsKey(queueName))
                {
                    throw new ArgumentException("Queue " + queueName + " has already a poll runnig.");
                }
                PollRequest pr = new PollRequest();
                pr.Subscription = message;
                pr.Handover     = synObj = new HandoverSyncObject <NetNotification>();
                syncSubscriptions.Add(queueName, pr);
            }

            receivedMessage = synObj.Get();
            lock (syncSubscriptions)
            {
                syncSubscriptions.Remove(queueName);
            }

            return(receivedMessage);
        }
        public ActionResult CreatePoll([FromBody] PollRequest request)
        {
            var poll = pollDac.Get(it => it.IsClose == false);

            if (poll == null)
            {
                var newPoll = new Poll
                {
                    Id       = Guid.NewGuid().ToString(),
                    ShopName = request.ShopName,
                    CreateBy = request.CreateBy,
                    CreateAt = DateTime.Now,
                    IsClose  = false,
                    Menus    = new List <Menu>
                    {
                        new Menu
                        {
                            Id        = Guid.NewGuid().ToString(),
                            IsDefault = true,
                            MenuName  = request.MenuName,
                            Voter     = new List <string>()
                        }
                    }
                };

                pollDac.Create(newPoll);
            }
            return(Ok());
        }
        private void HandleNotification(NetMessage message)
        {
            string subscription = message.Action.NotificationMessage.Subscription;

            NetAction.DestinationType destType = message.Action.NotificationMessage.DestinationType;

            if (destType != NetAction.DestinationType.TOPIC)
            {
                lock (this.syncSubscriptions)
                {
                    string subs = message.Action.NotificationMessage.Subscription;
                    if (syncSubscriptions.ContainsKey(subscription))
                    {
                        PollRequest request = syncSubscriptions[subs];
                        request.Handover.Offer(message.Action.NotificationMessage);
                        return;
                    }
                }
            }

            lock (subscriptions)
            {
                IDictionary <string, Subscription> destSubscriptions = subscriptions[destType == NetAction.DestinationType.TOPIC ? NetAction.DestinationType.TOPIC : NetAction.DestinationType.QUEUE];

                if (destSubscriptions.ContainsKey(subscription))
                {
                    destSubscriptions[subscription].FireOnMessage(message.Action.NotificationMessage);
                }
                else
                {
                    DealWithException(new UnexpectedMessageException("No registered subscribers for received message.", message));
                }
            }
        }
        public void CreatePollRequestAndNotifyIt_ResultsInWaitTaskBeingCompleted_Test()
        {
            var expectedValue = "this is a message";
            var request       = new PollRequest <string>();
            var task          = request.WaitAsync();

            request.Notify(expectedValue);

            Assert.True(task.IsCompletedSuccessfully);
        }
        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));
        }
        public override void Given()
        {
            CancellationToken = new CancellationTokenSource().Token;
            Query             = new Mock <IEpcisQuery>();
            Request           = new PollRequest {
                QueryName = "UnknownQuery", Parameters = null
            };
            Handler = new PollHandler(new[] { Query.Object });

            Query.SetupGet(x => x.Name).Returns("ExampleQuery");
        }
Beispiel #10
0
        /// <summary>
        /// Send consumer, reading messages one by one from stream and writes
        /// to websocket stream.
        /// </summary>
        /// <returns></returns>
        protected virtual async Task SendConsumerAsync(ICodecStream <S> codec)
        {
            if (_lastMessage == null)
            {
                _lastMessage = Message.Create(StreamId, _remoteId,
                                              PollRequest.Create((ulong)_timeout.TotalMilliseconds));
            }
            while (!_open.IsCancellationRequested)
            {
                try {
                    if (_lastMessage == null)
                    {
                        if (_send.Completion.IsCompleted)
                        {
                            // Pipeline closed, close the connection
                            _receive.Complete();
                            _open.Cancel();
                            break;
                        }
                        try {
                            _lastMessage = await _send.ReceiveAsync(_timeout,
                                                                    _open.Token).ConfigureAwait(false);

                            if (_lastMessage.Content is DataMessage data)
                            {
                                data.SequenceNumber = _nextSendSequenceNumber++;
                            }
                        }
                        catch (TimeoutException) {
                            _lastMessage = Message.Create(StreamId, _remoteId,
                                                          PollRequest.Create((ulong)_timeout.TotalMilliseconds));
                        }
                        catch (OperationCanceledException) when(!_open.IsCancellationRequested)
                        {
                            _lastMessage = Message.Create(StreamId, _remoteId,
                                                          PollRequest.Create((ulong)_timeout.TotalMilliseconds));
                        }
                    }
                    await codec.WriteAsync(_lastMessage, _open.Token).ConfigureAwait(false);

                    await codec.Stream.FlushAsync(_open.Token).ConfigureAwait(false);

                    _lastMessage.Dispose();
                    _lastMessage = null;
                }
                catch (OperationCanceledException) {
                    break;
                }
                catch (Exception e) {
                    ProxyEventSource.Log.StreamException(this, codec.Stream, e);
                    break;
                }
            }
        }
Beispiel #11
0
        public override void Given()
        {
            CancellationToken = new CancellationTokenSource().Token;
            Query             = new Mock <IEpcisQuery>();
            Request           = new PollRequest {
                QueryName = "ExampleQuery", Parameters = null
            };
            Handler = new PollHandler(new [] { Query.Object });

            Query.SetupGet(x => x.Name).Returns("ExampleQuery");
            Query.Setup(x => x.Handle(It.IsAny <QueryParameter[]>(), CancellationToken)).Returns(Task.FromResult(new PollResponse()));
        }
Beispiel #12
0
        public Message Poll(Message request)
        {
            try
            {
                var pollRequest = PollRequest.Parse(XElement.Parse(request.GetReaderAtBodyContents().ReadOuterXml()));
                var results     = _eventQuery.Execute(pollRequest.Name, pollRequest.Parameters);

                return(MessageResponse.CreatePollResponse(results.Root));
            }
            catch (Exception ex)
            {
                throw EpcisFault.Create(ex);
            }
        }
        public async Task <IActionResult> PutPoll(long id, PollRequest request)
        {
            if (id != request.PollID)
            {
                return(BadRequest());
            }

            Member member = GetAuthenticatedMember();

            Poll poll = _context.Polls
                        .Where(p => p.Creator.MemberID == member.MemberID)
                        .Include(p => p.Answers)
                        .Include(p => p.Participants)
                        .FirstOrDefault(p => p.PollID == request.PollID);

            // poll doesn't exist or member has no permission to edit
            if (poll == null)
            {
                return(PollNotFound());
            }

            // TODO: check if creating new object is actually securer
            poll.Answers = request.Answers.Select(a => new PollAnswer {
                Answer = a.Answer
            }).ToList();
            poll.Name         = request.Name;
            poll.Participants = request.Participants.Select(p => new PollParticipant {
                MemberID = p.MemberID
            }).ToList();

            _context.Entry(poll).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PollExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok(poll));
        }
Beispiel #14
0
        /// <summary>
        /// Open stream
        /// </summary>
        /// <param name="ct"></param>
        /// <returns></returns>
        public Task <IMessageStream> OpenAsync(CancellationToken ct)
        {
            CreateReceiveBlock();
            CreateSendBlock();

            // Start producer receiving from poll
            _receiveTask = Task.Factory.StartNew(async() => {
                var sendTimeout = TimeSpan.FromMilliseconds(_pollTimeout * 2);
                var receiver    = new IoTHubInvoker(_hubConnectionString);
                try {
                    ulong nextSequenceNumber = 0;
                    while (true)
                    {
                        using (var request = Message.Create(_streamId, _remoteId,
                                                            PollRequest.Create(_pollTimeout, nextSequenceNumber))) {
                            var response = await receiver.TryCallAsync(
                                _link, request, sendTimeout, _open.Token).ConfigureAwait(false);
                            //
                            // Poll receives back a timeout error in case no data was available
                            // within the requested timeout. This is decoupled from the consumers
                            // that time out on their cancellation tokens.
                            //
                            if (response != null && response.Error != (int)SocketError.Timeout)
                            {
                                if (!await _receive.SendAsync(response).ConfigureAwait(false))
                                {
                                    break;
                                }
                                nextSequenceNumber++;
                            }
                        }
                        // Continue polling until closed in which case we complete receive
                        _open.Token.ThrowIfCancellationRequested();
                    }
                }
                catch (OperationCanceledException) {
                }
                catch (Exception e) {
                    ProxyEventSource.Log.HandledExceptionAsError(this, e);
                    throw;
                }
                finally {
                    receiver.Dispose();
                }
            }, _open.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap();

            return(Task.FromResult((IMessageStream)this));
        }
        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()));
        }
        public PollRequestResult Create(PollRequest request)
        {
            var poll = new Model.Poll()
            {
                Description = request.PollDescription,
                Views       = 0
            };

            _repository.Insert(poll);

            _pollOptionBusiness.Create(poll.Id, request.Options);

            return(new PollRequestResult()
            {
                PollId = poll.Id
            });
        }
Beispiel #17
0
        private async Task PollAsync(CancellationToken cancellationToken)
        {
            var closeCode = int.MinValue;

            try
            {
                using var call = this.adaptorImpl.Poll();
                while (!cancellationToken.IsCancellationRequested)
                {
                    var request = new PollRequest()
                    {
                        Token = $"{this.adaptorImpl.Token}"
                    };
                    await call.RequestStream.WriteAsync(request);

                    await call.ResponseStream.MoveNext();

                    var reply = call.ResponseStream.Current;
                    if (reply.Code != int.MinValue)
                    {
                        closeCode = reply.Code;
                        break;
                    }
                    this.InvokeCallback(reply.Items);
                    reply.Items.Clear();
                    await Task.Delay(1);
                }
                await call.RequestStream.CompleteAsync();

                await call.ResponseStream.MoveNext();
            }
            catch (Exception e)
            {
                closeCode = -1;
                GrpcEnvironment.Logger.Error(e, e.Message);
            }
            if (closeCode != int.MinValue)
            {
                this.task = null;
                await this.adaptorImpl.AbortAsync();

                this.adaptorImpl = null;
                this.OnDisconnected(new CloseEventArgs(closeCode));
            }
        }
Beispiel #18
0
        public async Task <ActionResult> Post([FromBody] PollRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try {
                Poll poll = await _pollRepository.CreatePollAsync(request.Name, request.PollDefinitionId, request.Handle, request.Description, request.IsOpen);

                _logger.LogInformation(LoggingEvents.InsertPoll, "Poll {Id} Created", poll.Id);
                return(CreatedAtRoute("GetPoll", new { controller = "Polls", id = poll.Id }, poll));
            }
            catch (Exception e) {
                _logger.LogError(LoggingEvents.InsertPoll, $"Error creating new poll: Exception {e.Message}");
                return(StatusCode(500, e.Message));
            }
        }
Beispiel #19
0
        public async Task <IActionResult> GetMyPolling([FromBody] PollRequest request)
        {
            var requestToken = request.Token ?? default;

            if (requestToken != default)
            {
                requestToken = requestToken.Minus(Duration.FromSeconds(10));
            }

#pragma warning disable MA0040 // Flow the cancellation token
            if (request.Delivered?.Length > 0)
            {
                var tokens = request.Delivered.Select(x => TrackingToken.Parse(x));

                await userNotificationStore.TrackSeenAsync(tokens);
            }

            if (request.Seen?.Length > 0)
            {
                var tokens = request.Seen.Select(x => TrackingToken.Parse(x));

                await userNotificationStore.TrackSeenAsync(tokens);
            }

            foreach (var id in request.Confirmed.OrEmpty())
            {
                var token = TrackingToken.Parse(id);

                await userNotificationStore.TrackConfirmedAsync(token);
            }
#pragma warning restore MA0040 // Flow the cancellation token

            foreach (var id in request.Deleted.OrEmpty())
            {
                await userNotificationStore.DeleteAsync(id, HttpContext.RequestAborted);
            }

            var notifications = await userNotificationStore.QueryAsync(App.Id, UserId, DefaultQuery with {
                After = requestToken
            }, HttpContext.RequestAborted);
        private void HandleFault(NetMessage message)
        {
            string msgDest = message.Action.FaultMessage.Detail;

            if (message.Action.FaultMessage.Code.Equals(NetFault.PollTimeoutErrorMessage.Action.FaultMessage.Code) ||
                message.Action.FaultMessage.Code.Equals(NetFault.NoMessageInQueueErrorMessage.Action.FaultMessage.Code))
            {
                lock (this.syncSubscriptions)
                {
                    if (syncSubscriptions.ContainsKey(msgDest))
                    {
                        PollRequest request = syncSubscriptions[msgDest];
                        if (message.Action.FaultMessage.Code.Equals(NetFault.PollTimeoutErrorMessage.Action.FaultMessage.Code))
                        {
                            request.Handover.Offer(UnblockNotification);
                        }
                        else
                        {
                            request.Handover.Offer(NoMessageNotification);
                        }
                    }
                    return;
                }
            }

            message.Action.FaultMessage.Headers = message.Headers;

            if (!PendingAcceptRequestsManager.MessageFailed(message.Action.FaultMessage))
            {
                FaultHandler handler = OnFault;
                if (handler != null)
                {
                    OnFault(message.Action.FaultMessage);
                }
            }
        }
        //syncSubscriptions
        internal NetNotification GetSyncMessage(string queueName, NetMessage message)
        {
            NetNotification receivedMessage = null;
            HandoverSyncObject<NetNotification> synObj = null;
            lock (syncSubscriptions)
            {
                if (syncSubscriptions.ContainsKey(queueName))
                    throw new ArgumentException("Queue " + queueName + " has already a poll runnig.");
                PollRequest pr = new PollRequest();
                pr.Subscription = message;
                pr.Handover = synObj = new HandoverSyncObject<NetNotification>();
                syncSubscriptions.Add(queueName, pr);
            }

            receivedMessage = synObj.Get();
            lock (syncSubscriptions)
            {
                syncSubscriptions.Remove(queueName);
            }

            return receivedMessage;
        }
Beispiel #22
0
 public Poll(PollRequest body)
     : base(body)
 {
 }
Beispiel #23
0
        protected override async Task SendConsumerAsync(
            ICodecStream <HybridConnectionStream> codec)
        {
            while (!_open.IsCancellationRequested)
            {
                try {
                    if (_lastMessage == null)
                    {
                        if (_send.Completion.IsCompleted)
                        {
                            // Pipeline closed, close the connection
                            _receive.Complete();
                            _open.Cancel();
                            break;
                        }
                        try {
                            _lastMessage = await _send.ReceiveAsync(_timeout,
                                                                    _open.Token).ConfigureAwait(false);

                            var data = _lastMessage.Content as DataMessage;
                            if (data != null)
                            {
                                data.SequenceNumber = _nextSendSequenceNumber++;
                            }
                        }
                        catch (TimeoutException) {
                            _lastMessage = Message.Create(StreamId, _remoteId,
                                                          PollRequest.Create((ulong)_timeout.TotalMilliseconds));
                        }
                        catch (OperationCanceledException) when(!_open.IsCancellationRequested)
                        {
                            _lastMessage = Message.Create(StreamId, _remoteId,
                                                          PollRequest.Create((ulong)_timeout.TotalMilliseconds));
                        }
                    }
                    //
                    // Every write on the hybrid connection stream right now results in a binary
                    // message not an individual fragment.
                    // when using the codec directly on the stream then the first write confuses the
                    // proxy decoder, which assumes a websocket message contains an entire message.
                    // Override here to buffer the entire message in a memory stream before writing.
                    //
                    using (var mem = new MemoryStream()) {
                        _lastMessage.Encode(mem, CodecId.Mpack);
                        var buffered = mem.ToArray();
                        await codec.Stream.WriteAsync(
                            buffered, 0, buffered.Length, _open.Token).ConfigureAwait(false);
                    }
                    await codec.Stream.FlushAsync(_open.Token).ConfigureAwait(false);

                    _lastMessage.Dispose();
                    _lastMessage = null;
                }
                catch (OperationCanceledException) {
                    break;
                }
                catch (Exception e) {
                    ProxyEventSource.Log.StreamException(this, codec.Stream, e);
                    break;
                }
            }
        }