Example #1
0
        /// <summary>
        /// 同步等待action方法执行完成
        /// 创建新的同步上下文关联执行action
        /// 执行完成后切换为原始同步上下文
        /// </summary>
        /// <param name="action">要等待的同步或异步方法</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>当action有异步操作返回true</returns>
        public bool WaitAction(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException();
            }

            var previousContext = SynchronizationContext.Current;

            try
            {
                var currentContext = new AsyncSynchronizationContext(this);
                SynchronizationContext.SetSynchronizationContext(currentContext);
                action.Invoke();
                return(currentContext.WaitForPendingOperationsToComplete() > 0L);
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
Example #2
0
        private object RunAsyncVoidTestMethod(ITestExecutionContext context)
        {
            var previousContext = SynchronizationContext.Current;
            var currentContext = new AsyncSynchronizationContext();
            SynchronizationContext.SetSynchronizationContext(currentContext);

            try
            {
                object result = Reflect.InvokeMethod(testMethod.Method, context.TestObject, arguments);

                currentContext.WaitForOperationCompleted();

                if (currentContext.Exceptions.Count > 0)
                    throw new NUnitException("Rethrown", currentContext.Exceptions[0]);

                return result;
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
Example #3
0
        //readonly IsolatedStorageSettings _settings = IsolatedStorageSettings.ApplicationSettings;

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // set sync context for ui thread so async void exceptions can be handled, keeps process alive
            AsyncSynchronizationContext.Register();

            // ensure unobserved task exceptions (unawaited async methods returning Task or Task<T>) are handled
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard XAML initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                //Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Prevent the screen from turning off while under the debugger by disabling
                // the application's idle detection.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
        }
Example #4
0
        public async Task SourceManipulationSorted()
        {
            var context1 = new AsyncSynchronizationContext();
            var context2 = new AsyncSynchronizationContext();
            ISynchronizedObservableRangeDictionary <int, TestPerson> people = new SynchronizedObservableSortedDictionary <int, TestPerson>(context1);

            foreach (var kv in TestPerson.MakePeople().Select((person, index) => new KeyValuePair <int, TestPerson>(index, person)))
            {
                people.Add(kv);
            }
            using (var query = people.SwitchContext(context2))
            {
                Assert.AreEqual(14, query.Count);
                people.Add(14, new TestPerson("Daniel"));
                await Task.Delay(250);

                Assert.AreEqual(15, query.Count);
                people[14] = new TestPerson("Javon");
                await Task.Delay(250);

                Assert.AreEqual("Javon", query[14].Name);
                people[0] = people[14];
                await Task.Delay(250);

                Assert.AreEqual("Javon", query[0].Name);
                people.Remove(0);
                await Task.Delay(250);

                Assert.AreEqual(14, query.Count);
                people.Reset(new Dictionary <int, TestPerson> {
                    { 0, new TestPerson("Sarah") }
                });
                await Task.Delay(250);

                Assert.AreEqual(1, query.Count);
            }
        }
Example #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="startKind"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            bool forceToMainPage = false;

            // Check for updates (ignore resume)
            if (startKind == StartKind.Launch)
            {
                var latestUpdateInfo = await UpdateManager.IsUpdateAvailable();

                while (latestUpdateInfo == null || latestUpdateInfo.Status == UpdateManager.UpdateStatus.NoInternet)
                {
                    var dialog = new MessageDialog("Do you want try to connect again?", "No internet connection");

                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id != 0)
                    {
                        App.Current.Exit();
                    }
                    else
                    {
                        latestUpdateInfo = await UpdateManager.IsUpdateAvailable();
                    }
                }

                if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.UpdateAvailable)
                {
                    var dialog =
                        new MessageDialog(string.Format(Utils.Resources.CodeResources.GetString("UpdatedVersion"),
                                                        latestUpdateInfo.Version, latestUpdateInfo.Description));

                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id != 0)
                    {
                        return;
                    }

                    var t1 = UpdateManager.InstallUpdate();
                    forceToMainPage = true;
                }
                else if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.UpdateForced)
                {
                    //start forced update
                    var t1 = UpdateManager.InstallUpdate();
                    forceToMainPage = true;
                }
                else if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.NextVersionNotReady)
                {
                    var dialog = new MessageDialog("Please wait on next update", "This version is obsolete");
                    dialog.Commands.Add(new UICommand("OK"));
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    App.Current.Exit();
                }
            }


            AsyncSynchronizationContext.Register();
            var currentAccessToken = GameClient.LoadAccessToken();

            if (currentAccessToken == null || forceToMainPage)
            {
                await NavigationService.NavigateAsync(typeof(MainPage));
            }
            else
            {
                await GameClient.InitializeClient();

                NavigationService.Navigate(typeof(GameMapPage), GameMapNavigationModes.AppStart);
            }


            await Task.CompletedTask;
        }
Example #6
0
 /// <summary>
 /// It will register the async handler for unawaited void and Task unhandled exceptions thrown in the application.
 /// </summary>
 /// <remarks>
 /// This may be needed in special cases where the synchronization context could be null in early initialization.
 /// The async handlers are registered in the initialization process of the component.
 /// </remarks>
 public static void RegisterAsyncHandlerContext()
 {
     AsyncSynchronizationContext.ExceptionCaught += SyncContextExceptionHandler;
     AsyncSynchronizationContext.Register();
 }
Example #7
0
        /// <summary>
        /// Call this in the "OnLaunched" and "OnActivated" handlers of App.xaml.cs
        /// to capture unobserved async void errors.
        /// </summary>
        public void RegisterAsyncContextHandler()
        {
            AsyncSynchronizationContext.Register();

            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }
			public static AsyncSynchronizationContext Register()
			{
				var syncContext = Current;

				AsyncSynchronizationContext customSynchronizationContext = null;
				if (syncContext != null)
				{
					customSynchronizationContext = syncContext as AsyncSynchronizationContext;

					if (customSynchronizationContext == null)
					{
						customSynchronizationContext = new AsyncSynchronizationContext(syncContext);
						try
						{
							SetSynchronizationContext(customSynchronizationContext);
						}
						catch (System.Exception ex)
						{
							Console.WriteLine("SetSynchronizationContext Exception: {0}", ex);
						}
					}
				}
				return customSynchronizationContext;
			}
Example #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="startKind"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            if (!CheckWindowsBuildVersion())
            {
                var dialog = new MessageDialog("The minimum required Windows version for this App is 10.0.14393 (Aniversary Update). PoGo-UWP will exit now");
                await dialog.ShowAsync();

                App.Current.Exit();
            }

            bool forceToMainPage = false;

            // Check for updates (ignore resume)
            if (startKind == StartKind.Launch)
            {
                var latestUpdateInfo = await UpdateManager.IsUpdateAvailable();

                while (latestUpdateInfo == null || latestUpdateInfo.Status == UpdateManager.UpdateStatus.NoInternet)
                {
                    var dialog = new MessageDialog("Do you want try to connect again?", "No internet connection");

                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id != 0)
                    {
                        App.Current.Exit();
                    }
                    else
                    {
                        latestUpdateInfo = await UpdateManager.IsUpdateAvailable();
                    }
                }

                if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.UpdateAvailable)
                {
                    var dialog =
                        new MessageDialog(string.Format(Utils.Resources.CodeResources.GetString("UpdatedVersionText"),
                                                        latestUpdateInfo.Version, latestUpdateInfo.Description));

                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id == 0)
                    {
                        var t1 = UpdateManager.InstallUpdate();
                        forceToMainPage = true;
                    }
                }
                else if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.UpdateForced)
                {
                    //start forced update
                    var t1 = UpdateManager.InstallUpdate();
                    forceToMainPage = true;
                }
                else if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.NextVersionNotReady)
                {
                    var twoLines = Environment.NewLine + Environment.NewLine;
                    var dialog   = new MessageDialog("Niantic has raised the minimum API level above what we have access to, so we've temporarily disabled the app to protect your account." +
                                                     twoLines + "DO NOT attempt to bypass this check. Accounts that access lower APIs than the minimum WILL BE BANNED by Niantic." + twoLines +
                                                     "An update will be ready soon. Please DO NOT open an issue on GitHub, you are seeing this message because we already know about it, and this is how we're telling you. " +
                                                     "Thank you for your patience." + twoLines + "- The PoGo-UWP Team");
                    dialog.Commands.Add(new UICommand("OK"));
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    App.Current.Exit();
                }
            }

            var webConfigurationInfo = await WebConfigurationManager.GetWebConfiguration();

            if (webConfigurationInfo != null)
            {
                WebConfigurationInfo wci = (WebConfigurationInfo)webConfigurationInfo;
                GymsAreDisabled = wci.gymsaredisabled;
            }

            AsyncSynchronizationContext.Register();

            // See if there is a key for the PokeHash server, ask one from the user if there isn't
            if (String.IsNullOrEmpty(SettingsService.Instance.PokehashAuthKey))
            {
                HockeyClient.Current.TrackPageView("PokehashKeyPage");
                await NavigationService.NavigateAsync(typeof(PokehashKeyPage), GameMapNavigationModes.AppStart);

                return;
            }

            var currentAccessToken = GameClient.GetAccessToken();

            if (currentAccessToken == null || forceToMainPage)
            {
                HockeyClient.Current.TrackPageView("MainPage");
                await NavigationService.NavigateAsync(typeof(MainPage));

                return;
            }
            else
            {
                try
                {
                    await GameClient.InitializeSession();

                    if (GameClient.IsInitialized)
                    {
                        HockeyClient.Current.TrackPageView("GameMapPage");
                        NavigationService.Navigate(typeof(GameMapPage), GameMapNavigationModes.AppStart);
                    }
                }
                catch (PtcLoginException ex)
                {
                    var errorMessage          = ex.Message ?? Utils.Resources.CodeResources.GetString("PtcLoginFailed");
                    ConfirmationDialog dialog = new Views.ConfirmationDialog(errorMessage);
                    dialog.Show();

                    HockeyClient.Current.TrackPageView("MainPage");
                    await NavigationService.NavigateAsync(typeof(MainPage));
                }
                catch (LocationException)
                {
                    ConfirmationDialog dialog = new Views.ConfirmationDialog(Utils.Resources.CodeResources.GetString("CouldNotGetLocation"));
                    dialog.Closed += (ss, ee) => { App.Current.Exit(); };
                    dialog.Show();
                }
                //catch (PokeHashException)
                //{
                //    var errorMessage = Utils.Resources.CodeResources.GetString("PokeHashException");
                //    ConfirmationDialog dialog = new Views.ConfirmationDialog(errorMessage);
                //    dialog.Closed += (ss, ee) => { Application.Current.Exit(); };
                //    dialog.Show();
                //}
                catch (HashVersionMismatchException ex)
                {
                    var errorMessage          = ex.Message + Utils.Resources.CodeResources.GetString("PokeHashVersionMismatch");
                    ConfirmationDialog dialog = new Views.ConfirmationDialog(errorMessage);
                    dialog.Closed += (ss, ee) => { Application.Current.Exit(); };
                    dialog.Show();
                }
                catch (Exception ex)    // When the PokeHash server returns an error, it is not safe to continue. Ask for another PokeHash Key
                {
                    var errorMessage          = ex.Message ?? Utils.Resources.CodeResources.GetString("HashingKeyExpired");
                    ConfirmationDialog dialog = new Views.ConfirmationDialog(errorMessage);
                    dialog.Show();

                    HockeyClient.Current.TrackPageView("PokehashKeyPage");
                    await NavigationService.NavigateAsync(typeof(PokehashKeyPage), GameMapNavigationModes.AppStart);
                }
            }

            await Task.CompletedTask;
        }
Example #10
0
        private object RunAsyncVoidTestMethod(TestExecutionContext context)
        {
            var previousContext = SynchronizationContext.Current;
            var currentContext = new AsyncSynchronizationContext();
            SynchronizationContext.SetSynchronizationContext(currentContext);

            try
            {
                object result = Reflect.InvokeMethod(testMethod.Method, context.TestObject, arguments);

                currentContext.WaitForOperationCompleted();

                if (currentContext.Exceptions.Count > 0)
                    throw new NUnitException("Rethrown", currentContext.Exceptions[0]);

                return result;
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(previousContext);
            }
        }
Example #11
0
 /// <summary>
 /// On startup, register synchronization context
 /// </summary>
 /// <param name="e"></param>
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     AsyncSynchronizationContext.Register();
 }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="startKind"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            bool forceToMainPage = false;

            // Check for updates (ignore resume)
            if (startKind == StartKind.Launch)
            {
                var latestUpdateInfo = await UpdateManager.IsUpdateAvailable();

                while (latestUpdateInfo == null || latestUpdateInfo.Status == UpdateManager.UpdateStatus.NoInternet)
                {
                    var dialog = new MessageDialog("Do you want try to connect again?", "No internet connection");

                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id != 0)
                    {
                        App.Current.Exit();
                    }
                    else
                    {
                        latestUpdateInfo = await UpdateManager.IsUpdateAvailable();
                    }
                }

                if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.UpdateAvailable)
                {
                    var dialog =
                        new MessageDialog(string.Format(Utils.Resources.CodeResources.GetString("UpdatedVersion"),
                                                        latestUpdateInfo.Version, latestUpdateInfo.Description));

                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Utils.Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id != 0)
                    {
                        return;
                    }

                    var t1 = UpdateManager.InstallUpdate();
                    forceToMainPage = true;
                }
                else if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.UpdateForced)
                {
                    //start forced update
                    var t1 = UpdateManager.InstallUpdate();
                    forceToMainPage = true;
                }
                else if (latestUpdateInfo.Status == UpdateManager.UpdateStatus.NextVersionNotReady)
                {
                    var twoLines = Environment.NewLine + Environment.NewLine;
                    var dialog   = new MessageDialog("Niantic has raised the minimum API level above what we have access to, so we've temporarily disabled the app to protect your account." +
                                                     twoLines + "DO NOT attempt to bypass this check. Accounts that access lower APIs than the minimum WILL BE BANNED by Niantic." + twoLines +
                                                     "An update will be ready soon. Please DO NOT open an issue on GitHub, you are seeing this message because we already know about it, and this is how we're telling you. " +
                                                     "Thank you for your patience." + twoLines + "- The PoGo-UWP Team");
                    dialog.Commands.Add(new UICommand("OK"));
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;

                    var result = await dialog.ShowAsyncQueue();

                    App.Current.Exit();
                }
            }


            AsyncSynchronizationContext.Register();
            var currentAccessToken = GameClient.LoadAccessToken();

            if (currentAccessToken == null || forceToMainPage)
            {
                await NavigationService.NavigateAsync(typeof(MainPage));
            }
            else
            {
                await GameClient.InitializeClient();

                NavigationService.Navigate(typeof(GameMapPage), GameMapNavigationModes.AppStart);
            }


            await Task.CompletedTask;
        }
 public AsyncVoidInvocationRegion()
 {
     _previousContext = SynchronizationContext.Current;
     _currentContext  = new AsyncSynchronizationContext();
     SynchronizationContext.SetSynchronizationContext(_currentContext);
 }