Beispiel #1
0
        public override RequestQueue Execute(SensorRepository repSensors, RequestQueue LastWinner)
        {
            bool iWon = LastWinner != null && LastWinner.BehaviorName == m_Name;
            RequestQueue requests = new RequestQueue(m_Name);

            if (repSensors.SensorValueBool("IsPower") && repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_Fwd)
            {
                if(repSensors.SensorValueInt("DistL30") < repSensors.SensorValueInt("DistR30"))
                {
                    if(repSensors.SensorValueInt("DistL30") < 20 || (iWon && repSensors.SensorValueInt("DistL30") < 24))
                    {
                        requests.Enqueue(new Request() { Name = "Turn Right", Channel = "Drive", Command = "RT" });
                    }
                }
                else
                {
                    if(repSensors.SensorValueInt("DistR30") < 20 || (iWon && repSensors.SensorValueInt("DistR30") < 24))
                    {
                        requests.Enqueue(new Request() { Name = "Turn Left", Channel = "Drive", Command = "LF" });
                    }
                }
            }

            return requests;
        }
Beispiel #2
0
        public override IPAction ExecuteRest(SensorRepository repSensors, RequestQueue requests, bool iWon)
        {
            int currentDistance = repSensors.SensorValueInt("Encoder1");
            if (currentDistance == m_RequestedDistance)
            {
                // All done, move to next operator
                m_RequestedDistance = m_DesiredDistance;
                return IPAction.Increment;
            }
            else if (repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_Halt && currentDistance > 0)
            {
                // Something stopped us so start over and request the remaining distance
                m_RequestedDistance = m_DesiredDistance - currentDistance;
                return IPAction.DoFirst;
            }
            else if (repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_Fwd && m_DesiredHeading != -1)
            {
                // Heading hold
                int herr = HeadingError(repSensors.SensorValueInt("Heading"));
                int corr = m_HhPID.Calculate(herr);

                if (corr > 0)
                    requests.Enqueue(new Request() { Name = "Right Turn" + corr.ToString(), Channel = "Drive", Command = "RX" + corr.ToString() });
                else if (corr < 0)
                    requests.Enqueue(new Request() { Name = "Left Turn" + Math.Abs(corr).ToString(), Channel = "Drive", Command = "LX" + Math.Abs(corr).ToString() });
            }

            return IPAction.DoRest;
        }
Beispiel #3
0
        public override RequestQueue Execute(SensorRepository repSensors, RequestQueue LastWinner)
        {
            bool iWon = LastWinner != null && LastWinner.BehaviorName == m_Name;
            RequestQueue requests = new RequestQueue(m_Name);

            // Ignore if powered off or during a spin
            if (!repSensors.SensorValueBool("IsPower") ||
                repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_SpinCW ||
                repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_SpinCCW)
                return requests;

            if (repSensors.SensorValueInt("DistFwd") <= 8)
            {
                if (iWon || repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_Halt)
                {
                    // Halt already sent so create a NOP request to retain control
                    requests.Enqueue(new Request() { Name = "NOP", Channel = "NA", Command = "NP" });
                }
                else
                {
                    // Halt
                    requests.Enqueue(new Request() { Name = "Halt", Channel = "Drive", Command = "HL" });
                }
            }

            return requests;
        }
Beispiel #4
0
 public override IPAction ExecuteFirst(SensorRepository repSensors, RequestQueue requests, bool iWon)
 {
     if (!iWon)
     {
         requests.Enqueue(new Request() { Name = "Halt/Reset", Channel = "Drive", Command = "EH" });
         requests.Enqueue(new Request() { Name = "Fwd " + m_RequestedDistance, Channel = "Drive", Command = "FX" + m_RequestedDistance });
         return IPAction.DoFirst;
     }
     else
         return IPAction.DoRest;
 }
Beispiel #5
0
        public override RequestQueue Execute(SensorRepository repSensors, RequestQueue LastWinner)
        {
            bool iWon = LastWinner != null && LastWinner.BehaviorName == m_Name;
            RequestQueue requests = new RequestQueue(m_Name);

            if (!iWon && repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_Halt)
            {
                requests.Enqueue(new Request() { Name = "Halt/Reset", Channel = "Drive", Command = "EH" });
                requests.Enqueue(new Request() { Name = "Fwd " + m_CruiseDistance, Channel = "Drive", Command = "FX" + m_CruiseDistance });
            }

            return requests;
        }
Beispiel #6
0
        /// <summary>
        /// 添加到队列
        /// </summary>
        /// <param name="command"></param>
        public bool Enqueue(ServiceData command)
        {
            m_Logger.Debug(string.Format("服务入队。\r\nGuid:{0}。\r\n服务名称:{1}"
                                         , command.Command.Guid, command.Command.ServiceFullName));

            try
            {
                RequestQueue <ServiceData> queue = null;
                if (m_PriorityQueue.TryGetValue(command.Command.Priority, out queue))
                {
                    queue.Enqueue(command);
                    m_Logger.Debug("服务入队结束。");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                m_Logger.Debug("服务入队异常。");
                m_Logger.Fatal(string.Concat("服务入队 异常: ", ex.Message));
                m_Logger.Fatal(string.Concat("服务入队 异常: ", ex.StackTrace));
            }

            m_Logger.Debug("服务入队失败。");
            return(false);
        }
Beispiel #7
0
 protected sealed override Task <HttpResponseMessage> SendAsync(
     HttpRequestMessage request,
     CancellationToken cancellationToken)
 {
     RequestQueue.Enqueue(request);
     return(Task.FromResult(ResponseQueue.Dequeue()));
 }
        /// <summary>
        /// The one entry point, this is where requests should be sent
        /// </summary>
        public void AddJob(IJobRequest jobRequestObj)
        {
            // queue the object and notify the threadProc that there's work to do
            RequestQueue.Enqueue(jobRequestObj);

            QueueProcessHandle.Set( );
        }
        public virtual PreemptiveRequest Request(double priority = 1, bool preempt = false)
        {
            var request = new PreemptiveRequest(Environment, TriggerRelease, DisposeCallback, priority, preempt);

            RequestQueue.Enqueue(request);
            TriggerRequest();
            return(request);
        }
Beispiel #10
0
        public virtual Request Request()
        {
            var request = new Request(Environment, TriggerRelease, DisposeCallback);

            RequestQueue.Enqueue(request);
            TriggerRequest();
            return(request);
        }
Beispiel #11
0
 private void DispatchRetweetSuppression(bool suppress, Action succeeded, Action <Exception> failed)
 {
     this.IsCommunicating = true;
     RequestQueue.Enqueue(_source, new UpdateFriendshipsRequest(_target, suppress))
     .Finally(() => this.IsCommunicating = false)
     .Subscribe(_ => { },
                failed,
                succeeded);
 }
Beispiel #12
0
 private void DispatchAction(RelationKind work, Action succeeded, Action <Exception> failed)
 {
     this.IsCommunicating = true;
     RequestQueue.Enqueue(_source, new UpdateRelationRequest(_target, work))
     .Finally(() => this.IsCommunicating = false)
     .Subscribe(_ => { },
                failed,
                succeeded);
 }
Beispiel #13
0
        public override RequestQueue Execute(SensorRepository repSensors, RequestQueue LastWinner)
        {
            bool iWon = LastWinner != null && LastWinner.BehaviorName == m_Name;
            RequestQueue requests = new RequestQueue(m_Name);

            if (repSensors.SensorValueBool("IsPower") && repSensors.SensorValueInt("Direction") == (int)Cruise.MoveDir.Mov_Fwd && m_DesiredHeading != -1)
            {
                int herr = HeadingError(repSensors.SensorValueInt("Heading"));
                int corr = m_HhPID.Calculate(herr);

                if(corr > 0)
                    requests.Enqueue(new Request() { Name = "Right Turn" + corr.ToString(), Channel = "Drive", Command = "RX" + corr.ToString() });
                else if (corr < 0)
                    requests.Enqueue(new Request() { Name = "Left Turn" + Math.Abs(corr).ToString(), Channel = "Drive", Command = "LX" + Math.Abs(corr).ToString() });
            }

            return requests;
        }
Beispiel #14
0
 public override NavOperator.IPAction ExecuteFirst(SensorRepository repSensors, RequestQueue requests, bool iWon)
 {
     if (!iWon)
     {
         requests.Enqueue(new Request() { Name = "Set Speed" + m_Speed.ToString(), Channel = "Drive", Command = "S" + m_Speed.ToString() });
         return IPAction.DoFirst;
     }
     else
         return IPAction.Increment;
 }
Beispiel #15
0
 public override NavOperator.IPAction ExecuteFirst(SensorRepository repSensors, RequestQueue requests, bool iWon)
 {
     if (!iWon)
     {
         // Halt
         requests.Enqueue(new Request() { Name = "Halt", Channel = "Drive", Command = "HL" });
         return IPAction.DoFirst;
     }
     else
         return IPAction.Increment;
 }
 private void AddAsynchronRequest(Request request)
 {
     RequestQueue.Enqueue(request);
     Logger.Trace("Add new request {0}", request.RequestId);
     if (RequestQueue.Count > 0 &&
         (WorkerTask == null || WorkerTask.Status == TaskStatus.Canceled || WorkerTask.Status == TaskStatus.Faulted || WorkerTask.Status == TaskStatus.RanToCompletion))
     {
         CancelToken = new CancellationTokenSource();
         (WorkerTask = Task.Run(ServeNextRequest, CancelToken.Token)).ConfigureAwait(false);
     }
 }
Beispiel #17
0
        public override IPAction ExecuteFirst(SensorRepository repSensors, RequestQueue requests, bool iWon)
        {
            if (!iWon)
            {
                requests.Enqueue(new Request() { Name = "Halt/Reset", Channel = "Drive", Command = "EH" });

                // Calculate how many degrees to spin to get to desired heading
                int herr = HeadingError(repSensors.SensorValueInt("Heading"));
                m_RequestedCorrection = Math.Abs(herr);
                if (herr > 0)
                    requests.Enqueue(new Request() { Name = "SpinCCW " + m_RequestedCorrection.ToString(), Channel = "Drive", Command = "LX" + m_RequestedCorrection.ToString() });
                else if (herr < 0)
                    requests.Enqueue(new Request() { Name = "SpinCW " + m_RequestedCorrection.ToString(), Channel = "Drive", Command = "RX" + m_RequestedCorrection.ToString() });
                else
                    return IPAction.Increment;

                return IPAction.DoFirst;
            }
            else
                return IPAction.DoRest;
        }
Beispiel #18
0
        public void ReportAsSpam()
        {
            var msg = new TaskDialogMessage(new TaskDialogOptions
            {
                Title                   = "ユーザーをスパムとして報告",
                MainIcon                = VistaTaskDialogIcon.Warning,
                MainInstruction         = "ユーザー " + this.Status.User.ScreenName + " をスパム報告しますか?",
                Content                 = "全てのアカウントからブロックし、代表のアカウントからスパム報告します。",
                CustomButtons           = new[] { "スパム報告", "キャンセル" },
                AllowDialogCancellation = true,
            });
            var response = this.Parent.Messenger.GetResponse(msg);

            if (response.Response.CustomButtonResult != 0)
            {
                return;
            }
            // report as a spam
            var accounts = Setting.Accounts.Collection.ToArray();
            var reporter = accounts.FirstOrDefault();

            if (reporter == null)
            {
                return;
            }
            var rreq = new UpdateRelationRequest(this.User.User, RelationKind.Block);

            accounts.ToObservable()
            .SelectMany(a =>
                        RequestQueue.Enqueue(a, rreq)
                        .Do(r => BackstageModel.RegisterEvent(
                                new BlockedEvent(a.GetPserudoUser(), this.User.User))))
            .Merge(
                RequestQueue.Enqueue(reporter,
                                     new UpdateRelationRequest(this.User.User, RelationKind.ReportAsSpam))
                .Do(r =>
                    BackstageModel.RegisterEvent(
                        new BlockedEvent(reporter.GetPserudoUser(), this.User.User))))
            .Subscribe(
                _ => { },
                ex => BackstageModel.RegisterEvent(new InternalErrorEvent(ex.Message)), () =>
            {
                var tid    = this.Status.User.Id;
                var tidstr = tid.ToString(CultureInfo.InvariantCulture);
                StatusProxy.FetchStatuses(
                    s => s.User.Id == tid ||
                    (s.RetweetedOriginal != null && s.RetweetedOriginal.User.Id == tid),
                    "UserId = " + tidstr + " OR BaseUserId = " + tidstr)
                .Subscribe(s => StatusInbox.EnqueueRemoval(s.Id));
            });
        }
Beispiel #19
0
        public ResourceGroupRequest RequestGroup(IEnumerable <ResourceQuantity> requestedResources, double quantity = 1)
        {
            if (this.Resources.Count == 0)
            {
                throw new InvalidOperationException("No resources in ResourceGroup.");
            }
            if (this.Resources.Count != requestedResources.Count())
            {
                throw new InvalidOperationException("Not all resources requested.");
            }
            ResourceGroupRequest request = new ResourceGroupRequest(Environment, TriggerRelease, base.DisposeCallback, requestedResources, quantity);

            RequestQueue.Enqueue(request);
            TriggerRequest();
            return(request);
        }
Beispiel #20
0
 private IObservable <Tuple <TwitterAccount, TwitterStatus, Exception> > SendInternal(
     [NotNull] TwitterAccount account, [NotNull] RequestBase <TwitterStatus> request)
 {
     if (account == null)
     {
         throw new ArgumentNullException("account");
     }
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     return(RequestQueue.Enqueue(account, request)
            .Do(StatusInbox.Enqueue)
            .Select(s => Tuple.Create(account, s, (Exception)null))
            .Catch((Exception ex) =>
                   Observable.Return(Tuple.Create(account, (TwitterStatus)null, ex))));
 }
Beispiel #21
0
        public void FavoriteAndRetweetImmediate()
        {
            if (IsDirectMessage)
            {
                // disable on direct messages
                return;
            }
            if (!this.AssertQuickActionEnabled())
            {
                return;
            }
            var accounts = this.GetImmediateAccounts()
                           .ToObservable()
                           .Publish();

            if (!this.IsFavorited)
            {
                var freq = new FavoriteRequest(this.Status, true);
                accounts.Do(a => Task.Run(() => this.Model.AddFavoritedUser(a.Id)))
                .Do(_ => this.RaisePropertyChanged(() => this.IsFavorited))
                .SelectMany(a => RequestQueue.Enqueue(a, freq)
                            .Catch((Exception ex) =>
                {
                    Task.Run(() => this.Model.RemoveFavoritedUser(a.Id));
                    return(Observable.Empty <TwitterStatus>());
                }))
                .Do(_ => this.RaisePropertyChanged(() => this.IsFavorited))
                .Subscribe();
            }
            if (!this.IsRetweeted)
            {
                var rreq = new RetweetRequest(this.Status, true);
                accounts.Do(a => Task.Run(() => this.Model.AddRetweetedUser(a.Id)))
                .Do(_ => this.RaisePropertyChanged(() => this.IsRetweeted))
                .SelectMany(a => RequestQueue.Enqueue(a, rreq)
                            .Catch((Exception ex) =>
                {
                    Task.Run(() => this.Model.RemoveRetweetedUser(a.Id));
                    return(Observable.Empty <TwitterStatus>());
                }))
                .Do(_ => this.RaisePropertyChanged(() => this.IsRetweeted))
                .Subscribe();
            }
            accounts.Connect();
        }
Beispiel #22
0
        private void sendMessage()
        {
            if (messageTextBox.Text.Equals(""))
            {
                return;
            }

            IRCMessage message = new IRCMessage(messageTextBox.Text, true);

            Data.MessageList.AddMessage(message);

            RequestQueue outputQueue = RequestRepository.Instance.OutputRequests;

            outputQueue.Enqueue(new MessageRequest(message.Text, Companion.Login));

            UpdateMessageList();
            messageTextBox.Text = "";
        }
 public void PutRequest(Request request)
 {
     lock (this)
     {
         while (RequestQueue.Count >= MaxRequest)
         {
             try
             {
                 Monitor.Wait(this);
             }
             catch (ThreadInterruptedException)
             {
             }
         }
         RequestQueue.Enqueue(request);
         Monitor.PulseAll(this);
     }
 }
Beispiel #24
0
        public void Favorite(IEnumerable <TwitterAccount> infos, bool add)
        {
            if (IsDirectMessage)
            {
                // disable on direct messages
                return;
            }
            Action <TwitterAccount> expected;
            Action <TwitterAccount> onFail;

            if (add)
            {
                expected = a => Task.Run(() => this.Model.AddFavoritedUser(a.Id));
                onFail   = a => Task.Run(() => this.Model.RemoveFavoritedUser(a.Id));
            }
            else
            {
                expected = a => Task.Run(() => this.Model.RemoveFavoritedUser(a.Id));
                onFail   = a => Task.Run(() => this.Model.AddFavoritedUser(a.Id));
            }

            var freq = new FavoriteRequest(this.Status, add);

            infos.ToObservable()
            .Do(expected)
            .Do(_ => this.RaisePropertyChanged(() => this.IsFavorited))
            .SelectMany(a => RequestQueue.Enqueue(a, freq)
                        .Catch((Exception ex) =>
            {
                onFail(a);
                var desc = add
                                                      ? "お気に入り登録に失敗"
                                                      : "お気に入り登録解除に失敗";
                BackstageModel.RegisterEvent(new OperationFailedEvent(
                                                 desc + "(" + a.UnreliableScreenName + " -> " +
                                                 this.Status.User.ScreenName + ")", ex));
                return(Observable.Empty <TwitterStatus>());
            }))
            .Do(_ => this.RaisePropertyChanged(() => this.IsFavorited))
            .Subscribe();
        }
Beispiel #25
0
        private void ReadCallback(IAsyncResult ar)
        {
            var redisRequest = (ClientRequest)ar.AsyncState;
            var clientSocket = redisRequest.ClientSocket;
            var bytesRead    = 0;

            try
            {
                bytesRead = clientSocket.EndReceive(ar);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }


            if (bytesRead > 0)
            {
                var value = Encoding.ASCII.GetString(redisRequest.Buffer, 0, bytesRead);
                redisRequest.AddData(value);

                if (redisRequest.IsComplete())
                {
                    requestQueue.Enqueue(new Request
                    {
                        args    = redisRequest.Args,
                        command = redisRequest.Command,
                        client  = redisRequest.ClientSocket
                    });

//                    Console.WriteLine("Added request to queue");
//                    Console.WriteLine("request -->" + redisRequest.Command);

                    redisRequest.Reset();
                }
                clientSocket.BeginReceive(redisRequest.Buffer, 0, redisRequest.NumberOfBytesToRead, 0, ReadCallback, redisRequest);
            }
        }
Beispiel #26
0
            /// <summary>
            /// The one entry point, this is where requests should be sent
            /// </summary>
            public void TryPushRequest(IWebRequestObject requestObj, IResultHandler resultHandler)
            {
                // first, lock the queue
                RequestUpdateHandle.WaitOne( );

                // now we can be sure that it won't be pulled out and processed while we're trying to attach a handler.
                IWebRequestObject currObj = RequestQueue.Where(r => r.GetRequestUrl( ) == requestObj.GetRequestUrl( )).SingleOrDefault( );

                if (currObj != null)
                {
                    Rock.Mobile.Util.Debug.WriteLine(string.Format("{0} already requested. Not queueing.", currObj.GetRequestUrl( )));
                    currObj.AttachResultHandler(resultHandler);
                }
                else
                {
                    RequestQueue.Enqueue(requestObj);

                    Rock.Mobile.Util.Debug.WriteLine("Setting Wait Handle");
                    QueueProcessHandle.Set( );
                }

                // notify the thread it's ok to pull out more queue objects
                RequestUpdateHandle.Set( );
            }
Beispiel #27
0
        public void Delete()
        {
            TwitterAccount info;

            if (this.IsDirectMessage)
            {
                var ids = new[] { this.Status.User.Id, this.Status.Recipient.Id };
                info = ids
                       .Select(Setting.Accounts.Get).FirstOrDefault(_ => _ != null);
            }
            else
            {
                info = Setting.Accounts.Get(this.OriginalStatus.User.Id);
            }
            if (info == null)
            {
                return;
            }
            var dreq = new DeletionRequest(this.OriginalStatus);

            RequestQueue.Enqueue(info, dreq)
            .Subscribe(_ => StatusInbox.EnqueueRemoval(_.Id),
                       ex => BackstageModel.RegisterEvent(new OperationFailedEvent("ツイートを削除できませんでした", ex)));
        }
Beispiel #28
0
 public IActionResult AddPaymentReconciliation(PaymentReconciliation request)
 {
     RequestQueue.Enqueue(request);
     Console.WriteLine($"+++ PaymentReconciliation: {request.ProviderAccount}");
     return(Ok());
 }
Beispiel #29
0
        private void buttonEnter_Click(object sender, EventArgs e)
        {
            if (loginBox.Text.Length == 0)
            {
                MessageBox.Show("Login field is empty");
                return;
            }

            if (passwordBox.Text.Length == 0)
            {
                MessageBox.Show("Password field is empty");
                return;
            }

            FormManager.Instance.GetForm(FormType.Contacts).AddOwnedForm(this);             // просто костыль. я щас слишком спать хочу чтоб разбираться, что оно делает и почему без него не работает.

            OperationStatus.Instance.AuthFeedback = false;
            OperationStatus.Instance.AuthSuccess  = false;

            ParcedAddress address = new ParcedAddress();

            if (!Parcer.ParceAddress(addressBox.Text, address))
            {
                // if parced failed
                MessageBox.Show("Address format error! Example: 127.0.0.1:6666");
                return;
            }

            conData    = new ConnectionData(address.IP, address.Port, loginBox.Text, passwordBox.Text);
            connection = new ServerConnection();

            Session.Instance.Data = conData;
            if (!connection.Open(conData.Address, conData.Port))
            {
                MessageBox.Show("Connection failed. Host " + conData.Address + ":" + conData.Port.ToString() + " not found.");
                return;
            }
            connection.StartListen();

            ConnectionService.Instance.StartHandling(connection);

            RequestQueue outputQueue = RequestRepository.Instance.OutputRequests;

            outputQueue.Enqueue(new AuthRequest(conData.Login, conData.Password));
            while (!OperationStatus.Instance.AuthFeedback)
            {
                // do nothing
                Thread.Sleep(100);
            }

            if (!OperationStatus.Instance.AuthSuccess)
            {
                MessageBox.Show("Incorrect login/password");
                ConnectionService.Instance.Close(connection);
                return;
            }
            else
            {
                FormManager.Instance.GetForm(FormType.Contacts).Show();
            }

            outputQueue.Enqueue(new ContactListRequest());

            outputQueue.Enqueue(new MessageRequest("test", "mainadmin"));             // debugging

            this.Hide();
        }
Beispiel #30
0
        private void SendRequests(RequestQueue requests)
        {
            // Send requests out each channel
            Dictionary<string, CommLink>.ValueCollection valueColl = m_Channels.Values;
            foreach (CommLink comm in valueColl)
            {
                RequestQueue requestsChannel = new RequestQueue(requests.BehaviorName);
                foreach (Request req in requests)
                {
                    if (req.Channel == comm.Name)
                    {
                        requestsChannel.Enqueue(req);
                        m_LogEntries.AddEntry(new ActivityLogEntry(requestsChannel.BehaviorName + " sent " + req.Name + " (" + req.Command + ") via the " + req.Channel + " channel"));
                    }
                }

                if(requestsChannel.Count > 0)
                    comm.Send(requestsChannel);
            }
        }
Beispiel #31
0
 /// <summary>
 /// Adds the log event to asynchronous queue to be processed by
 /// the lazy writer thread.
 /// </summary>
 /// <param name="logEvent">The log event.</param>
 /// <remarks>
 /// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
 /// to ensure that the log event can be processed in another thread.
 /// </remarks>
 public override void Write(LogEventInfo logEvent)
 {
     WrappedTarget.PrecalculateVolatileLayouts(logEvent);
     RequestQueue.Enqueue(logEvent);
 }
Beispiel #32
0
        public IObservable <PostResult> Send()
        {
            var existedTags = TwitterRegexPatterns.ValidHashtag.Matches(Text)
                              .OfType <Match>()
                              .Select(_ => _.Groups[1].Value)
                              .Distinct()
                              .ToArray();
            var binds = !IsTagBindEnabled
                ? String.Empty
                : _boundTags.Guard().Except(existedTags)
                        .Distinct()
                        .Select(t => " #" + t)
                        .JoinString(String.Empty);
            RequestBase <TwitterStatus> request;

            if (IsDirectMessage)
            {
                request = new MessagePostingRequest(MessageRecipient, Text);
            }
            else
            {
                request = new TweetPostingRequest(Text + binds, InReplyTo,
                                                  AttachedGeoLocation, _attachedImage);
            }
            var s = Observable.Defer(() => Observable.Start(() => _accounts.Guard().ToObservable()))
                    .SelectMany(a => a)
                    .SelectMany(a => SendInternal(a, request))
                    .WaitForCompletion()
                    .Select(r => r.ToLookup(t => t.Item3 == null))
                    .Select(g =>
            {
                InputData succ  = null;
                InputData fail  = null;
                Exception[] exs = null;
                if (g.Contains(true))
                {
                    succ = this.Clone();
                    // succeeded results
                    var succeeds           = g[true].ToArray();
                    succ.AmendTargetTweets = succeeds.ToDictionary(t => t.Item1, t => t.Item2);
                    succ.Accounts          = succeeds.Select(t => t.Item1);
                }
                if (g.Contains(false))
                {
                    fail = this.Clone();
                    // failed results
                    var faileds   = g[false].ToArray();
                    fail.Accounts = faileds.Select(t => t.Item1);
                    exs           = faileds.Select(t => t.Item3).ToArray();
                }
                return(new PostResult(succ, fail, exs));
            });

            if (IsAmend)
            {
                return(AmendTargetTweets
                       .ToObservable()
                       .SelectMany(t => RequestQueue.Enqueue(t.Key, new DeletionRequest(t.Value)))
                       .Select(_ => (PostResult)null)
                       .Concat(s)
                       .Where(r => r != null));
            }
            return(s);
        }
Beispiel #33
0
 private void Enqueue(RequestContext context)
 {
     RequestQueue.Enqueue(context);
 }
        public void Test_RequestQueue_Enqueuing()
        {
            queue.Enqueue(new object());

            Assert.AreEqual(queue.Count, 1);
        }
Beispiel #35
0
 public IActionResult AddPaymentRequest(PaymentRequest request)
 {
     RequestQueue.Enqueue(request);
     Console.WriteLine($"+++ PaymentRequest: {request.PublicPaymentId}");
     return(Ok());
 }