/// <summary> /// Gets the query value as a date and time by a specific key. /// </summary> /// <param name="key">The key.</param> /// <param name="useUnixTimestamp">true if the value is unix timestamp; otherwise, false.</param> /// <returns>The query value as DateTime.</returns> public DateTime?TryGetDateTimeValue(string key, bool useUnixTimestamp = false) { var v = GetFirstValue(key, true); var l = TryGetInt64Value(key); return(l.HasValue ? (useUnixTimestamp ? WebFormat.ParseUnixTimestamp(l.Value) : WebFormat.ParseDate(l.Value)) : WebFormat.ParseDate(v)); }
/// <summary> /// Converts to query data. /// </summary> /// <returns>The query data.</returns> public virtual QueryData ToQueryData(QueryData q) { if (q == null) { q = new QueryData(); } if (string.IsNullOrWhiteSpace(ThreadId)) { q.Set("thread", ThreadId); } if (string.IsNullOrWhiteSpace(SenderAddress)) { q.Set("addr", SenderAddress); } if (SendStartTime.HasValue) { q.Set("start", WebFormat.ParseDate(SendStartTime.Value).ToString("g", CultureInfo.InvariantCulture)); } if (SendEndTime.HasValue) { q.Set("end", WebFormat.ParseDate(SendEndTime.Value).ToString("g", CultureInfo.InvariantCulture)); } if (Priority.HasValue) { q.Set("priority", ((int)Priority.Value).ToString("g", CultureInfo.InvariantCulture)); } if (Flag.HasValue) { q.Set("flag", ((int)Flag.Value).ToString("g", CultureInfo.InvariantCulture)); } return(q); }
private string GetBase64UrlEncode(object bytes) { if (Serializer != null) { return(WebFormat.Base64UrlEncode(Serializer(bytes))); } return(WebFormat.Base64UrlEncode(bytes)); }
/// <summary> /// Initializes a new instance of the JsonHttpClient class. /// </summary> public JsonHttpClient() { var d = WebFormat.GetJsonDeserializer <T>(true); if (d != null) { Deserializer = d; } }
protected override System.Data.DataTable GetData(HttpContext context, String query, int rows, Structures.Languages lang) { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(context.Application); String iso = Format.ToIso639_1(lang); query = query.ToLowerInvariant(); int natDex = 0; Int32.TryParse(query, out natDex); int limit = 0; if (context.Request.QueryString["limit"] != null) { limit = Convert.ToInt32(context.Request.QueryString["limit"]); if (natDex > limit) { return(null); } } Func <KeyValuePair <int, Species>, bool> filter; if (natDex > 0) { filter = pair => pair.Key == natDex; } else { filter = pair => pair.Key <= limit && pair.Value.Name[iso].ToLowerInvariant().Contains(query); } IEnumerable <Species> data; data = pokedex.Species.Where(filter).OrderBy(pair => pair.Key).Take(rows).Select(pair => pair.Value); DataTable dt = new DataTable(); dt.Columns.Add("Text", typeof(String)); dt.Columns.Add("Value", typeof(int)); dt.Columns.Add("html", typeof(String)); foreach (Species s in data) { String name = s.Name[iso]; String html = "<img src=\"" + Common.ResolveUrl(WebFormat.SpeciesImageSmall(s)) + "\" alt=\"" + Common.HtmlEncode(name) + "\" class=\"sprite speciesSmall\" width=\"40px\" height=\"32px\" />" + String.Format("{0} (#{1})", Common.HtmlEncode(name), s.NationalDex); dt.Rows.Add(name, s.NationalDex, html); } return(dt); }
/// <summary> /// Gets the Base64Url of signature. /// </summary> /// <returns>A string encoded of signature.</returns> public string ToSigntureBase64Url() { if (signature == null || !signature.CanSign) { return(signatureCache ?? string.Empty); } var bytes = signature.Sign($"{ToHeaderBase64Url()}.{ToPayloadBase64Url()}", Encoding.ASCII); return(WebFormat.Base64UrlEncode(bytes)); }
/// <summary> /// Adds a string to a collection of System.Net.Http.HttpContent objects that get serialized to multipart/form-data MIME type. /// </summary> /// <param name="content">The HTTP content of multipart form data.</param> /// <param name="name">The name for the HTTP content to add.</param> /// <param name="value">The property value.</param> /// <param name="dateFormat">A standard or custom date and time format string.</param> /// <param name="encoding">The character encoding to use.</param> /// <return>The HTTP content to add.</return> /// <exception cref="FormatException"> /// The length of format is 1, and it is not one of the format specifier characters defined for System.Globalization.DateTimeFormatInfo. /// -or- format does not contain a valid custom format pattern. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The date and time is outside the range of dates supported by the calendar used by the current culture. /// </exception> public static StringContent Add(this MultipartFormDataContent content, string name, DateTime value, string dateFormat = null, Encoding encoding = null) { if (content == null) { return(null); } var c = new StringContent(string.IsNullOrWhiteSpace(dateFormat) ? WebFormat.ParseDate(value).ToString() : value.ToString(dateFormat), encoding ?? Encoding.UTF8); content.Add(c, name); return(c); }
/// <inheritdoc /> public override DateTime?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null || reader.TokenType == JsonTokenType.False) { return(null); } if (reader.TokenType == JsonTokenType.String) { return(WebFormat.ParseDate(reader.GetString())); } return(WebFormat.ParseDate(reader.GetInt64())); }
protected String CreateWantedSpecies(object DataItem) { Pokedex.Pokedex pokedex = AppStateHelper.Pokedex(Application); GtsRecordBase record = (GtsRecordBase)DataItem; Species species = pokedex.Species[record.RequestedSpecies]; return("<img src=\"" + ResolveUrl(WebFormat.SpeciesImageSmall(species)) + "\" alt=\"" + Common.HtmlEncode(species.Name.ToString()) + "\" class=\"sprite speciesSmall\" width=\"40px\" height=\"32px\" />" + String.Format("{0} (#{1})", Common.HtmlEncode(species.Name.ToString()), record.RequestedSpecies)); }
/// <inheritdoc /> public override void Write(Utf8JsonWriter writer, DateTime?value, JsonSerializerOptions options) { var num = WebFormat.ParseDate(value); if (num.HasValue) { writer.WriteNumberValue(num.Value); } else { writer.WriteNullValue(); } }
/// <summary> /// Converts to JSON format string. /// </summary> /// <param name="options">The data contract serializer settings.</param> /// <returns>A JSON format string.</returns> public virtual string ToJsonString(DataContractJsonSerializerSettings options) { var m = new FragmentModel { Id = Id, Index = Index, State = State.ToString().ToLowerInvariant(), Tag = Tag, Creation = WebFormat.ParseDate(Creation), Modification = WebFormat.ParseDate(Modification) }; return(StringExtensions.ToJson(m, options)); }
/// <inheritdoc /> public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var v = WebFormat.ParseDate(reader.GetString()); if (v.HasValue) { return(v.Value); } throw new JsonException("The format is not correct.", new FormatException("The value should be a date time JSON token format.")); } return(WebFormat.ParseDate(reader.GetInt64())); }
protected String CreateOfferImage(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; return("<img src=\"" + ResolveUrl(WebFormat.PokemonImageLarge(record.Pokemon)) + "\" alt=\"" + Common.HtmlEncode(record.Pokemon.Species.Name.ToString()) + "\" class=\"sprite species\" width=\"96px\" height=\"96px\" />"); } catch { return("???"); } }
/// <summary> /// Verifies the JSON web token. /// </summary> /// <param name="algorithm">The signature algorithm instance.</param> /// <param name="checkName">true if check whether the algorithm name are same before verfiy; otherwise, false.</param> /// <returns>true if valid; otherwise, false.</returns> public bool Verify(ISignatureProvider algorithm, bool checkName = false) { if (checkName && !IsSameSignatureAlgorithmName(algorithm)) { return(false); } if (algorithm == null) { return(string.IsNullOrEmpty(SignatureBase64Url)); } var bytes = Encoding.ASCII.GetBytes($"{HeaderBase64Url}.{PayloadBase64Url}"); var sign = WebFormat.Base64UrlDecode(SignatureBase64Url); return(algorithm.Verify(bytes, sign)); }
/// <summary> /// Returns a string that represents the current object. /// </summary> /// <param name="encoding">The encoding.</param> /// <returns>A query string.</returns> public string ToString(Encoding encoding) { if (encoding == null) { encoding = DefaultEncoding ?? Encoding.UTF8; } var arr = new List <string>(); foreach (var item in this) { arr.Add(string.Format("{0}={1}", WebFormat.UrlEncode(item.Key, encoding), WebFormat.UrlEncode(item.Value, encoding))); } return(string.Join("&", arr)); }
/// <summary> /// Sets the System.Runtime.Serialization.SerializationInfo object with the parameter name and additional exception information. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { return; } info.AddValue(nameof(Id), Id, typeof(string)); info.AddValue(nameof(Index), Index, typeof(int)); info.AddValue(nameof(State), State.ToString().ToLowerInvariant(), typeof(string)); if (Tag != null) { info.AddValue(nameof(Tag), Tag, typeof(string)); } info.AddValue(nameof(Creation), WebFormat.ParseDate(Creation), typeof(long)); info.AddValue(nameof(Modification), WebFormat.ParseDate(Modification), typeof(long)); }
/// <summary> /// Converts to query data. /// </summary> /// <returns>A query data instance.</returns> public virtual QueryData ToQueryData() { var q = new QueryData { [nameof(Id)] = Id, [nameof(Index)] = Index.ToString(CultureInfo.InvariantCulture), [nameof(State)] = State.ToString().ToLowerInvariant() }; if (Tag != null) { q[nameof(Tag)] = Tag; } q[nameof(Creation)] = WebFormat.ParseDate(Creation).ToString(CultureInfo.InvariantCulture); q[nameof(Modification)] = WebFormat.ParseDate(Modification).ToString(CultureInfo.InvariantCulture); return(q); }
protected String CreateHeldItem(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; if (record.Pokemon.HeldItem == null) { return(""); } String itemName = Common.HtmlEncode(record.Pokemon.HeldItem.Name.ToString()); return("<img src=\"" + ResolveUrl(WebFormat.ItemImage(record.Pokemon.HeldItem)) + "\" alt=\"" + itemName + "\" class=\"sprite item\" width=\"24px\" height=\"24px\" />" + itemName); } catch { return("???"); } }
protected String CreatePokeball(object DataItem) { try { GtsRecordBase record = (GtsRecordBase)DataItem; // Hide pokeballs with incorrect numbers until we catalog them. if (record.Pokemon.Pokeball.Value4 > 15) { return(""); } String itemName = Common.HtmlEncode(record.Pokemon.Pokeball.Name.ToString()); return("<img src=\"" + ResolveUrl(WebFormat.ItemImage(record.Pokemon.Pokeball)) + "\" alt=\"" + itemName + "\" title=\"" + itemName + "\" class=\"sprite item\" width=\"24px\" height=\"24px\" />"); } catch { return("???"); } }
/// <summary> /// Adds a file to a collection of System.Net.Http.HttpContent objects that get serialized to multipart/form-data MIME type. /// </summary> /// <param name="content">The HTTP content of multipart form data.</param> /// <param name="name">The name for the HTTP content to add.</param> /// <param name="file">The file info instance.</param> /// <param name="fileName">The file name for the HTTP content to add to the collection.</param> /// <param name="mediaType">The MIME of the file.</param> /// <return>The HTTP content to add.</return> public static StreamContent Add(this MultipartFormDataContent content, string name, FileInfo file, string fileName = null, string mediaType = null) { if (content == null || file == null) { return(null); } var c = new StreamContent(file.OpenRead()); if (!string.IsNullOrWhiteSpace(mediaType)) { c.Headers.ContentType = new MediaTypeHeaderValue(mediaType); } else if (mediaType == null) { var mime = WebFormat.GetMime(file); if (!string.IsNullOrWhiteSpace(mime)) { c.Headers.ContentType = new MediaTypeHeaderValue(mime); } } content.Add(c, name, fileName ?? file.Name); return(c); }
/// <summary> /// Gets a copy of signature. /// </summary> /// <returns>A signature bytes.</returns> public byte[] GetSignature() { return(WebFormat.Base64UrlDecode(SignatureBase64Url)); }
/// <summary> /// Refreshs the cache. /// </summary> private void Refresh() { headerCache = WebFormat.Base64UrlDecodeTo <JsonWebTokenHeader>(HeaderBase64Url) ?? JsonWebTokenHeader.NoAlgorithm; payloadCache = WebFormat.Base64UrlDecodeTo <T>(PayloadBase64Url); }
/// <inheritdoc /> public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { var num = WebFormat.ParseUnixTimestamp(value); writer.WriteNumberValue(num); }
/// <summary> /// Parses from a JSON string. /// </summary> /// <param name="s">The string to parse.</param> public static Fragment Parse(string s) { if (string.IsNullOrWhiteSpace(s)) { throw new ArgumentNullException(nameof(s), "str should not be null or empty."); } s = s.Trim(); if (s.IndexOf("<") == 0) { var xml = XElement.Parse(s); string id = null; var index = 0; string stateStr = null; string tag = null; long? creation = null; long? modification = null; foreach (var ele in xml.Elements()) { if (string.IsNullOrWhiteSpace(ele?.Value)) { continue; } switch (ele.Name?.LocalName?.ToLowerInvariant()) { case "id": id = ele.Value; break; case "index": if (!int.TryParse(ele.Value, out index)) { index = 0; } break; case "state": stateStr = ele.Value; break; case "tag": tag = ele.Value; break; case "creation": if (long.TryParse(ele.Value, out var creationV)) { creation = creationV; } break; case "update": case "modification": if (long.TryParse(ele.Value, out var modificationV)) { modification = modificationV; } break; } } if (string.IsNullOrWhiteSpace(stateStr) || !Enum.TryParse(stateStr, true, out FragmentStates state2)) { state2 = FragmentStates.Pending; } return(new Fragment(id, index, state2, WebFormat.ParseDate(creation), WebFormat.ParseDate(modification), tag)); } if (s.IndexOfAny(new[] { '\"', '{' }) < 0) { var q = QueryData.Parse(s); var stateStr = q["State"] ?? q["state"]; if (!int.TryParse(q["Index"] ?? q["index"], out var index)) { index = 0; } if (string.IsNullOrWhiteSpace(stateStr) || !Enum.TryParse(stateStr, true, out FragmentStates state2)) { state2 = FragmentStates.Pending; } long?creation = null; long?modification = null; if (long.TryParse(q["Creation"] ?? q["creation"], out var creationV)) { creation = creationV; } if (long.TryParse(q["Modification"] ?? q["modification"] ?? q["Update"] ?? q["update"], out var modificationV)) { modification = modificationV; } return(new Fragment( q["Id"] ?? q["ID"] ?? q["id"], index, state2, WebFormat.ParseDate(creation), WebFormat.ParseDate(modification), q["Tag"] ?? q["tag"] )); } var m = JsonSerializer.Deserialize <FragmentModel>(s); if (string.IsNullOrWhiteSpace(m.State) || !Enum.TryParse(m.State, true, out FragmentStates state)) { state = FragmentStates.Pending; } return(new Fragment(m.Id, m.Index ?? 0, state, WebFormat.ParseDate(m.Creation), WebFormat.ParseDate(m.Modification), m.Tag)); }
/// <summary> /// Parses a JWT string encoded. /// </summary> /// <param name="jwt">The string encoded.</param> /// <param name="algorithm">The signature algorithm.</param> /// <param name="verify">true if verify the signature; otherwise, false.</param> /// <returns>A JSON web token object.</returns> /// <exception cref="ArgumentNullException">jwt was null or empty. -or- algorithm was null and verify is true.</exception> /// <exception cref="ArgumentException">jwt did not contain any information.</exception> /// <exception cref="FormatException">jwt was in incorrect format.</exception> /// <exception cref="InvalidOperationException">Verify failure.</exception> public static JsonWebToken <T> Parse(string jwt, ISignatureProvider algorithm, bool verify = true) { if (string.IsNullOrWhiteSpace(jwt)) { throw new ArgumentNullException(nameof(jwt), "jwt should not be null or empty."); } var prefix = $"{TokenInfo.BearerTokenType} "; if (jwt.IndexOf(prefix) == 0) { if (jwt.Length == prefix.Length) { throw new ArgumentException("jwt should not contain a scheme only.", nameof(jwt)); } jwt = jwt.Substring(prefix.Length); } var arr = jwt.Split('.'); if (arr.Length < 3) { throw new FormatException("jwt is not in the correct format."); } if (verify) { var bytes = Encoding.ASCII.GetBytes($"{arr[0]}.{arr[1]}"); var sign = WebFormat.Base64UrlDecode(arr[2]); if (algorithm != null) { if (!algorithm.Verify(bytes, sign)) { throw new InvalidOperationException("jwt signature is incorrect."); } } else { if (sign.Length > 0) { throw new ArgumentNullException(nameof(algorithm), "algorithm should not be null."); } } } var header = WebFormat.Base64UrlDecodeTo <JsonWebTokenHeader>(arr[0]); if (header == null) { throw new ArgumentException("jwt should contain header in Base64Url.", nameof(jwt)); } var payload = WebFormat.Base64UrlDecodeTo <T>(arr[1]); if (payload == null) { throw new ArgumentException("jwt should contain payload in Base64Url.", nameof(jwt)); } var obj = new JsonWebToken <T>(payload, algorithm) { headerBase64Url = arr[0], signatureCache = arr[2] }; obj.header.Type = header.Type; obj.header.AlgorithmName = header.AlgorithmName; return(obj); }
/// <summary> /// Initializes a new instance of the Fragment class. /// </summary> /// <param name="info">The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.</param> protected Fragment(SerializationInfo info, StreamingContext context) { if (info == null) { Id = Guid.NewGuid().ToString("n"); return; } try { var id = info.GetString(nameof(Id)); if (id != null) { Id = id; } } catch (SerializationException) { } try { Index = info.GetInt32(nameof(Index)); } catch (SerializationException) { } try { var stateStr = info.GetString(nameof(State)); if (!string.IsNullOrWhiteSpace(stateStr) && Enum.TryParse(stateStr, true, out FragmentStates state)) { State = state; } } catch (SerializationException) { } try { Tag = info.GetString(nameof(Tag)); } catch (SerializationException) { } try { Creation = WebFormat.ParseDate(info.GetInt64(nameof(Creation))); } catch (SerializationException) { } try { Modification = WebFormat.ParseDate(info.GetInt64(nameof(Modification))); } catch (SerializationException) { } }
private void Bind(PokemonParty4 pkmn) { litNickname.Text = pkmn.Nickname; bool shiny = pkmn.IsShiny; imgPokemon.ImageUrl = WebFormat.PokemonImageLarge(pkmn); imgPokemon.AlternateText = pkmn.Species.Name.ToString(); phShiny.Visible = shiny; litMarks.Text = WebFormat.Markings(pkmn.Markings); imgPokeball.ImageUrl = WebFormat.ItemImage(pkmn.Pokeball); imgPokeball.AlternateText = pkmn.Pokeball.Name.ToString(); imgPokeball.ToolTip = pkmn.Pokeball.Name.ToString(); litLevel.Text = pkmn.Level.ToString(); litGender.Text = WebFormat.Gender(pkmn.Gender); litTrainerMemo.Text = pkmn.TrainerMemo.ToString(); litCharacteristic.Text = pkmn.Characteristic.ToString(); litSpecies.Text = pkmn.Species.Name.ToString(); litPokedex.Text = pkmn.SpeciesID.ToString("000"); FormStats fs = pkmn.Form.BaseStats(Generations.Generation4); litType1.Text = fs.Type1 == null ? "" : WebFormat.RenderType(fs.Type1); litType2.Text = fs.Type2 == null ? "" : WebFormat.RenderType(fs.Type2); litOtName.Text = Common.HtmlEncode(pkmn.TrainerName); litTrainerId.Text = (pkmn.TrainerID & 0xffff).ToString("00000"); litExperience.Text = pkmn.Experience.ToString(); if (pkmn.Level < 100) { int expCurrLevel = PokemonBase.ExperienceAt(pkmn.Level, pkmn.Species.GrowthRate); int expNextLevel = PokemonBase.ExperienceAt(pkmn.Level + 1, pkmn.Species.GrowthRate); int progress = pkmn.Experience - expCurrLevel; int nextIn = expNextLevel - pkmn.Experience; litExperienceNext.Text = String.Format("next in {0}", nextIn); litExpProgress.Text = WebFormat.RenderProgress(progress, expNextLevel - expCurrLevel); } else { litExperienceNext.Text = ""; litExpProgress.Text = WebFormat.RenderProgress(0, 1); } if (pkmn.HeldItem != null) { imgHeldItem.Visible = true; imgHeldItem.ImageUrl = WebFormat.ItemImage(pkmn.HeldItem); litHeldItem.Text = pkmn.HeldItem.Name.ToString(); } else { imgHeldItem.Visible = false; litHeldItem.Text = ""; } litNature.Text = pkmn.Nature.ToString(); // todo: i18n litAbility.Text = pkmn.Ability == null ? "" : pkmn.Ability.Name.ToString(); litHpCurr.Text = pkmn.HP.ToString(); litHp.Text = pkmn.Stats[Stats.Hp].ToString(); litHpProgress.Text = WebFormat.RenderProgress(pkmn.HP, pkmn.Stats[Stats.Hp]); litAtk.Text = pkmn.Stats[Stats.Attack].ToString(); litDef.Text = pkmn.Stats[Stats.Defense].ToString(); litSAtk.Text = pkmn.Stats[Stats.SpecialAttack].ToString(); litSDef.Text = pkmn.Stats[Stats.SpecialDefense].ToString(); litSpeed.Text = pkmn.Stats[Stats.Speed].ToString(); phPkrs.Visible = pkmn.Pokerus == Pokerus.Infected; phPkrsCured.Visible = pkmn.Pokerus == Pokerus.Cured; rptMoves.DataSource = pkmn.Moves; rptMoves.DataBind(); rptRibbons.DataSource = pkmn.Ribbons; rptRibbons.DataBind(); rptUnknownRibbons.DataSource = pkmn.UnknownRibbons; rptUnknownRibbons.DataBind(); }
/// <summary> /// Parses a string to the query data. /// </summary> /// <param name="query">The query string.</param> /// <param name="append">true if append instead of override; otherwise, false.</param> /// <param name="encoding">The optional encoding.</param> /// <returns>The count of query item added.</returns> /// <exception cref="FormatException">The format is not correct.</exception> public int ParseSet(string query, bool append = false, Encoding encoding = null) { if (!append) { Clear(); } if (string.IsNullOrWhiteSpace(query)) { return(0); } var queryTrim = query.TrimStart(); if (queryTrim.IndexOf('{') == 0) { queryTrim = queryTrim.Substring(1).Trim(); var lastPos = queryTrim.LastIndexOf('}'); if (lastPos >= 0) { queryTrim = queryTrim.Substring(0, lastPos); } var count = 0; string name = null; StringBuilder sb = null; var level = new List <char>(); StringBuilder backSlash = null; bool ignoreRest = false; bool lastBackSlash = false; foreach (var c in queryTrim) { if (ignoreRest) { switch (c) { case '\r': case '\n': ignoreRest = false; break; } lastBackSlash = false; continue; } if (c == '\\') { if (lastBackSlash) { sb.Append(c); } else { backSlash = new StringBuilder(); } lastBackSlash = !lastBackSlash; continue; } lastBackSlash = false; if (backSlash != null) { if (StringExtensions.ReplaceBackSlash(sb, backSlash, c)) { backSlash = null; } continue; } if (sb == null) { if (c == '/') { ignoreRest = true; continue; } if (c == '"') { sb = new StringBuilder(); level.Add('"'); continue; } if (name == null) { if (NameChars.IndexOf(c) > -1) { sb = new StringBuilder(); level.Add(':'); sb.Append(c); } continue; } if (c == '{') { level.Add('}'); } else if (c == '[') { level.Add(']'); } else if (NumBoolChars.IndexOf(c) > -1) { level.Add(','); } else { continue; } sb = new StringBuilder(); sb.Append(c); continue; } if (level.Count == 0) { continue; } var lastLevelChar = level[level.Count - 1]; if (c == lastLevelChar) { level.RemoveAt(level.Count - 1); if (name == null) { name = sb.ToString(); sb = null; continue; } else if (level.Count == 0) { if (c == ',') { var sbStr = sb.ToString().Trim(); sb = new StringBuilder(sbStr); if (sbStr == "null" || sbStr == "undefined") { name = null; sb = null; continue; } } else if (c == '"') { } else { sb.Append(c); } ListExtensions.Add(this, name, sb.ToString()); name = null; sb = null; continue; } } else if (lastLevelChar == ':' && name == null) { if (c == '\r' || c == '\n' || c == '\t' || c == ' ' || c == ',' || c == '+') { sb = null; } else if (c == '/') { sb = null; ignoreRest = true; } else if (NameChars.IndexOf(c) < 0) { throw new FormatException("The format of query string is not correct."); } if (sb == null) { level.RemoveAt(level.Count - 1); continue; } } else if (c == '"') { level.Add('"'); } else if (lastLevelChar != '"') { if (c == '{') { level.Add('}'); } else if (c == '[') { level.Add(']'); } } if (sb == null) { sb = new StringBuilder(); } sb.Append(c); } if (!string.IsNullOrWhiteSpace(name) && sb != null) { var sbStr = sb.ToString().Trim(); if (sbStr != "null" && sbStr != "undefined") { ListExtensions.Add(this, name, sbStr); } } return(count); } if (encoding == null) { encoding = DefaultEncoding ?? Encoding.UTF8; } var pos = query.IndexOf("?"); if (pos >= 0) { query = query.Substring(pos + 1); } pos = query.IndexOf("#"); if (pos >= 0) { query = query.Substring(0, pos); } var arr = query.Split('&', '\r', '\n'); foreach (var item in arr) { pos = item.IndexOf("="); if (pos < 0) { if (item.Length == 0) { continue; } ListExtensions.Add(this, WebFormat.UrlDecode(item, encoding), string.Empty); } else { var key = item.Substring(0, pos); var value = item.Substring(pos + 1); if (key.Length == 0 && value.Length == 0) { continue; } ListExtensions.Add(this, WebFormat.UrlDecode(key, encoding), WebFormat.UrlDecode(value, encoding)); } } return(arr.Length); }
/// <summary> /// Encodes the value. /// </summary> /// <param name="value">The value.</param> /// <returns>The value encoded.</returns> protected virtual string EncodeValue(string value) { return(WebFormat.UrlEncode(value)); }
/// <summary> /// Encodes the key. /// </summary> /// <param name="key">The key.</param> /// <returns>The key encoded.</returns> protected virtual string EncodeKey(string key) { return(WebFormat.UrlEncode(key)); }