Beispiel #1
0
 private void fileUploader_UploadProcessingStarted(object sender, EventArgs e)
 {
     UIDispatcher.BeginInvoke(delegate
     {
         this.State = Constants.FileStates.Processing;
     });
 }
Beispiel #2
0
        private bool CheckingBroker = false;           // проверяется ли в текущий момент брокер или нет

        public void CheckBrokerAvailability()
        {
            if (CheckingBroker)
            {
                return;
            }
            CheckingBroker = true;

            var client = new PubsubClient(BaseAddres, true);

            client.SubscribeAsync("broker", 0,
                                  (created, topicId) =>
            {
                BrokerAvailable = true;
                if (GetDispatcher != null)
                {
                    UIDispatcher = GetDispatcher();                            // получаем текущий диспетчер UI
                }
                if (BrokerAvailabilityChecked != null && UIDispatcher != null)
                {
                    UIDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => BrokerAvailabilityChecked(null, null)));
                }
                CheckingBroker = false;
            },
                                  delegate(Subscription s, PubsubMessage m)
                                  { },
                                  delegate(Subscription s, Exception ex)
            {
                BrokerAvailable = false;
                if (GetDispatcher != null)
                {
                    UIDispatcher = GetDispatcher();                                              // получаем текущий диспетчер UI
                }
                if (BrokerAvailabilityChecked != null && UIDispatcher != null)
                {
                    UIDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => BrokerAvailabilityChecked(null, null)));
                }
                CheckingBroker = false;
            }
                                  );



            //client.CreateTopicAsyncAsString("broker",
            //    delegate(int topicId)
            //    {
            //        BrokerAvailable = true;
            //        if (GetDispatcher != null) UIDispatcher = GetDispatcher();// получаем текущий диспетчер UI
            //        if (BrokerAvailabilityChecked != null && UIDispatcher != null) UIDispatcher.BeginInvoke(() => BrokerAvailabilityChecked(null, null));
            //        CheckingBroker = false;
            //    },
            //    delegate(Exception ex)
            //    {
            //        BrokerAvailable = false;
            //        if (GetDispatcher != null) UIDispatcher = GetDispatcher();// получаем текущий диспетчер UI
            //        if (BrokerAvailabilityChecked != null && UIDispatcher != null) UIDispatcher.BeginInvoke(() => BrokerAvailabilityChecked(null, null));
            //        CheckingBroker = false;
            //    }
            //);
        }
Beispiel #3
0
 private void fileUploader_UploadDataSent(object sender, UploadDataSentArgs e)
 {
     UIDispatcher.BeginInvoke(delegate
     {
         this.BytesUploaded = e.TotalDataSent;
     });
 }
 private void OnPropertyChanged([CallerMemberName] string propertyName = "")
 {
     if (PropertyChanged != null)
     {
         UIDispatcher.BeginInvoke(PropertyChanged, this, new PropertyChangedEventArgs(propertyName));
     }
 }
Beispiel #5
0
        void OutQueueWorker()
        {
            UIDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => publisher_timer.Stop()));
            // если идет публикация или количество комманд в исходящем потоке равно нулю, выходим
            if (publishing || outQueue.Value.Count == 0)
            {
                UIDispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => publisher_timer.Start()));
                publishing = true;



                // берем все накопленные в потоке данные и отсылаем скопом
                List <SubscriptionMessageCommand> messages = new List <SubscriptionMessageCommand>();
                var comm  = outQueue.Value.ToArray();
                var topic = ""; // подразумеваем, что топик у всех один
                int i     = 0;
                //SubscriptionMessageCommand.ClearCounter();// сбросим накопительную добавку к штампу команды
                int OrderInPackage = 0;
                foreach (var tuple in comm)
                {
                    topic = tuple.Item1;
                    var command          = tuple.Item2;
                    var publishingObject = tuple.Item3 as SubscriptionMessageCommand;
                    publishingObject.OrderInPackage = OrderInPackage++;
                    //string jsonObject = fastJSON.JSON.Instance.ToJSON(publishingObject);
                    //var message = new SubscriptionMessageCommand { Command = command, JsonObject = jsonObject };
                    messages.Add(publishingObject);
                }
                var jsonmessages = fastJSON.JSON.Instance.ToJSON(messages.ToArray());
                Client.PublishByStringTopicAsync(topic, jsonmessages,
                                                 (pm) =>
                {
                    string ok = "published";
                    // убираем отработанную команду из потока
                    //outQueue.Value.Remove(outQueue.Value.First());
                    outQueue.Value.RemoveRange(0, comm.Length);
                    publishing = false;
                    // повторно запускаем процедуру, чтобы отработать оставшиеся команды
                    //OutQueueWorker();
                    UIDispatcher.BeginInvoke(DispatcherPriority.Background,
                                             new Action(
                                                 () => publisher_timer.Start()));
                },
                                                 (pm, ex) =>
                {
                    string er  = "NOT PUBLISHED";
                    publishing = false;
                    // повторно запускаем процедуру, чтобы отработать оставшиеся команды. по сути циклимся на последней не отосланной
                    //OutQueueWorker();
                    UIDispatcher.BeginInvoke(DispatcherPriority.Background,
                                             new Action(
                                                 () => publisher_timer.Start()));
                }
                                                 );
            }
        }
Beispiel #6
0
        private void fileUploader_UploadCanceled(object sender, EventArgs e)
        {
            UIDispatcher.BeginInvoke(delegate
            {
                // leave the file stream open if an upload is canceled, in case the UI allows re-sending

                _fileUploader = null;
                this.State    = Constants.FileStates.Canceled;
            });
        }
Beispiel #7
0
        private void fileUploader_UploadErrorOccurred(object sender, UploadErrorOccurredEventArgs e)
        {
            UIDispatcher.BeginInvoke(delegate
            {
                // leave the file stream open if an upload caused an error, in case the UI allows re-sending

                _fileUploader     = null;
                this.ErrorMessage = e.ErrorMessage;
                this.State        = Constants.FileStates.Error;
            });
        }
Beispiel #8
0
        /// <summary>
        /// Callback when the search text is changed
        /// </summary>
        private void SearchTextChanged(object sender, TextChangedEventArgs e)
        {
            StopTimer();

            _delayTimer = new Timer((o) =>
            {
                StopTimer();

                UIDispatcher.BeginInvoke(() => UpdateSource(sender as TextBox));
            }, null, this.PlaceFinderViewModel.TypingDelayBeforeSendingRequest, Timeout.Infinite);
        }
Beispiel #9
0
        private void fileUploader_UploadFinished(object sender, EventArgs e)
        {
            UIDispatcher.BeginInvoke(delegate
            {
                // close the file stream; this file will never be accessed again with this object
                this.FileStream.Dispose();

                _fileUploader = null;
                this.State    = Constants.FileStates.Finished;
            });
        }
Beispiel #10
0
 public void RunOnUIThread(Action action, DispatcherPriority priority = DispatcherPriority.Normal)
 {
     if (UIDispatcher == null)
     {
         action();
     }
     else
     {
         UIDispatcher.BeginInvoke(action, priority);
     }
 }
Beispiel #11
0
        /// <summary>Raises the <see cref="CanExecuteChanged" /> event on the UI thread.</summary>
        public void RaiseCanExecuteChanged()
        {
            EventHandler handler = this.canExecuteChangedHandler;

            if (handler == null)
            {
                return;
            }

            UIDispatcher.BeginInvoke(() => handler(this, EventArgs.Empty));
        }
 public ProjectManager() : base()
 {
     UIDispatcher.BeginInvoke(() =>
     {
         BindingOperations.EnableCollectionSynchronization(this.DataBlocks, this._dataBlocksLock);
         BindingOperations.EnableCollectionSynchronization(this.UdtNames, this._udtNamesLock);
         BindingOperations.EnableCollectionSynchronization(this.ImportedUdts, this._importedUdtsLock);
     });
     this.DataBlocks.CollectionChanged += new NotifyCollectionChangedEventHandler((o, e) => this.FirePropertyChanged("IsReadyForExport"));
     ((INotifyCollectionChanged)this.UdtNames).CollectionChanged += new NotifyCollectionChangedEventHandler((o, e) => this.FirePropertyChanged("IsReadyForExport"));
     this.TagTables.Add(this.DefaultTagTable);
 }
        public void LogAddMessage(Log logMessage)
        {
            ManageLogCommand manageLogCommand = this.ManageLogCommand as ManageLogCommand;

            if (manageLogCommand != null && manageLogCommand.ManageLogViewModel != null && manageLogCommand.ManageLogViewModel.AllLogCollection != null)
            {
                UIDispatcher.BeginInvoke((Action) delegate()
                {
                    logMessage.Time = DateTime.Now.ToString();
                    manageLogCommand.ManageLogViewModel.AllLogCollection.Add(logMessage);
                    dataEntities.Log.Add(logMessage);
                }, null);
            }
        }
        /// <summary>
        /// Starts the lost focus timer
        /// </summary>
        private void StartLostFocusTimer()
        {
            if (_lostFocusTimer == null)
            {
                _lostFocusTimer = new Timer((o) =>
                {
                    // Stop the timer
                    StopLostFocusTimer();

                    // Deactivate the menu
                    UIDispatcher.BeginInvoke(() => this.IsActive = false);
                }, null, 750, Timeout.Infinite);
            }
        }
Beispiel #15
0
        public void Enqueue(object userState)
        {
            if (userState == null)
            {
                throw new ArgumentNullException("userState");
            }

            CurrentContext = userState as BackgroundActionContext;
            if (CurrentContext == null)
            {
                throw new NotSupportedException("Not support non BackgroundActionContext type userState");
            }

            _latestOperation = UIDispatcher.BeginInvoke(() => DoWork(userState), DispatcherPriority.Background);
        }
Beispiel #16
0
        /// <summary>
        /// Setup the interaction mode
        /// </summary>
        private void SetupInteractionMode()
        {
            if (CurrentMap != null)
            {
                _settingUpInteractionMode = true;

                var newMode = (StreetViewInteractionIsActive) ? _interactionMode : null;

                UIDispatcher.BeginInvoke(() =>
                {
                    // Set (or reset) the interaction mode
                    CurrentMap.InteractionHandler.CurrentDynamicInteractionMode = newMode;
                });

                _settingUpInteractionMode = false;
            }
        }
Beispiel #17
0
 private void OnAccountInfoUpdateDelegate(AccountInfoData acctInfoData)
 {
     Debug.WriteLine(acctInfoData.dAvailable);
     if (UIDispatcher != null)
     {
         UIDispatcher.BeginInvoke(new Action(delegate
         {
             Available      = acctInfoData.dAvailable;
             Balance        = acctInfoData.dBalance;
             CurrMargin     = acctInfoData.dCurrMargin;
             Commission     = acctInfoData.dCommission;
             FrozenMargin   = acctInfoData.dFrozenMargin;
             FrozenCash     = acctInfoData.dFrozenCash;
             CloseProfit    = acctInfoData.dCloseProfit;
             PositionProfit = acctInfoData.dPositionProfit;
             UpdateTime     = DateTime.Now;
         }));
     }
 }
Beispiel #18
0
        /// <summary>
        /// Write to the JS Console
        /// </summary>
        public void WriteToJSConsole(int level, string message)
        {
            if (JSIsConsoleAvailable())
            {
                level = Math.Min(Math.Max(0, level), LogFunctionNames.Length - 1);

                var logFunctionName = LogFunctionNames[level];

                if (JSFunctionNeedsCreation(logFunctionName))
                {
                    JSCreateConsoleFunction(logFunctionName, JSLogFunctionNames[level]);
                }

                var logger = HtmlPage.Window.Eval(logFunctionName) as ScriptObject;

                if (logger != null)
                {
                    // Workaround: Cannot call InvokeSelf outside of UI thread, without dispatcher
                    UIDispatcher.BeginInvoke(() => logger.InvokeSelf(message));
                }
            }
        }
Beispiel #19
0
        protected virtual void Evaluate()
        {
            //Print some stuff if we're in debug mode
            if (DynamoViewModel.RunInDebug)
            {
            }

            // We have caught all possible exceptions in UpdateGraph call, I am
            // not certain if this try-catch block is still meaningful or not.
            try
            {
                Exception fatalException = null;
                bool      updated        = EngineController.UpdateGraph(ref fatalException);

                // If there's a fatal exception, show it to the user, unless of course
                // if we're running in a unit-test, in which case there's no user. I'd
                // like not to display the dialog and hold up the continuous integration.
                //
                if (IsTestMode == false && (fatalException != null))
                {
                    Action showFailureMessage = () => Nodes.Utilities.DisplayEngineFailureMessage(fatalException);

                    // The "Run" method is guaranteed to be called on a background
                    // thread (for Revit's case, it is the idle thread). Here we
                    // schedule the message to show up when the UI gets around and
                    // handle it.
                    //
                    if (UIDispatcher != null)
                    {
                        UIDispatcher.BeginInvoke(showFailureMessage);
                    }
                }

                // Currently just use inefficient way to refresh preview values.
                // After we switch to async call, only those nodes that are really
                // updated in this execution session will be required to update
                // preview value.
                if (updated)
                {
                    var nodes = DynamoViewModel.Model.HomeSpace.Nodes;
                    foreach (NodeModel node in nodes)
                    {
                        node.IsUpdated = true;
                    }
                }
            }
            catch (Exception ex)
            {
                /* Evaluation failed due to error */

                dynSettings.Controller.DynamoLogger.Log(ex);

                OnRunCancelled(true);

                //If we are testing, we need to throw an exception here
                //which will, in turn, throw an Assert.Fail in the
                //Evaluation thread.
                if (IsTestMode)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
Beispiel #20
0
 private void BeginInvoke(Action action)
 {
     UIDispatcher.BeginInvoke(action);
 }
Beispiel #21
0
 internal void OnQuited()
 {
     Reset();
     UIDispatcher.BeginInvoke(Quited);
 }
Beispiel #22
0
 public void EndLongOperation()
 {
     UIDispatcher.BeginInvoke(
         new Action(EndOperation),
         DispatcherPriority.Render);
 }
Beispiel #23
0
 /// <summary>
 /// Checks all changes, done via timer
 /// </summary>
 private void TimerCheckAllChanges(object state)
 {
     UIDispatcher.BeginInvoke(CheckMapLayerChanges);
 }