////////////////////////////////////////////////////////////////////// /// <summary>Retrieves information about the AuthSub token. /// If the <code>key</code> is non-null, the token will be used securely /// and the request to revoke the token will be signed. /// </summary> /// <param name="protocol">the protocol to use to communicate with the server</param> /// <param name="domain">the domain at which the authentication server exists</param> /// <param name="token">tthe AuthSub token for which to receive information </param> /// <param name="key">the private key to sign the request</param> /// <returns>the token information in the form of a Dictionary from the name of the /// attribute to the value of the attribute</returns> ////////////////////////////////////////////////////////////////////// public static Dictionary <String, String> GetTokenInfo(String protocol, String domain, String token, AsymmetricAlgorithm key) { HttpWebResponse response; try { string tokenInfoUrl = GetTokenInfoUrl(protocol, domain); Uri uri = new Uri(tokenInfoUrl); HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; string header = formAuthorizationHeader(token, key, uri, "GET"); request.Headers.Add(header); response = request.GetResponse() as HttpWebResponse; } catch (WebException e) { Tracing.TraceMsg("GetTokenInfo failed " + e.Status); throw new GDataRequestException("Execution of GetTokenInfo", e); } if (response != null) { int code = (int)response.StatusCode; if (code != 200) { throw new GDataRequestException("Execution of revokeToken request returned unexpected result: " + code, response); } TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream()); if (tokens != null) { return(tokens.CreateDictionary()); } } 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> /// 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> /// Returns the respective GDataAuthenticationException given the return /// values from the login URI handler. /// </summary> /// <param name="tokens">The tokencollection of the parsed return form</param> /// <param name="response">the webresponse</param> /// <returns>AuthenticationException</returns> private static LoggedException getAuthException(TokenCollection tokens, HttpWebResponse response) { String errorName = Utilities.FindToken(tokens, "Error"); int code= (int)response.StatusCode; if (errorName == null || errorName.Length == 0) { // no error given by Gaia, return a standard GDataRequestException throw new GDataRequestException("Execution of authentication request returned unexpected result: " +code, response); } if ("BadAuthentication".Equals(errorName)) { return new InvalidCredentialsException("Invalid credentials"); } else if ("AccountDeleted".Equals(errorName)) { return new AccountDeletedException("Account deleted"); } else if ("AccountDisabled".Equals(errorName)) { return new AccountDisabledException("Account disabled"); } else if ("NotVerified".Equals(errorName)) { return new NotVerifiedException("Not verified"); } else if ("TermsNotAgreed".Equals(errorName)) { return new TermsNotAgreedException("Terms not agreed"); } else if ("ServiceUnavailable".Equals(errorName)) { return new ServiceUnavailableException("Service unavailable"); } else if ("CaptchaRequired".Equals(errorName)) { String captchaPath = Utilities.FindToken(tokens, "CaptchaUrl"); String captchaToken = Utilities.FindToken(tokens, "CaptchaToken"); StringBuilder captchaUrl = new StringBuilder(); captchaUrl.Append(GoogleAuthentication.DefaultProtocol).Append("://"); captchaUrl.Append(GoogleAuthentication.DefaultDomain); captchaUrl.Append(GoogleAuthentication.AccountPrefix); captchaUrl.Append('/').Append(captchaPath); return new CaptchaRequiredException("Captcha required", captchaUrl.ToString(), captchaToken); } else { return new AuthenticationException("Error authenticating (check service name): " + errorName); } }
///////////////////////////////////////////////////////////////////////////// /// <summary> /// this will take the complete parameter string and split it into parts /// </summary> /// <param name="categories"></param> /// <returns></returns> private void ParseCategoryQueryString(string categories) { // split the string in parts char [] deli = {','}; TokenCollection tokens = new TokenCollection(categories, deli); foreach (String token in tokens) { ParseCategoryString(token); } }
// end of accessor public Thumbsize ////////////////////////////////////////////////////////////////////// /// <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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, deli); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDeli = { '=' }; String[] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "kind": this.kindsAsText = parameters[1]; break; case "tag": this.tags = parameters[1]; break; case "thumbsize": this.thumbsize = parameters[1]; break; case "access": if (String.Compare("all", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.Access = AccessLevel.AccessAll; } else if (String.Compare("private", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.Access = AccessLevel.AccessPrivate; } else { this.Access = AccessLevel.AccessPublic; } break; } } } } return this.Uri; }
////////////////////////////////////////////////////////////////////// /// <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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; TokenCollection 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 "format": if (parameters[1] != null) { string [] formats = parameters[1].Split(new char[] {','}); foreach (string f in formats) { if (String.Compare(f, "1", false, CultureInfo.InvariantCulture) == 0) { this.Formats.Add(VideoFormat.RTSP); } else if (String.Compare(f, "5", false, CultureInfo.InvariantCulture) == 0) { this.Formats.Add(VideoFormat.Embeddable); } else if (String.Compare(f, "6", false, CultureInfo.InvariantCulture) == 0) { this.Formats.Add(VideoFormat.Mobile); } } } break; case "orderby": this.OrderBy = parameters[1]; break; case "client": this.Client = parameters[1]; break; case "lr": this.LR = parameters[1]; break; case "location": this.Location = parameters[1]; break; case "location-radius": this.LocationRadius = parameters[1]; break; case "uploader": this.Uploader = parameters[1]; break; case "safeSearch": if ("none"==parameters[1]) { this.SafeSearch = SafeSearchValues.None; } else if ("moderate"==parameters[1]) { this.SafeSearch = SafeSearchValues.Moderate; } else if ("strict"==parameters[1]) { this.SafeSearch = SafeSearchValues.Strict; } break; case "restriction": this.Restriction = parameters[1]; break; case "time": if ("all_time" == parameters[1]) { this.Time = UploadTime.AllTime; } else if ("this_month" == parameters[1]) { this.Time = UploadTime.ThisMonth; } else if ("today" == parameters[1]) { this.Time = UploadTime.Today; } else if ("this_week" == parameters[1]) { this.Time = UploadTime.ThisWeek; } else { this.Time = UploadTime.UploadTimeUndefined; } break; } } } } return this.Uri; }
/// <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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, deli); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDeli = { '=' }; String[] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "dimensions": this.dimensions = parameters[1]; break; case "end-date": this.endDate = parameters[1]; break; case "filters": this.filters = parameters[1]; break; case "segment": this.segment = parameters[1]; break; case "ids": this.ids = parameters[1]; break; case "metrics": this.metrics = parameters[1]; break; case "sort": this.sort = parameters[1]; break; case "start-date": this.startDate = parameters[1]; break; case "prettyprint": this.prettyPrint = bool.Parse(parameters[1]); break; } } } } return this.Uri; }
/////////////////////////////////////////////////////////////////////// /// <summary>Parses the Google-Base specific parameters /// in the Uri.</summary> /////////////////////////////////////////////////////////////////////// protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&'}; TokenCollection 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 BqParameter: this.bq = System.Web.HttpUtility.UrlDecode(parameters[1]); break; case MaxValuesParameter: this.maxValues = NumberFormat.ToInt(parameters[1]); break; case OrderByParameter: this.orderby = System.Web.HttpUtility.UrlDecode(parameters[1]); break; case SortOrderParameter: this.ascending = "ascending".Equals(parameters[1]); break; case RefineParameter: this.refine = Utilities.XSDTrue.Equals(parameters[1]); break; case ContentParameter: this.content = System.Web.HttpUtility.UrlDecode(parameters[1]); break; } } } } return this.Uri; }
/// <summary>Standard constructor</summary> public TokenEnumerator(TokenCollection tokens) { this.tokens = tokens; }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>converts a form response stream to a TokenCollection, /// by parsing the contents of the stream for newlines and equal signs /// the input stream is assumed to be an ascii encoded form resonse /// </summary> /// <param name="inputStream">the stream to read and parse</param> /// <returns> the resulting TokenCollection </returns> ////////////////////////////////////////////////////////////////////// static public TokenCollection ParseStreamInTokenCollection(Stream inputStream) { // get the body and parse it ASCIIEncoding encoder = new ASCIIEncoding(); StreamReader readStream = new StreamReader(inputStream, encoder); String body = readStream.ReadToEnd(); readStream.Close(); Tracing.TraceMsg("got the following body back: " + body); // all we are interested is the token, so we break the string in parts TokenCollection tokens = new TokenCollection(body, '=', true, 2); return tokens; }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>searches tokenCollection for a specific NEXT value. /// The collection is assume to be a key/value pair list, so if A,B,C,D is the list /// A and C are keys, B and D are values /// </summary> /// <param name="tokens">the TokenCollection to search</param> /// <param name="key">the key to search for</param> /// <returns> the value string</returns> ////////////////////////////////////////////////////////////////////// static public string FindToken(TokenCollection tokens, string key) { string returnValue = null; bool fNextOne=false; foreach (string token in tokens ) { if (fNextOne == true) { returnValue = token; break; } if (key == token) { // next one is it fNextOne = true; } } return returnValue; }
// end of accessor public Thumbsize #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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&'}; TokenCollection 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 "kind": String[] kinds = parameters[1].Split(new char[] {','}); if (kinds != null && kinds.Length > 0) { this.kinds[0] = (Kinds) Enum.Parse(typeof(Kinds), kinds[0]); if (kinds.Length == 2) { this.kinds[1] = (Kinds) Enum.Parse(typeof(Kinds), kinds[1]); } } break; case "thumbsize": this.thumbsize = parameters[1]; break; case "access": if (String.Compare("all", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.Access = AccessLevel.AccessAll; } else if (String.Compare("private", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.Access = AccessLevel.AccessPrivate; } else { this.Access = AccessLevel.AccessPublic; } break; } } } } return this.Uri; }
///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests the tokenizer collection</summary> ////////////////////////////////////////////////////////////////////// [Test] public void TestTokenCollection() { Tracing.TraceMsg("Entering TestTokenCollection"); String toTest = "Test=Test?other=whatever\nTest2=Line2?other=whatishere"; TokenCollection tokens = new TokenCollection(toTest, new char[] {'\n', '='}); TokenCollection tokenSmart = new TokenCollection(toTest, '=', true, 2); int iTokens = 0; foreach (string token in tokens) { // tokens should have 5 tokens, as the = signs split into 5 iTokens++; if (iTokens == 1) { Assert.IsTrue(token.Equals("Test"), "The first token should be Test, but it is: " + token); } if (iTokens == 4) { Assert.IsTrue(token.Equals("Test2"), "The fourth token should be Test2 but it is: " + token); } } iTokens = 0; foreach (string token in tokenSmart) { // tokens should have 5 tokens, as the = signs split into 5 iTokens++; if (iTokens == 1) { Assert.IsTrue(token.Equals("Test"), "The first smart token should be Test, but it is: " + token); } if (iTokens == 4) { Assert.IsTrue(token.Equals("Line2?other=whatishere"), "The fourth smart token should be whatishere, but it is: " + token); } } }
// end of accessor public string SortOder #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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; TokenCollection 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 "group": this.Group = parameters[1]; break; } } } } return this.Uri; }
///////////////////////////////////////////////////////////////////////////// #if WindowsCE || PocketPC #else ////////////////////////////////////////////////////////////////////// /// <summary>Parses custom properties out of the incoming URI</summary> /// <param name="targetUri">A URI representing a query on a feed</param> /// <returns>returns the base uri</returns> ////////////////////////////////////////////////////////////////////// protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; TokenCollection 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 "title-exact": this.TitleExact = bool.Parse(parameters[1]); break; case "title": this.Title = parameters[1]; break; case "owner": this.Owner = parameters[1]; break; case "reader": this.Reader = parameters[1]; break; case "writer": this.Writer = parameters[1]; break; case "targetLanguage": this.TargetLanguage = parameters[1]; break; case "sourceLanguage": this.SourceLanguage = parameters[1]; break; case "showfolders": this.ShowFolders = bool.Parse(parameters[1]); break; case "ocr": this.Ocr = bool.Parse(parameters[1]); break; case "showDeleted": this.ShowDeleted = bool.Parse(parameters[1]); break; case "edited-min": this.EditedMin = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "edited-max": this.EditedMax = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; } } } } return this.Uri; }
/// <summary> /// Parses an incoming URI string and sets the instance variables of this object. /// </summary> /// <param name="targetUri">Takes an incoming Uri string and parses all the properties of it</param> /// <returns>Throws a query exception when it finds something wrong with the input, otherwise returns a baseuri.</returns> protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] delimiters = { '?', '&' }; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, delimiters); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDelimiters = { '=' }; String[] parameters = token.Split(otherDelimiters, 2); switch (parameters[0]) { case "performance.start": PerformanceStart = parameters[1]; break; case "performance.end": PerformanceEnd = parameters[1]; break; } } } } return this.Uri; }
///////////////////////////////////////////////////////////////////////////// #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); }
/// <summary> /// Parses an incoming URI string and sets the instance variables /// of this object. /// </summary> /// <param name="targetUri">Takes an incoming Uri string and parses all the properties of it</param> /// <returns>Throws a query exception when it finds something wrong with the input, otherwise returns a baseuri.</returns> protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] delimiters = { '?', '&' }; TokenCollection tokens = new TokenCollection(targetUri.Query, delimiters); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDelimiters = { '=' }; String[] parameters = token.Split(otherDelimiters, 2); switch (parameters[0]) { case "title": Title = parameters[1]; Exact = false; break; case "title-exact": Title = parameters[1]; Exact = true; break; } } } } return this.Uri; }
////////////////////////////////////////////////////////////////////// /// <summary>Parses custom properties out of the incoming URI</summary> /// <param name="targetUri">A URI representing a query on a feed</param> /// <returns>returns the base uri</returns> ////////////////////////////////////////////////////////////////////// protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; TokenCollection 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 "title-exact": this.TitleExact = bool.Parse(parameters[1]); break; case "title": this.Title = parameters[1]; break; case "showfolders": this.ShowFolders = bool.Parse(parameters[1]); break; } } } } return this.Uri; }
////////////////////////////////////////////////////////////////////// /// <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>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>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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri == null) { return this.Uri; } char[] deli = { '?', '&' }; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, deli); foreach (string token in tokens) { if (token.Length == 0) { continue; } char[] otherDeli = { '=' }; string[] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "format": if (parameters[1] != null) { string[] formats = parameters[1].Split(new char[] { ',' }); foreach (string f in formats) { this.Formats.Add((VideoFormat)Enum.Parse(typeof(VideoFormat), f)); } } break; case "orderby": this.OrderBy = parameters[1]; break; case "client": this.Client = parameters[1]; break; case "lr": this.LR = parameters[1]; break; case "location": this.Location = parameters[1]; break; case "location-radius": this.LocationRadius = parameters[1]; break; case "uploader": this.Uploader = parameters[1]; break; case "safeSearch": if ("none" == parameters[1]) { this.SafeSearch = SafeSearchValues.None; } else if ("moderate" == parameters[1]) { this.SafeSearch = SafeSearchValues.Moderate; } else if ("strict" == parameters[1]) { this.SafeSearch = SafeSearchValues.Strict; } break; case "restriction": this.Restriction = parameters[1]; break; case "time": if ("all_time" == parameters[1]) { this.Time = UploadTime.AllTime; } else if ("this_month" == parameters[1]) { this.Time = UploadTime.ThisMonth; } else if ("today" == parameters[1]) { this.Time = UploadTime.Today; } else if ("this_week" == parameters[1]) { this.Time = UploadTime.ThisWeek; } else { this.Time = UploadTime.UploadTimeUndefined; } break; } } return this.Uri; }
/// <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, IWebProxy proxyServer, 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"); } HttpWebRequest authRequest = WebRequest.Create(clientLoginHandler) as HttpWebRequest; authRequest.KeepAlive = fUseKeepAlive; if (proxyServer != null) { authRequest.Proxy = proxyServer; } string accountType = GoogleAuthentication.AccountType; if (!String.IsNullOrEmpty(gc.AccountType)) { accountType += gc.AccountType; } else { accountType += GoogleAuthentication.AccountTypeDefault; } WebResponse authResponse = null; HttpWebResponse response = 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(); response = authResponse as HttpWebResponse; } catch (WebException e) { response = e.Response as HttpWebResponse; if (response == null) { Tracing.TraceMsg("QueryAuthtoken failed " + e.Status + " " + e.Message); throw; } } 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); }
///////////////////////////////////////////////////////////////////////////// #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; }
////////////////////////////////////////////////////////////////////// /// <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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, deli); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDeli = { '=' }; String[] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "orderby": this.OrderBy = parameters[1]; break; } } } } return this.Uri; }
/// <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>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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&'}; TokenCollection 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 "start-min": this.startTime = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "start-max": this.endTime = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "recurrence-expansion-start": this.recurrenceStart = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "recurrence-expansion-end": this.recurrenceEnd = DateTime.Parse(Utilities.UrlDecodedValue(parameters[1]), CultureInfo.InvariantCulture); break; case "singleevents": this.singleEvents = bool.Parse(parameters[1]); break; case "futureevents": this.futureEvents = bool.Parse(parameters[1]); break; case "sortorder": this.sortOrder = (CalendarSortOrder) Enum.Parse(typeof(CalendarSortOrder), parameters[1]); break; case "ctz": this.timeZone = parameters[1]; break; } } } } return this.Uri; }
////////////////////////////////////////////////////////////////////// /// <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 override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = { '?', '&' }; TokenCollection 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 "orderby": this.OrderBy = parameters[1]; break; case "sortorder": this.SortOrder = parameters[1]; break; case "showdeleted": if (String.Compare("true", parameters[1], false, CultureInfo.InvariantCulture) == 0) { this.ShowDeleted = true; } break; } } } } return this.Uri; }
/// <summary> /// Parses an incoming URI string and sets the instance variables /// of this object. /// </summary> /// <param name="targetUri">Takes an incoming Uri string and parses all the properties of it</param> /// <returns>Throws a query exception when it finds something wrong with the input, otherwise returns a baseuri.</returns> protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] delimiters = { '?', '&'}; TokenCollection tokens = new TokenCollection(targetUri.Query, delimiters); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDelimiters = { '='}; String[] parameters = token.Split(otherDelimiters, 2); switch (parameters[0]) { case "sq": this.SpreadsheetQuery = parameters[1]; break; case "orderby": if (parameters[1].Equals("position")) { OrderByPosition = true; } else if (parameters[1].StartsWith("column:")) { OrderByColumn = parameters[1].Substring(("column:").Length); } else { throw new ClientQueryException(); } break; case "reverse": this.Reverse = bool.Parse(parameters[1]); break; } } } } return this.Uri; }
/// <summary> /// Parses an incoming URI string and sets the instance variables /// of this object. /// </summary> /// <param name="targetUri">Takes an incoming Uri string and parses all the properties of it</param> /// <returns>Throws a query exception when it finds something wrong with the input, otherwise returns a baseuri.</returns> protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] delimiters = { '?', '&'}; TokenCollection tokens = new TokenCollection(targetUri.Query, delimiters); foreach (String token in tokens) { if (token.Length > 0) { char[] otherDelimiters = { '='}; String[] parameters = token.Split(otherDelimiters, 2); switch (parameters[0]) { case "min-row": this.MinimumRow = uint.Parse(parameters[1]); break; case "max-row": this.MaximumRow = uint.Parse(parameters[1]); break; case "min-col": this.MinimumColumn = uint.Parse(parameters[1]); break; case "max-col": this.MaximumColumn = uint.Parse(parameters[1]); break; case "range": this.Range = parameters[1]; break; case "return-empty": this.ReturnEmpty = (ReturnEmtpyCells) Enum.Parse(typeof(ReturnEmtpyCells), parameters[1]); break; } } } } return this.Uri; }
///////////////////////////////////////////////////////////////////////////// #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) { // 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 segment = segment.Replace("%7B", "{"); segment = segment.Replace("%7D", "}"); segment = segment.Replace("%7C", "|"); // let's see if it's the only one... tokens = new TokenCollection(segment, new char[1] {'|'}); QueryCategoryOperator op = QueryCategoryOperator.AND; foreach (String token in tokens) { // each one is a category QueryCategory category = new QueryCategory(token, op); this.Categories.Add(category); op = QueryCategoryOperator.OR; } } 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(parameters[1], CultureInfo.InvariantCulture); break; case "updated-max": this.EndDate = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture); break; case "published-min": this.MinPublication = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture); break; case "published-max": this.MaxPublication = DateTime.Parse(parameters[1], CultureInfo.InvariantCulture); 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; } return null; }