Пример #1
1
 public TrackInfoPoller(NowPlayingTrackInfoProvider Provider, CoverManager CoverManager, Window window)
 {
     this.nowPlayingProvider = Provider;
     this.coverManager = CoverManager;
     this.window = window;
     this.dispatcher = App.Current.Dispatcher;
 }
Пример #2
0
 public void StartListen()
 {
     _dispatcher = Dispatcher.CurrentDispatcher;
     _presenceListener.StartListen();
     _onPresence = _dispatcher.Wrap<Client, Presence>(OnPresence);
     _presenceListener.PresenceReceived += _onPresence.Exec;
 }
Пример #3
0
        private void ChangeThemeCmd_Executed(object s, ExecutedRoutedEventArgs e, System.Windows.Threading.Dispatcher disp)
        {
            ThemesVM.EnTheme oldTheme = ThemesVM.EnTheme.Generic;

            try
            {
                if (e == null)
                {
                    return;
                }

                if (e.Parameter == null)
                {
                    return;
                }

                // Check if request is available
                if (e.Parameter is Themes.ThemesVM.EnTheme == false)
                {
                    return;
                }

                Themes.ThemesVM.EnTheme t = (Themes.ThemesVM.EnTheme)e.Parameter;

                oldTheme = this.Config.CurrentTheme;

                // The Work to perform on another thread
                ThreadStart start = delegate
                {
                    // This works in the UI tread using the dispatcher with highest Priority
                    disp.Invoke(DispatcherPriority.Send,
                                (Action)(() =>
                    {
                        try
                        {
                            this.Config.CurrentTheme = t;
                        }
                        catch (Exception exp)
                        {
                            logger.ErrorException(exp.Message, exp);
                            Edi.Msg.Box.Show(exp, App.IssueTrackerText, MsgBoxButtons.OK, MsgBoxImage.Error, MsgBoxResult.NoDefaultButton,
                                             App.IssueTrackerLink, App.IssueTrackerLink, App.IssueTrackerText, null, true);
                        }
                    }));
                };

                // Create the thread and kick it started!
                Thread thread = new Thread(start);

                thread.Start();
            }
            catch (Exception exp)
            {
                this.Config.CurrentTheme = oldTheme;

                logger.ErrorException(exp.Message, exp);
                Edi.Msg.Box.Show(exp, App.IssueTrackerText, MsgBoxButtons.OK, MsgBoxImage.Error, MsgBoxResult.NoDefaultButton,
                                 App.IssueTrackerLink, App.IssueTrackerLink, App.IssueTrackerText, null, true);
            }
        }
        private static void Show(Action action)
        {
            var startedEvent = new ManualResetEventSlim(initialState: false);

            System.Windows.Threading.Dispatcher dispatcher = null;
            var uiThread = new Thread(() =>
            {
                // Create and install a new dispatcher context
                SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
                dispatcher = Dispatcher.CurrentDispatcher;

                // Signal that it is initialized
                startedEvent.Set();

                // Start the dispatcher processing
                Dispatcher.Run();
            });

            // Set the apartment state
            uiThread.SetApartmentState(ApartmentState.STA);

            // Make the thread a background thread
            uiThread.IsBackground = true;

            // Start the thread
            uiThread.Start();
            startedEvent.Wait();
            dispatcher.Invoke(action);
            dispatcher.InvokeShutdown();
            uiThread.Join(1000);
            startedEvent.Dispose();
        }
Пример #5
0
        /// <summary>Called when the bootstrap application is run.</summary>
        protected override void Run()
        {
            _mainWindow  = GetApplicationUI();
            UIDispatcher = Threading.Dispatcher.CurrentDispatcher;

            if (_mainWindow != null)
            {
                try
                {
                    if (Command.Display == Wix.Display.Full ||
                        Command.Display == Wix.Display.Passive)
                    {
                        UIDispatcher        = _mainWindow.Dispatcher;
                        _mainWindow.Closed += OnWindowClosed;
                        _mainWindow.Show();
                    }

                    Engine.Detect();

                    Threading.Dispatcher.Run();

                    Engine.Quit(_mainWindow.Result);
                }
                catch (Exception ex)
                {
                    LogError(ex);
                    Engine.Quit(400);
                }
            }
            else
            {
                LogError("Failed to get an UI implementation.");
                Engine.Quit(404);
            }
        }
Пример #6
0
        private static void RequireInstance()
        {
            // Design-time is more of a no-op, won't be able to resolve the
            // dispatcher if it isn't already set in these situations.
            if (_designer || Application.Current == null)
            {
                return;
            }

            // Attempt to use the RootVisual of the plugin to retrieve a
            // dispatcher instance. This call will only succeed if the current
            // thread is the UI thread.
            try
            {
                _instance = Application.Current.Dispatcher;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("The first time SmartDispatcher is used must be from a user interface thread. Consider having the application call Initialize, with or without an instance.", e);
            }

            if (_instance == null)
            {
                throw new InvalidOperationException("Unable to find a suitable Dispatcher instance.");
            }
        }
Пример #7
0
            public Servidor(
                string tag,
                string link,
                int bytesPacote,
                int tempoResposta,
                int pingMS,
                Rectangle indicador1,
                System.Windows.Controls.Label labelTempo,
                System.Windows.Controls.Label labelnome,
                System.Windows.Controls.Label labelsemResposta,
                System.Windows.Controls.Label labelpacotes,
                System.Windows.Controls.Label labelbytes,
                Dispatcher dispatcher)

            {
                this.tag              = tag;
                this.link             = link;
                this.packetSize       = bytesPacote;
                this.tempoResposta    = tempoResposta;
                this.pingMS           = pingMS;
                this.indicador        = indicador1;
                this.labelTempo       = labelTempo;
                this.labelnome        = labelnome;
                this.labelsemResposta = labelsemResposta;
                this.labelpacotes     = labelpacotes;
                this.labelbytes       = labelbytes;
                this.Dispatcher       = dispatcher;
                this.listaTempo       = new System.Collections.Generic.List <int>();
            }
Пример #8
0
        // Dequeue the next file, load it as a BitmapImage, and return it. If there is no file, store the callback and dispatcher, to be called when the next file is enqueued.
        // If a file is under review, it will NOT be passed to the next module; it will silently exit the workflow.
        public ImageSource NextImage(NextImageCallback callback, System.Windows.Threading.Dispatcher dispatcher)
        {
            // TODO Consider reusing the dispatcher from BasicModule, which was added as part of logging.
            ImageSource returnValue = null;
            bool        gotLock     = false;

            while (!gotLock)
            {
                fileLock.Enter(ref gotLock);
            }

            // We have the lock.

            // Clear any saved callbacks; this request overrides them.
            nextImageCallback           = null;
            nextImageCallbackDispatcher = null;

            if (files.Count > 0)
            {
                // Great! We can dequeue.

                FileInfo file;

                // Get the next file to process.
                file = files.Dequeue();

                log($"ImageReviewer.NextImage: Dequeued file: {file.FullName}");

                // Save the file so we have it when the decision to accept/reject comes back.
                fileUnderReview = file;
                fileLock.Exit();

                // Load the image, AFTER exiting.
                try
                {
                    returnValue = makeImage(file);
                }
                catch (Exception e)
                {
                    log($"ImageReviewer.NextImage: makeImage threw exception: {e.Message}");
                    log("ImageReviewer.NextImage: Ignoring this image and recursing.");
                    returnValue = NextImage(callback, dispatcher);
                }
            }
            else
            {
                // Nothing to dequeue. Save a callback.

                nextImageCallback           = callback;
                nextImageCallbackDispatcher = dispatcher;

                fileLock.Exit();

                // And clear the current saved file.
                fileUnderReview = null;

                log($"ImageReviewer.NextImage: Nothing to dequeue. Saved callback.");
            }
            return(returnValue);
        }
Пример #9
0
        public void GetAndRunWpfDispatcher_invokeAndShutdown_invocationInDispatcherDone()
        {
            System.Windows.Threading.Dispatcher disp = null;
            var created = new ManualResetEvent(false);
            var t       = new Thread(x =>
            {
                disp = System.Windows.Threading.Dispatcher.CurrentDispatcher;
                created.Set();
                System.Windows.Threading.Dispatcher.Run();
            });

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            created.WaitOne();

            int    threadId = -1;
            bool   wasAct   = false;
            Action act      = () =>
            {
                wasAct   = true;
                threadId = Thread.CurrentThread.ManagedThreadId;
            };

            disp.Invoke(act);
            disp.InvokeShutdown();

            Assert.AreEqual(threadId, t.ManagedThreadId);
            Assert.That(wasAct, Is.True);
        }
        public MainViewModel()
        {
            _Dispatcher = Dispatcher.CurrentDispatcher;

            Items = new ObservableCollection<string>();
            Items.Add("Messages go here");
        }
Пример #11
0
        public ContactWatcher(Dispatcher dispatcher, ContactLoader loader, string directory, ContactWatcherEventCallback callback)
        {
            // Assert here rather than dynamically generate these arrays.  This class should include all the supported types.
            Assert.AreEqual(Contact.GetExtensionsFromType(ContactTypes.All).Split('|').Length, _Types.Length);

            var watchers = new ContactWatcherSingular[_Types.Length];
            try
            {
                for (int i = 0; i < _Types.Length; ++i)
                {
                    watchers[i] = new ContactWatcherSingular(dispatcher, loader, directory, _Types[i], callback);
                }

                _watchers = watchers;
                watchers = null;
            }
            finally
            {
                if (null != watchers)
                {
                    foreach (ContactWatcherSingular watcher in watchers)
                    {
                        if (null != watcher)
                        {
                            watcher.Dispose();
                        }
                    }
                }
            }
        }
 public UserRateListViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher, BaseEntityDTO entity)
     : base(userInterop, controllerInterop, dispatcher)
 {
     this.entity = entity;
     rates = new ObservableCollection<UserRateItemDTO>();
     Rates = new ReadOnlyObservableCollection<UserRateItemDTO>(rates);
 }
Пример #13
0
        //Constructor
        public SignalCollection(MainWindow uiWindow)
        {
            brushes = new List<SolidColorBrush>();
            brushes.Add(Brushes.MediumVioletRed);
            brushes.Add(Brushes.LightBlue);
            brushes.Add(Brushes.BurlyWood);
            brushes.Add(Brushes.LightPink);
            brushes.Add(Brushes.Yellow);
            brushes.Add(Brushes.LightGreen);
            brushes.Add(Brushes.Gold);
            window = uiWindow;
            dataDispatcher = window.Dispatcher;
            signals = new List<Signal>(0);
            this.view = uiWindow.view; //set initial view params
            //view.XMAX = 2000;
            view.YMIN = 0;
            view.YMAX = 1024;
            view.XMIN = 0;
            view.LINESCALE = 1;
            horizontals = new List<gridLine>(10);
            verticals = new List<gridLine>(10);
            plotlineH = createHLine(0,false);
            plotlineH.hideLabel();
            plotlineV = createVLine(0,false);
            plotlineV.hideLabel();
            preparePlot();

            drawWorkerDelegate w = drawWorker;
            w.BeginInvoke(null, null);

            //addSignal(true);
        }
Пример #14
0
        public SpeechMod(System.Windows.Shapes.Ellipse circle, System.Windows.Threading.Dispatcher dispatcher)
        {
            this.circle     = circle;
            this.Dispatcher = dispatcher;

            //init LifeCycleEvents..
            lce = new LifeCycleEvents("ASR", "FUSION", "speech-1", "acoustic", "command"); // LifeCycleEvents(string source, string target, string id, string medium, string mode)
            //mmic = new MmiCommunication("localhost",9876,"User1", "ASR");  //PORT TO FUSION - uncomment this line to work with fusion later
            mmic = new MmiCommunication("localhost", 8000, "User1", "ASR");                // MmiCommunication(string IMhost, int portIM, string UserOD, string thisModalityName)

            mmic.Send(lce.NewContextRequest());

            //load pt recognizer
            sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("pt-PT"));
            gr  = new Grammar(Environment.CurrentDirectory + "\\ptG.grxml", "rootRule");
            sre.LoadGrammar(gr);

            sre.SetInputToDefaultAudioDevice();
            sre.RecognizeAsync(RecognizeMode.Multiple);
            sre.SpeechRecognized   += Sre_SpeechRecognized;
            sre.SpeechHypothesized += Sre_SpeechHypothesized;

            // load speech synthetizer
            tts = new Tts();

            // introduce assistant
            Speak("Olá, eu sou o teu assistente de viagens. Tenho todo o gosto em ajudar-te a planear as tuas férias de sonho. Podes saber mais sobre mim dizendo: preciso de ajuda.", 12);
        }
Пример #15
0
        public SplashWindow()
        {
            InitializeComponent();

            //create our background worker and support cancellation
            worker = new BackgroundWorker();

            worker.DoWork += delegate(object s, DoWorkEventArgs doWorkArgs)
            {
//                try
//                {
                System.Threading.Thread.Sleep(5000);

                //And ask the WPF thread to open the next (OpenFile) Window
                System.Windows.Threading.Dispatcher winDispatcher = this.Dispatcher;
                OpenFilePageDelegate winDelegate = new OpenFilePageDelegate(this.close_click);
                //invoke the dispatcher and pass the percentage and max record count
                winDispatcher.BeginInvoke(winDelegate);
//                }
//                catch (Exception ex)
//                {
//                    ;
//                }
            };
            worker.RunWorkerAsync();
        }
 public TvVideoPage()
 {
     this.InitializeComponent();
     this.dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
     base.Loaded    += new RoutedEventHandler(this.TvVideoPage_Loaded);
     base.Unloaded  += new RoutedEventHandler(this.TvVideoPage_Unloaded);
 }
        /// <summary>
        ///     Creates a timer that is bound to the specified dispatcher and
        ///     will be processed at the specified priority, after the
        ///     specified timeout.
        /// </summary>
        /// <param name="interval">
        ///     The interval to tick the timer after.
        /// </param>
        /// <param name="priority">
        ///     The priority to process the timer at.
        /// </param>
        /// <param name="callback">
        ///     The callback to call when the timer ticks.
        /// </param>
        /// <param name="dispatcher">
        ///     The dispatcher to use to process the timer.
        /// </param>
        public DispatcherTimer(TimeSpan interval, DispatcherPriority priority, EventHandler callback, Dispatcher dispatcher) // NOTE: should be Priority
        {
            // 






            if(callback == null)
            {
                throw new ArgumentNullException("callback");
            }
            if(dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher");
            }

            if (interval.TotalMilliseconds < 0)
                throw new ArgumentOutOfRangeException("interval", SR.Get(SRID.TimeSpanPeriodOutOfRange_TooSmall));

            if (interval.TotalMilliseconds > Int32.MaxValue)
                throw new ArgumentOutOfRangeException("interval", SR.Get(SRID.TimeSpanPeriodOutOfRange_TooLarge));

            Initialize(dispatcher, priority, interval);
            
            Tick += callback;
            Start();
        }
Пример #18
0
 public CachedBitmap()
 {
     dispatcher = Dispatcher.CurrentDispatcher;
     _url = "";
     _source = null;
     _workItem = null;
 }
Пример #19
0
 public DispatcherTimer(Dispatcher dispatcher, ITaskScheduler scheduler, TimeSpan interval, DispatcherPriority priority)
 {
     this.dispatcher = dispatcher;
     this.scheduler = scheduler;
     this.Interval = interval;
     this.Priority = priority;
 }
    public VirtualPageManager( Dispatcher dispatcher,
      int pageSize, int maxRealizedItemCount, double preemptivePageQueryRatio )
    {
      if( dispatcher == null )
        throw new ArgumentNullException( "dispatcher" );

      if( pageSize < 1 )
        throw new ArgumentOutOfRangeException( "pageSize", pageSize, "pageSize must be greater than zero." );

      if( maxRealizedItemCount < pageSize )
        throw new ArgumentOutOfRangeException( "maxRealizedItemCount", maxRealizedItemCount, "maxRealizedItemCount must be greater than or equal to pageSize." );

      m_managedLists = new List<VirtualList>();
      m_pageNodes = new LinkedList<VirtualPage>();

      this.Dispatcher = dispatcher;

      m_pageSize = pageSize;
      m_maxRealizedItemCount = maxRealizedItemCount;

      m_maxRemovablePageCount = ( m_maxRealizedItemCount / m_pageSize );

      m_preemptivePageQueryRatio = preemptivePageQueryRatio;

      this.IsConnected = true;
    }
Пример #21
0
        protected override void Run()
        {
            this.Engine.Log(LogLevel.Verbose, "Launching Sparrow.Chart.Installer");
            BootstrapperDispatcher = Dispatcher.CurrentDispatcher;
            MainViewModel viewModel = new MainViewModel(this);
            viewModel.Bootstrapper.Engine.Detect();

            if (viewModel.Bootstrapper.Command.Action == LaunchAction.Install && !isInstalled)
            {
                MainView view = new MainView();
                view.DataContext = viewModel;
                view.Closed += (sender, e) => BootstrapperDispatcher.InvokeShutdown();
                view.Show();
                isInstalled = true;
            }

            if (viewModel.Bootstrapper.Command.Action == LaunchAction.Uninstall && !isUninstalled)
            {
                MainView view = new MainView();
                view.DataContext = viewModel;
                view.Closed += (sender, e) => BootstrapperDispatcher.InvokeShutdown();
                view.Show();
                isUninstalled = true;
            }

            Dispatcher.Run();

            this.Engine.Quit(0);
        }
Пример #22
0
		private void Application_Startup (object sender, StartupEventArgs e)
		{
			Panel root = new TestElement { Name = "Root" };
			root.Children.Add (CreateTemplated ("Button1"));
			d = root.Dispatcher;
			RootVisual = root;
			Delay (() => {
				Console.WriteLine ("Actual");
				Console.Write (sb.ToString ());

				Console.WriteLine ();
				Console.WriteLine ();
				Console.WriteLine (@"Expected
Button1: Loaded
Root: Loaded
Button2: Loaded
Button1: OnApplyTemplate
Button1: MeasureOverride
Button2: OnApplyTemplate
Button2: MeasureOverride
Button1: ArrangeOverride
Button2: ArrangeOverride
Root: LayoutUpdated
Button1: LayoutUpdated
Button2: LayoutUpdated");
			});
		}
        public InstituteAdminViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher, InstituteAdminDTO instituteAdmin)
            : base(userInterop, controllerInterop, dispatcher)
        {
            institutes = new List<InstituteDTO>();

            originalEntity = instituteAdmin;
        }
Пример #24
0
        public OrgStructureViewModel(string siteUrl,string subSiteUrl, StringBuilder log, string mainCheckListName)
        {
            _log = log;
            _dispatcher = Deployment.Current.Dispatcher;
            _OrgStructureServiceAgent = new OrgStructureServiceAgent(siteUrl, log);
            _mainCheckListName = mainCheckListName;
            _subSiteUrl = subSiteUrl;
            Levels = new ObservableCollection<OrgStructureEntityModel>();


            AddCommand = new RelayCommand(AddAction);
            AddCommand.IsEnabled = false;

            EditCommand = new RelayCommand(EditAction);
            EditCommand.IsEnabled = false;

            DeleteCommand = new RelayCommand(DeleteAction);
            DeleteCommand.IsEnabled = false;

            AddGlobalCommand = new RelayCommand(AddGlobalAction);
            AddGlobalCommand.IsEnabled = true;

            CancelCommand = new RelayCommand(CancelAction);
            CancelCommand.IsEnabled = true;

            _confirmDialog = new DialogService(340, 120);
            
            LoadOrgStructureEntityModel();

        }
Пример #25
0
		public DialogManager(
			ContentControl parent,
			Dispatcher dispatcher)
		{
			_dispatcher = dispatcher;
			_dialogHost = new DialogLayeringHelper(parent);
		}
        public InstituteAdminViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher)
            : base(userInterop, controllerInterop, dispatcher)
        {
            institutes = new List<InstituteDTO>();

            originalEntity = new InstituteAdminDTO() { Role = UserRoles.InstituteAdmin };
        }
Пример #27
0
      public Presenter(string[] startupArgs)
      {
         // Initialize logging system.
         Log.InitLogging();

         // Keep a handle to the current main GUI thread, so that we can have proper object
         // ownership when it comes time for this presenter to present new GUI objects.
         m_dispatcher = Dispatcher.CurrentDispatcher;

         // Create and initialize the controller for all the internal logic.
         m_controller = new SenescoController();
         m_controller.ProgressUpdated += progressUpdated;
         m_controller.Connected += connected;
         m_controller.Disconnected += disconnected;
         m_controller.ChatReceived += chatReceived;
         m_controller.UserListUpdate += userListUpdate;
         m_controller.PmReceived += pmReceived;
         m_controller.UserInfoReceived += userInfoReceived;
         m_controller.NewVersionAvailable += newVersionAvailable;

         // Create and show the main chat window.
         // Note that this creator is run in the main GUI thread, so this chat window is properly owned,
         // but other windows we create may be in different threads so we'll have to take extra care.
         m_chatWindow = new ChatWindow(this, m_controller);
         m_chatWindow.Show();

         // Process the command-line arguments.
         ProcessStartup(startupArgs);
      }
Пример #28
0
 public TaskViewModel(Dispatcher disp)
 {
     this._dispatcher = disp;
     AnnulerCommand = new GenericCommand<object>(ExecuteAnnulerCommand, CanExecuteAnnulerCommand);
     EffectuerCommand = new GenericCommand<object>(ExecuteEffectuerCommand, CanExecuteEffectuerCommand);
     DeclarerProbleme = new GenericCommand<object>(ExecuteDeclarerProblemeCommand, CanExecuteDeclarerProblemeCommand);
 }
Пример #29
0
 internal FileOpenModalDialog(Dispatcher dispatcher, Window parentWindow)
     : base(dispatcher, parentWindow)
 {
     Dialog = new CommonOpenFileDialog { EnsureFileExists = true };
     Filters = new List<FileDialogFilter>();
     FilePaths = new List<string>();
 }
Пример #30
0
        public FileWatcher(string directory, string filter)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;

            _watcher = new FileSystemWatcher();
            _watcher.BeginInit();
            _watcher.Path = directory;
            _watcher.Filter = filter;
            _watcher.IncludeSubdirectories = false;
            _watcher.InternalBufferSize = InitialBufferSize;

            _watcher.NotifyFilter
                = NotifyFilters.DirectoryName
                | NotifyFilters.FileName
                | NotifyFilters.LastWrite
                | NotifyFilters.Attributes
                | NotifyFilters.Security
                | NotifyFilters.Size;

            // note: all events are on threadpool threads!
            _watcher.Created += onCreated;
            _watcher.Deleted += onDeleted;
            _watcher.Changed += onChanged;
            _watcher.Renamed += onRenamed;
            _watcher.Error += onError;

            _watcher.EndInit();

            _watcher.EnableRaisingEvents = true;
        }
Пример #31
0
        public CathedraViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher, CathedraDTO cathedra)
            : base(userInterop, controllerInterop, dispatcher)
        {
            faculties = new List<FacultyDTO>();

            originalEntity = cathedra;
        }
Пример #32
0
        /// <summary>
        /// Creates a square image and attaches an event handler to the layout changed event that
        /// adds the the square in the upper right-hand corner of the TextView via the adornment layer
        /// </summary>
        /// <param name="view">The <see cref="IWpfTextView"/> upon which the adornment will be drawn</param>
        /// <param name="imageProvider">The <see cref="IImageProvider"/> which provides bitmaps to draw</param>
        /// <param name="setting">The <see cref="Setting"/> contains user image preferences</param>
        public ClaudiaIDE(IWpfTextView view, List<IImageProvider> imageProvider, Setting setting)
		{
		    try
		    {
		        _dispacher = Dispatcher.CurrentDispatcher;
                _imageProviders = imageProvider;
                _imageProvider = imageProvider.FirstOrDefault(x=>x.ProviderType == setting.ImageBackgroundType);
                _setting = setting;
                if (_imageProvider == null)
                {
                    _imageProvider = new SingleImageProvider(_setting);
                }
                _view = view;
                _image = new Image
                {
                    Opacity = setting.Opacity,
                    IsHitTestVisible = false
                };
                _adornmentLayer = view.GetAdornmentLayer("ClaudiaIDE");
				_view.ViewportHeightChanged += delegate { RepositionImage(); };
				_view.ViewportWidthChanged += delegate { RepositionImage(); };     
                _view.ViewportLeftChanged += delegate { RepositionImage(); };
                _setting.OnChanged += delegate { ReloadSettings(); };

                _imageProviders.ForEach(x => x.NewImageAvaliable += delegate { InvokeChangeImage(); });

                ChangeImage();
            }
			catch
			{
			}
		}
        public BackgroundDispatcher(string name)
        {
            AutoResetEvent are = new AutoResetEvent(false);

            Thread thread = new Thread((ThreadStart)delegate
            {
                _dispatcher = Dispatcher.CurrentDispatcher;
                _dispatcher.UnhandledException +=
                delegate(
                     object sender,
                     DispatcherUnhandledExceptionEventArgs e)
                {
                    e.Handled = true;
                };
                are.Set();
                Dispatcher.Run();
            });

            thread.Name = string.Format("BackgroundStaDispatcher({0})", name);
            thread.SetApartmentState(ApartmentState.MTA);
            thread.IsBackground = true;
            thread.Start();

            are.WaitOne();
            are.Close();
            are.Dispose();
        }
Пример #34
0
		internal DispatcherOperation (Dispatcher dis, DispatcherPriority prio, Delegate d, object arg)
			: this (dis, prio)
		{
			delegate_method = d;
			delegate_args = new object [1];
			delegate_args [0] = arg;
		}
Пример #35
0
		public DispatcherSynchronizationContext (Dispatcher dispatcher)
		{
			if (dispatcher == null)
				throw new ArgumentNullException ("dispatcher");

			this.dispatcher = dispatcher;
		}
Пример #36
0
        /// <summary>
        /// Thread entry point for WiX Toolset Bootstrapper Application.
        /// </summary>
        protected override void Run()
        {
            this.Engine.Log(LogLevel.Verbose, "Running the WiX BA.");
            WixBA.Model      = new Model(this);
            WixBA.Dispatcher = Threading.Dispatcher.CurrentDispatcher;
            RootViewModel viewModel = new RootViewModel();

            WixBA.View = new RootView(viewModel);

            // Create a Window to show UI.
            if (WixBA.Model.Command.Display == Display.Passive ||
                WixBA.Model.Command.Display == Display.Full)
            {
                this.Engine.Log(LogLevel.Verbose, "Creating a UI.");
                WixBA.View.Show();
            }

            // Kick off detect which will populate the view models.
            this.Engine.Detect();

            Threading.Dispatcher.Run();

            this.PostTelemetry();
            this.Engine.Quit(WixBA.Model.Result);
        }
            public MarketDataObservable(CurrencyPair currencyPair, Dispatcher dispatcher)
            {
                var spread  = currencyPair.DefaultSpread;
                var midRate = currencyPair.InitialPrice;
                var bid     = midRate - (spread * currencyPair.PipSize);
                var offer   = midRate + (spread * currencyPair.PipSize);
                var initial = new MarketData(currencyPair.Code, bid, offer);

                var currentPrice = initial;

                Value = currentPrice;

                var random = new Random();

                //for a given period, move prices by up to 5 pips
                _recurringAction = new RecurringAction(() =>
                {
                    int pips = random.Next(1, 5);
                    //move up or down between 1 and 5 pips
                    var adjustment        = Math.Round(pips * currencyPair.PipSize, currencyPair.DecimalPlaces);
                    MarketData marketData = random.NextDouble() > 0.5
                                                ? currentPrice + adjustment
                                                : currentPrice - adjustment;

                    dispatcher.Invoke(() =>
                                      Value = marketData, DispatcherPriority.Background);
                }, () => TimeSpan.FromSeconds(1 / (double)currencyPair.TickFrequency));
            }
Пример #38
0
 /// <summary>
 ///     This API supports the Entity Framework infrastructure and is not intended to be used directly from your code.
 /// </summary>
 /// <param name="disposing">This API supports the Entity Framework infrastructure and is not intended to be used directly from your code.</param>
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (disposing)
         {
             if (_xmlModel != null)
             {
                 try
                 {
                     _xmlModel.Dispose();
                 }
                 finally
                 {
                     _xmlModel = null;
                 }
             }
         }
         _dispatcher = null;
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
 public RemoveClientFromUserListTask(Dispatcher disp, TaskHandler handler, ClientConnectionList list, ClientConnection client, ObservableCollection<UserLocation> locs)
     : base(disp, handler)
 {
     ClientConnectionList = list;
     ClientConnection = client;
     UserLocations = locs;
 }
Пример #40
0
 public MainWindow(MyExtMainWrapper extMainWrapper, MainWindowWrapper mainWindowWrapper, Dispatcher theSodAccessDispatcher)
 {
     this.Closing += MainWindow_Closing;
     this.Topmost = true;
     InitializeComponent();
     CustomEventsInit();
 }
 private static void GuardUiaServerInvocation(Action invocation, Dispatcher dispatcher)
 {
     if (dispatcher == null)
         throw new ElementNotAvailableException();
     Exception remoteException = null;
     bool completed = false;
     dispatcher.Invoke(DispatcherPriority.Send, TimeSpan.FromMinutes(3.0), (Action)(() =>
     {
         try
         {
             invocation();
         }
         catch (Exception e)
         {
             remoteException = e;
         }
         catch
         {
             remoteException = null;
         }
         finally
         {
             completed = true;
         }
     }));
     if (completed)
     {
         if (remoteException != null)
             throw remoteException;
     }
     else if (dispatcher.HasShutdownStarted)
         throw new InvalidOperationException("AutomationDispatcherShutdown");
     else
         throw new TimeoutException("AutomationTimeout");
 }
Пример #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TaskEvents"/> class with the specified <see
        /// cref="SysDispatcher"/>.</summary>
        /// <param name="dispatcher">
        /// The <see cref="SysDispatcher"/> used to marshal calls to the foreground thread. This
        /// argument may be a null reference.</param>

        public TaskEvents(SysDispatcher dispatcher)
        {
            Dispatcher = dispatcher;

            // create & start timer
            Timer = new Stopwatch();
            Timer.Start();
        }
Пример #43
0
        private void ProcessSingleFile(string filename)
        {
            _rowsProcessed         = 0;
            _inputFileStreamLength = 0;
            _jaggedLines           = 0;
            // get the salt from the text box, which may or may not be visible..
            _salt = txtSalt.Text;

            System.Windows.Threading.Dispatcher dispatcher = Dispatcher;

            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;

            bool wasCancelled = false;
            int  columnIndexSelectedAsNHSNumber = cmbNHSNumber.SelectedIndex;

            // anonymous delegate, this could be moved out for readability?
            worker.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                if (MainWork(filename, columnIndexSelectedAsNHSNumber, dispatcher, ref wasCancelled))
                {
                    return;
                }
            };

            worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
            {
                string configWriteLine = "";
                if (!wasCancelled)
                {
                    configWriteLine = "Processing Finished At: " + DateTime.Now;
                    UpdateProgressDelegate update = new UpdateProgressDelegate(UpdateProgressText);
                    dispatcher.BeginInvoke(update, _inputFileStreamLength, _inputFileStreamLength, _rowsProcessed, _validNHSNumCount, _inValidNHSNumCount, _missingNHSNumCount);
                }
                else
                {
                    configWriteLine = "Processing Cancelled At: " + DateTime.Now;
                }

                var writeConfigStream = new FileStream(_outputRunLogFileName, FileMode.Append, FileAccess.Write);
                using (StreamWriter streamConfigWriter = new StreamWriter(writeConfigStream))
                {
                    streamConfigWriter.WriteLine(configWriteLine);
                    streamConfigWriter.WriteLine("Lines Processed: " + _rowsProcessed);
                    streamConfigWriter.WriteLine("Jagged Lines: " + _jaggedLines);
                    if (_performNHSNumberValidation)
                    {
                        streamConfigWriter.WriteLine("Valid NHSNumbers (10 character number found and passed checksum) : " + _validNHSNumCount);
                        streamConfigWriter.WriteLine("Invalid NHSNumbers (data was present but failed the checksum) : " + _inValidNHSNumCount);
                        streamConfigWriter.WriteLine("Missing NHSNumbers (blank string or space) : " + _missingNHSNumCount);
                    }
                }

                SignRunLogFile();
            };

            worker.RunWorkerAsync();
        }
        public MarketDataService(IStaticData staticData, Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;

            foreach (var item in staticData.CurrencyPairs)
            {
                _marketDataObservables[item.Code] = CreateObservableMarketData(item);
            }
        }
Пример #45
0
 public SuggestionInput()
 {
     m_uiDispatcher = t.Dispatcher.CurrentDispatcher;
     m_timer        = new t.DispatcherTimer
     {
         Interval  = TimeSpan.FromMilliseconds(300),
         IsEnabled = false
     };
     m_timer.Tick += OnFetch;
 }
Пример #46
0
        private List <EncryptedSaltDTO> SaltCollectMainWork(System.Windows.Threading.Dispatcher dispatcher, string address, string username, string password)
        {
            // try and connect to the KeyServer to get the public key
            var client = new RestClient(address);


            // call the API and get a list  of files they own
            client.Authenticator = new HttpBasicAuthenticator(username, password);
            var request = new RestRequest("Salt", Method.GET);

            List <EncryptedSaltDTO> myDtos     = new List <EncryptedSaltDTO>();
            List <EncryptedSaltDTO> shareddtos = new List <EncryptedSaltDTO>();

            IRestResponse <List <EncryptedSaltDTO> > response = client.Execute <List <EncryptedSaltDTO> >(request);

            // the restclient throws an exeception when trying to automatically deserialise our object, so we use Newtonsoft instead:
            using (Stream ms = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
            {
                myDtos = JsonConvert.DeserializeObject <List <EncryptedSaltDTO> >(new StreamReader(ms).ReadToEnd());
            }

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                // OK bind
            }
            else
            {
                //return errro;
            }



            // call the API and get a list  of files they can acess via shares
            request = new RestRequest("ShareSalt", Method.GET);

            response = client.Execute <List <EncryptedSaltDTO> >(request);
            // the restclient throws an exeception when trying to automatically deserialise our object, so we use Newtonsoft instead:
            using (Stream ms = new MemoryStream(Encoding.UTF8.GetBytes(response.Content)))
            {
                shareddtos = JsonConvert.DeserializeObject <List <EncryptedSaltDTO> >(new StreamReader(ms).ReadToEnd());
            }

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                // OK bind
            }
            else
            {
                //return errro;
            }

            // concatenate and return
            return(myDtos.Union(shareddtos).ToList());
        }
Пример #47
0
        public static void DoEvents(this System.Windows.Threading.Dispatcher dispatcher)
        {
            var frame = new DispatcherFrame();
            Action <DispatcherFrame> action = _ => { frame.Continue = false; };

            dispatcher.BeginInvoke(
                DispatcherPriority.SystemIdle,
                action,
                frame);
            Dispatcher.PushFrame(frame);
        }
Пример #48
0
 /// <summary>
 /// Invoke or execute
 /// </summary>
 /// <param name="dispatcher">The dispatcher</param>
 /// <param name="action">Action object</param>
 public static void InvokeOrExecute(this System.Windows.Threading.Dispatcher dispatcher, Action action)
 {
     if (dispatcher.CheckAccess())
     {
         action();
     }
     else
     {
         dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
     }
 }
 public DirectoryTreeWatcher(DirectoryTree target, int side, string path, System.Windows.Threading.Dispatcher disp, ChangeHandler Change,
                             HashSet <string> fullTextExtensions,
                             PleaseWait initProgress)
 {
     this.target             = target;
     this.side               = side;
     this.path               = path;
     this.Change            += Change;
     this.disp               = disp;
     this.fullTextExtensions = fullTextExtensions;
     init(initProgress);
 }
Пример #50
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //this.pictureBox1.Visible = true;


            this.backgroundWorker1.RunWorkerAsync();

            _dispatcher = Dispatcher.CurrentDispatcher;
            ShowColumnGraph(GetTableData());

            ShowLineGraph();
        }
Пример #51
0
 /// <summary>Sets the main window to the specified <paramref name="window"/>.</summary>
 /// <param name="window">The new main window.</param>
 public void SetMainWindow(BaseBAWindow window)
 {
     if (window == null)
     {
         Exception error = new ArgumentNullException("window");
         LogError(error);
         throw error;
     }
     _mainWindow.Closed -= OnWindowClosed;
     _mainWindow         = window;
     _mainWindow.Closed += OnWindowClosed;
     UIDispatcher        = _mainWindow.Dispatcher;
 }
Пример #52
0
        /// <summary>
        /// Starts the dispatcher on the main thread.
        /// </summary>
        /// <param name="thread">The thread.</param>
        /// <remarks>
        /// If the method has already been called previously, this new call will silently fail.
        /// </remarks>
        internal static void Run(Thread thread)
        {
            if (s_mainThreadDispather != null)
            {
                return;
            }

            s_mainThreadDispather = ThreadDispatcher.FromThread(thread) ?? ThreadDispatcher.CurrentDispatcher;

            s_oneSecondTimer = new DispatcherTimer(TimeSpan.FromSeconds(1),
                                                   DispatcherPriority.Background,
                                                   OneSecondTickTimer_Tick,
                                                   s_mainThreadDispather);
        }
        public static void Wait(System.Windows.Threading.Dispatcher Dispatcher, int Milliseconds)
        {
            var Frame = new DispatcherFrame();

            ThreadPool.QueueUserWorkItem(State =>
            {
                Thread.Sleep(Milliseconds);
                Frame.Continue = false;
            });

            MessageBox.Show("Complete!");
            Dispatcher.PushFrame(Frame);
            MessageBox.Show("Complete 2!");
        }
Пример #54
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Microsoft.Research.Science.Data.Utilities.DataSetReplicator"/> class.
        /// </summary>
        /// <param name="source">Source.</param>
        /// <param name="wpfDispatcher">Wpf dispatcher.</param>
        public DataSetReplicator(DataSet source, WPFDispatcher wpfDispatcher)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (wpfDispatcher == null)
            {
                throw new ArgumentNullException("wpfDispatcher");
            }

            this.source        = source;
            this.wpfDispatcher = wpfDispatcher;

            DataSetCommittedEventManager.AddListener(source, this);
        }
Пример #55
0
        public MainForm()
        {
            InitializeComponent();

            _dispatcher = Dispatcher.CurrentDispatcher;

            CreateHeader();

            this.ItemLinkLabel.Enabled = false;


            this.PathText.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
#if DEBUG
            this.PathText.Text = @"C:\Users\078134995";
#endif
        }
Пример #56
0
        /// <summary>
        /// Initializes a new instance of the DelayInvoker class.
        /// </summary>
        /// <param name="dispatcher">The Dispatcher to execute the action.</param>
        /// <param name="action">The action to execute with delay. Null is allowed.</param>
        /// <param name="delayTime">Time to wait before executing the action.</param>
        /// <param name="dispatcherPriority">The priority at which execute the action.</param>
        /// <param name="delegatePriority">The dispatcher priority to use for methods and properties of this class if the caller is not in the thread for dispatcher.</param>
        public DelayInvoker(TheDispatcher dispatcher, Action action, TimeSpan delayTime, TheDispatcherPriority dispatcherPriority, TheDispatcherPriority delegatePriority)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException(nameof(dispatcher));
            }

            _dispatcher       = dispatcher;
            _action           = action;
            _delegatePriority = delegatePriority;

            // Creates a timer.
            _dispatcherTimer          = new TheDispatcherTimer(dispatcherPriority, dispatcher);
            _dispatcherTimer.Interval = delayTime;
            _dispatcherTimer.Tick    += DispatcherTimer_Tick;
        }
Пример #57
0
        /************************************************************************************************************************************/
        /* Constructors */
        /************************************************************************************************************************************/
        /// <summary>
        /// Initializes a shared virtual bus to act as a communication channel between modules.
        /// </summary>
        /// <param name="dispatcher">A dispatcher used to run event notifications on the GUI thread.</param>
        public VirtualBus(System.Windows.Threading.Dispatcher dispatcher)
        {
            Debug.Write("Initializing the virtual bus...\n");
            _updatedNodes = Queue.Synchronized(new Queue());
            _nodes        = new ConcurrentDictionary <BusNode, NodeEntry>();
            _dispatcher   = dispatcher;

            foreach (BusNode node in BusNode.Values)
            {
                if (!IsValidType(node.NodeType))
                {
                    throw new ArgumentException("Cannot initialize a node of type '" + node.NodeType.Name + "' as the type is not serializable.");
                }

                _nodes[node] = new NodeEntry(node, null, new List <VirtualBus.OnValueChangedCallback>());
            }
        }
 private void FitToBounds(System.Windows.Threading.Dispatcher dispatcher, ZoomControl zoom)
 {
     if (dispatcher != null)
     {
         dispatcher.BeginInvoke(new Action(()
                                           =>
         {
             zoom.ZoomToFill();
             zoom.Mode = ZoomControlModes.Custom;
             //zoom.FitToBounds();
         }), DispatcherPriority.Loaded);
     }
     else
     {
         zoom.ZoomToFill();
         zoom.Mode = ZoomControlModes.Custom;
     }
 }
Пример #59
0
        public DispatcherQueue(System.Windows.Threading.Dispatcher dispatcher)
        {
            InitializeComponent();

            // set data context to enable binding
            DataContext = this;

            // start a timer that is used to update the input field every second
            perSecondTimer          = new DispatcherTimer(DispatcherPriority.Normal);
            perSecondTimer.Tick    += new EventHandler(perSecondTimer_Tick);
            perSecondTimer.Interval = new TimeSpan(0, 0, 1);
            perSecondTimer.Start();

            // remember the dispatcher that should be monitored
            this.dispatcher = dispatcher;
            // add a hook to the dispatcher that is monitored
            dispatcher.Hooks.OperationPosted += new System.Windows.Threading.DispatcherHookEventHandler(Hooks_OperationPosted);
        }
Пример #60
0
        public PythonScriptRunner(string scriptDirectory, string exeLocation)
        {
            _scriptDirectory  = scriptDirectory;
            _fileToRun        = @"\run_no_gui.py";
            _programArguments = _scriptDirectory + @"\config.txt";
            _exeLocation      = exeLocation;
            _isRunning        = false;
            _jsonDirectory    = _scriptDirectory + @"\json\";
            _jsonReader       = PythonScriptRunnerFactory.Instance.CreateJsonReader();

            // hopefully nobody creates this guy outside of the main thread
            _threadDispatcherOnConstruction = System.Windows.Threading.Dispatcher.CurrentDispatcher;

            // later I want to use c# processes instead of python proceses:
            // branchList = run_cmd(pythonScriptDirectory+"\run_get_branches.py", "");
            // for branchList:
            //      run_cmd(pythonScriptDirectory+"\run_no_gui.py", "branchName");
            // for processList:
            //      if process.processHasFinished:
            //          send back data to parent (the view) that it needs to update that branch's visualisation
        }