//[Fact] public async void Can_Authenticate_With_OAuth() { WwwFormUrlDecoder decoder; var baseUrl = "https://api.twitter.com"; var client = new RestClient(baseUrl); client.Authenticator = OAuth1Authenticator.ForRequestToken( "CONSUMER_KEY", "CONSUMER_SECRET" ); var request = new RestRequest("oauth/request_token"); var response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); decoder = new WwwFormUrlDecoder(response.Content); var oauth_token = decoder.GetFirstValueByName("oauth_token"); var oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret"); //var qs = HttpUtility.ParseQueryString(response.Content); //var oauth_token = qs["oauth_token"]; //var oauth_token_secret = qs["oauth_token_secret"]; Assert.IsNotNull(oauth_token); Assert.IsNotNull(oauth_token_secret); request = new RestRequest("oauth/authorize?oauth_token=" + oauth_token); var url = client.BuildUri(request).ToString(); //Process.Start(url); var verifier = "123456"; // <-- Breakpoint here (set verifier in debugger) request = new RestRequest("oauth/access_token"); client.Authenticator = OAuth1Authenticator.ForAccessToken( "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauth_token, oauth_token_secret, verifier ); response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); decoder = new WwwFormUrlDecoder(response.Content); oauth_token = decoder.GetFirstValueByName("oauth_token"); oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret"); //qs = HttpUtility.ParseQueryString(response.Content); //oauth_token = qs["oauth_token"]; //oauth_token_secret = qs["oauth_token_secret"]; Assert.IsNotNull(oauth_token); Assert.IsNotNull(oauth_token_secret); request = new RestRequest("account/verify_credentials.xml"); client.Authenticator = OAuth1Authenticator.ForProtectedResource( "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauth_token, oauth_token_secret ); response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); }
internal void HandleUri(Uri uri) { var query = new Dictionary <string, string>(); if (uri.Query.Length > 0) { var decoder = new WwwFormUrlDecoder(uri.Query); query = decoder.ToDictionary(x => x.Name, x => x.Value); } switch (uri.Host) { case "settitle": // I'm not entirely sure if this is applicable // Sets values like title=Confirmations or title=Chat break; case "lostauth": // This code had a massive tantrum when run outside the application's thread this.account.RefreshSession(this.web, async success => { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (success == Success.Success) { Action <object, RoutedEventArgs> call = this.ChatWeb.Visibility == Visibility.Visible ? this.MessageButton_Click : this.ConfirmationWeb.Visibility == Visibility.Visible ? this.ConfirmationsButton_Click : (Action <object, RoutedEventArgs>) this.SteamGuardButton_Click; call(null, null); } else if (success == Success.Error) { this.SteamGuardButton_Click(null, null); } else { Storage.Logout(); this.Frame.Navigate(typeof(LoginPage)); } }); }); break; case "steamguard": if (query["op"] != "conftag") { break; } this.account.GenerateConfirmationQueryParams(this.web, query["arg1"], async response => { try { string[] args = { "window.SGHandler.update('" + response + "', 'ok');" }; await this.ConfirmationWeb.InvokeScriptAsync("eval", args); } catch (Exception) { // We're probably here because the webview was unloaded // Just reload the view this.ConfirmationsButton_Click(null, null); } }); break; default: Debug.WriteLine("Unhandled uri: " + uri.AbsoluteUri); break; } }
public static string ExtractParamterFromQuery(this Uri uri, string parameterName) { var urlDecoder = new WwwFormUrlDecoder(uri.Query); return(urlDecoder.GetFirstValueByName(parameterName)); }
public override async Task AuthorizeAsync() { if (LocalAccessToken.IsUseable) { AccessToken = LocalAccessToken.Value; Uid = LocalAccessToken.Uid; } else { var authorizeUri = new Uri("https://api.weibo.com/oauth2/authorize", UriKind.Absolute); var authorizeUriBuilder = new UriBuilder(authorizeUri); var authorizeQuery = new Dictionary <string, string>() { ["client_id"] = AppKey, ["redirect_uri"] = RedirectUri }; if (Scope != null) { authorizeQuery["scope"] = Scope; } if (DeviceFamilyHelper.IsMobile) { authorizeQuery["display"] = "mobile"; } if (!CultureInfo.CurrentUICulture.Name.StartsWith("zh", StringComparison.OrdinalIgnoreCase)) { authorizeQuery["language"] = "en"; } authorizeUriBuilder.Query = ToUriQuery(authorizeQuery); authorizeUri = authorizeUriBuilder.Uri; var authorizeResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authorizeUri, new Uri(RedirectUri, UriKind.Absolute)); switch (authorizeResult.ResponseStatus) { case WebAuthenticationStatus.Success: var responseUrl = authorizeResult.ResponseData; var responseUri = new Uri(responseUrl, UriKind.Absolute); var responseUriDecoder = new WwwFormUrlDecoder(responseUri.Query); var authorizeCode = responseUriDecoder.GetFirstValueByName("code"); var getAccessTokenQuery = new Dictionary <string, string>() { ["client_id"] = AppKey, ["client_secret"] = AppSecret, ["grant_type"] = "authorization_code", ["code"] = authorizeCode, ["redirect_uri"] = RedirectUri }; var requestTime = DateTimeOffset.Now; var json = await HttpPostAsync("https://api.weibo.com/oauth2/access_token", getAccessTokenQuery, false); var accessToken = JsonConvert.DeserializeObject <AccessToken>(json); AccessToken = accessToken.Value; Uid = accessToken.Uid; LocalAccessToken.Value = accessToken.Value; LocalAccessToken.Uid = accessToken.Uid; LocalAccessToken.ExpiresAt = requestTime.AddSeconds(accessToken.ExpiresIn); break; case WebAuthenticationStatus.UserCancel: throw new UserCancelAuthorizeException(authorizeResult); case WebAuthenticationStatus.ErrorHttp: throw new AuthorizeErrorHttpException(authorizeResult); } } }
private async Task HandleProtocolActivation(IActivatedEventArgs args) { var protocolArgs = (ProtocolActivatedEventArgs)args; var uri = protocolArgs.Uri; if (string.IsNullOrEmpty(uri.Query)) { return; } WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query); switch (uri.Host) { case "goto": if (decoder[0]?.Name == "page") { if (decoder[0]?.Value == VLCPage.SettingsPageUI.ToString()) { Locator.NavigationService.Go(VLCPage.SettingsPageUI); } } break; case "openstream": // do stuff if (decoder[0]?.Name == "from") { switch (decoder[0]?.Value) { case "clipboard": await Task.Delay(1000); var dataPackage = Clipboard.GetContent(); Uri url = null; if (dataPackage.Contains(StandardDataFormats.ApplicationLink)) { url = await dataPackage.GetApplicationLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.WebLink)) { url = await dataPackage.GetWebLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.Text)) { url = new Uri(await dataPackage.GetTextAsync()); } if (url != null) { await Locator.MediaPlaybackViewModel.PlayStream(url.AbsoluteUri); } break; case "useraction": Locator.NavigationService.Go(VLCPage.MainPageNetwork); break; case "url": if (decoder[1]?.Name == "url") { if (!string.IsNullOrEmpty(decoder[1]?.Value)) { await Locator.MediaPlaybackViewModel.PlayStream(decoder[1].Value); } } break; } } break; } }
private async Task ProcessCommand(WwwFormUrlDecoder querybag, IOutputStream outstream) { try { if (!bot.HasArduino) { throw new IOException("No Arduino Device Connected"); } string botCmd = querybag.GetFirstValueByName("cmd").ToLowerInvariant(); // Throws System.ArgumentException if not found switch (botCmd) { case "stop": { await bot.Stop(); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "status": { if (bot.IsMoving) { float moveProgress = bot.MoveProgress; var moveProg = Math.Floor(moveProgress * 100.0f); string s = "{command=\"" + lastCommand + "\", percent=\"" + moveProg.ToString() + "\"}"; await WriteResponseAsync("200 OK", s, outstream); } else { string s = "{command=\"" + lastCommand + "\"}"; await WriteResponseAsync("200 OK", s, outstream); } break; } case "move": { float dst = float.Parse(querybag.GetFirstValueByName("dst")); await bot.Move(dst); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "movelr": { float dstl = float.Parse(querybag.GetFirstValueByName("dstl")); float dstr = float.Parse(querybag.GetFirstValueByName("dstr")); await bot.Move(dstl, dstr); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "rotate": { float deg = float.Parse(querybag.GetFirstValueByName("deg")); await bot.Rotate(deg); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "mission": { try { int m = int.Parse(querybag.GetFirstValueByName("mission")); await bot.Mission(m); await WriteResponseAsync("200 OK", successMsg, outstream); } catch { } } break; case "shutdown": { await WriteResponseAsync("200 OK", successMsg, outstream); // how do I initiate shutdown? break; } default: { await WriteResponseAsync("400 Bad Request", string.Format("UNSUPPORTED COMMAND: {0}", botCmd), outstream); break; } } lastCommand = botCmd; } catch (ArgumentException) { await WriteResponseAsync("400 Bad Request", "INVALID QUERY STRING", outstream); } catch (Exception e) { await WriteResponseAsync("500 Internal Server Error", e.Message + e.StackTrace, outstream); } }
protected override void OnActivated(IActivatedEventArgs e) { Frame rootFrame = InitRootFrame(e.PreviousExecutionState); // Handle toast activation if (e.Kind == ActivationKind.ToastNotification) { var toastActivationArgs = e as ToastNotificationActivatedEventArgs; logger.Info($"ToastActivation with argument '{toastActivationArgs.Argument}'."); // Parse the query string (using QueryString.NET) var args = new WwwFormUrlDecoder(toastActivationArgs.Argument); // See what action is being requested switch (args.GetFirstValueByName("action")) { // Open the image case "reopenApp": if (rootFrame.Content == null) { rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo()); } break; } } else if (e.Kind == ActivationKind.Protocol) { var args = e as ProtocolActivatedEventArgs; var uri = args.Uri.ToString(); var currentMainPage = (rootFrame.Content as MainPage); logger.Info($"ProtocolActivation with uri '{uri}'."); var targetPwaUri = SpotifyShareUriHelper.GetPwaUri(uri); if (string.IsNullOrWhiteSpace(targetPwaUri)) { // Invalid uri, will launch default page if (currentMainPage == null) { // if MainPage is not opened, navigate to MainPage with the necessary argument rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo()); } } else { var argument = "pageUrl=" + WebUtility.UrlEncode(targetPwaUri); if (uri.ToLower().StartsWith("spotify:nl:")) { var autoplay = targetPwaUri.ToLower().Contains("/track/") ? "track" : "playlist"; argument += "&autoplay=" + autoplay; argument += "&source=cortana"; } if (currentMainPage == null) { // if MainPage is not opened, navigate to MainPage with the necessary argument rootFrame.Navigate(typeof(MainPage), argument); } else { // if MainPage is opened already, send a signal to it so it can navigate to the new url. currentMainPage.NavigateWithConfig(argument); } } } // TODO: Handle other types of activation // Ensure the current window is active Window.Current.Activate(); }
private async Task ProcessCommand(WwwFormUrlDecoder querybag, IOutputStream outstream) { try { if (!bot.HasArduino) { throw new IOException("No Arduino Device Connected"); } string botCmd = querybag.GetFirstValueByName("cmd").ToLowerInvariant(); // Throws System.ArgumentException if not found switch (botCmd) { case "stop": { await bot.Stop(); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "status": { if (bot.IsMoving) { float moveProgress = bot.MoveProgress; var moveProg = Math.Floor(moveProgress * 100.0f); string s = "{command=\"" + lastCommand + "\", percent=\"" + moveProg.ToString() + "\"}"; await WriteResponseAsync("200 OK", s, outstream); } else { string s = "{command=\"" + lastCommand + "\"}"; await WriteResponseAsync("200 OK", s, outstream); } break; } case "move": { float dst = float.Parse(querybag.GetFirstValueByName("dst")); await bot.Move(dst); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "movelr": { float dstl = float.Parse(querybag.GetFirstValueByName("dstl")); float dstr = float.Parse(querybag.GetFirstValueByName("dstr")); await bot.Move(dstl, dstr); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "setcolor": { byte r = 0; byte g = 0; byte b = 0; // queryBag will throw an exception if it doesn't find it. // And you can't query if it is there. try { r = byte.Parse(querybag.GetFirstValueByName("r")); } catch { } try { g = byte.Parse(querybag.GetFirstValueByName("g")); } catch { } try { b = byte.Parse(querybag.GetFirstValueByName("b")); } catch { } await bot.SetLedColor(r, g, b); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "rotate": { float deg = float.Parse(querybag.GetFirstValueByName("deg")); await bot.Rotate(deg); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "neckextend": { await bot.RaiseNeck(); await WriteResponseAsync("200 OK", botCmd, outstream); break; } case "neckretract": { await bot.LowerNeck(); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "armextend": { await bot.RaiseArm(); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "armretract": { await bot.LowerArm(); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "neckextendtime": { int time = int.Parse(querybag.GetFirstValueByName("ms")); await bot.RaiseNeck(time); await WriteResponseAsync("200 OK", botCmd, outstream); break; } case "neckretracttime": { int time = int.Parse(querybag.GetFirstValueByName("ms")); await bot.LowerNeck(time); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "armextendtime": { int time = int.Parse(querybag.GetFirstValueByName("ms")); await bot.RaiseArm(time); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "armretracttime": { int time = int.Parse(querybag.GetFirstValueByName("ms")); await bot.LowerArm(time); await WriteResponseAsync("200 OK", successMsg, outstream); break; } case "camcapture": { await WriteResponseAsync("400 OK", successMsg, outstream); break; } case "getbattery": { string s = "{success=\"ok\", \"percent\"=\"50\"}"; await WriteResponseAsync("200 OK", s, outstream); break; } case "getwifi": { string s = "{success=\"ok\", \"percent\"=\"90\"}"; await WriteResponseAsync("200 OK", s, outstream); break; } case "getcompass": { string s = "{success=\"ok\", \"heading\"=\"90\"}"; await WriteResponseAsync("200 OK", s, outstream); break; } case "getaltitude": { string s = "{success=\"ok\", \"altitude\"=\"2400m\"}"; await WriteResponseAsync("200 OK", s, outstream); break; } case "gettemp": { string s = "{success=\"ok\", \"temp\"=\"72f\"}"; await WriteResponseAsync("200 OK", s, outstream); break; } case "shutdown": { await WriteResponseAsync("200 OK", successMsg, outstream); // how do I initiate shutdown? break; } default: { await WriteResponseAsync("400 Bad Request", string.Format("UNSUPPORTED COMMAND: {0}", botCmd), outstream); break; } } lastCommand = botCmd; } catch (ArgumentException) { await WriteResponseAsync("400 Bad Request", "INVALID QUERY STRING", outstream); } catch (Exception e) { await WriteResponseAsync("500 Internal Server Error", e.Message + e.StackTrace, outstream); } }
private void DevicePortalConnection_RequestReceived(DevicePortalConnection sender, DevicePortalConnectionRequestReceivedEventArgs args) { var req = args.RequestMessage; var res = args.ResponseMessage; if (req.RequestUri.AbsolutePath.ToString() == statusUri.ToString()) { args.ResponseMessage.StatusCode = HttpStatusCode.Ok; MemoryStream mem = new MemoryStream(); serializer.WriteObject(mem, AppSettings.Current); mem.Position = 0; args.ResponseMessage.Content = new HttpStringContent(new StreamReader(mem).ReadToEnd()); args.ResponseMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); return; } if (req.RequestUri.AbsolutePath.ToString() == updateUri.ToString()) { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(req.RequestUri.Query); AppSettings.Current.DARKSKY_API_KEY = decoder.GetFirstValueByName("DARKSKY_API_KEY"); AppSettings.Current.RAIL_API_KEY = decoder.GetFirstValueByName("RAIL_API_KEY"); AppSettings.Current.STATION_CRS = decoder.GetFirstValueByName("STATION_CRS"); AppSettings.Current.LOCATION_LAT = double.Parse(decoder.GetFirstValueByName("LOCATION_LAT")); AppSettings.Current.LOCATION_LNG = double.Parse(decoder.GetFirstValueByName("LOCATION_LNG")); AppSettings.Current.GET_DRINK_TIME = int.Parse(decoder.GetFirstValueByName("GET_DRINK_TIME")); AppSettings.Current.DRINK_UP_TIME = int.Parse(decoder.GetFirstValueByName("DRINK_UP_TIME")); AppSettings.Current.WALK_TIME_TO_STATION = int.Parse(decoder.GetFirstValueByName("WALK_TIME_TO_STATION")); AppSettings.Current.Save(); args.ResponseMessage.StatusCode = HttpStatusCode.Ok; args.ResponseMessage.Content = new HttpStringContent("{ \"status\": \"good\" }"); args.ResponseMessage.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); return; } if (req.RequestUri.LocalPath.ToLower().Contains("/www/") || req.RequestUri.LocalPath.ToLower().EndsWith("/")) { var filePath = req.RequestUri.AbsolutePath.Replace('/', '\\').ToLower(); //filePath = filePath.Replace("\\departureboard", ""); if (filePath.EndsWith(@"\")) { filePath += @"\www\index.html"; } try { var fileStream = Windows.ApplicationModel.Package.Current.InstalledLocation.OpenStreamForReadAsync(filePath).GetAwaiter().GetResult(); res.StatusCode = HttpStatusCode.Ok; res.Content = new HttpStreamContent(fileStream.AsInputStream()); res.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/html"); } catch (FileNotFoundException e) { string con = String.Format("<h1>{0} - not found</h1>\r\n", filePath); con += "Exception: " + e.ToString(); res.Content = new HttpStringContent(con); res.StatusCode = HttpStatusCode.NotFound; res.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("text/html"); } return; } args.ResponseMessage.StatusCode = HttpStatusCode.NotFound; }
public SaveParameters(string uri) { // Restor de recursos ResourceLoader labels = new Windows.ApplicationModel.Resources.ResourceLoader(); // Analizador de parametros en URL WwwFormUrlDecoder decoder; try { decoder = new WwwFormUrlDecoder(uri.Substring(uri.IndexOf("?"), uri.Length - uri.IndexOf("?"))); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W00)"); } // Comprobamos los parámetros obligatorios uno a uno // Nombre del fichero (opcional) try { this.fileName = decoder.GetFirstValueByName(FILENAME); } catch (Exception) { fileName = null; } // Extensión del fichero (opcional) try { this.extension = decoder.GetFirstValueByName(EXTENSION); if (!this.extension.StartsWith(".")) { this.extension = "." + this.extension; } } catch (Exception) { this.extension = EXTENSION_DEFAULT; } // Descripción del fichero (opcional) try { this.description = decoder.GetFirstValueByName(DESCRIPTION); } catch (Exception) { this.description = null; } // Entorno GUI de origen (opcional, en caso de error o ausencia se toma el escritorio clásico como origen) try { Boolean.TryParse(decoder.GetFirstValueByName(FROM), out this.metro); } catch (Exception) { metro = false; } // *********************** // *** Datos a guardar *** // *********************** string dataBase64 = null; try { dataBase64 = decoder.GetFirstValueByName(DATA); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W02)"); } // Deshacemos la codificación URL si existiese dataBase64 = dataBase64.Replace('_', '/').Replace('-', '+'); try { // Guardamos los datos descodificados this.data = Convert.FromBase64String(dataBase64); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W10)"); } }
public static DrxCommand Parse(Uri uri) { var segments = uri.Segments; var action = "open"; if (!string.IsNullOrWhiteSpace(uri.Query)) { var decoder = new WwwFormUrlDecoder(uri.Query); action = decoder.GetFirstValueByName("action"); } // Examples: // drx://localhost/stores/0d0a0dc4-4ed5-479a-b6db-706ca6e80cb6/documents/70abd4d3-46fb-4707-bf30-a8c29794835d?action=properties // drx://localhost[?action={new/restore}] // drx://localhost/[store][?action={delete/properties/backup}] // drx://localhost/[store]/documents[?action={new}] // drx://localhost/[store]/documents/[document][?action={delete/properties}] // drx://localhost/[store]/flags[?action={new}] // drx://localhost/[store]/flags/[flag][?action={delete/properties]] // drx://192.168.1.27:43105/stores/0d0a0dc4-4ed5-479a-b6db-706ca6e80cb6 (remote) if (uri.Host != "localhost") { return(null); // TODO: remote host not yet implemented } switch (segments[1].Trim('/')) { case "stores": // We're executing a command on the store service if (segments.Length <= 2) { return new DrxCommand { Command = action, Subject = DrxCommandSubject.StoreService } } ; if (!Guid.TryParse(segments[2].Trim('/'), out var storeId)) { return(null); } var command = new DrxCommand { Command = action, Parameters = { ["storeId"] = storeId } }; // We're executing a command on the store if (segments.Length == 3) { command.Subject = DrxCommandSubject.Store; return(command); } var isRoot = segments.Length == 4; switch (segments[3].Trim('/')) { case "documents": command.Subject = isRoot ? DrxCommandSubject.StoreDocuments : DrxCommandSubject.Document; break; case "flags": command.Subject = isRoot ? DrxCommandSubject.StoreFlags : DrxCommandSubject.Flag; break; default: return(null); } if (isRoot) { return(command); } if (!Guid.TryParse(segments[4].Trim('/'), out var ctxId)) { return(null); } command.Parameters["contextId"] = ctxId; return(command); default: return(null); } }
public SignParameters(string uri) { // Restor de recursos ResourceLoader labels = new Windows.ApplicationModel.Resources.ResourceLoader(); // Analizador de parametros en URL WwwFormUrlDecoder decoder; try { decoder = new WwwFormUrlDecoder(uri.Substring(uri.IndexOf("?"), uri.Length - uri.IndexOf("?"))); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W00)"); } // Comprobamos los parámetros obligatorios uno a uno // Direccion del servlet de almacenamiento, comprobamos que exista y que sea una URI // valida con http o https string servlet; try { servlet = decoder.GetFirstValueByName(SERVLET_STORAGE); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W01)"); } try { this.servletUri = new Uri(servlet); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W02)"); } if (servletUri.Scheme != "http" && servletUri.Scheme != "https") { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W03)"); } // Id del fichero a firmar. try { this.id = decoder.GetFirstValueByName(ID); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W04)"); } // Formato de firma (CAdES, XAdES, PAdES...) try { this.format = decoder.GetFirstValueByName(FORMAT); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W05)"); } if (!supportedSignatureFormats.Contains(this.format.ToLower())) { throw new UnsupportedSignatureFormat(this.format); } // Algoritmo de firma (SHA1withRSA, SHA512withRSA, etc.) try { this.algorithm = decoder.GetFirstValueByName(ALGORITHM); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W06)"); } if (!supportedSignatureAlgorithms.Contains(this.algorithm)) { throw new UnsupportedSignatureAlgorithm(this.algorithm); } // Propiedades adicionales string base64Properties = null; try { base64Properties = decoder.GetFirstValueByName(PROPERTIES); } catch(Exception) { this.properties = new Dictionary<string,string>(); } if (base64Properties != null) { // Deshacemos la codificacion URL si existiese base64Properties = base64Properties.Replace('_', '/').Replace('-', '+'); // Deshacemos el Base64 try { byte[] binaryProperties = Convert.FromBase64String(base64Properties); this.properties = Properties2Dictionary(System.Text.Encoding.UTF8.GetString(binaryProperties, 0, binaryProperties.Length)); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W07)"); } } // Entorno GUI de origen (opcional, en caso de error o ausencia se toma el escritorio clásico como origen) try { Boolean.TryParse(decoder.GetFirstValueByName(FROM), out this.metro); } catch (Exception) { metro = false; } // Clave DES de cifrado string key; try { key = decoder.GetFirstValueByName(KEY); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W08)"); } this.desKey = key; if (this.desKey.Length != 8) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W09)"); } // Datos a firmar string dataBase64; try { dataBase64 = decoder.GetFirstValueByName(DATA); } catch (Exception) { dataBase64 = null; } // Nos pasan los datos en la URL if (dataBase64 != null) { // Deshacemos la codificación URL si existiese dataBase64 = dataBase64.Replace('_', '/').Replace('-', '+'); try { // Guardamos los datos descodificados this.data = Convert.FromBase64String(dataBase64); } catch (Exception) { throw new ParameterException(labels.GetString("Error_parametros") + " (ERR:W10)"); } } //no tiene sentido esto aqui. //this.data = null; }
/// <summary> /// This function extracts access_token from the response returned from web authentication broker /// and uses that token to get user information using facebook graph api. /// </summary> /// <param name="responseData">responseData returned from AuthenticateAsync result.</param> private async Task GetFacebookUserNameAsync(string responseData) { var decoder = new WwwFormUrlDecoder(responseData); var error = decoder.TryGetValue("error"); if (error != null) { FacebookUserName.Text = $"Error: {error}"; return; } // You can store access token locally for further use. string access_token = decoder[0].Value; this.fb_token = decoder[0].Value; string expires_in = decoder.TryGetValue("expires_in"); // expires_in is optional Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); Uri uri = new Uri($"https://graph.facebook.com/me?fields=id,name,picture,birthday&access_token={Uri.EscapeDataString(access_token)}"); HttpGetStringResult result = await httpClient.TryGetStringAsync(uri); if (result.Succeeded) { Windows.Data.Json.JsonObject userInfo = Windows.Data.Json.JsonObject.Parse(result.Value).GetObject(); FacebookUserName.Text = userInfo.GetNamedString("name"); this.userID = userInfo.GetNamedString("id"); } else { FacebookUserName.Text = "Error contacting Facebook"; } Windows.Web.Http.HttpClient httpClient2 = new Windows.Web.Http.HttpClient(); Uri uri2 = new Uri($"https://graph.facebook.com/{this.userID}/accounts?fields=name,access_token&access_token={this.fb_token}"); HttpGetStringResult myresult = await httpClient.TryGetStringAsync(uri2); if (myresult.Succeeded) { Windows.Data.Json.JsonObject userInfo2 = Windows.Data.Json.JsonObject.Parse(myresult.Value).GetObject(); this.Page_token = userInfo2["data"].GetArray()[0].GetObject().GetNamedString("access_token"); } else { Debug.Write("man ta osso!"); } Windows.Web.Http.HttpClient httpClient3 = new Windows.Web.Http.HttpClient(); Uri uri3 = new Uri($"https://graph.facebook.com/{this.userID}/accounts?access_token={this.fb_token}"); HttpGetStringResult result3 = await httpClient.TryGetStringAsync(uri3); if (result3.Succeeded) { Windows.Data.Json.JsonObject userInfo = Windows.Data.Json.JsonObject.Parse(result3.Value).GetObject(); this.PageId = userInfo["data"].GetArray()[0].GetObject().GetNamedString("id"); } else { FacebookUserName.Text = "Error contacting Facebook"; } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { Uri StartUri = new Uri(String.Format( "https://login.live.com/oauth20_authorize.srf?client_id={0}&scope={1}&response_type=token&redirect_uri={2}", "000000004812E450", "wl.signin onedrive.readwrite", WebUtility.UrlEncode("http://kiewic.com/"))); Uri EndUri = new Uri("http://kiewic.com/"); WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, StartUri, EndUri); string testData = "http://kiewic.com/#access_token=EwCQAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAASu2H0Plv73qlsNgaAsNtK931pWT/wMdIa4zJzNKDNz9Er%2b97p7qo0XGR4%2bkfr%2bTCh4EV5wQ5NTYHufWeIdlvlm9lkdt3S6SotwygCJtUJqoVBI4fGJxXdTz6tCiqsC2NbZNxGR9od4osWN33ZuNIHp2f3%2b0KiX0fs%2bLJK8wIHW22LtUsj%2bCZY/K9qA%2bEbxAfgIpZDsAzV2U1NdjUobSKkvA3SEaARx/exIm0jZTRvM0XRoNHn/ZhlcMrd1nehEpOM3SFp3%2bkIfKiFiHXVm0P/vRS/VJFHXyNyCDFqGuw63vOklnqT4w2LhQyGu3G/%2bUIJBpBfuSHNwikthHPm3xjYoDZgAACO1iT9UawnDVYAFVZk/mv7wwb58vrJc1l0v7UClfth7j5bm/%2b7yYB0Rr9WHdquSqrotvovjR//V2Kmtgn3rzLQYg8ma5/2t6VgtyPIwbQm6kRP382CYpS3n5ZdvyX7nNWHwM9RlsKkZdS9zT7kkwxVsbW7MJaqSlcnbnkWaad84KzfrjSyxr9ceUb/eajRu3ltRy9Tbtkt2A8QjXtKw2Th82WjIrZjDg10JoeRqvFtfu1IeEBlofUgAPUK7VkbDdKVbgDIl97TZD5qW9m8JTQkhlbq6%2btZhiqFN/JZLOPum6a4sEOAf46v1sw70UDv0raxewMA6y2j6gGMGFojFse6vWHXTLQRpqnBwpc3iOnaaqcMGGCRimdMhtCmKITW9%2bJ/NbKo8DbTk65ancQYmBgNpNHNVStZTGex3MwcxEY9mQ1p69aXN0fXhWY7GL%2bB0wEuwJn50H04s4WtlepIv2Ww0QhfZ1vxkd1HIRdwE%3d&authentication_token=eyJhbGciOiJIUzI1NiIsImtpZCI6IjEiLCJ0eXAiOiJKV1QifQ.eyJ2ZXIiOjEsImlzcyI6InVybjp3aW5kb3dzOmxpdmVpZCIsImV4cCI6MTQyNTYxMjU0NCwidWlkIjoiNmM0NzY5YjcxMmZlNDBjYTY0MDAyYTg4MDI1NjBkMjgiLCJhdWQiOiJraWV3aWMuY29tIiwidXJuOm1pY3Jvc29mdDphcHB1cmkiOiJhcHBpZDovLzAwMDAwMDAwNDgxMkU0NTAiLCJ1cm46bWljcm9zb2Z0OmFwcGlkIjoiMDAwMDAwMDA0ODEyRTQ1MCJ9.Xzw94LXFH3wIwwSWpQmxPH9HAB9H-qyLLW4WZfcSY9o&token_type=bearer&expires_in=3600&scope=wl.signin%20onedrive.readwrite%20wl.basic%20wl.contacts_skydrive%20wl.skydrive%20wl.skydrive_update&user_id=6c4769b712fe40ca64002a8802560d28"; testData = result.ResponseData; var urlDecoder = new WwwFormUrlDecoder(testData); foreach (var decoderEntry in urlDecoder) { Debug.WriteLine(decoderEntry.Name + " " + decoderEntry.Value); } string token = urlDecoder.GetFirstValueByName("http://kiewic.com/#access_token"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", String.Format("bearer {0}", token)); HttpStringContent createSessionContent = new HttpStringContent( "{ \"@name.conflictBehavior\": \"rename\" }", UnicodeEncoding.Utf8, "application/json"); Uri createSessionUri = new Uri("https://api.onedrive.com/v1.0/drive/root:/Foo/bar2.txt:/upload.createSession"); var response = await client.PostAsync(createSessionUri, createSessionContent); var responseString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseString); JsonObject jsonObject = JsonObject.Parse(responseString); Uri uploadUrl = new Uri(jsonObject.GetNamedString("uploadUrl")); HttpStringContent putContent1 = new HttpStringContent( "hello ", UnicodeEncoding.Utf8, "text/plain"); putContent1.Headers.Add("Content-Range", "bytes 0-5/11"); HttpStringContent putContent2 = new HttpStringContent( "world", UnicodeEncoding.Utf8, "text/plain"); putContent2.Headers.Add("Content-Range", "bytes 6-10/11"); response = await client.PutAsync(uploadUrl, putContent2); responseString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseString); response = await client.PutAsync(uploadUrl, putContent1); responseString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseString); }
public async void Can_Authenticate_LinkedIN_With_OAuth() { WwwFormUrlDecoder decoder; const string consumerKey = "TODO_CONSUMER_KEY_HERE"; const string consumerSecret = "TODO_CONSUMER_SECRET_HERE"; // request token var client = new RestClient { BaseUrl = "https://api.linkedin.com/uas/oauth", Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret, "http://localhost") }; var requestTokenRequest = new RestRequest("requestToken"); var requestTokenResponse = await client.ExecuteAsync(requestTokenRequest); Assert.IsNotNull(requestTokenResponse); Assert.AreEqual((int)HttpStatusCode.OK, requestTokenResponse.StatusCode); decoder = new WwwFormUrlDecoder(requestTokenResponse.Content); var requestToken = decoder.GetFirstValueByName("oauth_token"); var requestSecret = decoder.GetFirstValueByName("oauth_token_secret"); //var requestTokenResponseParameters = HttpUtility.ParseQueryString( requestTokenResponse.Content ); //var requestToken = requestTokenResponseParameters[ "oauth_token" ]; //var requestSecret = requestTokenResponseParameters[ "oauth_token_secret" ]; Assert.IsNotNull(requestToken); Assert.IsNotNull(requestSecret); // redirect user requestTokenRequest = new RestRequest("authenticate?oauth_token=" + requestToken); var redirectUri = client.BuildUri(requestTokenRequest); //Process.Start( redirectUri.ToString() ); var requestUrl = "TODO: put browser URL here"; // replace this via the debugger with the return url from LinkedIN. Simply copy it from the opened browser if (!Debugger.IsAttached) { Debugger.Launch(); } Debugger.Break(); // get the access token decoder = new WwwFormUrlDecoder(new Uri(requestUrl).Query); var requestVerifier = decoder.GetFirstValueByName("oauth_verifier"); //var requestTokenQueryParameters = HttpUtility.ParseQueryString( new Uri( requestUrl ).Query ); //var requestVerifier = requestTokenQueryParameters[ "oauth_verifier" ]; client.Authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, requestToken, requestSecret, requestVerifier); var requestAccessTokenRequest = new RestRequest("accessToken"); var requestActionTokenResponse = await client.ExecuteAsync(requestAccessTokenRequest); Assert.IsNotNull(requestActionTokenResponse); Assert.AreEqual((int)HttpStatusCode.OK, requestActionTokenResponse.StatusCode); decoder = new WwwFormUrlDecoder(requestActionTokenResponse.Content); var accessToken = decoder.GetFirstValueByName("oauth_token"); var accessSecret = decoder.GetFirstValueByName("oauth_token_secret"); //var requestActionTokenResponseParameters = HttpUtility.ParseQueryString( requestActionTokenResponse.Content ); //var accessToken = requestActionTokenResponseParameters[ "oauth_token" ]; //var accessSecret = requestActionTokenResponseParameters[ "oauth_token_secret" ]; Assert.IsNotNull(accessToken); Assert.IsNotNull(accessSecret); }
private async void MainWebView_LoadCompleted(object sender, NavigationEventArgs e) { if (e.Uri.ToString().StartsWith(Authorization.SpotifyLoginUri) && LocalConfiguration.IsLoggedInByFacebook) { if (await WebViewHelper.TryPushingFacebookLoginButton()) { logger.Info("Pushed the facebook login button."); return; } } if (e.Uri.ToString().StartsWith("https://open.spotify.com/static/offline.html?redirectUrl=")) { var url = e.Uri.ToString(); logger.Info("Clearing local storage and redirecting..."); var result = await WebViewHelper.ClearPlaybackLocalStorage(); try { if (result.Length > 0) { initialPlaybackState = JsonConvert.DeserializeObject <LocalStoragePlayback>(result); logger.Info("initial playback volume = " + initialPlaybackState.volume); } else { logger.Info("localStorage.playback was undefined."); } } catch { logger.Warn("Decoding localStorage.playback failed."); logger.Info("localStorage.playback content was: " + result); } var urlDecoder = new WwwFormUrlDecoder(url.Substring(url.IndexOf('?') + 1)); WebViewHelper.Navigate(new Uri(urlDecoder.GetFirstValueByName("redirectUrl"))); return; } if (e.Uri.ToString().ToLower().Contains(WebViewHelper.SpotifyPwaUrlBeginsWith.ToLower())) { var justInjected = await WebViewHelper.InjectInitScript(); if (ThemeHelper.GetCurrentTheme() == Theme.Light) { await WebViewHelper.InjectLightThemeScript(); } if (justInjected) { SetInitialPlaybackState(); } if (autoPlayAction != AutoPlayAction.None) { AutoPlayOnStartup(autoPlayAction); autoPlayAction = AutoPlayAction.None; } } var currentStateName = VisualStateManager.GetVisualStateGroups(mainGrid).FirstOrDefault().CurrentState.Name; if (currentStateName == "SplashScreen" || currentStateName == "LoadFailedScreen") { if (e.Uri.ToString().ToLower().Contains(WebViewHelper.SpotifyPwaUrlBeginsWith.ToLower())) { VisualStateManager.GoToState(this, "MainScreen", false); } else { VisualStateManager.GoToState(this, "MainScreenQuick", false); } if (shouldShowWhatsNew) { OpenWhatsNew(); } else if (developerMessage != null) { // Don't show developer message now if what's new is being shown. // It'll be shown after user closes the what's new flyout. OpenDeveloperMessage(developerMessage); developerMessage = null; } } if (e.Uri.ToString().StartsWith(Authorization.RedirectUri)) { FinalizeAuthorization(e.Uri.ToString()); } if (!await WebViewHelper.CheckLoggedIn()) { Authorize("https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F", clearExisting: true); AnalyticsHelper.Log("mainEvent", "notLoggedIn"); } }
protected override async void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); if (!IsInternet()) { await new MessageDialog("Seems you are not connected to the Internet").ShowAsync(); return; } else { if (args.Kind == ActivationKind.VoiceCommand) { VoiceCommandActivatedEventArgs voiceCommandArgs = args as VoiceCommandActivatedEventArgs; Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = voiceCommandArgs.Result; String text = speechRecognitionResult.Text; Frame rootFrame = Window.Current.Content as Frame; string voiceCommandName = speechRecognitionResult.RulePath[0]; var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (rootFrame == null) { rootFrame = new Frame(); } rootFrame.NavigationFailed += OnNavigationFailed; if (localSettings.Values["LoggedIn"] == null) { string readtext = "You need to login first"; ReadSpeech(new MediaElement(), readtext); rootFrame.Navigate(typeof(MainPage), speechRecognitionResult); } else { switch (voiceCommandName) { case "simpleOpeningApp": rootFrame.Navigate(typeof(Navigation.NavigationPage), speechRecognitionResult); break; case "voicecommand2": rootFrame.Navigate(typeof(Navigation.NavigationPage)); break; case "toCustomLocationApp": Arguments parameters = await ToCustomLocation(voiceCommandArgs); rootFrame.Navigate(typeof(BookingPage), parameters); break; case "bookcheapestApp": Arguments data = await ProcessBookCheapest(voiceCommandArgs); rootFrame.Navigate(typeof(BookingPage), data); break; case "costEstimateApp": rootFrame.Navigate(typeof(EstimationList), speechRecognitionResult); break; case "bookFromXToYApp": rootFrame.Navigate(typeof(BookingPage), ProcessBookFromXToY(speechRecognitionResult)); break; } } Window.Current.Content = rootFrame; Window.Current.Activate(); } else if (args.Kind == ActivationKind.Protocol) { var protocolArgs = args as ProtocolActivatedEventArgs; var queryArgs = new WwwFormUrlDecoder(protocolArgs.Uri.Query); Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; rootFrame.Navigate(typeof(CabsPage), queryArgs); Window.Current.Activate(); } } } }
/// <summary> /// Login script for OAUTHv2 using a WebView. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void LC_WebView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { if (LiveCodingAPI != null) { Uri e = args.Uri; // check to see if we at the callback URL stage if (e.AbsoluteUri.StartsWith(LiveCodingAPI.CallbackUri.OriginalString)) { // check the callback ? int q_index = e.AbsoluteUri.IndexOf('?', LiveCodingAPI.CallbackUri.OriginalString.Length); // for errors if (q_index > 0) { // TODO(duan): log, maybe alert box? string error_message = "Unknown error"; try { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(e.Query); error_message = decoder.GetFirstValueByName("error"); } catch (Exception ex) { error_message = ex.Message; } NavigationHelper.GoBack(); } else { string error_message = "ERROR_SUCCESS"; // we got good feedback attemp to decode // check the callback ? int sharp_index = e.AbsoluteUri.IndexOf('#', LiveCodingAPI.CallbackUri.OriginalString.Length); if (sharp_index > 0) { // parse the query string string query = e.AbsoluteUri.Substring(sharp_index + 1); try { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(query); // valid check LiveCodingAPI.OAuthToken = decoder.GetFirstValueByName("access_token"); //LiveCodingAPI.State = decoder.GetFirstValueByName("state"); //decoder.GetFirstValueByName("access_token") //decoder.GetFirstValueByName("token_type") //decoder.GetFirstValueByName("state") //decoder.GetFirstValueByName("expires_in") //decoder.GetFirstValueByName("scope") // save credential to local storage Windows.Storage.ApplicationData.Current.LocalSettings.Values["API"] = Serialize(LiveCodingAPI); } catch (Exception ex) { error_message = ex.Message; // error parsing the token, return to login page this.Frame.GoBack(); } } // we good goto main page this.Frame.Navigate(typeof(MainPage), LiveCodingAPI); } } } }
private async Task ProcessRequestAsync(StreamSocket socket) { try { // Read in the HTTP request, we only care about type 'GET' StringBuilder requestFull = new StringBuilder(string.Empty); using (IInputStream input = socket.InputStream) { byte[] data = new byte[bufLen]; IBuffer buffer = data.AsBuffer(); uint dataRead = bufLen; while (dataRead == bufLen) { await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial); requestFull.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } using (IOutputStream output = socket.OutputStream) { try { if (requestFull.Length == 0) { throw (new Exception("WTF dude?")); } string requestStart = requestFull.ToString().Split('\n')[0]; string[] requestParts = requestStart.Split(' '); string requestMethod = requestParts[0]; if (requestMethod.ToUpper() != "GET") { throw (new Exception("UNSUPPORTED HTTP REQUEST METHOD")); } string requestPath = requestParts[1]; var splits = requestPath.Split('?'); if (splits.Length < 2) { throw (new Exception("EMPTY OR MISSING QUERY STRING")); } string botCmd = splits[1].ToLower(); if (string.IsNullOrEmpty(botCmd)) { throw (new Exception("EMPTY OR MISSING QUERY STRING")); } WwwFormUrlDecoder queryBag = new WwwFormUrlDecoder(botCmd); await ProcessCommand(queryBag, output); } catch (Exception e) { // We use 'Bad Request' here since chances are the exception was caused by bad query strings await WriteResponseAsync("400 Bad Request", e.Message + e.StackTrace, output); } } } catch (Exception e) { // Server can force shutdown which generates an exception. Spew it. Debug.WriteLine(e.Message); Debug.WriteLine(e.StackTrace); } }
protected override async Task OnActivateApplicationAsync(IActivatedEventArgs args) { var pageManager = Container.Resolve <PageManager>(); var hohoemaApp = Container.Resolve <HohoemaApp>(); try { if (!hohoemaApp.IsLoggedIn && AccountManager.HasPrimaryAccount()) { await hohoemaApp.SignInWithPrimaryAccount(); } } catch { } // ログインしていない場合、 bool isNeedNavigationDefault = !hohoemaApp.IsLoggedIn; try { if (args.Kind == ActivationKind.ToastNotification) { //Get the pre-defined arguments and user inputs from the eventargs; var toastArgs = args as IActivatedEventArgs as ToastNotificationActivatedEventArgs; var arguments = toastArgs.Argument; if (arguments == ACTIVATION_WITH_ERROR) { await ShowErrorLog().ConfigureAwait(false); } else if (arguments.StartsWith("cache_cancel")) { var query = arguments.Split('?')[1]; var decode = new WwwFormUrlDecoder(query); var videoId = decode.GetFirstValueByName("id"); var quality = (NicoVideoQuality)Enum.Parse(typeof(NicoVideoQuality), decode.GetFirstValueByName("quality")); await hohoemaApp.CacheManager.CancelCacheRequest(videoId, quality); } else { var nicoContentId = Helpers.NicoVideoExtention.UrlToVideoId(arguments); if (Mntone.Nico2.NiconicoRegex.IsVideoId(nicoContentId)) { await PlayVideoFromExternal(nicoContentId); } else if (Mntone.Nico2.NiconicoRegex.IsLiveId(nicoContentId)) { await PlayLiveVideoFromExternal(nicoContentId); } } } else if (args.Kind == ActivationKind.Protocol) { var param = (args as IActivatedEventArgs) as ProtocolActivatedEventArgs; var uri = param.Uri; var maybeNicoContentId = new string(uri.OriginalString.Skip("niconico://".Length).TakeWhile(x => x != '?' && x != '/').ToArray()); if (Mntone.Nico2.NiconicoRegex.IsVideoId(maybeNicoContentId) || maybeNicoContentId.All(x => x >= '0' && x <= '9')) { await PlayVideoFromExternal(maybeNicoContentId); } else if (Mntone.Nico2.NiconicoRegex.IsLiveId(maybeNicoContentId)) { await PlayLiveVideoFromExternal(maybeNicoContentId); } } else { if (hohoemaApp.IsLoggedIn) { pageManager.OpenStartupPage(); } else { pageManager.OpenPage(HohoemaPageType.RankingCategoryList); } } } catch { /* * if (!pageManager.NavigationService.CanGoBack()) * { * if (!hohoemaApp.IsLoggedIn && AccountManager.HasPrimaryAccount()) * { * await hohoemaApp.SignInWithPrimaryAccount(); * * pageManager.OpenStartupPage(); * } * else * { * pageManager.OpenPage(HohoemaPageType.Login); * } * } */ } await base.OnActivateApplicationAsync(args); }
private async Task HandleProtocolActivation(IActivatedEventArgs args) { var protocolArgs = (ProtocolActivatedEventArgs)args; var uri = protocolArgs.Uri; if (string.IsNullOrEmpty(uri.Query)) { return; } WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(uri.Query); switch (uri.Host) { case "goto": if (decoder[0]?.Name == "page") { if (decoder[0]?.Value == VLCPage.SettingsPageUI.ToString()) { Locator.NavigationService.Go(VLCPage.SettingsPageUI); } } break; case "openstream": // do stuff if (decoder[0]?.Name == "from") { switch (decoder[0]?.Value) { case "clipboard": await Task.Delay(1000); var dataPackage = Clipboard.GetContent(); Uri url = null; if (dataPackage.Contains(StandardDataFormats.ApplicationLink)) { url = await dataPackage.GetApplicationLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.WebLink)) { url = await dataPackage.GetWebLinkAsync(); } else if (dataPackage.Contains(StandardDataFormats.Text)) { url = new Uri(await dataPackage.GetTextAsync()); } if (url != null) { await Locator.MediaPlaybackViewModel.PlayStream(url.AbsoluteUri); } break; case "useraction": Locator.MainVM.GoToStreamPanel.Execute(null); break; case "url": if (decoder[1]?.Name == "url") { StorageFile subsFd = null; try { var subsFrom = decoder.Where((item, index) => item.Name == "subs_from").FirstOrDefault(); var subsValue = decoder.Where((item, index) => item.Name == "subs").FirstOrDefault(); if (!(subsFrom == default(IWwwFormUrlDecoderEntry) && subsValue == default(IWwwFormUrlDecoderEntry))) { switch (subsFrom.Value) { case "path": //this StorageFile is like a File Descriptor from Unix subsFd = await StorageFile.GetFileFromPathAsync(subsValue.Value); if (subsFd == null) { ToastHelper.Basic("Failed to Load Subtitles: Couln´t find the file."); } else if (!StorageApplicationPermissions.FutureAccessList.CheckAccess(subsFd)) { StorageApplicationPermissions.FutureAccessList.Add(subsFd); } break; case "url": using (var httpClient = new System.Net.Http.HttpClient()) { var subsContent = await httpClient.GetStringAsync(subsValue.Value); subsFd = await ApplicationData.Current.LocalFolder.CreateFileAsync(subsContent.GetHashCode().ToString(), CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(subsFd, subsContent); } break; case "picker": var openPicker = new FileOpenPicker(); openPicker.FileTypeFilter.Add(".srt"); openPicker.FileTypeFilter.Add(".txt"); openPicker.SuggestedStartLocation = PickerLocationId.Downloads; subsFd = await openPicker.PickSingleFileAsync(); break; } } } //StorageFile.GetFileFromPath or CreateFileAsync failed catch (UnauthorizedAccessException) { ToastHelper.Basic("Failed to Load Subtitles: Access Denied to the file."); } //HttpClient usually fails with an AggregateException instead of WebException or HttpRequest...Exception catch (AggregateException) { ToastHelper.Basic("Failed to Load Subtitles: Problems downloading the subtitles"); } //HttpClient fails with a WebException when there´s no connectivity catch (System.Net.WebException) { ToastHelper.Basic("Failed to Load Subtitles: No Connectivity"); } catch (Exception ex) { ToastHelper.Basic("Failed to Load Subtitles: " + ex.GetType().ToString()); } await Locator.MediaPlaybackViewModel.PlayStream(decoder[1].Value); if (subsFd != null) { ToastHelper.Basic("Subtitles Loaded Successfully"); Locator.MediaPlaybackViewModel.OpenSubtitleCommand.Execute(subsFd); } } break; } } break; } }
/// <summary> /// Authenticates against the PTC login service and acquires an Authentication Ticket. /// </summary> /// <param name="loginData">The <see cref="PtcLoginParameters" /> to use from this request. Obtained by calling <see cref="GetLoginParameters(HttpClient)"/>.</param> /// <returns></returns> private async Task <string> GetAuthenticationTicket(PtcLoginParameters loginData) { HttpResponseMessage responseMessage; if (loginData != null) { var requestData = new Dictionary <string, string> { { "lt", loginData.Lt }, { "execution", loginData.Execution }, { "_eventId", "submit" }, { "username", Username }, { "password", Password } }; responseMessage = await HttpClient.PostAsync(Constants.LoginUrl, new FormUrlEncodedContent(requestData)).ConfigureAwait(false); } else { responseMessage = await HttpClient.GetAsync(Constants.LoginUrl); } // robertmclaws: No need to even read the string if we have results from the location query. if (responseMessage.StatusCode == HttpStatusCode.Found && responseMessage.Headers.Location != null) { var decoder = new WwwFormUrlDecoder(responseMessage.Headers.Location.Query); if (decoder.Count == 0) { if (Debugger.IsAttached) { Debugger.Break(); } throw new LoginFailedException(); } return(decoder.GetFirstValueByName("ticket")); } var responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); PtcAuthenticationTicketResponse response = null; // @robertmclaws: Let's try to catch situations we haven't thought of yet. try { response = JsonConvert.DeserializeObject <PtcAuthenticationTicketResponse>(responseContent); } catch (Exception ex) { Logger.Write(ex.Message); throw new LoginFailedException("We encountered a response from the PTC login servers thet we didn't anticipate. Please take a screenshot and open a ticket." + Environment.NewLine + responseContent.Replace("/n", "")); } if (!string.IsNullOrWhiteSpace(response.ErrorCode) && response.ErrorCode.EndsWith("activation_required")) { throw new LoginFailedException($"Your two-day grace period has expired, and your PTC account must now be activated." + Environment.NewLine + $"Please visit {response.Redirect}."); } var loginFailedWords = new string[] { "incorrect", "disabled" }; var loginFailed = loginFailedWords.Any(failedWord => response.Errors.Any(error => error.Contains(failedWord))); if (loginFailed) { throw new LoginFailedException(response.Errors[0]); } throw new Exception($"Pokemon Trainer Club responded with the following error(s): '{string.Join(", ", response.Errors)}'"); }
/// <summary> /// [WIP]<para/> /// Parses XMPP IRIs and URIs based on RFC 5122 and returns the result. /// </summary> /// <param name="uri">The URI or IRI that should get parsed.</param> /// <returns>The URI or IRI result or null if an error occurred.</returns> public static IUriAction parse(Uri uri) { if (!string.IsNullOrEmpty(uri?.OriginalString)) { if (string.Equals(uri.Scheme.ToLowerInvariant(), "xmpp")) { string tmp = uri.OriginalString; // 1. remove 'xmpp:' tmp = tmp.Substring(5); // 2. Authority string authority = null; if (tmp.StartsWith("//")) { tmp.Substring(2); int authEnd = tmp.IndexOf('/'); if (authEnd < 0) { authEnd = tmp.IndexOf('?'); if (authEnd < 0) { authEnd = tmp.IndexOf('#'); if (authEnd < 0) { authEnd = tmp.Length <= 0 ? 0 : tmp.Length - 1; } } authority = tmp.Substring(0, authEnd); tmp = tmp.Substring(authEnd + 1); } } if (string.Equals(uri.AbsolutePath, "iot-register")) { WwwFormUrlDecoder query = parseUriQuery(uri); IWwwFormUrlDecoderEntry macEntry = query.FirstOrDefault(x => x.Name.StartsWith("mac")); if (macEntry is null || string.IsNullOrEmpty(macEntry.Value)) { Logger.Error("None or invalid IoT MAC address: " + uri.OriginalString); return(null); } IWwwFormUrlDecoderEntry algoEntry = query.FirstOrDefault(x => x.Name.StartsWith("algo")); if (algoEntry is null || string.IsNullOrEmpty(algoEntry.Value)) { Logger.Error("None or invalid IoT key algorithm: " + uri.OriginalString); return(null); } IWwwFormUrlDecoderEntry keyEntry = query.FirstOrDefault(x => x.Name.StartsWith("key")); if (keyEntry is null || string.IsNullOrEmpty(keyEntry.Value)) { Logger.Error("None or invalid IoT key: " + uri.OriginalString); return(null); } return(new RegisterIoTUriAction(macEntry.Value, algoEntry.Value, keyEntry.Value)); } else { // Check if is OMEMO fingerprint URI: WwwFormUrlDecoder query = parseUriQuery(uri); IWwwFormUrlDecoderEntry entry = query.FirstOrDefault(x => x.Name.StartsWith("omemo-sid-")); if (!(entry is null)) { ECPublicKey pubKey = null; try { byte[] fingerprintBytes = CryptoUtils.hexStringToByteArray(entry.Value); pubKey = Curve.decodePoint(fingerprintBytes, 0); } catch (Exception e) { Logger.Error("Failed to parse XMPP URI. Parsing fingerprint failed: " + entry.Value, e); return(null); } if (uint.TryParse(entry.Name.Replace("omemo-sid-", "").Trim(), out uint deviceId)) { SignalProtocolAddress address = new SignalProtocolAddress(uri.LocalPath, deviceId); return(new OmemoFingerprintUriAction(new OmemoFingerprint(pubKey, address))); } else { Logger.Warn("Failed to parse XMPP URI. Invalid device ID: " + entry.Name); } } } } else { Logger.Warn("Failed to parse XMPP URI. No 'xmpp' scheme."); } } return(null); }
protected override async Task OnActivateApplicationAsync(IActivatedEventArgs args) { await HohoemaInitializeAsync(args); var niconicoSession = Container.Resolve <NiconicoSession>(); // 外部から起動した場合にサインイン動作と排他的動作にさせたい // こうしないと再生処理を正常に開始できない using (await niconicoSession.SigninLock.LockAsync()) { await Task.Delay(50); } if (args.Kind == ActivationKind.ToastNotification) { bool isHandled = false; //Get the pre-defined arguments and user inputs from the eventargs; var toastArgs = args as IActivatedEventArgs as ToastNotificationActivatedEventArgs; var arguments = toastArgs.Argument; try { var serialize = Newtonsoft.Json.JsonConvert.DeserializeObject <LoginRedirectPayload>(arguments); if (serialize != null) { if (serialize.RedirectPageType == HohoemaPageType.VideoPlayer) { PlayVideoFromExternal(serialize.RedirectParamter); } else { var pageManager = Container.Resolve <Services.PageManager>(); pageManager.OpenPage(serialize.RedirectPageType, serialize.RedirectParamter); } isHandled = true; } } catch { } if (!isHandled) { if (arguments == ACTIVATION_WITH_ERROR) { await ShowErrorLog().ConfigureAwait(false); } else if (arguments == ACTIVATION_WITH_ERROR_COPY_LOG) { var error = await GetMostRecentErrorText(); Services.Helpers.ClipboardHelper.CopyToClipboard(error); } else if (arguments == ACTIVATION_WITH_ERROR_OPEN_LOG) { await ShowErrorLogFolder(); } else if (arguments.StartsWith("cache_cancel")) { var query = arguments.Split('?')[1]; var decode = new WwwFormUrlDecoder(query); var videoId = decode.GetFirstValueByName("id"); var quality = (NicoVideoQuality)Enum.Parse(typeof(NicoVideoQuality), decode.GetFirstValueByName("quality")); var cacheManager = Container.Resolve <Models.Cache.VideoCacheManager>(); await cacheManager.CancelCacheRequest(videoId, quality); } else { var nicoContentId = Models.Helpers.NicoVideoIdHelper.UrlToVideoId(arguments); if (Mntone.Nico2.NiconicoRegex.IsVideoId(nicoContentId)) { PlayVideoFromExternal(nicoContentId); } else if (Mntone.Nico2.NiconicoRegex.IsLiveId(nicoContentId)) { PlayLiveVideoFromExternal(nicoContentId); } } } } else if (args.Kind == ActivationKind.Protocol) { var param = (args as IActivatedEventArgs) as ProtocolActivatedEventArgs; var uri = param.Uri; var maybeNicoContentId = new string(uri.OriginalString.Skip("niconico://".Length).TakeWhile(x => x != '?' && x != '/').ToArray()); if (Mntone.Nico2.NiconicoRegex.IsVideoId(maybeNicoContentId) || maybeNicoContentId.All(x => x >= '0' && x <= '9')) { PlayVideoFromExternal(maybeNicoContentId); } else if (Mntone.Nico2.NiconicoRegex.IsLiveId(maybeNicoContentId)) { PlayLiveVideoFromExternal(maybeNicoContentId); } } await base.OnActivateApplicationAsync(args); }
public void OnToastNotificationActivated(ToastActivationType activationType, string args) { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args); uint activeCallID = 0; uint incomingCallID = 0; Call activeCall = null; Call incomingCall = null; Frame frame = null; switch (decoder.GetFirstValueByName(NotificationSystem.ACTION)) { case NotificationSystem.END: activeCallID = uint.Parse(decoder.GetFirstValueByName(NotificationSystem.ACTIVE_CALL_ID)); activeCall = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == activeCallID); //if (activeCall?.AvailableActions.EndCallAvailable ?? false) //{ activeCall?.End(); //} //else //{ // //LOG //} break; case NotificationSystem.REJECT: incomingCallID = uint.Parse(decoder.GetFirstValueByName(NotificationSystem.INCOMING_CALL_ID)); incomingCall = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == incomingCallID); incomingCall?.RejectIncoming(); break; case NotificationSystem.TEXT_REPLY: incomingCallID = uint.Parse(decoder.GetFirstValueByName(NotificationSystem.INCOMING_CALL_ID)); break; case NotificationSystem.END_AND_ANSWER: activeCallID = uint.Parse(decoder.GetFirstValueByName(NotificationSystem.ACTIVE_CALL_ID)); activeCall = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == activeCallID); //if (activeCall?.AvailableActions.EndCallAvailable ?? false) //{ activeCall?.End(); //} //else //{ // //LOG //} goto case NotificationSystem.ANSWER; case NotificationSystem.HOLD_AND_ANSWER: activeCallID = uint.Parse(decoder.GetFirstValueByName(NotificationSystem.ACTIVE_CALL_ID)); activeCall = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == activeCallID); //if (activeCall?.AvailableActions.HoldAvailable ?? false) //{ activeCall?.SetHold(true); //} //else //{ // //LOG //} goto case NotificationSystem.ANSWER; case NotificationSystem.ANSWER: incomingCallID = uint.Parse(decoder.GetFirstValueByName(NotificationSystem.INCOMING_CALL_ID)); incomingCall = CallSystem.CallManager.CurrentCalls.FirstOrDefault(x => x.ID == incomingCallID); //if (incomingCall?.AvailableActions.AnswerAvailable ?? false) //{ incomingCall?.AcceptIncomingEx(); //} //else //{ // //LOG //} if (activationType == ToastActivationType.Foreground) { goto case NotificationSystem.SHOW_CALL_UI; } else { break; } case NotificationSystem.SHOW_CALL_UI: UISystem.ShowCallUIWindow(); //frame = Window.Current.Content as Frame; //frame.Navigate(typeof(InCallUI)); break; case NotificationSystem.SHOW_INCOMING_CALL_UI: frame = Window.Current.Content as Frame; //frame.Navigate(typeof(IncomingCallUI)); break; } }
//[Fact] public async void Can_Authenticate_Netflix_With_OAuth() { WwwFormUrlDecoder decoder; const string consumerKey = ""; const string consumerSecret = ""; var baseUrl = "http://api.netflix.com"; var client = new RestClient(baseUrl); client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret); var request = new RestRequest("oauth/request_token"); var response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); decoder = new WwwFormUrlDecoder(response.Content); var oauth_token = decoder.GetFirstValueByName("oauth_token"); var oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret"); var applicationName = decoder.GetFirstValueByName("application_name"); //var qs = HttpUtility.ParseQueryString(response.Content); //var oauth_token = qs["oauth_token"]; //var oauth_token_secret = qs["oauth_token_secret"]; //var applicationName = qs["application_name"]; Assert.IsNotNull(oauth_token); Assert.IsNotNull(oauth_token_secret); Assert.IsNotNull(applicationName); var baseSslUrl = "https://api-user.netflix.com"; var sslClient = new RestClient(baseSslUrl); request = new RestRequest("oauth/login"); request.AddParameter("oauth_token", oauth_token); request.AddParameter("oauth_consumer_key", consumerKey); request.AddParameter("application_name", applicationName); var url = sslClient.BuildUri(request).ToString(); //Process.Start(url); request = new RestRequest("oauth/access_token"); // <-- Breakpoint here, login to netflix client.Authenticator = OAuth1Authenticator.ForAccessToken( consumerKey, consumerSecret, oauth_token, oauth_token_secret ); response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); decoder = new WwwFormUrlDecoder(response.Content); oauth_token = decoder.GetFirstValueByName("oauth_token"); oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret"); var user_id = decoder.GetFirstValueByName("user_id"); //qs = HttpUtility.ParseQueryString(response.Content); //oauth_token = qs["oauth_token"]; //oauth_token_secret = qs["oauth_token_secret"]; //var user_id = qs["user_id"]; Assert.IsNotNull(oauth_token); Assert.IsNotNull(oauth_token_secret); Assert.IsNotNull(user_id); client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauth_token, oauth_token_secret); request = new RestRequest("users/{user_id}/queues/disc"); request.AddUrlSegment("user_id", user_id); request.AddParameter("max_results", "2"); var queueResponse = await client.ExecuteAsync(request); // var deserializer = new RestRT.Deserializers.JsonDeserializer(); var result = (Queue)deserializer.Deserialize(response, typeof(Queue)); Assert.IsNotNull(queueResponse); Assert.AreEqual((int)HttpStatusCode.OK, queueResponse.StatusCode); Assert.IsNotNull(result); Assert.AreEqual(2, result.Items.Count); }
private async void LoginWebviewOnNavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) { // Clearing challenge if (args.Uri.PathAndQuery == "/" || string.IsNullOrEmpty(args.Uri.PathAndQuery)) { WebviewPopup.IsOpen = false; } // Facebook OAuth Login if (args.Uri.PathAndQuery.Contains("accounts/signup", StringComparison.OrdinalIgnoreCase)) { // Uri looks like this: https://www.instagram.com/accounts/signup/?#access_token=... WebviewPopup.IsOpen = false; if (_loading) { return; } DisableButtons(); try { var query = args.Uri.Fragment.Substring(1); // turn fragment into query (remove the '#') var urlParams = new WwwFormUrlDecoder(query); var fbToken = urlParams.GetFirstValueByName("access_token"); if (string.IsNullOrEmpty(fbToken)) { await ShowLoginErrorDialog("Failed to acquire access token"); return; } var result = await ViewModel.LoginWithFacebook(fbToken).ConfigureAwait(true); if (!result.IsSucceeded) { if (result.Value == LoginResult.TwoFactorRequired) { await TwoFactorAuthAsync(); } else { await ShowLoginErrorDialog(result.Message); } return; } await TryNavigateToMainPage(); } catch (Exception e) { await ShowLoginErrorDialog( "Unexpected error occured while logging in with Facebook. Please try again later or log in with Instagram account instead."); DebugLogger.LogException(e); } finally { EnableButtons(); } } }
public async Task Can_Authenticate_With_OAuth() { WwwFormUrlDecoder decoder; const string consumerKey = ""; const string consumerSecret = ""; var baseUrl = "http://api.twitter.com"; var client = new RestClient(baseUrl); client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret); var request = new RestRequest("oauth/request_token", Method.POST); var response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); decoder = new WwwFormUrlDecoder(response.Content); var oauth_token = decoder.GetFirstValueByName("oauth_token"); var oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret"); //var qs = HttpUtility.ParseQueryString(response.Content); //var oauth_token = qs["oauth_token"]; //var oauth_token_secret = qs["oauth_token_secret"]; Assert.IsNotNull(oauth_token); Assert.IsNotNull(oauth_token_secret); request = new RestRequest("oauth/authorize"); request.AddParameter("oauth_token", oauth_token); var url = client.BuildUri(request).ToString(); //Process.Start(url); var verifier = "123456"; // <-- Breakpoint here (set verifier in debugger) request = new RestRequest("oauth/access_token", Method.POST); client.Authenticator = OAuth1Authenticator.ForAccessToken( consumerKey, consumerSecret, oauth_token, oauth_token_secret, verifier ); response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); //qs = HttpUtility.ParseQueryString(response.Content); decoder = new WwwFormUrlDecoder(response.Content); oauth_token = decoder.GetFirstValueByName("oauth_token"); oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret"); //oauth_token = qs["oauth_token"]; //oauth_token_secret = qs["oauth_token_secret"]; Assert.IsNotNull(oauth_token); Assert.IsNotNull(oauth_token_secret); request = new RestRequest("account/verify_credentials.xml"); client.Authenticator = OAuth1Authenticator.ForProtectedResource( consumerKey, consumerSecret, oauth_token, oauth_token_secret ); response = await client.ExecuteAsync(request); Assert.IsNotNull(response); Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode); //request = new RestRequest("statuses/update.json", Method.POST); //request.AddParameter("status", "Hello world! " + DateTime.Now.Ticks.ToString()); //client.Authenticator = OAuth1Authenticator.ForProtectedResource( // consumerKey, consumerSecret, oauth_token, oauth_token_secret //); //response = client.Execute(request); //Assert.NotNull(response); //Assert.Equal(HttpStatusCode.OK, response.StatusCode); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { // Handle the events from the Back button, but do not show it. systemNavigationManager = SystemNavigationManager.GetForCurrentView(); systemNavigationManager.BackRequested += OnBackRequested; // Parse the URI query parameters. They tell us what to load. var decoder = new WwwFormUrlDecoder((string)e.Parameter); Trip = TripData.FromId(GetDecoderField(decoder, "id")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Trip")); if (Trip == null) { // Invalid trip. return; } if (!int.TryParse(GetDecoderField(decoder, "todo"), out previousSelectedIndex)) { previousSelectedIndex = -1; } // If applicable, perform a connected animation to make the page transition smoother. var animationService = ConnectedAnimationService.GetForCurrentView(); var animation = animationService.GetAnimation("drillin"); if (animation != null) { animation.TryStart(HeroGrid); } // Update the title of the view to match the trip the user is looking at. ApplicationView.GetForCurrentView().Title = Trip.Title; // Generate a UserActivity that says that the user is looking at this trip. var channel = UserActivityChannel.GetDefault(); string activityId = $"trip?id={Trip.Id}"; var activity = await channel.GetOrCreateUserActivityAsync(activityId); // The system uses this URI to resume the activity. activity.ActivationUri = new Uri($"{App.ProtocolScheme}:{activityId}"); // Describe the activity. activity.VisualElements.DisplayText = Trip.Title; activity.VisualElements.Description = Trip.Description; // Build the adaptive card JSON with the helper classes in the NuGet package. // You are welcome to generate your JSON using any library you like. var card = new AdaptiveCard(); card.BackgroundImage = Trip.ImageSourceUri; card.Body.Add(new AdaptiveTextBlock(Trip.Title) { Size = AdaptiveTextSize.Large, Weight = AdaptiveTextWeight.Bolder }); card.Body.Add(new AdaptiveTextBlock(Trip.Description)); var adaptiveCardJson = card.ToJson(); // Turn the JSON into an adaptive card and set it on the activity. activity.VisualElements.Content = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(adaptiveCardJson); // Save it to the activity feed. await activity.SaveAsync(); // Start a session. This tels the system know that the user is engaged in the activity right now. this.activitySession = activity.CreateSession(); // Subscribe to the UserActivityRequested event if the system supports it. if (ApiInformation.IsEventPresent(typeof(UserActivityRequestManager).FullName, "UserActivityRequested")) { activityRequestManager = UserActivityRequestManager.GetForCurrentView(); activityRequestManager.UserActivityRequested += OnUserActivityRequested; } }
public static string FindParamInQueryString(this string hit, string param) { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(hit); return(decoder.GetFirstValueByName(param)); }