private async void SignIn() { ShowProgressRing(true); // First of all, try to get OAuth URL by using specified ServerUrl try { await CRMHelper.DiscoveryAuthority(); } catch (Exception ex) { // If failed, then simply go back to page without doing anything more. ShowProgressRing(false); return; } // Assing ServerUrl, ResourceName to CRMHelper._proxy CRMHelper._proxy.ServiceUrl = CRMHelper.ResourceName = txtServerUrl.Text; // Cache ServerUrl await Util.SaveToLocal(txtServerUrl.Text, "serverUrl.dat"); // Register background task. await Util.RegisterBackgroundTask("CRMtoGoBackgroundTasks.UpdateSystemUserTimeZone", "UpdateSystemUserTimeZone", new SystemTrigger(SystemTriggerType.TimeZoneChange, false), new SystemCondition(SystemConditionType.InternetAvailable)); // Initialize CRMHelper await CRMHelper.Initialize(); Frame.Navigate(typeof(Home)); // To prevent user from back to this page by pressing back button, remove this page history from Navigation history Frame.BackStack.RemoveAt(Frame.BackStackDepth - 1); }
/// <summary> /// This method try to obtain AccessToken by using OAuth2 authentication agianst Microsoft Azure AD. /// </summary> static public async Task GetTokenSilent() { // Before create AuthenticationContext, check if Authority(OAuthUrl) is available. if (String.IsNullOrEmpty(CRMHelper.OAuthUrl)) { bool success = true; try { await CRMHelper.DiscoveryAuthority(); } catch (Exception ex) { // If failed to retireve OAuthUrl, then make success as false success = false; } // If failed to retrieve OAuthUrl, chances are user mistype ServerUrl. if (!success) { MessageDialog dialog = new MessageDialog("OAuth Url retrieve failed. Please check Service URL again."); await dialog.ShowAsync(); return; } } if (CRMHelper.SignOut) { if (authContext != null) { authContext.TokenCache.Clear(); } CRMHelper.SignOut = false; } // Create AuthenticationContext by using OAuthUrl. if (authContext == null) { authContext = await AuthenticationContext.CreateAsync(CRMHelper.OAuthUrl); } // Try to acquire token without prompting user first. AuthenticationResult result = await authContext.AcquireTokenSilentAsync(CRMHelper.ResourceName, CRMHelper.ClientId); // Check the result. if (result != null && result.Status == AuthenticationStatus.Success) { // A token was successfully retrieved. Then store it. StoreToken(result); } // If failed to obtain token without prompting, then prompt user for credentials else { // Clear AccessToken CRMHelper._proxy.AccessToken = ""; // In case credential was wrong, clear the token cache first. authContext.TokenCache.Clear(); // Acquiring a token without user interaction was not possible. // Trigger an authentication experience and specify that once a token has been obtained the StoreToken method should be called. authContext.AcquireTokenAndContinue(CRMHelper.ResourceName, CRMHelper.ClientId, new Uri(CRMHelper.RedirectUri), StoreToken); } }