////////////////////////////////////////////////////////////////////// /// <summary> /// Parses and returns the AuthSub token returned by Google on a successful /// AuthSub login request. The token will be appended as a query parameter /// to the continue URL specified while making the AuthSub request. /// </summary> /// <param name="uri">The reply URI to parse </param> /// <returns>the token value of the URI, or null if none </returns> ////////////////////////////////////////////////////////////////////// public static string getTokenFromReply(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } char [] deli = { '?', '&' }; TokenCollection tokens = new TokenCollection(uri.Query, deli); foreach (String token in tokens) { if (token.Length > 0) { char [] otherDeli = { '=' }; String [] parameters = token.Split(otherDeli, 2); if (parameters[0] == "token") { return(parameters[1]); } } } return(null); }
/// <summary> /// this will take one category part and parse it /// </summary> /// <param name="category"></param> /// <returns></returns> private void ParseCategoryString(string category) { // take the string, and create some category objects out of it... // replace the curly braces and the or operator | so that we can tokenize better category = category.Replace("%7B", "{"); category = category.Replace("%7D", "}"); category = category.Replace("%7C", "|"); category = Utilities.UrlDecodedValue(category); // let's see if it's the only one... TokenCollection tokens = new TokenCollection(category, new char[1] { '|' }); QueryCategoryOperator op = QueryCategoryOperator.AND; foreach (String token in tokens) { // each one is a category QueryCategory cat = new QueryCategory(token, op); this.Categories.Add(cat); op = QueryCategoryOperator.OR; } }
////////////////////////////////////////////////////////////////////// /// <summary>goes to the Google auth service, and gets a new auth token</summary> /// <returns>the auth token, or NULL if none received</returns> ////////////////////////////////////////////////////////////////////// public static string QueryClientLoginToken(GDataCredentials gc, string serviceName, string applicationName, bool fUseKeepAlive, Uri clientLoginHandler ) { //Tracing.Assert(gc != null, "Do not call QueryAuthToken with no network credentials"); if (gc == null) { throw new System.ArgumentNullException("nc", "No credentials supplied"); } //ServicePointManager.CertificatePolicy = delegate { return true; }; ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; ServicePointManager.CheckCertificateRevocationList = false; HttpWebRequest authRequest = WebRequest.Create(clientLoginHandler) as HttpWebRequest; authRequest.KeepAlive = fUseKeepAlive; string accountType = GoogleAuthentication.AccountType; if (!String.IsNullOrEmpty(gc.AccountType)) { accountType += gc.AccountType; } else { accountType += GoogleAuthentication.AccountTypeDefault; } WebResponse authResponse = null; string authToken = null; try { authRequest.ContentType = HttpFormPost.Encoding; authRequest.Method = HttpMethods.Post; ASCIIEncoding encoder = new ASCIIEncoding(); string user = gc.Username == null ? "" : gc.Username; string pwd = gc.getPassword() == null ? "" : gc.getPassword(); // now enter the data in the stream string postData = GoogleAuthentication.Email + "=" + Utilities.UriEncodeUnsafe(user) + "&"; postData += GoogleAuthentication.Password + "=" + Utilities.UriEncodeUnsafe(pwd) + "&"; postData += GoogleAuthentication.Source + "=" + Utilities.UriEncodeUnsafe(applicationName) + "&"; postData += GoogleAuthentication.Service + "=" + Utilities.UriEncodeUnsafe(serviceName) + "&"; if (gc.CaptchaAnswer != null) { postData += GoogleAuthentication.CaptchaAnswer + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaAnswer) + "&"; } if (gc.CaptchaToken != null) { postData += GoogleAuthentication.CaptchaToken + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaToken) + "&"; } postData += accountType; byte[] encodedData = encoder.GetBytes(postData); authRequest.ContentLength = encodedData.Length; Stream requestStream = authRequest.GetRequestStream(); requestStream.Write(encodedData, 0, encodedData.Length); requestStream.Close(); authResponse = authRequest.GetResponse(); } catch (WebException) { //Tracing.TraceMsg("QueryAuthtoken failed " + e.Status + " " + e.Message); throw; } HttpWebResponse response = authResponse as HttpWebResponse; if (response != null) { // check the content type, it must be text if (!response.ContentType.StartsWith(HttpFormPost.ReturnContentType)) { throw new GDataRequestException("Execution of authentication request returned unexpected content type: " + response.ContentType, response); } TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream()); authToken = Utilities.FindToken(tokens, GoogleAuthentication.AuthToken); if (authToken == null) { throw Utilities.getAuthException(tokens, response); } // failsafe. if getAuthException did not catch an error... int code = (int)response.StatusCode; if (code != 200) { throw new GDataRequestException("Execution of authentication request returned unexpected result: " + code, response); } } //Tracing.Assert(authToken != null, "did not find an auth token in QueryAuthToken"); if (authResponse != null) { authResponse.Close(); } return(authToken); }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>parses a form response stream in token form for a specific value /// </summary> /// <param name="inputStream">the stream to read and parse</param> /// <param name="key">the key to search for</param> /// <returns> the string in the tokenized stream </returns> ////////////////////////////////////////////////////////////////////// static public string ParseValueFormStream(Stream inputStream, string key) { TokenCollection tokens = ParseStreamInTokenCollection(inputStream); return(FindToken(tokens, key)); }
/// <summary>Standard constructor</summary> public TokenEnumerator(TokenCollection tokens) { this.tokens = tokens; }
///////////////////////////////////////////////////////////////////////////// #if WindowsCE || PocketPC #else ////////////////////////////////////////////////////////////////////// /// <summary>protected void ParseUri</summary> /// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param> /// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns> ////////////////////////////////////////////////////////////////////// protected virtual Uri ParseUri(Uri targetUri) { Reset(); StringBuilder newPath = null; UriBuilder newUri = null; if (targetUri != null) { TokenCollection tokens; // want to check some basic things on this guy first... ValidateUri(targetUri); newPath = new StringBuilder("", 2048); newUri = new UriBuilder(targetUri); newUri.Path = null; newUri.Query = null; // now parse the query string and take the properties out string [] parts = targetUri.Segments; bool fCategory = false; foreach (string part in parts) { string segment = CleanPart(part); if (segment.Equals("-") == true) { // found the category simulator fCategory = true; } else if (fCategory == true) { ParseCategoryString(segment); } else { newPath.Append(part); } } char [] deli = { '?', '&' }; tokens = new TokenCollection(targetUri.Query, deli); foreach (String token in tokens) { if (token.Length > 0) { char [] otherDeli = { '=' }; String [] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "q": this.Query = parameters[1]; break; case "author": this.Author = parameters[1]; break; case "start-index": this.StartIndex = int.Parse(parameters[1], CultureInfo.InvariantCulture); break; case "max-results": this.NumberToRetrieve = int.Parse(parameters[1], CultureInfo.InvariantCulture); break; case "updated-min": this.StartDate = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "updated-max": this.EndDate = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "published-min": this.MinPublication = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "published-max": this.MaxPublication = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "category": ParseCategoryQueryString(parameters[1]); break; case "xoauth_requestor_id": this.OAuthRequestorId = Utilities.UrlDecodedValue(parameters[1]); break; default: break; } } } } if (newPath != null) { if (newPath[newPath.Length - 1] == '/') { newPath.Length = newPath.Length - 1; } newUri.Path = newPath.ToString(); this.baseUri = newUri.Uri.AbsoluteUri; this.UseSSL = this.baseUri.StartsWith("https://"); } return(null); }