private async Task<Token> GetAccessToken() { var token = new Token(); var startUrl = Common.FormatAuthUrl(AuthorizationEndpointUrl, ResponseTypes.Token, ConsumerKey, WebUtility.UrlEncode(CallbackUrl), DisplayTypes.Popup); var startUri = new Uri(startUrl); var endUri = new Uri(CallbackUrl); var webAuthenticationResult = await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync( Windows.Security.Authentication.Web.WebAuthenticationOptions.None, startUri, endUri); switch (webAuthenticationResult.ResponseStatus) { case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success: var responseData = webAuthenticationResult.ResponseData; var responseUri = new Uri(responseData); var decoder = new WwwFormUrlDecoder(responseUri.Fragment.Replace("#", "?")); token.AccessToken = decoder.GetFirstValueByName("access_token"); token.RefreshToken = decoder.GetFirstValueByName("refresh_token"); token.InstanceUrl = WebUtility.UrlDecode(decoder.GetFirstValueByName("instance_url")); return token; case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp: throw new Exception(webAuthenticationResult.ResponseErrorDetail.ToString()); default: throw new Exception(webAuthenticationResult.ResponseData); } }
private async void WebViewer_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args) { // Check if new location is redirect uri if (args.Uri.AbsoluteUri.IndexOf(App.RedirectUri) == 0) { // Get parameters var encoder = new WwwFormUrlDecoder(args.Uri.AbsoluteUri.Replace('#', '&')); // Replacing # with ? to make GetFirstValueByName() work var accessToken = encoder.GetFirstValueByName("access_token"); var expires = encoder.GetFirstValueByName("expires"); if (!String.IsNullOrEmpty(accessToken)) { // Success App.AccessToken = accessToken; App.Expires = expires; Frame.GoBack(); var successDialog = new MessageDialog("Successfully logged in.", "Success!"); await successDialog.ShowAsync(); return; } // Show error message, if something went wrong var errorDialog = new MessageDialog("Whoops, we could not log you in successfully. Sorry for that!", "Something went wrong..."); await errorDialog.ShowAsync(); Frame.GoBack(); } }
private string ExtractCode(string redirectedUrl) { var url = new Uri(redirectedUrl); var decoder = new WwwFormUrlDecoder(url.Query); return decoder.GetFirstValueByName("code"); }
/// <summary> /// Performs the first step in the OAuth2 workflow and retreives the auth code /// </summary> /// <param name="authCodeUri">The box api uri to retrieve the auth code. BoxConfig.AuthCodeUri should be used for this field</param> /// <param name="redirectUri">The redirect uri that the page will navigate to after granting the auth code</param> /// <returns></returns> public static async Task<string> GetAuthCode(Uri authCodeUri, Uri redirectUri = null) { Uri callbackUri = redirectUri == null ? WebAuthenticationBroker.GetCurrentApplicationCallbackUri() : redirectUri; WebAuthenticationResult war = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, authCodeUri, callbackUri); switch (war.ResponseStatus) { case WebAuthenticationStatus.Success: // grab auth code var response = war.ResponseData; WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(new Uri(response).Query); return decoder.GetFirstValueByName("code"); case WebAuthenticationStatus.UserCancel: throw new Exception("User Canceled Login"); case WebAuthenticationStatus.ErrorHttp: default: throw new Exception("Error returned by GetAuthCode() : " + war.ResponseStatus.ToString()); } }
public static async Task<string> GetAccessToken(string username, string password) { try { var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip, AllowAutoRedirect = false }; using (var tempHttpClient = new HttpClient(handler)) { //Get session cookie var sessionResp = await tempHttpClient.GetAsync(Resources.PtcLoginUrl); var data = await sessionResp.Content.ReadAsStringAsync(); var lt = JsonHelper.GetValue(data, "lt"); var executionId = JsonHelper.GetValue(data, "execution"); //Login var loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("lt", lt), new KeyValuePair<string, string>("execution", executionId), new KeyValuePair<string, string>("_eventId", "submit"), new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password) })); var decoder = new WwwFormUrlDecoder(loginResp.Headers.Location.Query); var ticketId = decoder.GetFirstValueByName("ticket"); if (string.IsNullOrEmpty(ticketId)) throw new PtcOfflineException(); //Get tokenvar var tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("client_id", "mobile-app_pokemon-go"), new KeyValuePair<string, string>("redirect_uri", "https://www.nianticlabs.com/pokemongo/error"), new KeyValuePair<string, string>("client_secret", "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR"), new KeyValuePair<string, string>("grant_type", "refresh_token"), new KeyValuePair<string, string>("code", ticketId) })); var tokenData = await tokenResp.Content.ReadAsStringAsync(); decoder = new WwwFormUrlDecoder(tokenData); return decoder.GetFirstValueByName("access_token"); } } catch (Exception) { return string.Empty; } }
public async Task<bool> CompleteOAuthFlowAsync(string responseData) { // responseData value eg http://example.com/path?code=4cba03187d6cd6720217&state=6dfa60685ac94a29bdde2d9f3cbdce0e var responseUri = new Uri(responseData); var decoder = new WwwFormUrlDecoder(responseUri.Query); var code = decoder.GetFirstValueByName("code"); var state = decoder.GetFirstValueByName("state"); string storedState = VaultManager.GetPassword(VaultStateResourceKey, VaultDefaultUnusedUserName); if (storedState != state) return false; // We are storing the code to later be able to refresh the access token VaultManager.Save(VaultTokenCodeResourceKey, VaultDefaultUnusedUserName, code); bool ok = await AcquireAccessTokenAsync(code, state).ConfigureAwait(false); ; return ok; }
public static string GetQueryParameter(this Uri uri, string parameterName) { string query = uri.Query; if (query.Length <= 1) { return null; } WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(query); return decoder.GetFirstValueByName(parameterName); }
private void webView_LoadCompleted(object sender, NavigationEventArgs e) { if (e.Uri.AbsoluteUri.Contains("access_token")) { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(e.Uri.AbsoluteUri); long uID = 0; long.TryParse(decoder.GetFirstValueByName("user_id"), out uID); storage.SetToken( decoder.GetFirstValueByName(Constants.TokenMarker)); storage.SetCurrUserID(uID); this.Frame.Navigate(typeof(MyProfile)); } else { progressRing.IsActive = false; webView.Visibility = Windows.UI.Xaml.Visibility.Visible; } }
private async Task<string> GetTokenFromCode(string code) { var uri = $"{TokenUri}?client_id={Credentials.AppId}&client_secret={Credentials.AppSecret}&code={code}"; using (var client = new HttpClient()) { var response = await client.PostAsync(uri, null); var query = await response.Content.ReadAsStringAsync(); var decoder = new WwwFormUrlDecoder(query); return decoder.GetFirstValueByName("access_token"); } }
private static IEnumerable<VideoInfo> GetVideoInfos(string source) { var t = new WwwFormUrlDecoder(source); var videoTitle = t.GetFirstValueByName("title"); var splitByUrls = t.GetFirstValueByName("url_encoded_fmt_stream_map").Split(','); var videoInfos = new List<VideoInfo>(); foreach (var s in splitByUrls) { var queries = new WwwFormUrlDecoder(s); var url = queries.GetFirstValueByName("url"); var decoder = new WwwFormUrlDecoder(url.Substring(url.IndexOf('?'))); byte formatCode; if (!Byte.TryParse(decoder.GetFirstValueByName("itag"), out formatCode)) continue; var fallbackHost = WebUtility.UrlDecode(queries.GetFirstValueByName("fallback_host")); var sig = WebUtility.UrlDecode(queries.GetFirstValueByName("sig")); var item = VideoInfo.Defaults.SingleOrDefault(videoInfo => videoInfo.FormatCode == formatCode); var info = item != null ? item.Clone() : new VideoInfo(formatCode); info.DownloadUri = new Uri(url + "&fallback_host=" + fallbackHost + "&signature=" + sig); info.Title = videoTitle; videoInfos.Add(info); } return videoInfos; }
private static string ExtracktTicketFromResponse(HttpResponseMessage loginResp) { var location = loginResp.Headers.Location; if (location == null) throw new LoginFailedException(loginResp); var decoder = new WwwFormUrlDecoder(loginResp.Headers.Location.Query); var ticketId = decoder.GetFirstValueByName("ticket"); if (ticketId == null) throw new PtcOfflineException(); return ticketId; }
public static async Task<ExternalLoginResult> GetExternalAccessTokenAsync(string externalLoginUri, bool silentMode = false) { Uri authorizationRequestUri = new Uri(new Uri(ClientFactory.BaseAddress), externalLoginUri); WebAuthenticationOptions webAuthenticationOptions = silentMode ? WebAuthenticationOptions.SilentMode : WebAuthenticationOptions.None; WebAuthenticationResult authenticationResult = await WebAuthenticationBroker.AuthenticateAsync(webAuthenticationOptions, authorizationRequestUri); ExternalLoginResult loginExternalResult = new ExternalLoginResult() { WebAuthenticationResult = authenticationResult }; if (authenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { Uri responseDataUri = new Uri(authenticationResult.ResponseData); string fragment = responseDataUri.Fragment; if (fragment != null && fragment.Length > 0) { WwwFormUrlDecoder wwwFormUrlDecoder = new WwwFormUrlDecoder(fragment.Substring(1)); loginExternalResult.AccessToken = wwwFormUrlDecoder.GetFirstValueByName("access_token"); } } return loginExternalResult; }
protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { var commandArgs = args as ProtocolActivatedEventArgs; Windows.Foundation.WwwFormUrlDecoder decoder = new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query); var destination = decoder.GetFirstValueByName("LaunchContext"); string uriToLaunch = destination; var uri = new Uri(uriToLaunch); var success = Windows.System.Launcher.LaunchUriAsync(uri); Application.Current.Exit(); // this.Suspending += OnSuspending; } // base.OnActivated(args); }
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); }
public async Task<List<VideoItem>> ParseAsync(string url) { var id = GetVideoId(url); AssertUtil.HasText(id, "no id"); var query = string.Format(Api, id); var result = await _httpClientService.GetStringAsync(query); AssertUtil.HasText(result, "no info from server"); var form = new WwwFormUrlDecoder(result); var adaptiveFmts = form.GetFirstValueByName("adaptive_fmts"); AssertUtil.HasText(result, "no videos"); var adaptiveFmtsform = new WwwFormUrlDecoder(adaptiveFmts); //TODO test only var dic = new Dictionary<string, string>(); var quality = ""; var type = ""; foreach (var item in adaptiveFmtsform) { var key = item.Name; var value = item.Value; Debug.WriteLine(key + ":" + value); if ("url" == key) { if (type.Contains("codecs=\"avc")) { dic.Add(quality, value); } } else if ("quality_label" == key) { quality = value; } else if ("type" == key) { type = value; } } var videoUrl = ""; if (dic.ContainsKey("1080p")) { videoUrl = dic["1080p"]; } else if (dic.ContainsKey("1080p60")) { videoUrl = dic["1080p60"]; } else if (dic.ContainsKey("720p60")) { videoUrl = dic["720p60"]; } else if (dic.ContainsKey("720p")) { videoUrl = dic["720p"]; } else if (dic.ContainsKey("480p")) { videoUrl = dic["480p"]; } else if (dic.ContainsKey("240p")) { videoUrl = dic["240p"]; } else if (dic.ContainsKey("144p")) { videoUrl = dic["144p"]; } var videoItem = new VideoItem { Url = videoUrl }; var items = new List<VideoItem>(1) { videoItem }; return items; }
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 ); }
public static string ExtractParamterFromQuery(this Uri uri, string parameterName) { var urlDecoder = new WwwFormUrlDecoder(uri.Query); return urlDecoder.GetFirstValueByName(parameterName); }
//[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); }
// return series ID static string ParseIDFromBookLink(string link) { Uri uri = new Uri(SeverBaseUri, link); var decoder = new WwwFormUrlDecoder(uri.Query); return decoder.GetFirstValueByName("id"); }
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 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; }
private static async Task<string> GetToken(System.Net.Http.HttpClient tempHttpClient, string ticketId) { HttpResponseMessage tokenResp; var tokenRequest = GenerateTokenVarRequest(ticketId); using (var formUrlEncodedContent = new FormUrlEncodedContent(tokenRequest)) { tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth, formUrlEncodedContent).ConfigureAwait(false); } var tokenData = await tokenResp.Content.ReadAsStringAsync().ConfigureAwait(false); var decoder = new WwwFormUrlDecoder(tokenData); return decoder.GetFirstValueByName("access_token"); }
/** * Launch the oAuth User Agent login dialog **/ public async Task<String> oAuthUserAgentFlow() { //if we already have an Access Token, just return that if (AccessToken != "") { return AccessToken; } //If we have a refresh token available, use the Refresh Token flow to get a new Access Token if (RefreshToken != "" && RefreshToken != null) { AccessToken = await RefreshTokenFlow(); return AccessToken; } //prepare the request uri and the callback uri Uri requestUri = new Uri("https://login.salesforce.com/services/oauth2/authorize?response_type=token&display=touch&client_id="+ConsumerKey+"&redirect_uri="+WebUtility.UrlEncode(RedirectUri)); Uri callbackUri = new Uri(RedirectUri); //launch the authentication process using WebAuthenticationBroker WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, callbackUri); if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { //parse the response Uri to get access token, etc. Uri responseUri = new Uri(webAuthenticationResult.ResponseData.ToString()); //just treat it as a query string so we can use WwwFormUrlDecoder to parse it WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(responseUri.Fragment.Replace("#", "?")); AccessToken = decoder.GetFirstValueByName("access_token"); RefreshToken = decoder.GetFirstValueByName("refresh_token"); InstanceUrl = WebUtility.UrlDecode(decoder.GetFirstValueByName("instance_url")); PersistData.SetSerializedValue("instance_url", InstanceUrl); Debug.WriteLine("Access Token: "+AccessToken); return AccessToken; } else { return ""; } }
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); } }
public static bool ParseResponseData(string responseData) { try { Uri uri = new Uri(responseData); if (!String.IsNullOrEmpty(uri.Query)) { // Error example: // http://kiewic.com/?error_code=1349126&error_message=App%20Not%20Setup%3A%20The%20developers%20of%20this%20app%20have%20not%20set%20up%20this%20app%20properly%20for%20Facebook%20Login.#_=_ WwwFormUrlDecoder queryString = new WwwFormUrlDecoder(uri.Query); string errorCode = queryString.GetFirstValueByName("error_code"); if (!String.IsNullOrEmpty(errorCode)) { string errorMessage = queryString.GetFirstValueByName("error_message"); ShowError(errorMessage, String.Format("Error {0}", errorCode)); return false; } } if (!String.IsNullOrEmpty(uri.Fragment)) { // Token example: // http://kiewic.com/#access_token=CAAUVp1iaXIoBADZA6TV0BPB7hUGkqF7I6ZAcvWWlabBznOWzdicE4ZBeF1c2G3IOsHbaKiSedCr7PpQxAZAqmhPiIGV6dYndtqGBIaIXwcWc3Rj6lLfYQlGDdtRwt0ZBEu4KuZCYIel1S4FVeND5q2lfH0gYMFpU2ncmdTN6BTLDA0HVmKvKWLKH71YzmrFP3mdB7CR5TcHAZDZD&expires_in=4774 WwwFormUrlDecoder queryString = new WwwFormUrlDecoder(uri.Fragment.Substring(1)); string accessToken = queryString.GetFirstValueByName("access_token"); AccessToken = accessToken; Debug.WriteLine(AccessToken); return true; } } catch (Exception ex) { ShowError(ex.Message, String.Format("Error 0x{0:X}", ex.HResult)); } return false; }
protected override void OnActivated(IActivatedEventArgs args) { base.OnActivated(args); InitMangers(); InitWindow(); switch (args.Kind) { case ActivationKind.VoiceCommand: CortanaManager.OnActivated(args as VoiceCommandActivatedEventArgs); Window.Current.Activate(); break; case ActivationKind.Protocol: var a = args as ProtocolActivatedEventArgs; WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(a.Uri.Query); var wheelmapParams = WheelmapParams.FromString(decoder.GetFirstValueByName("LaunchContext")); ShowMainPage(args, wheelmapParams); break; default: ShowMainPage(args); break; } }
private async void ShowPopup(string parameter) { WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(parameter); Debug.WriteLine(decoder.GetFirstValueByName("num")); Debug.WriteLine(decoder.GetFirstValueByName("offset")); var menu = new PopupMenu(); menu.Commands.Add(new UICommand("Citer", (command) => { Debug.WriteLine("VM Open param=" + parameter); })); var chosenCommand = await menu.ShowAsync(new Point(100, Convert.ToDouble(decoder.GetFirstValueByName("offset")) + 44.0)); if (chosenCommand == null) { Debug.WriteLine("VM Dismiss param=" + parameter); } }
static NovelPositionIdentifier ParseIDFromReadLink(string link) { var pos = new NovelPositionIdentifier(); Uri uri = new Uri(SeverBaseUri, link); var decoder = new WwwFormUrlDecoder(uri.Query); pos.ChapterId = decoder.GetFirstValueByName("chapterId"); pos.VolumeId = decoder.GetFirstValueByName("volId"); pos.SeriesId = decoder.GetFirstValueByName("bookId"); return pos; }
async protected override void OnActivated(IActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { CreateRootFrame(); if (!RootFrame.Navigate(typeof(MainPage))) { throw new Exception("Failed to create initial page"); } Window.Current.Activate(); } if (args.Kind == ActivationKind.Launch) { var toastArgs = args as LaunchActivatedEventArgs; if (toastArgs == null) { return; } var arguments = JsonConvert.DeserializeObject <ToastNotificationArgs>(toastArgs.Arguments); if (arguments.openBookmarks) { var bookmarkCommand = new NavigateToBookmarksCommand(); bookmarkCommand.Execute(null); return; } if (arguments != null && arguments.openPrivateMessages) { var openPms = new NavigateToPrivateMessageListPageCommand(); openPms.Execute(null); return; } } //Find out if this is activated from a toast; if (args.Kind == ActivationKind.ToastNotification) { //Get the pre-defined arguments and user inputs from the eventargs; var toastArgs = args as ToastNotificationActivatedEventArgs; if (toastArgs == null) { return; } var arguments = JsonConvert.DeserializeObject <ToastNotificationArgs>(toastArgs.Argument); if (arguments != null && arguments.threadId > 0) { var bookmarkCommand = new NavigateToBookmarksCommand(); bookmarkCommand.Execute(arguments.threadId); return; } var forumEntity = JsonConvert.DeserializeObject <ForumEntity>(toastArgs.Argument); if (forumEntity != null) { var navigateCommand = new NavigateToThreadListPageCommandViaTile(); navigateCommand.Execute(forumEntity); } } // Cortana if (args.Kind == ActivationKind.VoiceCommand) { var commandArgs = args as VoiceCommandActivatedEventArgs; HandleVoiceRequest(commandArgs); } if (args.Kind == ActivationKind.Protocol) { var commandArgs = args as ProtocolActivatedEventArgs; Windows.Foundation.WwwFormUrlDecoder decoder = new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query); var destination = decoder.GetFirstValueByName("LaunchContext"); var jsonTest = WebUtility.UrlDecode(destination); var arguments = JsonConvert.DeserializeObject <ToastNotificationArgs>(jsonTest); if (arguments != null && arguments.threadId > 0) { var bookmarkCommand = new NavigateToBookmarksCommand(); bookmarkCommand.Execute(arguments.threadId); return; } if (arguments != null && arguments.openPrivateMessages) { var openPms = new NavigateToPrivateMessageListPageCommand(); openPms.Execute(null); return; } var forumEntity = JsonConvert.DeserializeObject <ForumEntity>(jsonTest); if (forumEntity != null) { var navigateCommand = new NavigateToThreadListPageCommandViaTile(); navigateCommand.Execute(forumEntity); } } //... }
/// <summary> /// Invoked when the application is activated by some other means other than launching /// </summary> /// <param name="e">Event data for the event.</param> protected override async void OnActivated(IActivatedEventArgs args) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif 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; // Place the frame in the current Window Window.Current.Content = rootFrame; } if (args.Kind == ActivationKind.VoiceCommand) { try { // now get the parameters pased in VoiceCommandActivatedEventArgs commandArgs = args as VoiceCommandActivatedEventArgs; SpeechRecognitionResult speechRecognitionResult = commandArgs.Result; string voiceCommandName = speechRecognitionResult.RulePath[0]; string textSpoken = speechRecognitionResult.Text; IReadOnlyList <string> recognisedVoiceCommandPhrases; System.Diagnostics.Debug.WriteLine("Voice CommandName: " + voiceCommandName); System.Diagnostics.Debug.WriteLine("text Spoken: " + textSpoken); switch (voiceCommandName) { case "readBook": { string bookName = this.SemanticInterpretation("bookName", speechRecognitionResult); var folder = ApplicationData.Current.LocalFolder; var subFolder = await folder.GetFolderAsync("books"); var files = await subFolder.GetFilesAsync(); foreach (StorageFile sf in files) { if (sf.DisplayName.Equals(bookName)) { book = sf.Name; break; } } break; } default: { break; } } // end Switch(voiceCommandName) System.Diagnostics.Debug.WriteLine("go to main page Now "); } catch (Exception) { MessageDialog msgDialog = new MessageDialog("Crashed"); await msgDialog.ShowAsync(); } } else if (args.Kind == ActivationKind.Protocol) { var commandArgs = args as ProtocolActivatedEventArgs; Windows.Foundation.WwwFormUrlDecoder decoder = new Windows.Foundation.WwwFormUrlDecoder(commandArgs.Uri.Query); var destination = decoder.GetFirstValueByName("LaunchContext"); } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(EnterByVoice), args.PreviousExecutionState); } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Finishes the login process asynchronously. /// </summary> /// <param name="webAuthenticationResult">The web authentication result.</param> private async Task FinishLoginAsync(WebAuthenticationResult webAuthenticationResult) { if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { this._exceptionHandler.Handle(new Exception(webAuthenticationResult.ResponseData)); } else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel) { LogTo.Debug("User cancelled the login."); } else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) { var responseUri = new Uri(webAuthenticationResult.ResponseData); var decoder = new WwwFormUrlDecoder(responseUri.Query); string accessToken = decoder.GetFirstValueByName("code"); var client = this.GetClient(); await client.Core.OAuth2.TokenAsync(accessToken); AccountInfo dropboxUserInfo = await client.Core.Accounts.AccountInfoAsync(); this._sessionService.UserLoggedIn(client.UserAccessToken, dropboxUserInfo.uid); await this._eventAggregator.PublishOnUIThreadAsync(new UserLoggedInEvent()); } }
private static IEnumerable<Uri> ExtractDownloadUrls(string source) { #if NETFX_CORE string urlMap = new WwwFormUrlDecoder(source).GetFirstValueByName("url_encoded_fmt_stream_map"); #else string urlMap = HttpUtility.ParseQueryString(source).Get("url_encoded_fmt_stream_map"); #endif string[] splitByUrls = urlMap.Split(','); foreach (string s in splitByUrls) { #if NETFX_CORE var decoder = new WwwFormUrlDecoder(s); string url = string.Format("{0}&fallback_host={1}&signature={2}", decoder.GetFirstValueByName("url"), decoder.GetFirstValueByName("fallback_host"), decoder.GetFirstValueByName("sig")); url = WebUtility.UrlDecode(url); url = WebUtility.UrlDecode(url); #else var queries = HttpUtility.ParseQueryString(s); string url = string.Format("{0}&fallback_host={1}&signature={2}", queries["url"], queries["fallback_host"], queries["sig"]); url = HttpUtility.UrlDecode(url); url = HttpUtility.UrlDecode(url); #endif yield return new Uri(url); } }
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); }