public Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { var wait = new TaskCompletionSource <BrowserResult>(); _sf = new SFAuthenticationSession( new NSUrl(options.StartUrl), options.EndUrl, (callbackUrl, error) => { if (error != null) { var errorResult = new BrowserResult { ResultType = BrowserResultType.UserCancel, Error = error.ToString() }; wait.SetResult(errorResult); } else { var result = new BrowserResult { ResultType = BrowserResultType.Success, Response = callbackUrl.AbsoluteString }; wait.SetResult(result); } }); _sf.Start(); return(wait.Task); }
/// <inheritdoc /> public async Task <BrowserResultType> LogoutAsync(bool federated) { var logoutUrl = $"https://{_options.Domain}/v2/logout"; var dictionary = new Dictionary <string, string>(); dictionary.Add("client_id", _oidcClient.Options.ClientId); dictionary.Add("returnTo", _oidcClient.Options.PostLogoutRedirectUri); string endSessionUrl = new RequestUrl(logoutUrl).Create(dictionary); if (federated) { endSessionUrl += "&federated"; } var logoutRequest = new LogoutRequest(); BrowserResult browserResult = await _oidcClient.Options.Browser.InvokeAsync(new BrowserOptions(endSessionUrl, _oidcClient.Options.PostLogoutRedirectUri ?? string.Empty) { Timeout = TimeSpan.FromSeconds(logoutRequest.BrowserTimeout), DisplayMode = logoutRequest.BrowserDisplayMode }); return(browserResult.ResultType); }
public void TestSeveralNamespacesAssembly() { result = browser.Browse(@"Assemblies\Newtonsoft.Json.dll"); Assert.AreEqual(result.Namespaces.Count, 12); Assert.IsTrue(result.Namespaces.All(obj => obj.DataTypes.Count > 0)); Assert.IsTrue(result.Namespaces[8].DataTypes.All(ex => ex.Members.Count > 0)); }
public void TestInvalidAssembly() { result = browser.Browse(@"Assemblies\appxpackaging.dll"); Assert.AreEqual(result, null); result = browser.Browse(@"Assemblies\libcurl.dll"); Assert.AreEqual(result, null); }
internal async Task OnBrowserNavigating(object sender, WebNavigatingEventArgs e) { Loading = true; if (!(sender is WebView browser)) { Loading = false; throw new Exception($"Sender is not of type WebView"); } if (!Uri.TryCreate(e.Url, UriKind.Absolute, out Uri uri)) { Loading = false; throw new Exception($"Uri creation failed for: {e.Url}"); } if (string.IsNullOrEmpty(_options.EndUrl) == false) //IF THE CONDITION OVER HERE & FOR INNER IF CONDITIONS FAILS, LOADER WASNT SET TO FALSE { if (uri.AbsoluteUri.StartsWith(_options.EndUrl)) { _result = new BrowserResult() { ResultType = BrowserResultType.Success, Response = uri.Fragment.Substring(1) }; e.Cancel = true; if (!_navPopped) { _navPopped = true; Loading = false; await PopPageModel(); } } } Loading = false; }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken token = default) { using (var form = _formFactory.Invoke()) using (var browser = new ExtendedWebBrowser() { Dock = DockStyle.Fill }) { var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult { ResultType = BrowserResultType.UserCancel }; form.FormClosed += (o, e) => { signal.Release(); }; browser.NavigateError += (o, e) => { if (e.Url.StartsWith(options.EndUrl)) { e.Cancel = true; result.ResultType = BrowserResultType.Success; result.Response = e.Url; signal.Release(); } }; browser.DocumentCompleted += (o, e) => { if (e.Url.AbsoluteUri.StartsWith(options.EndUrl)) { result.ResultType = BrowserResultType.Success; result.Response = e.Url.AbsoluteUri; signal.Release(); } }; try { form.Controls.Add(browser); browser.Show(); form.Show(); browser.Navigate(options.StartUrl); await signal.WaitAsync(); } finally { form.Hide(); browser.Hide(); } return(result); } }
private void SetResult(BrowserResult result = BrowserResult.Succeed, string error = null) { if (tcs == null) { return; } switch (result) { case BrowserResult.Cancelled: { tcs.SetCanceled(); break; } case BrowserResult.Exception: { tcs.SetException(new Exception(error)); break; } case BrowserResult.Succeed: default: { tcs.SetResult(result); break; } } }
internal async Task OnBrowserNavigated(object sender, WebNavigatedEventArgs e) { Loading = false; if (!(sender is WebView browser)) { throw new Exception($"Sender is not of type WebView"); } if (!Uri.TryCreate(e.Url, UriKind.Absolute, out Uri uri)) { throw new Exception($"Uri creation failed for: {e.Url}"); } if (string.IsNullOrEmpty(_options.EndUrl)) { if (uri.LocalPath.ToLowerInvariant() == "/account/logout") { _result = new BrowserResult() { ResultType = BrowserResultType.Success }; if (!_navPopped) { _navPopped = true; await PopPageModel(); } } } }
private void SendTextData(Type objType, object obj, KeyValueCollection userData, iCallData value) { try { DataParser objDataParser = new DataParser(); string data = objDataParser.ParseTextString(objType, obj, userData, objURLConfiguration.DataToPost, objURLConfiguration.Delimiter, objURLConfiguration.ValueSeperator); if (objURLConfiguration.BrowserType == Pointel.Integration.Core.Data.BrowserType.AID) { logger.Info("Browser enabled inside the application to the web integration '" + objURLConfiguration.ApplicationName + "'"); DesktopMessenger.communicateUI.NotifyWebUrl(objURLConfiguration.PopupURL + "?" + data, objURLConfiguration.ApplicationName, DesktopMessenger.totalWebIntegration, objURLConfiguration.IsEnableNewWindowHook, objURLConfiguration.AllowDuplicateWindow, objURLConfiguration.IsSuppressScript, null); } else { // Code to handle External browser. browserHelper = new BrowserHelper(); BrowserResult result = browserHelper.Navigate((Pointel.WebDriver.BrowserType)((int)objURLConfiguration.BrowserType), objURLConfiguration.PopupURL + "?" + data); // System.Windows.MessageBox.Show(objURLConfiguration.PopupURL + "?" + data); if (!result.IsSuccess) { logger.Warn("External browser getting error while callin,'" + result.Message + "'"); } } } catch (Exception exception) { logger.Error("Error occurred as " + exception.ToString()); } }
private void PopupLoginPage() { try { if (string.IsNullOrEmpty(objURLConfiguration.LoginURL)) { logger.Warn("Login page is null or empty"); return; } if (objURLConfiguration.BrowserType == Pointel.Integration.Core.Data.BrowserType.AID) { logger.Info("Browser enabled inside the application to the web integration '" + objURLConfiguration.ApplicationName + "'"); DesktopMessenger.communicateUI.NotifyWebUrl(objURLConfiguration.LoginURL, objURLConfiguration.ApplicationName, DesktopMessenger.totalWebIntegration, objURLConfiguration.IsEnableNewWindowHook, objURLConfiguration.AllowDuplicateWindow, objURLConfiguration.IsSuppressScript); } else { // Code to handle External browser. browserHelper = new BrowserHelper(); BrowserResult result = browserHelper.Navigate((Pointel.WebDriver.BrowserType)((int)objURLConfiguration.BrowserType), objURLConfiguration.LoginURL); // System.Windows.MessageBox.Show(objURLConfiguration.LoginURL); if (!result.IsSuccess) { logger.Warn("External browser getting error while callin,'" + result.Message + "'"); } } } catch (Exception _generalException) { logger.Error("Error occurred as " + _generalException.Message); } }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { _options = options; var window = new Window() { Width = 900, Height = 625, Title = "TerminalMACS IdentityServer Login" }; // Note: Unfortunately, WebBrowser is very limited and does not give sufficient information for // robust error handling. The alternative is to use a system browser or third party embedded // library (which tend to balloon the size of your application and are complicated). var webBrowser = new WebBrowser(); var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult() { ResultType = BrowserResultType.UserCancel }; bool isSignalRelease = false; webBrowser.Navigating += (s, e) => { if (BrowserIsNavigatingToRedirectUri(e.Uri)) { e.Cancel = true; result = new BrowserResult() { ResultType = BrowserResultType.Success, Response = e.Uri.AbsoluteUri }; signal.Release(); isSignalRelease = true; window.Close(); } }; window.Closing += (s, e) => { if (!isSignalRelease) { signal.Release(); } }; window.Content = webBrowser; window.Show(); webBrowser.Source = new Uri(_options.StartUrl); await signal.WaitAsync(); return(result); }
private void BrowseAssembly() { AssemblyBrowser browser = new AssemblyBrowser(); BrowserResult result = browser.Browse(AssemblyPath); AssemblyFullName = result.FullName; AssemblyInfo = result.Namespaces; }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { _options = options; var window = new Window() { Width = 1100, Height = 625, Title = "IdentityServer Demo Login" }; // Note: Unfortunately, WebBrowser is very limited and does not give sufficient information for // robust error handling. The alternative is to use a system browser or third party embedded // library (which tend to balloon the size of your application and are complicated). var webBrowser = new WebBrowser(); var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult() { ResultType = BrowserResultType.UserCancel }; webBrowser.Navigating += (s, e) => { if (BrowserIsNavigatingToRedirectUri(e.Uri)) { e.Cancel = true; var responseData = GetResponseDataFromFormPostPage(webBrowser); result = new BrowserResult() { ResultType = BrowserResultType.Success, Response = responseData }; signal.Release(); window.Close(); } }; window.Closing += (s, e) => { signal.Release(); }; webBrowser.Source = new Uri(_options.StartUrl); window.Content = webBrowser; window.Show(); await signal.WaitAsync(); return(result); }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { _options = options; var semaphoreSlim = new SemaphoreSlim(0, 1); var browserResult = new BrowserResult() { ResultType = BrowserResultType.UserCancel }; var signinWindow = new Window() { Width = 800, Height = 600, Title = "Sign In", WindowStartupLocation = WindowStartupLocation.CenterScreen }; signinWindow.Closing += (s, e) => { semaphoreSlim.Release(); }; var webView = new WebView2(); webView.NavigationStarting += (s, e) => { if (IsBrowserNavigatingToRedirectUri(new Uri(e.Uri))) { e.Cancel = true; browserResult = new BrowserResult() { ResultType = BrowserResultType.Success, Response = new Uri(e.Uri).AbsoluteUri }; semaphoreSlim.Release(); signinWindow.Close(); } }; signinWindow.Content = webView; signinWindow.Show(); // Initialization await webView.EnsureCoreWebView2Async(null); // Delete existing Cookies so previous logins won't remembered webView.CoreWebView2.CookieManager.DeleteAllCookies(); // Navigate webView.CoreWebView2.Navigate(_options.StartUrl); await semaphoreSlim.WaitAsync(); return(browserResult); }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { var window = _windowFactory.Invoke(); try { var grid = new Grid(); window.Content = grid; var browser = new WebBrowser(); var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult { ResultType = BrowserResultType.UserCancel }; window.Closed += (o, e) => { signal.Release(); }; browser.LoadCompleted += (sender, args) => { if (args.Uri.ToString().StartsWith(options.EndUrl)) { result.ResultType = BrowserResultType.Success; result.Response = args.Uri.ToString(); signal.Release(); } }; grid.Children.Add(browser); window.Show(); browser.Navigate(options.StartUrl); await signal.WaitAsync(); if (!_shouldCloseWindow) { grid.Children.Clear(); } return(result); } finally { if (_shouldCloseWindow) { window.Close(); } } }
public static void ProcessResponse(Uri responseData) { var result = new BrowserResult { Response = responseData.OriginalString, ResultType = BrowserResultType.Success }; _inFlightRequest.SetResult(result); _inFlightRequest = null; }
/// <inheritdoc /> public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { var window = _windowFactory.Invoke(); using (var browser = new WebBrowser()) { var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult { ResultType = BrowserResultType.UserCancel }; window.Closed += (s, e) => { signal.Release(); }; browser.LoadCompleted += (s, e) => { if (e.Uri.ToString().StartsWith(options.EndUrl)) { result.ResultType = BrowserResultType.Success; result.Response = e.Uri.ToString(); signal.Release(); } }; try { window.Content = browser; window.Show(); browser.Navigate(options.StartUrl); await signal.WaitAsync(); } finally { if (_shouldCloseWindow) { window.Close(); } else { window.Content = null; } } return(result); } }
public void TestExtensionMethods() { result = browser.Browse(@"Assemblies\Chess.dll"); Assert.AreEqual(result.Namespaces[0].DataTypes.Single(obj => obj.Name == "ColorMethods").Members.Count, 0); IMember member = result.Namespaces[0].DataTypes.Single(obj => obj.Name == "Color").Members.Single(ex => ex.Name == "SwitchColor"); Assert.IsTrue((member as AssemblyMethod).Note == "ext" && (member as AssemblyMethod).Parameters[0].Name == "color"); Assert.AreEqual(result.Namespaces[0].DataTypes.Single(obj => obj.Name == "FigureMethods").Members.Count, 0); member = result.Namespaces[0].DataTypes.Single(obj => obj.Name == "Figure").Members.Single(ex => ex.Name == "GetColor"); Assert.IsTrue((member as AssemblyMethod).Note == "ext" && (member as AssemblyMethod).Parameters[0].ParameterType.Name == "Figure"); }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { if (!HttpListener.IsSupported) { throw new Exception("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); } cancellationToken.ThrowIfCancellationRequested(); using HttpListener listener = new HttpListener(); listener.Prefixes.Add(options.EndUrl); listener.Start(); var psi = new ProcessStartInfo { FileName = options.StartUrl, UseShellExecute = true }; Process.Start(psi); cancellationToken.ThrowIfCancellationRequested(); var context = await listener.GetContextAsync(); var result = new BrowserResult { ResultType = BrowserResultType.Success, Response = context.Request.Url.AbsoluteUri, }; context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Encoding.UTF8; var assembly = Assembly.GetExecutingAssembly(); var resourceName = "Boardgames.WpfClient.Resources.LoginSuccessful.html"; using (var stream = assembly.GetManifestResourceStream(resourceName)) { await stream.CopyToAsync(context.Response.OutputStream, cancellationToken); await context.Response.OutputStream.FlushAsync(cancellationToken); } context.Response.Close(); listener.Stop(); cancellationToken.ThrowIfCancellationRequested(); return(result); }
private void NavigateExternalBrowser(string url) { try { if (_browserHelperCaseData == null) { _browserHelperCaseData = new BrowserHelper(); } BrowserResult result = _browserHelperCaseData.Navigate((Pointel.WebDriver.BrowserType)((int)_himmsConfiguration.BrowserType), url); } catch (Exception generalException) { _logger.Error("Error occuured as " + generalException.Message); _logger.Trace("Error Trace: " + generalException.StackTrace); } }
public void TestSimpleAssembly() { result = browser.Browse(@"Assemblies\Tracer.dll"); Assert.AreEqual(result.Namespaces.Count, 1); Assert.AreEqual(result.Namespaces[0].Name, "Tracer"); Assert.AreEqual(result.Namespaces[0].DataTypes.Count, 7); Assert.IsTrue(result.Namespaces[0].DataTypes.Exists(obj => obj.Name == "TracerMain")); Assert.IsTrue(result.Namespaces[0].DataTypes.Exists(obj => obj.Name == "TraceResult")); Assert.IsTrue(result.Namespaces[0].DataTypes.Exists(obj => obj.Name == "ITracer")); List <IMember> members = result.Namespaces[0].DataTypes.Single(obj => obj.Name == "ThreadStack").Members; Assert.IsTrue(members.Exists(obj => obj.Name == "TraceWatches")); members = result.Namespaces[0].DataTypes.Single(obj => obj.Name == "ThreadItem").Members; Assert.IsTrue(members.Exists(obj => obj.Name == "ThreadID")); Assert.IsTrue(members.Single(obj => obj.Name == "ThreadID").Accessor == "public"); IMember member = result.Namespaces[0].DataTypes.Single(obj => obj.Name == "TracerMain").Members.Single(ex => ex.Name == "AddToTraceResult"); Assert.AreEqual((member as AssemblyMethod).Parameters[0].Name, "watch"); }
public Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { var wait = new TaskCompletionSource <BrowserResult>(); _af = new ASWebAuthenticationSession( new NSUrl(options.StartUrl), options.EndUrl, (callbackUrl, error) => { if (error != null) { var errorResult = new BrowserResult { ResultType = BrowserResultType.UserCancel, Error = error.ToString() }; wait.SetResult(errorResult); } else { var result = new BrowserResult { ResultType = BrowserResultType.Success, Response = callbackUrl.AbsoluteString }; wait.SetResult(result); } }); // iOS 13 requires the PresentationContextProvider set if (UIDevice.CurrentDevice.CheckSystemVersion(13, 0)) { _af.PresentationContextProvider = new PresentationContextProviderToSharedKeyWindow(); } _af.Start(); return(wait.Task); }
public async Task Browse(string url, string token) { var window = new Window() { Width=900, Height=625, Title = "IdentityServer Website" }; // Note: Unfortunately, WebBrowser is very limited and does not give sufficient information for // robust error handling. The alternative is to use a system browser or third party embedded // library (which tend to balloon the size of your application and are complicated). var webBrowser = new WebBrowser(); var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult() { ResultType = BrowserResultType.UserCancel }; webBrowser.Navigating += (s, e) => { }; window.Closing += (s, e) => { signal.Release(); }; window.Content = webBrowser; window.Show(); webBrowser.Source = new Uri(url + "?access_token=" + token); await signal.WaitAsync(); }
private void PopupLoginUrl(string url) { try { if (_himmsConfiguration.BrowserType == Pointel.Integration.Core.Data.BrowserType.IExplorer) { if (!_himmsConfiguration.IsEnableSingleWindowPopup) { _loginBrowser = null; } if (_loginBrowser == null) { isCaseIDOpened = isCaseURLOpened = isMIDOpened = false; try { _loginBrowser = (SHDocVw.WebBrowser)(new SHDocVw.InternetExplorer()); _loginBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(_loginBrowser_DocumentComplete); _loginBrowser.AddressBar = _himmsConfiguration.IsEnableAddressBar; _loginBrowser.StatusBar = _himmsConfiguration.IsEnableStatusBar; if (_himmsConfiguration.WindowWidth != 0) { _loginBrowser.Width = _himmsConfiguration.WindowWidth; } if (_himmsConfiguration.WindowHeight != 0) { _loginBrowser.Height = _himmsConfiguration.WindowHeight; } _loginBrowser.FullScreen = _himmsConfiguration.IsEnableFullScreen; _loginBrowser.MenuBar = _himmsConfiguration.IsEnableMenuBar; _loginBrowser.Resizable = _himmsConfiguration.IsEnableResizeWindow; } catch (Exception generalExcption) { _logger.Error("Error occurred as " + generalExcption.Message); _logger.Trace("Error trace : " + generalExcption.StackTrace); return; } } _logger.Trace("Try to navigate through IE browser for login."); try { _loginBrowser.Navigate(url); var inptr = new IntPtr(_loginBrowser.HWND); ShowWindow(inptr, 9); } catch (Exception generalException) { _logger.Warn("Error occurred as " + generalException.Message); _loginBrowser = null; PopupLoginUrl(url); } } else if (_himmsConfiguration.BrowserType == Pointel.Integration.Core.Data.BrowserType.AID) { DesktopMessenger.communicateUI.NotifyWebUrl(url, "himms", DesktopMessenger.totalWebIntegration); } else if (_himmsConfiguration.BrowserType == Pointel.Integration.Core.Data.BrowserType.Chrome || _himmsConfiguration.BrowserType == Pointel.Integration.Core.Data.BrowserType.Firefox) { if (_browserHelperCaseData == null) { _browserHelperCaseData = new BrowserHelper(); } BrowserResult result = _browserHelperCaseData.Navigate((Pointel.WebDriver.BrowserType)((int)_himmsConfiguration.BrowserType), url); } else { _logger.Trace("Try to navigate through IE shell browser for login."); NavigateIEShell(url, ""); } } catch (Exception generalException) { _logger.Error("Error occurred as " + generalException.Message); _logger.Trace("Error Trace : " + generalException.StackTrace); } }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { using (var form = _formFactory.Invoke()) using (var browser = new ExtendedWebBrowser() { Dock = DockStyle.Fill }) { var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult { ResultType = BrowserResultType.UserCancel }; form.FormClosed += (o, e) => { signal.Release(); }; browser.NavigateError += (o, e) => { e.Cancel = true; result.ResultType = BrowserResultType.HttpError; result.Error = e.StatusCode.ToString(); signal.Release(); }; browser.BeforeNavigate2 += (o, e) => { if (e.Url.StartsWith(options.EndUrl)) { e.Cancel = true; result.ResultType = BrowserResultType.Success; if (options.ResponseMode == OidcClientOptions.AuthorizeResponseMode.FormPost) { result.Response = Encoding.UTF8.GetString(e.PostData ?? new byte[] { }).Trim('\0'); } else { result.Response = e.Url; } signal.Release(); } }; form.Controls.Add(browser); browser.Show(); System.Threading.Timer timer = null; form.Show(); browser.Navigate(options.StartUrl); await signal.WaitAsync(); if (timer != null) { timer.Change(Timeout.Infinite, Timeout.Infinite); } form.Hide(); browser.Hide(); return(result); } }
//public event EventHandler<HiddenModeFailedEventArgs> HiddenModeFailed; public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { using (var form = _formFactory.Invoke()) using (var browser = new ExtendedWebBrowser() { Dock = DockStyle.Fill }) { var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult { ResultType = BrowserResultType.UserCancel }; form.FormClosed += (o, e) => { signal.Release(); }; browser.NavigateError += (o, e) => { e.Cancel = true; result.ResultType = BrowserResultType.HttpError; result.Error = e.StatusCode.ToString(); signal.Release(); }; browser.DocumentCompleted += (o, e) => { if (e.Url.ToString().StartsWith(options.EndUrl)) { result.ResultType = BrowserResultType.Success; if (options.ResponseMode == OidcClientOptions.AuthorizeResponseMode.FormPost) { //result.Response = Encoding.UTF8.GetString(e.PostData ?? new byte[] { }); } else { result.Response = e.Url.ToString(); } signal.Release(); } }; form.Controls.Add(browser); browser.Show(); System.Threading.Timer timer = null; if (options.DisplayMode != DisplayMode.Visible) { //result.ResultType = InvokeResultType.Timeout; //timer = new System.Threading.Timer((o) => //{ // var args = new HiddenModeFailedEventArgs(result); // HiddenModeFailed?.Invoke(this, args); // if (args.Cancel) // { // browser.Stop(); // form.Invoke(new Action(() => form.Close())); // } // else // { // form.Invoke(new Action(() => form.Show())); // } //}, null, (int)options.InvisibleModeTimeout.TotalSeconds * 1000, Timeout.Infinite); } else { form.Show(); } browser.Navigate(options.StartUrl); await signal.WaitAsync(); if (timer != null) { timer.Change(Timeout.Infinite, Timeout.Infinite); } form.Hide(); browser.Hide(); return(result); } }
public Task <BrowserResult> InvokeAsync(BrowserOptions options) { if (string.IsNullOrWhiteSpace(options.StartUrl)) { throw new ArgumentException("Missing StartUrl", nameof(options)); } if (string.IsNullOrWhiteSpace(options.EndUrl)) { throw new ArgumentException("Missing EndUrl", nameof(options)); } // must be able to wait for the authentication session to be finished to continue // with setting the task result var tcs = new TaskCompletionSource <BrowserResult>(); // For iOS 12, we use ASWebAuthenticationSession if (UIDevice.CurrentDevice.CheckSystemVersion(12, 0)) { // create the authentication session _asWebAuthenticationSession = new ASWebAuthenticationSession( new NSUrl(options.StartUrl), options.EndUrl, (callbackUrl, error) => { var browserResult = new BrowserResult(); if (error != null) { if (error.Code == (long)ASWebAuthenticationSessionErrorCode.CanceledLogin) { browserResult.ResultType = BrowserResultType.UserCancel; } else { browserResult.ResultType = BrowserResultType.UnknownError; } browserResult.Error = error.ToString(); tcs.SetResult(browserResult); } else { tcs.SetResult(new BrowserResult { ResultType = BrowserResultType.Success, Response = callbackUrl.AbsoluteString }); } }); // launch authentication session _asWebAuthenticationSession.Start(); } // For iOS 11, we use SFAuthenticationSession else if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { // create the authentication session _sfAuthenticationSession = new SFAuthenticationSession( new NSUrl(options.StartUrl), options.EndUrl, (callbackUrl, error) => { var browserResult = new BrowserResult(); if (error != null) { if (error.Code == (long)SFAuthenticationError.CanceledLogin) { browserResult.ResultType = BrowserResultType.UserCancel; } else { browserResult.ResultType = BrowserResultType.UnknownError; } browserResult.Error = error.ToString(); tcs.SetResult(browserResult); } else { tcs.SetResult(new BrowserResult { ResultType = BrowserResultType.Success, Response = callbackUrl.AbsoluteString }); } }); // launch authentication session _sfAuthenticationSession.Start(); } else // For pre-iOS 11, we use a normal SFSafariViewController { // create Safari controller _safari = new SFSafariViewController(new NSUrl(options.StartUrl)) { Delegate = this }; ActivityMediator.MessageReceivedEventHandler callback = null; callback = async(response) => { // remove handler ActivityMediator.Instance.ActivityMessageReceived -= callback; if (response == "UserCancel") { tcs.SetResult(new BrowserResult { ResultType = BrowserResultType.UserCancel }); } else { // Close Safari await _safari.DismissViewControllerAsync(true); // set result tcs.SetResult(new BrowserResult { Response = response, ResultType = BrowserResultType.Success }); } }; // attach handler ActivityMediator.Instance.ActivityMessageReceived += callback; // https://forums.xamarin.com/discussion/24689/how-to-acces-the-current-view-uiviewcontroller-from-an-external-service var window = UIApplication.SharedApplication.KeyWindow; var vc = window.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } // launch Safari vc.PresentViewController(_safari, true, null); } // Result for this task will be set in the authentication session // completion handler return(tcs.Task); }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { var window = new Window { Width = 900, Height = 625, Title = "Вход в аккаунт" }; var browser = new WebView(); var signal = new SemaphoreSlim(0, 1); var result = new BrowserResult { ResultType = BrowserResultType.UserCancel }; browser.DOMContentLoaded += (s, e) => { Log($"Loaded {e?.ToString()}"); }; browser.Loaded += (s, e) => { Log($"Loaded {e?.ToString()}"); }; browser.NavigationCompleted += (s, e) => { Log($"NavigationCompleted {e.Uri.AbsoluteUri}"); }; browser.NavigationStarting += (s, e) => { Log($"NavigationStarting {e.Uri.AbsoluteUri}"); if (!e.Uri.AbsoluteUri.StartsWith(options.EndUrl)) { return; } e.Cancel = true; var responseData = GetResponseDataFromFormPostPage(browser); result = new BrowserResult { ResultType = BrowserResultType.Success, Response = responseData }; signal.Release(); window.Close(); }; window.Closing += (s, e) => signal.Release(); window.Content = browser; window.Show(); browser.Navigate(new Uri(options.StartUrl)); await signal.WaitAsync(); return(result); }