public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var pair = (SwaggerOperationsExtended)value; writer.WriteStartObject(); var count = pair.Keys.Count; for (var i = 0; i < count; i++) { var key = pair.Keys.ElementAt(i); var oVal = pair.Values.ElementAt(i); writer.WritePropertyName(key.ToString().ToLower()); var tokenReader = new JTokenReader(JToken.FromObject(oVal)); writer.WriteToken(tokenReader); } writer.WriteEndObject(); }
public override object ReadJson (Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var store = (PropertyStore)existingValue; var items = JToken.ReadFrom (reader); foreach (var item in items) { var typeName = (string)item["$type"]; if (typeName != null) { var type = ((EtoBinder)serializer.Binder).BindToType (typeName); if (type != null) { foreach (var prop in (IDictionary<string, JToken>)item) { if (prop.Key == "$type") continue; var memberName = "Set" + prop.Key; var member = type.GetRuntimeMethods().FirstOrDefault(r => r.IsStatic && r.Name == memberName); if (member == null) throw new JsonSerializationException(string.Format(CultureInfo.CurrentCulture, "Could not find attachable property {0}.{1}", type.Name, memberName)); var parameters = member.GetParameters(); if (parameters.Length != 2) throw new JsonSerializationException(string.Format(CultureInfo.CurrentCulture, "Invalid number of parameters")); var propType = parameters[1].ParameterType; using (var propReader = new JTokenReader(prop.Value)) { var propValue = serializer.Deserialize(propReader, propType); member.Invoke (null, new object[] { store.Parent, propValue }); } } } } } return existingValue; }
public override object ReadJson (Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var store = existingValue as PropertyStore; var items = JArray.ReadFrom (reader); foreach (var item in (IEnumerable<JToken>)items) { var typeName = (string)item["$type"]; if (typeName != null) { var type = ((EtoBinder)serializer.Binder).BindToType (typeName); if (type != null) { foreach (var prop in (IDictionary<string, JToken>)item) { if (prop.Key == "$type") continue; var memberName = "Set" + prop.Key; var member = type.GetMethod(memberName, BindingFlags.Static | BindingFlags.Public); if (member == null) throw new JsonSerializationException(string.Format ("Could not find attachable property {0}.{1}", type.Name, memberName)); var parameters = member.GetParameters(); if (parameters.Length != 2) throw new JsonSerializationException("Invalid number of parameters"); var propType = parameters[1].ParameterType; using (var propReader = new JTokenReader(prop.Value)) { var propValue = serializer.Deserialize(propReader, propType); member.Invoke (null, new object[] { store.Parent, propValue }); } } } } } return existingValue; }
public static object ToObject(this JToken token, Type targetType, JsonSerializerSettings settings) { var jsonSerializer = JsonSerializer.Create(settings); using (var jtokenReader = new JTokenReader(token)) { return jsonSerializer.Deserialize(jtokenReader, targetType); } }
public object ConvertTo(Type type) { // A non generic implementation of ToObject<T> on JToken using (var jsonReader = new JTokenReader(_value)) { var serializer = new JsonSerializer(); return serializer.Deserialize(jsonReader, type); } }
public Task<IEnumerable<User>> SearchUser(string username) { return this.GetDynamicAsync(string.Format("/search/users?q={0}", username)).ContinueWith(t => { var serializer = JsonSerializer.Create(new JsonSerializerSettings()); var users = ((JObject)t.Result)["items"]; var reader = new JTokenReader(users); return serializer.Deserialize<IEnumerable<User>>(reader); }); }
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var result = new Document(); JObject bag = serializer.Deserialize<JObject>(reader); foreach (JProperty field in bag.Properties()) { // Skip OData @search annotations. These are deserialized separately. if (field.Name.StartsWith("@search.", StringComparison.Ordinal)) { continue; } object value; if (field.Value == null) { value = null; } else if (field.Value is JArray) { JArray array = (JArray)field.Value; if (array.Count == 0) { // Assume string arrays for now. value = EmptyStringArray; } else { value = array.Select(t => t.Value<string>()).ToArray(); } } else if (field.Value is JObject) { var tokenReader = new JTokenReader(field.Value); // Assume GeoPoint for now. value = serializer.Deserialize<GeographyPoint>(tokenReader); } else { value = field.Value.ToObject(typeof(object), serializer); } result[field.Name] = value; } return result; }
/// <summary> /// Resolves a parameter value based on the provided object. /// </summary> /// <param name="descriptor">Parameter descriptor.</param> /// <param name="value">Value to resolve the parameter value from.</param> /// <returns>The parameter value.</returns> public virtual object ResolveParameter(ParameterDescriptor descriptor, JToken value) { if (value.GetType() == descriptor.Type) { return value; } // A non generic implementation of ToObject<T> on JToken using (var jsonReader = new JTokenReader(value)) { var serializer = new JsonSerializer(); return serializer.Deserialize(jsonReader, descriptor.Type); } }
public IList<object> Deserialize(object json) { JArray data; if (json is string) { data = JArray.Parse((string)json); } else if (json is JArray) data = (JArray)json; else throw new DextopException(); var result = new List<object>(); foreach (var o in data) using (var reader = new JTokenReader(o)) result.Add(DextopUtil.JsonSerializer.Deserialize(reader, Meta.ModelType)); return result; }
/// <summary> /// Extrae un personaje de la fuente de datos en JSON. /// </summary> /// <param name="name"> /// El nombre del pesonaje a extraer de la fuente de datos. /// </param> /// <returns> /// Un objeto Character cuyo nombre coincide con el solicitado. /// </returns> /// <pre>true</pre> /// <post>(this.Contains(name) => (returnValue != null) && (returnValue.Name.Equals(name)))</post> public FullCharacter GetCharacterFromSource(string name) { FullCharacter character = null; // Obtenemos un lector de tokens de Json. Para ello creamos primero un stream de la // cadena json, luego creamos un lector de texto usando ese stream y por último creamos // un lector de tokens utilizando el lector de texto y lo inicializamos JsonReader reader = new JsonTextReader(new StringReader(jsonString)); JTokenReader tokenreader = new JTokenReader(JToken.ReadFrom(reader)); tokenreader.Read(); // Obtenemos el token cuyo nombre corresponde al deseado, utilizando para ello una // expresión JSonPath // Para más información sobre JPath: http://goessner.net/articles/JsonPath/ JToken token = tokenreader.CurrentToken.SelectToken("$.[?(@.name=='" + name + "')]", false); // Si existe un token con dihco nombre, existe el personaje buscado if (token != null) { // Creamos un nuevo objeto de tipo Character e incrementamos el correspondiente // contador character = new FullCharacter(); createdCharacters++; // Extraemos el valor de la Propiedad Nombre del correspondiente token character.Name = token.SelectToken("name").Value<String>(); // Extraemos el valor de la Propiedad Nombre del correspondiente token character.Description = token.SelectToken("description").Value<String>(); IEnumerable<JToken> relatedCharactersTokens = token.SelectToken("related_characters").Values<JToken>(); // Construimos la colección de personajes relacionados con la colección de tokens JSON FillRelatedCharacters(character, relatedCharactersTokens); } // if // Cerramos los lectores que estén abiertos tokenreader.Close(); reader.Close(); return character; }
public void ReadBytesFailure() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject o = new JObject( new JProperty("Test1", 1) ); using (JTokenReader jsonReader = new JTokenReader(o)) { jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); jsonReader.ReadAsBytes(); } }, "Error reading bytes. Unexpected token: Integer. Path 'Test1'."); }
public DataTable ToDataTable(JToken token) { if (!(token is JArray)) { JArray container = new JArray(); container.Add(token); token = container; } JTokenReader reader = new JTokenReader(token); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new DataTableConverter()); DataTable dataTable = serializer.Deserialize<DataTable>(reader); if (!dataTable.Columns.Contains("crmid")) { dataTable.Columns.Add("crmid", typeof(int)); foreach (DataRow row in dataTable.Rows) { row["crmid"] = ToCrmId(row["id"].ToString()); } dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["crmid"] }; } return dataTable; }
public void ReadBytes() { byte[] data = Encoding.UTF8.GetBytes("Hello world!"); JObject o = new JObject( new JProperty("Test1", data) ); using (JTokenReader jsonReader = new JTokenReader(o)) { jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); byte[] readBytes = jsonReader.ReadAsBytes(); Assert.AreEqual(data, readBytes); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } }
public void Should_be_able_to_suck_out_an_object() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { var message = (TestMessage)_serializer.Deserialize(jsonReader, typeof(TestMessage)); message.Name.ShouldBe("Joe"); message.Details.Count.ShouldBe(2); } }
public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); }
public void ReadBytesFromString() { var bytes = new HasBytes { Bytes = new byte[] { 1, 2, 3, 4 } }; var json = JsonConvert.SerializeObject(bytes); TextReader textReader = new StringReader(json); JsonReader jsonReader = new JsonTextReader(textReader); var jToken = JToken.ReadFrom(jsonReader); jsonReader = new JTokenReader(jToken); var result2 = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); Assert.AreEqual(new byte[] { 1, 2, 3, 4 }, result2.Bytes); }
public void ReadBytesFromEmptyString() { var bytes = new HasBytes { Bytes = new byte[0] }; var json = JsonConvert.SerializeObject(bytes); TextReader textReader = new StringReader(json); JsonReader jsonReader = new JsonTextReader(textReader); var jToken = JToken.ReadFrom(jsonReader); jsonReader = new JTokenReader(jToken); var result2 = (HasBytes)JsonSerializer.Create(null) .Deserialize(jsonReader, typeof(HasBytes)); CollectionAssert.AreEquivalent(new byte[0], result2.Bytes); }
public void YahooFinance() { JObject o = new JObject( new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))), new JProperty("Test3", "Test3Value"), new JProperty("Test4", null) ); using (JTokenReader jsonReader = new JTokenReader(o)) { IJsonLineInfo lineInfo = jsonReader; jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); Assert.AreEqual(false, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); Assert.AreEqual(false, lineInfo.HasLineInfo()); jsonReader.Read(); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), jsonReader.Value); Assert.AreEqual(false, lineInfo.HasLineInfo()); Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(0, lineInfo.LineNumber); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test2", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test3", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.String, jsonReader.TokenType); Assert.AreEqual("Test3Value", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test4", jsonReader.Value); jsonReader.Read(); Assert.AreEqual(JsonToken.Null, jsonReader.TokenType); Assert.AreEqual(null, jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } using (JsonReader jsonReader = new JTokenReader(o.Property("Test2"))) { Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test2", jsonReader.Value); Assert.IsTrue(jsonReader.Read()); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); Assert.IsFalse(jsonReader.Read()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } }
public void InitialPath_ArrayBase_PropertyToken() { JObject o = new JObject { { "prop1", true } }; JTokenReader reader = new JTokenReader(o, "[0]"); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0].prop1", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0].prop1", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0]", reader.Path); Assert.IsFalse(reader.Read()); Assert.AreEqual("[0]", reader.Path); }
public RegistrationBaseUrlRewritingJsonReader(JTokenReader innerReader, List<KeyValuePair<string, string>> replacements) : base(innerReader, RegistrationPathsToIntercept) { _replacements = replacements; }
public void InitialPath_ArrayBase_ArrayToken() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a, "[0]"); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0][0]", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0][1]", reader.Path); Assert.IsTrue(reader.Read()); Assert.AreEqual("[0]", reader.Path); Assert.IsFalse(reader.Read()); Assert.AreEqual("[0]", reader.Path); }
/// <summary> /// Gas gauge chart. /// </summary> /// <param name="query">The query.</param> /// <param name="_options">GraphOptions.</param> /// <param name="binaryOutput">if set to <c>true</c> the image will output in the response stream.</param> /// <returns></returns> public static System.Drawing.Bitmap GasGauge( string query, Dictionary<string, object> _options, bool binaryOutput ) { ( "FUNCTION /w binaryStream gasGauge" ).Debug( 10 ); JToken jtOpt = JToken.FromObject( _options ); JsonSerializer serializer = new JsonSerializer(); GraphOptions options = null; using( JTokenReader jtr = new JTokenReader( jtOpt ) ) { options = ( GraphOptions )serializer.Deserialize( jtr, typeof( GraphOptions ) ); } GraphPane myPane = new GraphPane( new System.Drawing.Rectangle( 0, 0, options.Width, options.Height ), options.Title, "", "" ); myPane.Title.Text = options.Title; // Define the title myPane.Title.Text = "Gas Gauge Demo"; // Fill the pane with gray myPane.Fill = new Fill( System.Drawing.Color.LightGray, System.Drawing.Color.White, 45.0f ); // Fill the chart rect with blue myPane.Chart.Fill = new Fill( System.Drawing.Color.White, System.Drawing.Color.SkyBlue, 45.0f ); // Don't show any axes for the gas gauge myPane.XAxis.IsVisible = false; myPane.Y2Axis.IsVisible = false; myPane.YAxis.IsVisible = false; //Define needles; can add more than one GasGaugeNeedle gg1 = new GasGaugeNeedle( "Cereal", 30.0f, System.Drawing.Color.Black ); GasGaugeNeedle gg2 = new GasGaugeNeedle( "Milk", 80.0f, System.Drawing.Color.DarkGreen ); myPane.CurveList.Add( gg1 ); myPane.CurveList.Add( gg2 ); //Define all regions GasGaugeRegion ggr1 = new GasGaugeRegion( "Red", 0.0f, 33.0f, System.Drawing.Color.Red ); GasGaugeRegion ggr2 = new GasGaugeRegion( "Yellow", 33.0f, 66.0f, System.Drawing.Color.Yellow ); GasGaugeRegion ggr3 = new GasGaugeRegion( "Green", 66.0f, 100.0f, System.Drawing.Color.Green ); // Add the curves myPane.CurveList.Add( ggr1 ); myPane.CurveList.Add( ggr2 ); myPane.CurveList.Add( ggr3 ); System.Drawing.Bitmap image = myPane.GetImage( true ); if( binaryOutput ) { using( MemoryStream ms = new MemoryStream() ) { image.Save( ms, System.Drawing.Imaging.ImageFormat.Png ); if(HttpContext.Current!=null){ HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/png"; HttpContext.Current.Response.AddHeader( "Expires", "0" );/* RFC 2616 14.21 Content has already expired */ HttpContext.Current.Response.AddHeader( "Cache-Control", "no-store" );/* RFC 2616 14.9.2 Don't ever cache */ HttpContext.Current.Response.AddHeader( "Pragma", "no-store" );/* RFC 2616 14.32 Pragma - same as cache control */ ms.WriteTo( HttpContext.Current.Response.OutputStream ); } } image.Dispose(); } return image; }
private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) { id = null; newValue = null; if (reader.TokenType == JsonToken.StartObject) { JObject current = (JObject)reader.CurrentToken; JToken refToken = current[JsonTypeReflector.RefPropertyName]; if (refToken != null) { if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null) throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); JToken property = refToken.Parent; JToken additionalContent = null; if (property.Next != null) additionalContent = property.Next; else if (property.Previous != null) additionalContent = property.Previous; string reference = (string)refToken; if (reference != null) { if (additionalContent != null) throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); newValue = Serializer.GetReferenceResolver().ResolveReference(this, reference); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); reader.Skip(); return true; } } JToken typeToken = current[JsonTypeReflector.TypePropertyName]; if (typeToken != null) { string qualifiedTypeName = (string)typeToken; JsonReader typeTokenReader = typeToken.CreateReader(); CheckedRead(typeTokenReader); ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); JToken valueToken = current[JsonTypeReflector.ValuePropertyName]; if (valueToken != null) { while (true) { CheckedRead(reader); if (reader.TokenType == JsonToken.PropertyName) { if ((string)reader.Value == JsonTypeReflector.ValuePropertyName) return false; } CheckedRead(reader); reader.Skip(); } } } JToken idToken = current[JsonTypeReflector.IdPropertyName]; if (idToken != null) { id = (string)idToken; } JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; if (valuesToken != null) { JsonReader listReader = valuesToken.CreateReader(); CheckedRead(listReader); newValue = CreateList(listReader, objectType, contract, member, existingValue, id); reader.Skip(); return true; } } CheckedRead(reader); return false; }
/// <summary> /// Bar chart. /// </summary> /// <param name="query">The query.</param> /// <param name="_options">GraphOptions.</param> /// <param name="binaryOutput">if set to <c>true</c> the image will output in the response stream.</param> /// <returns></returns> public static System.Drawing.Bitmap BarChart( string query, Dictionary<string, object> _options, bool binaryOutput ) { ( "FUNCTION /w binaryStream barChart" ).Debug( 10 ); /* * 0 = name * 1 = value * 2 = color1 * 3 = color2 * 4 = angle */ GraphOptions options = null; JToken jtOpt = JToken.FromObject( _options ); using( JTokenReader tr = new JTokenReader( jtOpt ) ) { JsonSerializer serializer = new JsonSerializer(); options = ( GraphOptions )serializer.Deserialize( tr, typeof( GraphOptions ) ); } System.Drawing.Bitmap image = null; GraphPane myPane = null; using(SqlConnection cn = Site.CreateConnection(true, true)) { cn.Open(); try { using(SqlCommand cmd = new SqlCommand(query, cn)) { myPane = new GraphPane(new System.Drawing.Rectangle(0, 0, options.Width, options.Height), options.Title, "", ""); myPane.Title.Text = options.Title; myPane.XAxis.Title.Text = options.XAxisTitle; myPane.YAxis.Title.Text = options.YAxisTitle; if(options.Orientation) { myPane.YAxis.Type = AxisType.Ordinal; } else { myPane.XAxis.Type = AxisType.Ordinal; } float barLocation = 0; using(SqlDataReader r = cmd.ExecuteReader()) { if(r.HasRows) { while(r.Read()) { PointPairList list = new PointPairList(); if(options.Orientation) { list.Add(Convert.ToDouble(r.GetValue(1)), barLocation); BarItem myCurve = myPane.AddBar(r.GetString(0), list, System.Drawing.Color.FromName(r.GetString(2))); myCurve.Bar.Fill = new Fill( System.Drawing.Color.FromName(r.GetString(2)), System.Drawing.Color.FromName(r.GetString(3)), System.Drawing.Color.FromName(r.GetString(2)), (float)r.GetInt32(4) ); } else { list.Add(barLocation, Convert.ToDouble(r.GetValue(1))); BarItem myCurve = myPane.AddBar(r.GetString(0), list, System.Drawing.Color.FromName(r.GetString(2))); myCurve.Bar.Fill = new Fill( System.Drawing.Color.FromName(r.GetString(2)), System.Drawing.Color.FromName(r.GetString(3)), (float)r.GetInt32(4) ); } barLocation += options.BarSpacing; } }else{ if(image == null) { image = new Bitmap(700, 700); } image = WriteImageError(image, options.NoDataMessage, options.FontFamily, options.XAxisFontSize); return image; } } if(options.Orientation) { myPane.YAxis.IsVisible = false; //myPane.YAxis.Scale.Max=barLocation; myPane.YAxis.Scale.Min = 0; myPane.BarSettings.Base = BarBase.Y; } else { myPane.XAxis.IsVisible = false; myPane.XAxis.Scale.Min = 0; //myPane.XAxis.Scale.Max=barLocation-options.barSpacing; myPane.BarSettings.Base = BarBase.X; } // Fill the chart background with a color gradient myPane.Chart.Fill = new Fill( System.Drawing.Color.FromName(options.Fill.StartColor), System.Drawing.Color.FromName(options.Fill.EndColor), options.Fill.Angle); myPane.AxisChange(); // Create TextObj's to provide labels for each bar BarItem.CreateBarLabels(myPane, false, "f0"); image = myPane.GetImage(true); using(MemoryStream ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); if(HttpContext.Current != null) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "image/png"; HttpContext.Current.Response.AddHeader("Expires", "0");/* RFC 2616 14.21 Content has already expired */ HttpContext.Current.Response.AddHeader("Cache-Control", "no-store");/* RFC 2616 14.9.2 Don't ever cache */ HttpContext.Current.Response.AddHeader("Pragma", "no-store");/* RFC 2616 14.32 Pragma - same as cache control */ ms.WriteTo(HttpContext.Current.Response.OutputStream); } } } } catch(Exception ex) { if(image == null) { image = new Bitmap(700, 700); } image = WriteImageError(image, ex.Message, "Arial", 8f); } } return image; }
public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); }
public void ReadBytesFailure() { JObject o = new JObject( new JProperty("Test1", 1) ); using (JTokenReader jsonReader = new JTokenReader(o)) { jsonReader.Read(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); jsonReader.Read(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); jsonReader.ReadAsBytes(); } }
public void Should_be_able_to_suck_out_an_interface() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { Type proxyType = TypeCache.GetImplementationType(typeof(MessageA)); var message = (MessageA)Activator.CreateInstance(proxyType); _serializer.Populate(jsonReader, message); message.Name.ShouldBe("Joe"); } }
/// <summary> /// Barcodes from http://www.codeproject.com/KB/graphics/BarcodeLibrary.aspx by Brad Barnhill /// License: http://www.codeproject.com/info/cpol10.aspx GPL (*CPOL) /// </summary> /// <param name="barType">Type of the bar.</param> /// <param name="barValue">The bar value.</param> /// <param name="barOptions">The bar options.</param> /// <returns> /// Bitmap image /// </returns> public static System.Drawing.Bitmap BarCode( string barType, string barValue, Dictionary<string, object> barOptions ) { ( "FUNCTION /w binaryStream barCode" ).Debug( 10 ); JToken jtOpt = JToken.FromObject( barOptions ); JsonSerializer serializer = new JsonSerializer(); BarOptions options = null; using( JTokenReader jtr = new JTokenReader( jtOpt ) ) { options = ( BarOptions )serializer.Deserialize( jtr, typeof( BarOptions ) ); } BarcodeLib.TYPE type = BarcodeLib.TYPE.UPCA; switch( barType.ToString().Trim().ToUpper() ) { case "UPC-A": type = BarcodeLib.TYPE.UPCA; break; case "UPC-E": type = BarcodeLib.TYPE.UPCE; break; case "UPC 2 DIGIT EXT.": type = BarcodeLib.TYPE.UPC_SUPPLEMENTAL_2DIGIT; break; case "UPC 5 DIGIT EXT.": type = BarcodeLib.TYPE.UPC_SUPPLEMENTAL_5DIGIT; break; case "EAN-13": type = BarcodeLib.TYPE.EAN13; break; case "JAN-13": type = BarcodeLib.TYPE.JAN13; break; case "EAN-8": type = BarcodeLib.TYPE.EAN8; break; case "ITF-14": type = BarcodeLib.TYPE.ITF14; break; case "CODABAR": type = BarcodeLib.TYPE.Codabar; break; case "POSTNET": type = BarcodeLib.TYPE.PostNet; break; case "BOOKLAND/ISBN": type = BarcodeLib.TYPE.BOOKLAND; break; case "CODE 11": type = BarcodeLib.TYPE.CODE11; break; case "CODE 39": type = BarcodeLib.TYPE.CODE39; break; case "CODE 39 Extended": type = BarcodeLib.TYPE.CODE39Extended; break; case "CODE 93": type = BarcodeLib.TYPE.CODE93; break; case "LOGMARS": type = BarcodeLib.TYPE.LOGMARS; break; case "MSI": type = BarcodeLib.TYPE.MSI_Mod10; break; case "INTERLEAVED 2 OF 5": type = BarcodeLib.TYPE.Interleaved2of5; break; case "STANDARD 2 OF 5": type = BarcodeLib.TYPE.Standard2of5; break; case "CODE 128": type = BarcodeLib.TYPE.CODE128; break; case "CODE 128-A": type = BarcodeLib.TYPE.CODE128A; break; case "CODE 128-B": type = BarcodeLib.TYPE.CODE128B; break; case "CODE 128-C": type = BarcodeLib.TYPE.CODE128C; break; case "TELEPEN": type = BarcodeLib.TYPE.TELEPEN; break; } AlignmentPositions align = AlignmentPositions.CENTER; switch( options.Alignment.Trim().ToUpper() ) { case "CENTER": align = AlignmentPositions.CENTER; break; case "LEFT": align = AlignmentPositions.LEFT; break; case "RIGHT": align = AlignmentPositions.RIGHT; break; } System.Drawing.Bitmap oBmp = null; using( System.Drawing.Font font = new System.Drawing.Font( options.FontFamily, options.FontSize ) ) { using( BarcodeLib.Barcode bar = new BarcodeLib.Barcode() ) { using( MemoryStream stream = new MemoryStream() ) { System.Drawing.Color foreground = System.Drawing.Color.FromName( options.Foreground ); System.Drawing.Color background = System.Drawing.Color.FromName( options.Background ); bar.Height = options.Height; bar.Width = options.Width; bar.IncludeLabel = options.IncludeLabel; bar.LabelFont = font; bar.Alignment = align; System.Drawing.Image img = bar.Encode( type, barValue, foreground, background, options.Width, options.Height ); img.Save( stream, System.Drawing.Imaging.ImageFormat.Png ); oBmp = new System.Drawing.Bitmap( stream ); } } } return oBmp; }
void DoDeserialize() { Envelope result; using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(_body), false)) using (var reader = new StreamReader(memoryStream)) using (var jsonReader = new JsonTextReader(reader)) { result = _deserializer.Deserialize<Envelope>(jsonReader); } using (var jsonReader = new JTokenReader(result.Message as JToken)) { var message = (MessageA)Activator.CreateInstance(_proxyType); _serializer.Populate(jsonReader, message); } }
public void ReadLineInfo() { string input = @"{ CPU: 'Intel', Drives: [ 'DVD read/writer', ""500 gigabyte hard drive"" ] }"; JObject o = JObject.Parse(input); using (JTokenReader jsonReader = new JTokenReader(o)) { IJsonLineInfo lineInfo = jsonReader; Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(0, lineInfo.LineNumber); Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(false, lineInfo.HasLineInfo()); Assert.AreEqual(null, jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o, jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "CPU"); Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(7, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("CPU"), jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "Intel"); Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(15, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("CPU").Value, jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "Drives"); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(10, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("Drives"), jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(12, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("Drives").Value, jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "DVD read/writer"); Assert.AreEqual(4, lineInfo.LineNumber); Assert.AreEqual(22, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o["Drives"][0], jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive"); Assert.AreEqual(5, lineInfo.LineNumber); Assert.AreEqual(30, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o["Drives"][1], jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(12, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o["Drives"], jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o, jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(null, jsonReader.CurrentToken); jsonReader.Read(); Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(null, jsonReader.CurrentToken); } }