System.Windows.Threading.Dispatcher.Invoke(System.Delegate, System.TimeSpan, System.Windows.Threading.DispatcherPriority, params object[])

Here are the examples of the csharp api System.Windows.Threading.Dispatcher.Invoke(System.Delegate, System.TimeSpan, System.Windows.Threading.DispatcherPriority, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

890 Examples 7

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async Task GetTodoList(bool isAppStarting)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();
            if (!accounts.Any())
            {
                SignInButton.Content = SignInString;
                return;
            }

            // Get an access token to call the To Do service.
            AuthenticationResult result = null;
            try
            {
                result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                    .ExecuteAsync()
                    .ConfigureAwait(false);

                Dispatcher.Invoke(
                    () =>
                    {
                        SignInButton.Content = ClearCacheString;
                        SetUserName(result.Account);
                    });
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                if (!isAppStarting)
                {
                    MessageBox.Show("Please sign in to view your To-Do list");
                    SignInButton.Content = SignInString;
                }
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }
                MessageBox.Show(message);

                UserName.Content = Properties.Resources.UserNotSignedIn;
                return;
            }

            // Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do list service.
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Call the To Do list service.
            HttpResponseMessage response = await _httpClient.GetAsync(TodoListApiAddress);

            if (response.IsSuccessStatusCode)
            {
                // Read the response and data-bind to the GridView to display To Do items.
                string s = await response.Content.ReadreplacedtringAsync();
                List<TodoItem> toDoArray = JsonConvert.DeserializeObject<List<TodoItem>>(s);

                Dispatcher.Invoke(() =>
                {
                    TodoList.ItemsSource = toDoArray.Select(t => new { t.replacedle });
                });
            }
            else
            {
                await DisplayErrorMessage(response);
            }
        }

19 View Source File : FaceVerificationPage.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void PersonImageFolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            var faceServiceClient = FaceServiceClientHelper.GetInstance(this);
            // Test whether the group already exists
            try
            {
                MainWindow.Log("Request: Group {0} will be used to build a person database. Checking whether the group exists.", GroupName);

                await faceServiceClient.LargePersonGroup.GetAsync(GroupName);
                groupExists = true;
                MainWindow.Log("Response: Group {0} exists.", GroupName);
            }
            catch (APIErrorException ex)
            {
                if (ex.Body.Error.Code != "LargePersonGroupNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Group {0} did not exist previously.", GroupName);
                }
            }

            if (groupExists)
            {
                var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setting up a new person database. Click OK to proceed, group \"{0}\" will be cleared.", GroupName), "Warning", MessageBoxButton.OKCancel);
                if (cleanGroup == MessageBoxResult.OK)
                {
                    await faceServiceClient.LargePersonGroup.DeleteAsync(GroupName);
                    PersonVerifyResult = string.Empty;
                    Person.Faces.Clear();
                }
                else
                {
                    return;
                }
            }

            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            // Set the suggestion count is intent to minimum the data preparation step only,
            // it's not corresponding to service side constraint
            const int SuggestionCount = 15;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                FacesCollection.Clear();
                PersonVerifyButton.IsEnabled = (FacesCollection.Count != 0 && RightFaceResultCollection.Count != 0);

                // Call create large person group REST API
                // Create large person group API call will failed if group with the same name already exists
                MainWindow.Log("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.LargePersonGroup.CreateAsync(GroupName, GroupName, recognitionModel: recognitionModel);
                    MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (APIErrorException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                    return;
                }

                int processCount = 0;
                bool forceContinue = false;

                MainWindow.Log("Request: Preparing person for verification, detecting faces in chosen folder.");

                // Enumerate top level directories, each directory contains one person's images

                var tasks = new List<Task>();
                var tag = System.IO.Path.GetFileName(dlg.SelectedPath);
                Person = new Person();
                Person.PersonName = tag;

                var faces = new ObservableCollection<Face>();
                Person.Faces = faces;

                // Call create person REST API, the new create person id will be returned
                MainWindow.Log("Request: Creating person \"{0}\"", Person.PersonName);
                Person.PersonId =
                    (await faceServiceClient.LargePersonGroupPerson.CreateAsync(GroupName, Person.PersonName)).PersonId.ToString();
                MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", Person.PersonName, Person.PersonId);

                string img;
                var imageList =
                    new ConcurrentBag<string>(
                        Directory.EnumerateFiles(dlg.SelectedPath, "*.*", SearchOption.AllDirectories)
                            .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif")));

                // Enumerate images under the person folder, call detection
                int invalidImageCount = 0;
                while (imageList.TryTake(out img))
                {
                    tasks.Add(Task.Factory.StartNew(
                        async (obj) =>
                        {
                            var imgPath = obj as string;

                            using (var fStream = File.OpenRead(imgPath))
                            {
                                try
                                {
                                    var persistFace =
                                        await
                                            faceServiceClient.LargePersonGroupPerson.AddFaceFromStreamAsync(GroupName, Guid.Parse(Person.PersonId), fStream, imgPath, detectionModel: detectionModel);
                                    return new Tuple<string, PersistedFace>(imgPath, persistFace);
                                }
                                catch (APIErrorException ex)
                                {
                                    // if operation conflict, retry.
                                    if (ex.Body.Error.Code.Equals("ConcurrentOperationConflict"))
                                    {
                                        imageList.Add(imgPath);
                                        return null;
                                    }
                                    // if operation cause rate limit exceed, retry.
                                    else if (ex.Body.Error.Code.Equals("RateLimitExceeded"))
                                    {
                                        imageList.Add(imgPath);
                                        return null;
                                    }
                                    else if (ex.Body.Error.Message.Contains("more than 1 face in the image."))
                                    {
                                        Interlocked.Increment(ref invalidImageCount);
                                    }
                                    // Here we simply ignore all detection failure in this sample
                                    // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                    return new Tuple<string, PersistedFace>(imgPath, null);
                                }
                            }
                        },
                        img).Unwrap().ContinueWith((detectTask) =>
                        {
                            // Update detected faces for rendering
                            var detectionResult = detectTask?.Result;
                            if (detectionResult?.Item2 == null)
                            {
                                return;
                            }

                            this.Dispatcher.Invoke(
                                new Action
                                    <ObservableCollection<Face>, string, PersistedFace>(
                                    UIHelper.UpdateFace),
                                FacesCollection,
                                detectionResult.Item1,
                                detectionResult.Item2);
                        }));
                    processCount++;

                    if (processCount >= SuggestionCount && !forceContinue)
                    {
                        var continueProcess =
                            System.Windows.Forms.MessageBox.Show(
                                "The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?",
                                "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                        {
                            forceContinue = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                    {
                        await Task.WhenAll(tasks);
                        tasks.Clear();
                    }
                }

                Person.Faces = FacesCollection;

                PersonVerifyButton.IsEnabled = (FacesCollection.Count != 0 && RightFaceResultCollection.Count != 0);

                if (invalidImageCount > 0)
                {
                    MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount);
                }
                MainWindow.Log("Response: Success. Total {0} faces are detected.", Person.Faces.Count);
            }
            GC.Collect();
        }

19 View Source File : FrameworkElementAnimations.cs
License : MIT License
Project Creator : angelsix

public static void MarqueeAsync(this FrameworkElement element, float seconds = 3f)
        {
            // Create the storyboard
            var sb = new Storyboard();

            // Run until element is unloaded
            var unloaded = false;

            // Monitor for element unloading
            element.Unloaded += (s, e) => unloaded = true;

            // Run a loop off the caller thread
            TaskManager.Run(async () =>
            {
                // While the element is still available, recheck the size
                // after every loop in case the container was resized
                while (element != null && !unloaded)
                {
                    // Create width variables
                    var width = 0d;
                    var innerWidth = 0d;

                    try
                    {
                        // Check if element is still loaded
                        if (element == null || unloaded)
                            break;

                        // Try and get current width
                        width = element.ActualWidth;
                        innerWidth = ((element as Border).Child as FrameworkElement).ActualWidth;
                    }
                    catch
                    {
                        // Any issues then stop animating (presume element destroyed)
                        break;
                    }

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        // Add marquee animation
                        sb.AddMarquee(seconds, width, innerWidth);

                        // Start animating
                        sb.Begin(element);

                        // Make page visible
                        element.Visibility = Visibility.Visible;
                    });

                    // Wait for it to finish animating
                    await Task.Delay((int)seconds * 1000);

                    // If this is from first load or zero seconds of animation, do not repeat
                    if (seconds == 0)
                        break;
                }
            });
        }

19 View Source File : CountdownControl.cs
License : MIT License
Project Creator : AntonyCorbett

public void Stop()
        {
            Dispatcher.Invoke(() =>
            {
                if (_donut == null || _secondsBall == null || _pie == null || _time == null)
                {
                    return;
                }

                _timer!.Stop();

                Animations.FadeOut(
                    this, 
                    new FrameworkElement[] { _donut, _secondsBall, _pie, _time },
                    (sender, args) =>
                    {
                        Visibility = Visibility.Hidden;
                    });
            });
        }

19 View Source File : WebDisplayManager.cs
License : MIT License
Project Creator : AntonyCorbett

public void ShowMirror()
        {
            Log.Logger.Debug("Attempting to open mirror");

            if (Mutex.TryOpenExisting("OnlyMMirrorMutex", out var _))
            {
                Log.Logger.Debug("OnlyMMirrorMutex mutex exists");
                return;
            }

            var folder = Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly()?.Location);
            if (folder == null)
            {
                Log.Logger.Error("Could not get replacedembly folder");
                return;
            }

            const string mirrorExeFileName = "OnlyMMirror.exe";

            var mirrorExePath = Path.Combine(folder, mirrorExeFileName);
            if (!File.Exists(mirrorExePath))
            {
                Log.Logger.Error($"Could not find {mirrorExeFileName}");
                return;
            }

            Log.Logger.Debug($"Mirror path = {mirrorExePath}");

            var mainWindow = Application.Current.MainWindow;
            if (mainWindow == null)
            {
                Log.Logger.Error("Could not get main window");
                return;
            }

            var handle = new WindowInteropHelper(mainWindow).Handle;
            var onlyMMonitor = _monitorsService.GetMonitorForWindowHandle(handle);
            var mediaMonitor = _monitorsService.GetSystemMonitor(_optionsService.MediaMonitorId);

            if (onlyMMonitor?.MonitorId == null || mediaMonitor?.MonitorId == null)
            {
                Log.Logger.Error("Cannot get monitor - unable to display mirror");
                return;
            }

            if (mediaMonitor.MonitorId.Equals(onlyMMonitor.MonitorId))
            {
                Log.Logger.Error("Cannot display mirror since OnlyM and Media window share a monitor");
                return;
            }

            Log.Logger.Debug($"Main monitor = {onlyMMonitor.Monitor?.DeviceName}");
            Log.Logger.Debug($"Media monitor = {mediaMonitor.Monitor?.DeviceName}");

            StatusEvent?.Invoke(this, new WebBrowserProgressEventArgs { Description = Properties.Resources.LAUNCHING_MIRROR });

            try
            {
                var zoomStr = _optionsService.MirrorZoom.ToString(CultureInfo.InvariantCulture);
                var hotKey = _optionsService.MirrorHotKey;

                var commandLineArgs =
                    $"{onlyMMonitor.Monitor?.DeviceName} {mediaMonitor.Monitor?.DeviceName} {zoomStr} {hotKey}";

                Log.Logger.Debug($"Starting mirror exe with args = {commandLineArgs}");

                _mirrorProcess = new Process
                {
                    StartInfo =
                    {
                        FileName = mirrorExePath,
                        Arguments = commandLineArgs,
                    },
                    EnableRaisingEvents = true,
                };

                _mirrorProcess.Exited += HandleMirrorProcessExited;

                if (!_mirrorProcess.Start())
                {
                    Log.Logger.Error("Could not launch mirror");
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Could not launch mirror");
            }
            finally
            {
                Task.Delay(1000).ContinueWith(_ => Application.Current.Dispatcher.Invoke(() 
                    => StatusEvent?.Invoke(this, new WebBrowserProgressEventArgs { Description = string.Empty })));
            }
        }

19 View Source File : BaseDialogUserControl.cs
License : MIT License
Project Creator : angelsix

public Task ShowDialog<T>(T viewModel)
            where T : BaseDialogViewModel
        {
            // Create a task to await the dialog closing
            var tcs = new TaskCompletionSource<bool>();

            // Run on UI thread
            Application.Current.Dispatcher.Invoke(() =>
            {
                try
                {
                    // Match controls expected sizes to the dialog windows view model
                    mDialogWindow.ViewModel.WindowMinimumWidth = WindowMinimumWidth;
                    mDialogWindow.ViewModel.WindowMinimumHeight = WindowMinimumHeight;
                    mDialogWindow.ViewModel.replacedleHeight = replacedleHeight;
                    mDialogWindow.ViewModel.replacedle = string.IsNullOrEmpty(viewModel.replacedle) ? replacedle : viewModel.replacedle;

                    // Set this control to the dialog window content
                    mDialogWindow.ViewModel.Content = this;

                    // Setup this controls data context binding to the view model
                    DataContext = viewModel;

                    // Show in the center of the parent
                    mDialogWindow.Owner = Application.Current.MainWindow;
                    mDialogWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                    // Show dialog
                    mDialogWindow.ShowDialog();
                }
                finally
                {
                    // Let caller know we finished
                    tcs.TrySetResult(true);
                }
            });

            return tcs.Task;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async Task GetTodoList(bool isAppStarting)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();
            if (!accounts.Any())
            {
                SignInButton.Content = SignInString;
                return;
            }

            // Get an access token to call the To Do service.
            AuthenticationResult result = null;
            try
            {
                result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                    .ExecuteAsync()
                    .ConfigureAwait(false);

                Dispatcher.Invoke(
                    () =>
                    {
                        SignInButton.Content = ClearCacheString;
                        SetUserName(result.Account);
                    });
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                if (!isAppStarting)
                {
                    MessageBox.Show("Please sign in to view your To-Do list");
                    SignInButton.Content = SignInString;
                }
                return;
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }
                MessageBox.Show(message);

                UserName.Content = Properties.Resources.UserNotSignedIn;
                return;
            }

            // Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do list service.
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Call the To Do list service.
            HttpResponseMessage response = await _httpClient.GetAsync(TodoListApiAddress);

            if (response.IsSuccessStatusCode)
            {
                // Read the response and data-bind to the GridView to display To Do items.
                string s = await response.Content.ReadreplacedtringAsync();
                List<TodoItem> toDoArray = JsonConvert.DeserializeObject<List<TodoItem>>(s);

                Dispatcher.Invoke(() =>
                {
                    TodoList.ItemsSource = toDoArray.Select(t => new { t.replacedle });
                });
            }
            else
            {
                if (response.StatusCode == System.Net.HttpStatusCode.Forbidden && response.Headers.WwwAuthenticate.Any())
                {
                    await HandleChallengeFromWebApi(response, result.Account);
                }
                else
                {
                    await DisplayErrorMessage(response);
                }
            }
        }

19 View Source File : BasicLineChartControl.xaml.cs
License : MIT License
Project Creator : alfarok

private void NodeModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "DataUpdated")
            {
                var model = sender as BasicLineChartNodeModel;

                // Invoke on UI thread
                this.Dispatcher.Invoke(() =>
                {
                    LineSeries[] seriesRange = new LineSeries[model.Labels.Count];

                    for (var i = 0; i < model.Labels.Count; i++)
                    {
                        seriesRange[i] = new LineSeries
                        {
                            replacedle = model.Labels[i],
                            Values = new ChartValues<double>(model.Values[i]),
                            Stroke = model.Colors[i],
                            Fill = Brushes.Transparent,
                            //PointGeometrySize = 0
                        };
                    }

                    BasicLineChart.Series.Clear();
                    BasicLineChart.Series.AddRange(seriesRange);
                });
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private void WriteLine(TextBox log, string format, params object[] args)
        {
            var formattedStr = string.Format(CultureInfo.InvariantCulture, format, args);
            Trace.WriteLine(formattedStr);
            this.Dispatcher.Invoke(() =>
            {
                log.AppendText((formattedStr + "\n"));
                log.ScrollToEnd();
            });
        }

19 View Source File : ScatterPlotControl.xaml.cs
License : MIT License
Project Creator : alfarok

private void NodeModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "DataUpdated")
            {
                var model = sender as ScatterPlotNodeModel;

                // Invoke on UI thread
                this.Dispatcher.Invoke(() =>
                {
                    ScatterPlot.Series.Clear();

                    var plots = new List<ScatterSeries>();

                    // For each set of points
                    for (var i = 0; i < model.Labels.Count; i++)
                    {

                        ChartValues<ObservablePoint> points = new ChartValues<ObservablePoint>();

                        // For each x-value list
                        for (int j = 0; j < model.XValues[i].Count; j++)
                        {
                            points.Add(new ObservablePoint
                            {
                                X = model.XValues[i][j],
                                Y = model.YValues[i][j]
                            });
                        }

                        plots.Add(new ScatterSeries
                        {
                            replacedle = model.Labels[i],
                            Values = points,
                            Fill = model.Colors[i]
                        });
                    }

                    ScatterPlot.Series.AddRange(plots);
                });
            }
        }

19 View Source File : SnackbarService.cs
License : MIT License
Project Creator : AntonyCorbett

public void Enqueue(
            object content,
            object actionContent,
            Action<object?>? actionHandler,
            object? actionArgument,
            bool promote,
            bool neverConsiderToBeDuplicate)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (Application.Current.MainWindow?.WindowState != WindowState.Minimized)
                {
                    TheSnackbarMessageQueue.Enqueue(
                        content,
                        actionContent,
                        actionHandler,
                        actionArgument,
                        promote,
                        neverConsiderToBeDuplicate);
                }
            });
        }

19 View Source File : OperatorViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void HandleWebStatusEvent(object? sender, WebBrowserProgressEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var item = GetActiveWebItem();
                if (item != null)
                {
                    item.MiscText = e.Description;
                }
            });
        }

19 View Source File : NotifyCommandManager.cs
License : GNU General Public License v3.0
Project Creator : Angelinsky7

private static void OnQuit() {
            Application.Current.Dispatcher.Invoke(new Action(() => {
                try {
                    TaskTrayService.Notify.StartReverse();
                    ServiceLocator.Current.GetInstance<ServiceMonitor>().Stop();
                    ServiceLocator.Current.GetInstance<ServiceMonitor>().Release();
                    ServiceLocator.Current.GetInstance<NotifyIconViewModel>().ShowBalloonTip(Loc.Get<String>("replacedleLabel"), Loc.Get<String>("ServiceStoppedLabel"), BalloonIcon.Info);
                    TaskTrayService.Dispose();
                } finally {
                    Application.Current.Shutdown();
                }
            }));
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Assistant

private async void LoadVersionsAsync()
        {
            try
            {
                var resp = await HttpClient.GetAsync(Utils.Constants.BeatModsVersions);
                var body = await resp.Content.ReadreplacedtringAsync();
                List<string> versions = JsonSerializer.Deserialize<string[]>(body).ToList();

                resp = await HttpClient.GetAsync(Utils.Constants.BeatModsAlias);
                body = await resp.Content.ReadreplacedtringAsync();
                Dictionary<string, string[]> aliases = JsonSerializer.Deserialize<Dictionary<string, string[]>>(body);

                Dispatcher.Invoke(() =>
                {
                    GameVersion = GetGameVersion(versions, aliases);

                    GameVersionsBox.ItemsSource = versions;
                    GameVersionsBox.SelectedValue = GameVersion;

                    if (!string.IsNullOrEmpty(GameVersionOverride))
                    {
                        GameVersionsBox.Visibility = Visibility.Collapsed;
                        GameVersionsBoxOverride.Visibility = Visibility.Visible;
                        GameVersionsBoxOverride.Text = GameVersionOverride;
                        GameVersionsBoxOverride.IsEnabled = false;
                    }

                    if (!string.IsNullOrEmpty(GameVersion) && Properties.Settings.Default.Agreed)
                    {
                        Instance.ModsButton.IsEnabled = true;
                    }
                });

                VersionLoadStatus.SetResult(true);
            }
            catch (Exception e)
            {
                Dispatcher.Invoke(() =>
                {
                    GameVersionsBox.IsEnabled = false;
                    MessageBox.Show($"{Application.Current.FindResource("MainWindow:GameVersionLoadFailed")}\n{e}");
                });

                VersionLoadStatus.SetResult(false);
            }
        }

19 View Source File : MainWindow.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan

private void SetLabelState(State state)
        {
            string strState = "Off";
            Brush brush = Brushes.White;

            switch (state)
            {
                case State.Active:
                    strState = "Active";
                    brush = Brushes.Chartreuse;
                    break;
                case State.NotAsk:
                    strState = "Dont ask";
                    brush = Brushes.Red;
                    break;
            }

            this.Dispatcher.Invoke(() =>
            {
                LabelStateValue.Foreground = brush;
                LabelStateValue.Content = strState;
            });
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void SignIn(object sender = null, RoutedEventArgs args = null)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            // If there is already a token in the cache, clear the cache and update the label on the button.
            if (SignInButton.Content.ToString() == ClearCacheString)
            {
                TodoList.ItemsSource = string.Empty;

                // Clears the library cache. Does not affect the browser cookies.
                while (accounts.Any())
                {
                    await _app.RemoveAsync(accounts.First());
                    accounts = (await _app.GetAccountsAsync()).ToList();
                }

                SignInButton.Content = SignInString;
                UserName.Content = Properties.Resources.UserNotSignedIn;
                return;
            }

            // Get an access token to call the To Do list service.
            try
            {
                var result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                    .ExecuteAsync()
                    .ConfigureAwait(false);

                Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    SetUserName(result.Account);
                    GetTodoList();
                }
                );
            }
            catch (MsalUiRequiredException)
            {
            try
            {
                    // Force a sign-in (Prompt.SelectAccount), as the MSAL web browser might contain cookies for the current user
                    // and we don't necessarily want to re-sign-in the same user
                    var builder = _app.AcquireTokenInteractive(Scopes)
                        .WithAccount(accounts.FirstOrDefault())
                        .WithPrompt(Prompt.SelectAccount);

                    if (!_app.IsEmbeddedWebViewAvailable())
                    {
                        // You app should install the embedded browser WebView2 https://aka.ms/msal-net-webview2
                        // but if for some reason this is not possible, you can fall back to the system browser 
                        // in this case, the redirect uri needs to be set to "http://localhost"
                        builder = builder.WithUseEmbeddedWebView(false);
                    }

                    var result = await builder.ExecuteAsync().ConfigureAwait(false);

                    Dispatcher.Invoke(() =>
                    {
                        SignInButton.Content = ClearCacheString;
                        SetUserName(result.Account);
                        GetTodoList();
                    }
                    );
                }
                catch (MsalException ex)
                {
                    if (ex.ErrorCode == "access_denied")
                    {
                        // The user canceled sign in, take no action.
                    }
                    else
                    {
                        // An unexpected error occurred.
                        string message = ex.Message;
                        if (ex.InnerException != null)
                        {
                            message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                        }

                    MessageBox.Show(message);
                }

                    Dispatcher.Invoke(() =>
                    {
                        UserName.Content = Properties.Resources.UserNotSignedIn;
                    });
                }
            }
        }

19 View Source File : Information.cs
License : MIT License
Project Creator : AngryCarrot789

public static void Show(string text, string type)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                InformationAdded?.Invoke(new InformationModel(type, DateTime.Now, text));
                //MessageBox.Show(text);
            });
        }

19 View Source File : FaceFindSimilarPage.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            var faceServiceClient = FaceServiceClientHelper.GetInstance(this);
            try
            {
                MainWindow.Log("Request: Large Face List {0} will be used to build a person database. Checking whether the large face list exists.", _largeFaceListName);

                await faceServiceClient.LargeFaceList.GetAsync(_largeFaceListName);
                groupExists = true;
                MainWindow.Log("Response: Large Face List {0} exists.", _largeFaceListName);
            }
            catch (APIErrorException ex)
            {
                if (ex.Body.Error.Code != "LargeFaceListNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Large Face List {0} did not exist previously.", _largeFaceListName);
                }
            }

            if (groupExists)
            {
                var cleanFaceList = System.Windows.MessageBox.Show(string.Format("Requires a clean up for large face list \"{0}\" before setting up a new large face list. Click OK to proceed, large face list \"{0}\" will be cleared.", _largeFaceListName), "Warning", MessageBoxButton.OKCancel);
                if (cleanFaceList == MessageBoxResult.OK)
                {
                    await faceServiceClient.LargeFaceList.DeleteAsync(_largeFaceListName);
                }
                else
                {
                    return;
                }
            }

            OpenFaceButton.IsEnabled = false;
            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            bool forceContinue = false;

            
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // Enumerate all ".jpg" files in the folder, call detect
                List<Task> tasks = new List<Task>();

                FacesCollection.Clear();
                TargetFaces.Clear();
                FindSimilarMatchPersonCollection.Clear();
                FindSimilarMatchFaceCollection.Clear();
                SelectedFile = null;

                // Set the suggestion count is intent to minimum the data preparation step only,
                // it's not corresponding to service side constraint
                const int SuggestionCount = 10;
                int processCount = 0;

                MainWindow.Log("Request: Preparing, detecting faces in chosen folder.");

                await faceServiceClient.LargeFaceList.CreateAsync(_largeFaceListName, _largeFaceListName, "large face list for sample", recognitionModel);

                var imageList =
                    new ConcurrentBag<string>(
                        Directory.EnumerateFiles(dlg.SelectedPath, "*.*", SearchOption.AllDirectories)
                            .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif")));
                
                string img;
                int invalidImageCount = 0;
                while (imageList.TryTake(out img))
                {
                    tasks.Add(Task.Factory.StartNew(
                        async (obj) =>
                        {
                            var imgPath = obj as string;                            
                            // Call detection
                            using (var fStream = File.OpenRead(imgPath))
                            {
                                try
                                {
                                    var faces =
                                        await faceServiceClient.LargeFaceList.AddFaceFromStreamAsync(_largeFaceListName, fStream, detectionModel: detectionModel);
                                    return new Tuple<string, PersistedFace>(imgPath, faces);
                                }
                                catch (APIErrorException ex)
                                {
                                    // if operation conflict, retry.
                                    if (ex.Body.Error.Code.Equals("ConcurrentOperationConflict"))
                                    {
                                        imageList.Add(imgPath);
                                        return null;
                                    }
                                    // if operation cause rate limit exceed, retry.
                                    else if (ex.Body.Error.Code.Equals("RateLimitExceeded"))
                                    {
                                        imageList.Add(imgPath);
                                        return null;
                                    }
                                    else if (ex.Body.Error.Message.Contains("more than 1 face in the image."))
                                    {
                                        Interlocked.Increment(ref invalidImageCount);
                                    }
                                    // Here we simply ignore all detection failure in this sample
                                    // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                    return new Tuple<string, PersistedFace>(imgPath, null);
                                }
                            }
                        },
                        img).Unwrap().ContinueWith((detectTask) =>
                        {
                            var res = detectTask?.Result;
                            if (res?.Item2 == null)
                            {
                                return;
                            }

                            // Update detected faces on UI
                            this.Dispatcher.Invoke(
                            new Action
                                <ObservableCollection<Face>, string, PersistedFace>(
                                UIHelper.UpdateFace),
                            FacesCollection,
                            res.Item1,
                            res.Item2);
                        }));

                    processCount++;

                    if (processCount >= SuggestionCount && !forceContinue)
                    {
                        var continueProcess =
                            System.Windows.Forms.MessageBox.Show(
                                "The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?",
                                "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                        {
                            forceContinue = true;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                    {
                        await Task.WhenAll(tasks);
                        tasks.Clear();
                    }

                }
                if (invalidImageCount > 0)
                {
                    MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to large face list.", invalidImageCount);
                }
                MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count);

                try
                {
                    // Start to train the large face list.
                    MainWindow.Log("Request: Training large face list \"{0}\"", _largeFaceListName);
                    await faceServiceClient.LargeFaceList.TrainAsync(_largeFaceListName);

                    // Wait until the training is completed.
                    while (true)
                    {
                        await Task.Delay(1000);
                        var trainingStatus = await faceServiceClient.LargeFaceList.GetTrainingStatusAsync(_largeFaceListName);
                        MainWindow.Log("Response: {0}. Large face list \"{1}\" training process is {2}", "Success", _largeFaceListName, trainingStatus.Status);
                        if (trainingStatus.Status != TrainingStatusType.Running)
                        {
                            if (trainingStatus.Status == TrainingStatusType.Failed)
                            {
                                MainWindow.Log("Response: Training failed with message {0}.", trainingStatus.Message);
                            }

                            break;
                        }
                    }
                    OpenFaceButton.IsEnabled = true;
                }
                catch (APIErrorException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                }
            }

            GC.Collect();
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

public void AddTextToEventsList(string Text, bool IsAsync)
        {
            if (Text == "" || Text == null || Text == "Error: ")
            {
                return;
            }

            if (IsAsync == true)
            {
                this.Dispatcher.Invoke(() =>
                {
                    EventsList.Items.Add(Text);
                    EventsList.ScrollIntoView(EventsList.Items.Count - 1);
                });
            }
            else
            {
                EventsList.Items.Add(Text);
                EventsList.ScrollIntoView(EventsList.Items.Count - 1);
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

public string GetFile()
        {
            string filePath = "";
            this.Dispatcher.Invoke(() =>
            {
                filePath = this.fileNameTextBox.Text;
            });
            if (!File.Exists(filePath))
            {
                MessageBox.Show("File does not exist!");
                this.WriteLine(this.baseModelLogText, "--- Error : File does not exist! ---");
                this.WriteLine(this.customModelLogText, "--- Error : File does not exist! ---");
                this.EnableButtons();
                return "";
            }
            return filePath;
        }

19 View Source File : CreditView.xaml.cs
License : MIT License
Project Creator : anoyetta

private void StartCreadit()
        {
            this.isCreditRunning = true;

            Storyboard.SetTargetName(this.CreaditAnimation, nameof(this.Names));
            Storyboard.SetTargetProperty(this.CreaditAnimation, new PropertyPath(TextBlock.OpacityProperty));
            this.CreaditAnimationStory.Children.Add(this.CreaditAnimation);

            this.showCreditTask = Task.Run(() =>
            {
                foreach (var credit in this.CreditList)
                {
                    if (!this.isCreditRunning)
                    {
                        break;
                    }

                    this.Dispatcher.Invoke(() =>
                    {
                        this.Names.Opacity = 0;

                        this.Subreplacedle.Text = credit.Subreplacedle;
                        this.Names.Text = string.Join(Environment.NewLine, credit.Names);

                        this.Subreplacedle.Visibility = !string.IsNullOrEmpty(credit.Subreplacedle) ?
                            Visibility.Visible :
                            Visibility.Collapsed;

                        this.CreaditAnimationStory.Begin(this, true);
                    });

                    Thread.Sleep(TimeSpan.FromSeconds(7));
                }

                this.Dispatcher.Invoke(() =>
                {
                    this.Close();
                });
            });
        }

19 View Source File : PageService.cs
License : MIT License
Project Creator : AntonyCorbett

private void PermanentBackDropHack()
        {
            if (_mediaWindow == null)
            {
                EnsureMediaWindowCreated();

                CheckMediaWindow();
                _mediaWindow!.Show();

                Task.Delay(10).ContinueWith(_ =>
                {
                    System.Windows.Application.Current.Dispatcher.Invoke(() =>
                    {
                        RelocateMediaWindow();
                        _mediaWindow.Hide();
                    });
                });
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

private void RemoveTaskFromTasksList(int ProcessID, bool IsAsync)
        {
            if (IsAsync == true)
            {
                this.Dispatcher.Invoke(() =>
                {
                    ObservableCollection<TaskListTask> taskListsNew = new ObservableCollection<TaskListTask>();
                    foreach (TaskListTask tlt in tasksList)
                    {
                        if (tlt.TaskID == ProcessID)
                        {
                            continue;
                        }
                        taskListsNew.Add(new TaskListTask { TaskID = tlt.TaskID });
                    }
                    tasksList = taskListsNew;
                    TasksList.ItemsSource = taskListsNew;
                });
            }
            else
            {
                ObservableCollection<TaskListTask> taskListsNew = new ObservableCollection<TaskListTask>();
                foreach (TaskListTask tlt in tasksList)
                {
                    if (tlt.TaskID == ProcessID)
                    {
                        continue;
                    }
                    taskListsNew.Add(new TaskListTask { TaskID = tlt.TaskID });
                }
                tasksList = taskListsNew;
                TasksList.ItemsSource = taskListsNew;
            }
        }

19 View Source File : WebDisplayManager.cs
License : MIT License
Project Creator : AntonyCorbett

private void HandleBrowserLoadingStateChanged(object? sender, LoadingStateChangedEventArgs e)
        {
            if (e.IsLoading)
            {
                StatusEvent?.Invoke(this, new WebBrowserProgressEventArgs
                {
                    Description = Properties.Resources.WEB_LOADING,
                });
            }
            else
            {
                StatusEvent?.Invoke(this, new WebBrowserProgressEventArgs { Description = string.Empty });
            }

            Application.Current.Dispatcher.Invoke(async () =>
            {
                Log.Debug(e.IsLoading ? $"Loading web page = {_browser.Address}" : "Loaded web page");

                if (!e.IsLoading && !_showing && _currentMediaItemUrl != null)
                {
                    // page is loaded so fade in...
                    _showing = true;
                    await InitBrowserFromDatabase(_currentMediaItemUrl);

                    FadeBrowser(true, () =>
                    {
                        OnMediaChangeEvent(CreateMediaEventArgs(_mediaItemId, MediaChange.Started));
                        _browserGrid.Focus();

                        if (_useMirror)
                        {
                            ShowMirror();
                        }
                    });
                }
            });
        }

19 View Source File : PieChartControl.xaml.cs
License : MIT License
Project Creator : alfarok

private void NodeModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "DataUpdated")
            {
                var nodeModel = sender as PieChartNodeModel;

                // Invoke on UI thread
                this.Dispatcher.Invoke(() =>
                {
                    var seriesRange = new PieSeries[nodeModel.Labels.Count];

                    for (var i = 0; i < nodeModel.Labels.Count; i++)
                    {
                        seriesRange[i] = new PieSeries
                        {
                            replacedle = nodeModel.Labels[i],
                            Fill = nodeModel.Colors[i],
                            //StrokeThickness = 0,
                            Values = new ChartValues<double> { nodeModel.Values[i] },
                            DataLabels = true,
                            //LabelPoint = PointLabel
                        };
                    }

                    PieChart.Series.Clear();
                    PieChart.Series.AddRange(seriesRange);
                });
            }
        }

19 View Source File : SnackbarService.cs
License : MIT License
Project Creator : AntonyCorbett

public void Enqueue(object content, object actionContent, Action actionHandler, bool promote = false)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (Application.Current.MainWindow?.WindowState != WindowState.Minimized)
                {
                    TheSnackbarMessageQueue.Enqueue(content, actionContent, actionHandler, promote);
                }
            });
        }

19 View Source File : OperatorPageViewModel.cs
License : MIT License
Project Creator : AntonyCorbett

private void HandleTimerStartStopFromApi(object? sender, OnlyT.EventArgs.TimerStartStopEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                // always on UI thread to prevent synchronisation issues.
                Log.Logger.Debug("Handling timer control from API");

                CheckTalkExists(e.TalkId);

                var success = TalkId == e.TalkId || IsNotRunning;
                
                if (success)
                {
                    TalkId = e.TalkId;
                    success = TalkId == e.TalkId;

                    if (success)
                    {
                        switch (e.Command)
                        {
                            case StartStopTimerCommands.Start:
                                success = IsNotRunning;
                                if (success)
                                {
                                    StartTimer();
                                }

                                break;

                            case StartStopTimerCommands.Stop:
                                success = IsRunning;
                                if (success)
                                {
                                    // fire and forget
#pragma warning disable PH_S030 // Async Void Method Invocation
                                    StopTimer();
#pragma warning restore PH_S030 // Async Void Method Invocation
                                }

                                break;

                            default:
                                break;
                        }
                    }
                }
                
                e.CurrentStatus = _timerService.GetStatus();
                if (success)
                {
                    e.CurrentStatus.IsRunning = e.Command == StartStopTimerCommands.Start;
                }

                e.Success = success;
            });
        }

19 View Source File : DiagnosticMainViewModel.cs
License : MIT License
Project Creator : alvpickmans

private void OnSessionEnded(object sender, EventArgs e)
        {
            double min = Double.PositiveInfinity;
            double max = 0;
            CallingDispatcher.Invoke(() =>
            {
                foreach (var dataPoint in this.NodeProfilingData)
                {
                    dataPoint.UpdateWeight();

                    if (dataPoint.Weight < min) min = dataPoint.Weight;
                    if (dataPoint.Weight > max) max = dataPoint.Weight;
                }

                this.MinimumExecutionTime = min;
                this.MaximumExecutionTime = max;
            });        
        }

19 View Source File : SnackbarService.cs
License : MIT License
Project Creator : AntonyCorbett

public void EnqueueWithOk(object content)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (Application.Current.MainWindow?.WindowState != WindowState.Minimized)
                {
                    TheSnackbarMessageQueue.Enqueue(content, Properties.Resources.OK, () => { });
                }
            });
        }

19 View Source File : TelegramApi.cs
License : Apache License 2.0
Project Creator : AlexWan

public async Task<bool> LogIn(int key, string token, string phone)
        {
            try
            {
                if (_client == null)
                {
                    _client = new TelegramClient(key, token);
                    await _client.ConnectAsync();
                }
                if (_user != null)
                {
                    return true;
                }
                _phone = phone;

                var hash = await _client.SendCodeRequestAsync(_phone);

                string code = "";
                
                Application.Current.Dispatcher.Invoke(() =>
                {
                    var input = new InputBox();
                    input.ShowDialog();
                    code = input.Code;
                });
                
                if (string.IsNullOrEmpty(code))
                {
                    MessageBox.Show("Empty code!");
                    return false;
                }

                _user = await _client.MakeAuthAsync(_phone, hash, code);
                if (_user != null)
                {
                    return true;
                }

                return false;
            }
            catch (Exception e)
            {
                _client?.Dispose();
                _client = null;
                _user = null;
                return false;
            }
        }

19 View Source File : TestWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

private void ValidateAllFiles_OnClick(object sender, RoutedEventArgs e)
        {
            AddonValidator.Insatnce.UpdateLogText = s => Dispatcher.Invoke(() =>
            {
                LogText.AppendText(s);
                LogText.ScrollToLine(LogText.LineCount - 1);
            });

            AddonValidator.Insatnce.Validate(AddonManager.CurrentAddon);
        }

19 View Source File : UIManager.cs
License : MIT License
Project Creator : angelsix

public Task ShowMessage(MessageBoxDialogViewModel viewModel)
        {
            // Create a task completion source
            var tcs = new TaskCompletionSource<bool>();

            // Run on UI thread
            Application.Current.Dispatcher.Invoke(async () =>
            {
                try
                {
                    // Show the dialog box
                    await new DialogMessageBox().ShowDialog(viewModel);
                }
                finally
                {
                    // Flag we are done
                    tcs.SetResult(true);
                }
            });

            // Return the task once complete
            return tcs.Task;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : awaescher

public void ShowAndActivate()
		{
			Dispatcher.Invoke(() =>
			{
				PlaceFormByTaskbarLocation();

				if (!IsShown)
					Show();

				Activate();
				txtFilter.Focus();
				txtFilter.SelectAll();
			});
		}

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : aivarasatk

private Task<bool> LoadFromTorrentSource(ITorrentDataSource source, int currentPage)
        {
            return Task.Run(async () =>
            {
                TorrentQueryResult pirateResult = null;
                if(Model.SelectedTorrentCategory == TorrentCategory.All)
                    pirateResult = await source.GetTorrentsAsync(Model.SearchValue, currentPage, Model.SelectedSearchSortOrder.Key);
                else
                    pirateResult = await source.GetTorrentsByCategoryAsync(Model.SearchValue, currentPage, Model.SelectedSearchSortOrder.Key, Model.SelectedTorrentCategory);

                _dispatcher.Invoke(() =>
                {
                    foreach (var entry in pirateResult.TorrentEntries)
                        Model.TorrentEntries.Add(entry);
                });

                return pirateResult.IsLastPage;
            });
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void AddTodoItem(object sender, RoutedEventArgs e)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (!accounts.Any())
            {
                MessageBox.Show("Please sign in first");
                return;
            }
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            // Get an access token to call the To Do service.
            AuthenticationResult result = null;
            try
            {
                result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                    .ExecuteAsync()
                    .ConfigureAwait(false);

                Dispatcher.Invoke(() =>
                {
                    SetUserName(result.Account);
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                });
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                MessageBox.Show("Please re-sign");
                SignInButton.Content = SignInString;
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }

                Dispatcher.Invoke(() =>
               {
                   UserName.Content = Properties.Resources.UserNotSignedIn;
                   MessageBox.Show("Unexpected error: " + message);
               });


                return;
            }

            //
            // Call the To Do service.
            //

            // Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do service.
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode Todo item, to POST to the todo list web api.
            TodoItem todoItem = new TodoItem() { replacedle = TodoText.Text };
            string json = JsonConvert.SerializeObject(todoItem);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            // Call the To Do list service.

            HttpResponseMessage response = await _httpClient.PostAsync(TodoListApiAddress, content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                GetTodoList();
            }
            else
            {
                    await DisplayErrorMessage(response);
            }
        }

19 View Source File : Information.cs
License : MIT License
Project Creator : AngryCarrot789

public static void Show(string text)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                InformationAdded?.Invoke(new InformationModel("Info", DateTime.Now, text));
            });
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void AddTodoItem(object sender, RoutedEventArgs e)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();

            if (!accounts.Any())
            {
                MessageBox.Show("Please sign in first");
                return;
            }
            if (string.IsNullOrEmpty(TodoText.Text))
            {
                MessageBox.Show("Please enter a value for the To Do item name");
                return;
            }

            // Get an access token to call the To Do service.
            AuthenticationResult result = null;
            try
            {
                result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                    .ExecuteAsync()
                    .ConfigureAwait(false);
                Dispatcher.Invoke(() =>
                {
                    SetUserName(result.Account);
                    UserName.Content = Properties.Resources.UserNotSignedIn;
                });
            }
            // There is no access token in the cache, so prompt the user to sign-in.
            catch (MsalUiRequiredException)
            {
                MessageBox.Show("Please re-sign");
                SignInButton.Content = SignInString;
            }
            catch (MsalException ex)
            {
                // An unexpected error occurred.
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                }

                Dispatcher.Invoke(() =>
               {
                   UserName.Content = Properties.Resources.UserNotSignedIn;
                   MessageBox.Show("Unexpected error: " + message);
               });


                return;
            }

            // Call the To Do service.
            // Once the token has been returned by MSAL, add it to the http authorization header, before making the call to access the To Do service.
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

            // Forms encode Todo item, to POST to the todo list web api.
            TodoItem todoItem = new TodoItem() { replacedle = TodoText.Text };
            string json = JsonConvert.SerializeObject(todoItem);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");

            // Call the To Do list service.

            HttpResponseMessage response = await _httpClient.PostAsync(TodoListApiAddress, content);

            if (response.IsSuccessStatusCode)
            {
                TodoText.Text = "";
                GetTodoList();
            }
            else
            {
                if (response.StatusCode == System.Net.HttpStatusCode.Forbidden && response.Headers.WwwAuthenticate.Any())
                {
                    await HandleChallengeFromWebApi(response, result.Account);
                }
                else
                {
                    await DisplayErrorMessage(response);
                }
            }
        }

19 View Source File : BarChartControl.xaml.cs
License : MIT License
Project Creator : alfarok

private void NodeModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "DataUpdated")
            {
                var model = sender as BarChartNodeModel;

                // Invoke on UI thread
                this.Dispatcher.Invoke(() =>
                {
                    var seriesRange = new ColumnSeries[model.Labels.Count];

                    for (var i = 0; i < model.Labels.Count; i++)
                    {
                        seriesRange[i] = new ColumnSeries
                        {
                            replacedle = model.Labels[i],
                            Values = new ChartValues<double>(model.Values[i]),
                            Fill = model.Colors[i]
                        };
                    }

                    BarChart.Series.Clear();
                    BarChart.Series.AddRange(seriesRange);
                });
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void SignIn(object sender = null, RoutedEventArgs args = null)
        {
            var accounts = (await _app.GetAccountsAsync()).ToList();
            // If there is already a token in the cache, clear the cache and update the label on the button.
            if (SignInButton.Content.ToString() == ClearCacheString)
            {
                TodoList.ItemsSource = string.Empty;

                // clear the cache
                while (accounts.Any())
                {
                    await _app.RemoveAsync(accounts.First());
                    accounts = (await _app.GetAccountsAsync()).ToList();
                }
                // Also clear cookies from the browser control.
                SignInButton.Content = SignInString;
                UserName.Content = Properties.Resources.UserNotSignedIn;
                return;
            }

            // Get an access token to call the To Do list service.
            try
            {
                var result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
                    .ExecuteAsync()
                    .ConfigureAwait(false);

                Dispatcher.Invoke(() =>
                {
                    SignInButton.Content = ClearCacheString;
                    SetUserName(result.Account);
                    GetTodoList();
                }
                );
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    // Force a sign-in (Prompt.SelectAccount), as the MSAL web browser might contain cookies for the current user
                    // and we don't necessarily want to re-sign-in the same user
                    var result = await _app.AcquireTokenInteractive(Scopes)
                        .WithAccount(accounts.FirstOrDefault())
                        .WithPrompt(Prompt.SelectAccount)
                        .ExecuteAsync()
                        .ConfigureAwait(false);

                    Dispatcher.Invoke(() =>
                    {
                        SignInButton.Content = ClearCacheString;
                        SetUserName(result.Account);
                        GetTodoList();
                    }
                    );
                }
                catch (MsalException ex)
                {
                    if (ex.ErrorCode == "access_denied")
                    {
                        // The user canceled sign in, take no action.
                    }
                    else
                    {
                        // An unexpected error occurred.
                        string message = ex.Message;
                        if (ex.InnerException != null)
                        {
                            message += "Error Code: " + ex.ErrorCode + "Inner Exception : " + ex.InnerException.Message;
                        }

                        MessageBox.Show(message);
                    }

                    Dispatcher.Invoke(() =>
                    {
                        UserName.Content = Properties.Resources.UserNotSignedIn;
                    });
                }
            }
        }

19 View Source File : Information.cs
License : MIT License
Project Creator : AngryCarrot789

public static void Show(string text, InfoTypes type)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                InformationAdded?.Invoke(new InformationModel(type, DateTime.Now, text));
            });
        }

19 View Source File : FaceIdentificationPage.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            var faceServiceClient = FaceServiceClientHelper.GetInstance(this);
            // Test whether the group already exists
            try
            {
                MainWindow.Log("Request: Group {0} will be used to build a person database. Checking whether the group exists.", GroupName);

                await faceServiceClient.LargePersonGroup.GetAsync(GroupName);
                groupExists = true;
                MainWindow.Log("Response: Group {0} exists.", GroupName);
            }
            catch (APIErrorException ex)
            {
                if (ex.Body.Error.Code != "LargePersonGroupNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Group {0} did not exist previously.", GroupName);
                }
            }

            if (groupExists)
            {
                var cleanGroup = System.Windows.MessageBox.Show(string.Format("Requires a clean up for group \"{0}\" before setting up a new person database. Click OK to proceed, group \"{0}\" will be cleared.", GroupName), "Warning", MessageBoxButton.OKCancel);
                if (cleanGroup == MessageBoxResult.OK)
                {
                    await faceServiceClient.LargePersonGroup.DeleteAsync(GroupName);
                }
                else
                {
                    return;
                }
            }

            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            // Set the suggestion count is intent to minimum the data preparation step only,
            // it's not corresponding to service side constraint
            const int SuggestionCount = 15;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // User picked a root person database folder
                // Clear person database
                Persons.Clear();
                TargetFaces.Clear();
                SelectedFile = null;
                IdentifyButton.IsEnabled = false;

                // Call create large person group REST API
                // Create large person group API call will failed if group with the same name already exists
                MainWindow.Log("Request: Creating group \"{0}\"", GroupName);
                try
                {
                    await faceServiceClient.LargePersonGroup.CreateAsync(GroupName, GroupName, recognitionModel: recognitionModel);
                    MainWindow.Log("Response: Success. Group \"{0}\" created", GroupName);
                }
                catch (APIErrorException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                }

                int processCount = 0;
                bool forceContinue = false;

                MainWindow.Log("Request: Preparing faces for identification, detecting faces in chosen folder.");

                // Enumerate top level directories, each directory contains one person's images
                int invalidImageCount = 0;
                foreach (var dir in System.IO.Directory.EnumerateDirectories(dlg.SelectedPath))
                {
                    var tasks = new List<Task>();
                    var tag = System.IO.Path.GetFileName(dir);
                    Person p = new Person();
                    p.PersonName = tag;

                    var faces = new ObservableCollection<Face>();
                    p.Faces = faces;

                    // Call create person REST API, the new create person id will be returned
                    MainWindow.Log("Request: Creating person \"{0}\"", p.PersonName);
                    p.PersonId = (await faceServiceClient.LargePersonGroupPerson.CreateAsync(GroupName, p.PersonName)).PersonId.ToString();
                    MainWindow.Log("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId);

                    string img;
                    // Enumerate images under the person folder, call detection
                    var imageList =
                    new ConcurrentBag<string>(
                        Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories)
                            .Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".bmp") || s.ToLower().EndsWith(".gif")));
                    
                    while (imageList.TryTake(out img))
                    {
                        tasks.Add(Task.Factory.StartNew(
                            async (obj) =>
                            {
                                var imgPath = obj as string;

                                using (var fStream = File.OpenRead(imgPath))
                                {
                                    try
                                    {
                                        // Update person faces on server side
                                        var persistFace = await faceServiceClient.LargePersonGroupPerson.AddFaceFromStreamAsync(GroupName, Guid.Parse(p.PersonId), fStream, imgPath, detectionModel: detectionModel);
                                        return new Tuple<string, PersistedFace>(imgPath, persistFace);
                                    }
                                    catch (APIErrorException ex)
                                    {
                                        // if operation conflict, retry.
                                        if (ex.Body.Error.Code.Equals("ConcurrentOperationConflict"))
                                        {
                                            imageList.Add(imgPath);
                                            return null;
                                        }
                                        // if operation cause rate limit exceed, retry.
                                        else if (ex.Body.Error.Code.Equals("RateLimitExceeded"))
                                        {
                                            imageList.Add(imgPath);
                                            return null;
                                        }
                                        else if (ex.Body.Error.Message.Contains("more than 1 face in the image."))
                                        {
                                            Interlocked.Increment(ref invalidImageCount);
                                        }
                                        // Here we simply ignore all detection failure in this sample
                                        // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                        return new Tuple<string, PersistedFace>(imgPath, null);
                                    }
                                }
                            },
                            img).Unwrap().ContinueWith((detectTask) =>
                            {
                                // Update detected faces for rendering
                                var detectionResult = detectTask?.Result;
                                if (detectionResult == null || detectionResult.Item2 == null)
                                {
                                    return;
                                }

                                this.Dispatcher.Invoke(
                                    new Action<ObservableCollection<Face>, string, PersistedFace>(UIHelper.UpdateFace),
                                    faces,
                                    detectionResult.Item1,
                                    detectionResult.Item2);
                            }));
                        if (processCount >= SuggestionCount && !forceContinue)
                        {
                            var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                            if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                            {
                                forceContinue = true;
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                        {
                            await Task.WhenAll(tasks);
                            tasks.Clear();
                        }
                    }

                    Persons.Add(p);
                }
                if (invalidImageCount > 0)
                {
                    MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount);
                }
                MainWindow.Log("Response: Success. Total {0} faces are detected.", Persons.Sum(p => p.Faces.Count));

                try
                {
                    // Start train person group
                    MainWindow.Log("Request: Training large person group \"{0}\"", GroupName);
                    await faceServiceClient.LargePersonGroup.TrainAsync(GroupName);

                    // Wait until train completed
                    while (true)
                    {
                        await Task.Delay(1000);
                        var status = await faceServiceClient.LargePersonGroup.GetTrainingStatusAsync(GroupName); // Bug
                        MainWindow.Log("Response: {0}. Large person group \"{1}\" training process is {2}", "Success", GroupName, status.Status);
                        if (status.Status != TrainingStatusType.Running)
                        {
                            break;
                        }
                    }
                    IdentifyButton.IsEnabled = true;
                }
                catch (APIErrorException ex)
                {
                    MainWindow.Log("Response: {0}. {1}", ex.Body.Error.Code, ex.Body.Error.Message);
                }
            }
            GC.Collect();
        }

19 View Source File : FolderInfoPanel.xaml.cs
License : MIT License
Project Creator : adyanth

private void BeginLoadDirectory(string path)
        {
            new Task(() =>
            {
                var root = new FileEntry(Path.GetDirectoryName(path), true);
                _fileEntries.Add(path, root);

                LoadItemsFromFolder(path, ref _stop,
                    out var totalDirsL, out var totalFilesL, out var totalSizeL);

                Dispatcher.Invoke(() =>
                {
                    if (_disposed)
                        return;

                    fileListView.SetDataContext(_fileEntries[path].Children.Keys);
                    totalSize.Content =
                        $"Total size: {totalSizeL.ToPrettySize(2)}";
                    numFolders.Content =
                        $"Folders: {totalDirsL}";
                    numFiles.Content = 
                        $"Files: {totalFilesL}";
                });

                LoadPercent = 100d;
            }).Start();
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : Azure-Samples

private async Task RunRecognizer(SpeechRecognizer recognizer, RecoType recoType, TaskCompletionSource<int> source)
        {
            //subscribe to events
            bool isChecked = false;
            this.Dispatcher.Invoke(() =>
            {
                isChecked = this.immediateResultsCheckBox.IsChecked == true;
            });

            EventHandler<SpeechRecognitionEventArgs> recognizingHandler = (sender, e) => RecognizingEventHandler(e, recoType);
            if (isChecked)
            {
                recognizer.Recognizing += recognizingHandler;
            }

            EventHandler<SpeechRecognitionEventArgs> recognizedHandler = (sender, e) => RecognizedEventHandler(e, recoType);
            EventHandler<SpeechRecognitionCanceledEventArgs> canceledHandler = (sender, e) => CanceledEventHandler(e, recoType, source);
            EventHandler<SessionEventArgs> sessionStartedHandler = (sender, e) => SessionStartedEventHandler(e, recoType);
            EventHandler<SessionEventArgs> sessionStoppedHandler = (sender, e) => SessionStoppedEventHandler(e, recoType, source);
            EventHandler<RecognitionEventArgs> speechStartDetectedHandler = (sender, e) => SpeechDetectedEventHandler(e, recoType, "start");
            EventHandler<RecognitionEventArgs> speechEndDetectedHandler = (sender, e) => SpeechDetectedEventHandler(e, recoType, "end");

            recognizer.Recognized += recognizedHandler;
            recognizer.Canceled += canceledHandler;
            recognizer.SessionStarted += sessionStartedHandler;
            recognizer.SessionStopped += sessionStoppedHandler;
            recognizer.SpeechStartDetected -= speechStartDetectedHandler;
            recognizer.SpeechEndDetected -= speechEndDetectedHandler;

            //start,wait,stop recognition
            await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);
            await source.Task.ConfigureAwait(false);
            await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);

            this.EnableButtons();

            // unsubscribe from events
            if (isChecked)
            {
                recognizer.Recognizing -= recognizingHandler;
            }
            recognizer.Recognized -= recognizedHandler;
            recognizer.Canceled -= canceledHandler;
            recognizer.SessionStarted -= sessionStartedHandler;
            recognizer.SessionStopped -= sessionStoppedHandler;
            recognizer.SpeechStartDetected -= speechStartDetectedHandler;
            recognizer.SpeechEndDetected -= speechEndDetectedHandler;
        }

19 View Source File : SearchPage.xaml.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private void SearchImage(GrayImage grayImage, Jocr.Ocr.RunOcrHandler runOcrHandler = null)
        {
            if (!JocrWrapper.IsOcrParametersInit)
                progressRing.StartAnimation();

            Task.Run(() =>
            {
                if (!JocrWrapper.IsOcrParametersInit)
                    JocrWrapper.InitOcrParameters();

                currentDispatcher.Invoke(() =>
                {
                    var textBlocks = JocrWrapper.RunOcr(grayImage, runOcrHandler);
                    SearchJOcrResults(textBlocks);
                    progressRing.StopAnimation();
                    OcrFinishedEvent?.Invoke(null, null);
                });
            });
        }

19 View Source File : HeatSeriesControl.xaml.cs
License : MIT License
Project Creator : alfarok

private void NodeModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "DataUpdated")
            {
                var model = sender as HeatSeriesNodeModel;

                // Invoke on UI thread
                this.Dispatcher.Invoke(() =>
                {
                    var chartValues = new ChartValues<HeatPoint>();

                    for (var i = 0; i < model.XLabels.Count; i++)
                    {
                        for (var j = 0; j < model.YLabels.Count; j++)
                        {
                            chartValues.Add(new HeatPoint(i, j, model.Values[i][j]));
                        }
                    }

                    var colors = BuildColors(model);
                    var hoverIconColor = new SolidColorBrush(Color.FromArgb(255, 94, 92, 90));

                    HeatSeriesUI.Series.Clear();
                    XAxis.Labels = model.XLabels;
                    YAxis.Labels = model.YLabels;
                    HeatSeriesUI.Series.Add(new HeatSeries()
                    {
                        Values = chartValues,
                        DrawsHeatRange = false,
                        GradientStopCollection = colors,
                        Fill = hoverIconColor,
                        PointGeometry = DefaultGeometries.Square
                        //DataLabels = true
                    });
                });
            }
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : adrianlungu

private void TurnOff_OnClick(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                if (MyNotifyIcon.ContextMenu != null) MyNotifyIcon.ContextMenu.IsOpen = false;
            });

            Screen.SetScreenState(ScreenState.Off);
        }

19 View Source File : FileExplorerViewModel.cs
License : MIT License
Project Creator : afxw

private void HandleGetDirectory(IPacket packet)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Files.Clear();
            });

            var previousDirectory = CurrentDirectory;

            var directoryResponse = (GetDirectoryResponsePacket)packet;

            CurrentDirectory = new FileSystemEntry(directoryResponse.Name, directoryResponse.Path, 0, FileType.Directory);

            if (previousDirectory != null)
            {
                BackHistory.Push(previousDirectory);
            }

            OnPropertyChanged(() => CanGoForward);
            OnPropertyChanged(() => CanGoBackward);

            for (int i = 0; i < directoryResponse.Folders.Length; i++)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Files.Add(new FileSystemEntry
                    (
                        directoryResponse.Folders[i],
                        System.IO.Path.Combine(CurrentDirectory.Path, directoryResponse.Folders[i]),
                        0,
                        FileType.Directory
                    ));
                });
            }

            for (int i = 0; i < directoryResponse.Files.Length; i++)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    Files.Add(new FileSystemEntry
                    (
                        directoryResponse.Files[i],
                        System.IO.Path.Combine(CurrentDirectory.Path, directoryResponse.Files[i]),
                        directoryResponse.FileSizes[i],
                        FileType.File
                    ));
                });
            }
        }

19 View Source File : AddClientDialogUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan

private void ButtonAccept_Click(object sender, RoutedEventArgs e)
        {
            var name = ClientName.Text;

            if (_allClientsName == null || _allClientsName.Find(c => c.Name == name) == null)
            {
                CreatedName = ClientName.Text;
                Close();
                return;
            }

            var message = OsLocalization.MainWindow.NewClientErrorName;
            TbText.Text = message;

            Task.Run(() =>
            {
                Thread.Sleep(5000);
                Dispatcher.Invoke(() => TbText.Text = null);
            });
        }

19 View Source File : XYLineChartControl.xaml.cs
License : MIT License
Project Creator : alfarok

private void NodeModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "DataUpdated")
            {
                var model = sender as XYLineChartNodeModel;

                // Invoke on UI thread
                this.Dispatcher.Invoke(() =>
                {
                    LineSeries[] seriesRange = new LineSeries[model.Labels.Count];

                    for (var i = 0; i < model.Labels.Count; i++)
                    {
                        ChartValues<ObservablePoint> points = new ChartValues<ObservablePoint>();

                        for (int j = 0; j < model.XValues[i].Count; j++)
                        {
                            points.Add(new ObservablePoint
                            {
                                X = model.XValues[i][j],
                                Y = model.YValues[i][j]
                            });
                        }

                        seriesRange[i] = new LineSeries
                        {
                            replacedle = model.Labels[i],
                            Values = points,
                            Stroke = model.Colors[i],
                            Fill = Brushes.Transparent
                            //PointGeometrySize = 0
                        };
                    }

                    XYLineChart.Series.Clear();
                    XYLineChart.Series.AddRange(seriesRange);
                });
            }
        }

19 View Source File : ClockControl.cs
License : MIT License
Project Creator : AntonyCorbett

private static void DurationSectorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sector = (DurationSector?)e.NewValue;
            var c = (ClockControl)d;

            if (sector == null)
            {
                c._sectorPath1.Data = null;
                c._sectorPath2.Data = null;
                c._sectorPath3.Data = null;
            }
            else
            {
                var delay = e.OldValue == null;
                if (delay)
                {
                    // the first time we display the sector we delay it for aesthetics
                    // (so it doesn't appear just as the clock is fading out)
                    Task.Delay(1000).ContinueWith(_ => { c.Dispatcher?.Invoke(() => { DrawSector(c, sector); }); });
                }
                else
                {
                    DrawSector(c, sector);
                }
            }
        }

See More Examples