public static IExpressionConstant Transform(JValue obj) { // TODO: make this do something //var val = obj.Value; if (obj.Type.Equals(JTokenType.Integer)) { return NumericValue.Create(obj.ToObject<int>()); } else if (obj.Type.Equals(JTokenType.Float)) { return NumericValue.Create(obj.ToObject<decimal>()); } else if (obj.Type.Equals(JTokenType.String)) { return new StringValue(obj.ToObject<String>()); } else if (obj.Type.Equals(JTokenType.Boolean)) { return new BooleanValue(obj.ToObject<bool>()); } else if (obj.Type.Equals(JTokenType.Null)) { //throw new ApplicationException("NULL Not implemented yet"); return null; // TODO: Change this to an option } else { throw new Exception("Don't know how to transform a " +obj.GetType()+ "."); } }
public static JToken ConvertPesudoTypes(JToken data, FormatOptions fmt) { var reqlTypes = data.SelectTokens("$..$reql_type$").ToList(); foreach ( var typeToken in reqlTypes ) { var reqlType = typeToken.Value<string>(); //JObject -> JProerty -> JVaule:$reql_type$, go backup the chain. var pesudoObject = typeToken.Parent.Parent as JObject; JToken convertedValue = null; if( reqlType == Time ) { if( fmt.RawTime ) continue; convertedValue = new JValue(GetTime(pesudoObject)); } else if( reqlType == GroupedData ) { if( fmt.RawGroups ) continue; convertedValue = new JValue(GetGrouped(pesudoObject)); } else if( reqlType == Binary ) { if( fmt.RawBinary ) continue; convertedValue = new JArray(GetBinary(pesudoObject)); } pesudoObject.Replace(convertedValue); } return data; }
/// <summary> /// Processes the specified context. /// </summary> /// <param name="context">The context to process.</param> public override void Process(FormBuilderContext context) { if (context.Property.GetCustomAttribute<FormDisplayAttribute>() != null) { FormDisplayAttribute formDisplayAttribute = context.Property.GetCustomAttribute<FormDisplayAttribute>(); // Build a new hierarchy object for the element JObject hierachyObject = new JObject(); JArray hierarcyItems = new JArray(); hierachyObject["type"] = new JValue("section"); hierachyObject["items"] = hierarcyItems; if (context.CurrentFormElement != null) { // Move the current element into the form hierarcy hierarcyItems.Add(context.CurrentFormElement); context.CurrentFormElementParent.Remove(context.CurrentFormElement); context.CurrentFormElementParent.Add(hierachyObject); } // Set the new parent element to the current hierarchy context.CurrentFormElementParent = hierarcyItems; string cssClasses = ConvertDisplayWidthToCssClass(formDisplayAttribute.DisplayWidth); if (!string.IsNullOrEmpty(cssClasses)) { hierachyObject["htmlClass"] = new JValue(cssClasses); } } }
public void FromObjectTimeSpan() { var token1 = new JValue(TimeSpan.FromDays(1)); var token2 = JToken.FromObject(token1); Assert.IsTrue(JToken.DeepEquals(token1, token2)); Assert.AreEqual(token1.Type, token2.Type); }
public void FromObjectUri() { var token1 = new JValue(new Uri("http://www.newtonsoft.com")); var token2 = JToken.FromObject(token1); Assert.IsTrue(JToken.DeepEquals(token1, token2)); Assert.AreEqual(token1.Type, token2.Type); }
public object ToJsonObject() { var content = new JObject(new JProperty(NAME, new JObject())); if (_boost == null && _minSimilarity == null && _prefixLength == null) { content[NAME][_name] = new JValue(_value); } else { content[NAME][_name] = new JObject(); content[NAME][_name]["value"] = new JValue(_value); if (_boost != null) { content[NAME][_name]["boost"] = _boost; } if (_minSimilarity != null) { content[NAME][_name]["min_similarity"] = _minSimilarity; } if (_prefixLength != null) { content[NAME][_name]["prefix_length"] = _prefixLength; } } return content; }
/// <summary> /// Processes the specified context. /// </summary> /// <param name="context">The context to process.</param> public override void Process(FormBuilderContext context) { FormArrayAttribute arrayAttribute = context.Property.GetCustomAttribute<FormArrayAttribute>(); // Test to the form subobject attribute if (arrayAttribute != null) { if (context.Property.PropertyType.GetInterfaces() .Where(i => i.GetTypeInfo().IsGenericType) .Select(i => i.GetGenericTypeDefinition()).Any(i => i == typeof (IEnumerable<>))) { // Get the subtype from a generic type argument Type subType = context.Property.PropertyType.GetGenericArguments()[0]; // Create the subform JContainer properties = context.FormBuilder.BuildForm(subType, context.OriginDtoType, context.TargetCulture, context.FullPropertyPath + "[]"); // Merge the properties of the sub object into the current context JObject currentFormElement = context.GetOrCreateCurrentFormElement(); currentFormElement["key"] = context.FullPropertyPath; currentFormElement["items"] = properties; if (!string.IsNullOrEmpty(arrayAttribute.AddButtonTitle)) { string addText = GetTextForKey(arrayAttribute.AddButtonTitle, context); currentFormElement["add"] = new JValue(addText); } } else { throw new InvalidOperationException("An FormArrayAttribute must always be on a property with a type derived from IEnumerable<>"); } } }
public object ToJsonObject() { var content = new JObject(); content[_fieldName] = new JObject(); if (_order != SortOrder.ASC) { content[_fieldName]["order"] = "desc"; } if (_missing != null) { content[_fieldName]["missing"] = new JValue(_missing); } if (_ignoreUnampped != null) { content[_fieldName]["ignore_unmapped"] = _ignoreUnampped; } if (_nestedFilter != null) { content[_fieldName]["nested_filter"] = _nestedFilter.ToJsonObject() as JObject; } return content; }
public void Example() { #region Usage JValue s1 = new JValue("A string"); JValue s2 = new JValue("A string"); JValue s3 = new JValue("A STRING"); Console.WriteLine(JToken.DeepEquals(s1, s2)); // true Console.WriteLine(JToken.DeepEquals(s2, s3)); // false JObject o1 = new JObject { { "Integer", 12345 }, { "String", "A string" }, { "Items", new JArray(1, 2) } }; JObject o2 = new JObject { { "Integer", 12345 }, { "String", "A string" }, { "Items", new JArray(1, 2) } }; Console.WriteLine(JToken.DeepEquals(o1, o2)); // true Console.WriteLine(JToken.DeepEquals(s1, o1["String"])); // true #endregion }
public void ChangeValue() { JValue v = new JValue(true); Assert.AreEqual(true, v.Value); Assert.AreEqual(JTokenType.Boolean, v.Type); v.Value = "Pie"; Assert.AreEqual("Pie", v.Value); Assert.AreEqual(JTokenType.String, v.Type); v.Value = null; Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); v.Value = (int?)null; Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); v.Value = "Pie"; Assert.AreEqual("Pie", v.Value); Assert.AreEqual(JTokenType.String, v.Type); v.Value = DBNull.Value; Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); byte[] data = new byte[0]; v.Value = data; Assert.AreEqual(data, v.Value); Assert.AreEqual(JTokenType.Bytes, v.Type); }
/// <summary> /// Processes the specified context. /// </summary> /// <param name="context">The context to process.</param> public override void Process(FormBuilderContext context) { // Get all help attributes List<FormHelpAttribute> helps = context.Property.GetCustomAttributes<FormHelpAttribute>().ToList(); // If the current property has no helps this module has nothing to to if (!helps.Any()) { return; } foreach (FormHelpAttribute help in helps) { string helpCssClases = DetermineHelpCssClasses(help.HelpType); string helpText = GetTextForKey(help.HelpText, context); // Create the help JSON object JObject helpObject = new JObject(); helpObject["type"] = new JValue("help"); helpObject["helpvalue"] = new JValue("<div class=\"" + helpCssClases + "\" >" + helpText + "</div>"); if (!string.IsNullOrEmpty(help.Condition)) { helpObject["condition"] = ConvertConditionToAbsolutePath(context.DtoType.Name, context.FullPropertyPath, help.Condition); } context.CurrentFormElementParent.Add(helpObject); } }
static int Equals(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue), typeof(Newtonsoft.Json.Linq.JValue))) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); Newtonsoft.Json.Linq.JValue arg0 = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 2); bool o = obj != null?obj.Equals(arg0) : arg0 == null; LuaDLL.lua_pushboolean(L, o); return(1); } else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue), typeof(object))) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); object arg0 = ToLua.ToVarObject(L, 2); bool o = obj != null?obj.Equals(arg0) : arg0 == null; LuaDLL.lua_pushboolean(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: Newtonsoft.Json.Linq.JValue.Equals")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public void FromObjectGuid() { var token1 = new JValue(Guid.NewGuid()); var token2 = JToken.FromObject(token1); Assert.IsTrue(JToken.DeepEquals(token1, token2)); Assert.AreEqual(token1.Type, token2.Type); }
private string LabelToTrafficLight(JValue value) { if ((double) value > 0 && (double) value < 60) return "green"; if ((double)value >= 60 && (double)value < 200) return "yellow"; if ((double)value >= 200) return "red"; return null; }
internal FirebasePriority(JValue priority) { if (priority == null || priority.Type == JTokenType.Null) { Type = PriorityType.None; return; } switch (priority.Type) { case JTokenType.None: Type = PriorityType.None; return; case JTokenType.Integer: case JTokenType.Float: Type = PriorityType.Numeric; _fp = priority.Value<float>(); return; case JTokenType.String: int value; if (int.TryParse(priority.Value<string>(), out value)) { Type = PriorityType.Numeric; _fp = value; } else { Type = PriorityType.String; _sp = priority.Value<string>(); } return; default: throw new Exception(string.Format("Unable to load priority of type: {0}", priority.Type)); } }
///// <summary> ///// Produce a string in double quotes with backslash sequences in all the right places. ///// ///// 常用的用法:String.Format("{0}.setValue({1});", ClientJavascriptID, JsHelper.Enquote(Text)) ///// 大部分情况下,可以使用 GetJsString 函数代替此函数 ///// 此函数返回的是双引号括起来的字符串,用来作为JSON属性比较合适,一般用在OnAjaxPreRender ///// 但是作为HTML属性时,由于HTML属性本身就是双引号括起来的,就容易引起冲突 ///// ///// </summary> ///// <param name="s">A String</param> ///// <returns>A String correctly formatted for insertion in a JSON message.</returns> /// <summary> /// 返回的是双引号括起来的字符串,用来作为JSON属性比较合适 /// </summary> /// <param name="s">源字符串</param> /// <returns>双引号括起来的字符串</returns> public static string Enquote(string s) { string jsonString = new JValue(s).ToString(Formatting.None); // The browser HTML parser will see the </script> within the string and it will interpret it as the end of the script element. // http://www.xiaoxiaozi.com/2010/02/24/1708/ // http://stackoverflow.com/questions/1659749/script-tag-in-javascript-string jsonString = jsonString.Replace("</script>", @"<\/script>"); return jsonString; /* if (s == null || s.Length == 0) { return "\"\""; } char c; int i; int len = s.Length; StringBuilder sb = new StringBuilder(len + 4); string t; sb.Append('"'); for (i = 0; i < len; i += 1) { c = s[i]; if ((c == '\\') || (c == '"') || (c == '>')) { sb.Append('\\'); sb.Append(c); } else if (c == '\b') sb.Append("\\b"); else if (c == '\t') sb.Append("\\t"); else if (c == '\n') sb.Append("\\n"); else if (c == '\f') sb.Append("\\f"); else if (c == '\r') sb.Append("\\r"); else { if (c < ' ') { //t = "000" + Integer.toHexString(c); string tmp = new string(c, 1); t = "000" + int.Parse(tmp, System.Globalization.NumberStyles.HexNumber); sb.Append("\\u" + t.Substring(t.Length - 4)); } else { sb.Append(c); } } } sb.Append('"'); return sb.ToString(); * */ }
public static void DeleteJObject(this SharpDBTransaction transaction, JValue idToken) { object documentId = idToken.Value; byte[] documentIdBytes = transaction.Connection.Serializer.SerializeDocumentId(documentId); transaction.Connection.DeleteInternal(documentIdBytes, transaction); }
/// <summary>Creates a <see cref="JsonValueModel"/> from a <see cref="JValue"/> and a given schema. </summary> /// <param name="value">The value. </param> /// <param name="schema">The schema. </param> /// <returns>The <see cref="JsonValueModel"/>. </returns> public static JsonValueModel FromJson(JValue value, JsonSchema4 schema) { return new JsonValueModel { Schema = schema, Value = value.Value }; }
/// <summary> /// Converts the filter to its JSON representation. /// </summary> /// <param name="codec">The codec to use for encoding values.</param> public override JObject ConvertToJson(ICodec codec) { JObject json = base.ConvertToJson(codec); json[_familyPropertyName] = new JValue(codec.Encode(_family)); json[_qualifierPropertyName] = new JValue(codec.Encode(_qualifier)); json[_latestVersionPropertyName] = new JValue(_latestVersion); return json; }
/// <summary> /// Converts the filter to its JSON representation. /// </summary> /// <param name="codec">The codec to use for encoding values.</param> public virtual JObject ConvertToJson(ICodec codec) { var json = new JObject(); json[_typePropertyName] = new JValue(GetFilterType()); return json; }
private ValidationResult ValidateOne(string path, IMetadataDefinition definition, JValue value) { if (definition.ChoiceSet.Contains(value)) { return ValidationResult.Success; } return ValidationResult.Fail(ValidationErrorCodes.WellknownMetadata.UndefinedValue, $"Bad metadata: Value {value.ToString()} is undefined for {path}.", path); }
public static void DeleteJObject(this SharpDBConnection connection, JValue idToken) { object documentId = idToken.Value; byte[] documentIdBytes = connection.Serializer.SerializeDocumentId(documentId); connection.DeleteInternal(documentIdBytes); }
public void ChangeValue() { JValue v = new JValue(true); Assert.AreEqual(true, v.Value); Assert.AreEqual(JTokenType.Boolean, v.Type); v.Value = "Pie"; Assert.AreEqual("Pie", v.Value); Assert.AreEqual(JTokenType.String, v.Type); v.Value = null; Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); v.Value = (int?) null; Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); v.Value = "Pie"; Assert.AreEqual("Pie", v.Value); Assert.AreEqual(JTokenType.String, v.Type); #if !(NETFX_CORE || PORTABLE) v.Value = DBNull.Value; Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); #endif byte[] data = new byte[0]; v.Value = data; Assert.AreEqual(data, v.Value); Assert.AreEqual(JTokenType.Bytes, v.Type); v.Value = StringComparison.OrdinalIgnoreCase; Assert.AreEqual(StringComparison.OrdinalIgnoreCase, v.Value); Assert.AreEqual(JTokenType.Integer, v.Type); v.Value = new Uri("http://json.codeplex.com/"); Assert.AreEqual(new Uri("http://json.codeplex.com/"), v.Value); Assert.AreEqual(JTokenType.Uri, v.Type); v.Value = TimeSpan.FromDays(1); Assert.AreEqual(TimeSpan.FromDays(1), v.Value); Assert.AreEqual(JTokenType.TimeSpan, v.Type); Guid g = Guid.NewGuid(); v.Value = g; Assert.AreEqual(g, v.Value); Assert.AreEqual(JTokenType.Guid, v.Type); #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE) BigInteger i = BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990"); v.Value = i; Assert.AreEqual(i, v.Value); Assert.AreEqual(JTokenType.Integer, v.Type); #endif }
public void SetValueWithInvalidIndex() { ExceptionAssert.Throws<ArgumentException>(@"Set JConstructor values with invalid key value: ""badvalue"". Argument position index expected.", () => { JConstructor c = new JConstructor(); c["badvalue"] = new JValue(3); }); }
/// <summary> /// Converts the filter to its JSON representation. /// </summary> /// <param name="codec">The codec to use for encoding values.</param> public override JObject ConvertToJson(ICodec codec) { JObject json = base.ConvertToJson(codec); json[_operationPropertyName] = new JValue(_comparisonTypes[_comparison]); json[_comparatorPropertyName] = new BinaryComparator(_value).ConvertToJson(codec); return json; }
public static JObject ListReplace(string path, int index, JValue toReplace, JValue replaceWith) { return JObject.FromObject(new { p = new[] { path, index.ToString()}, ld = toReplace, li = replaceWith }); }
static int ToString(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue))) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); string o = obj.ToString(); LuaDLL.lua_pushstring(L, o); return(1); } else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue), typeof(System.IFormatProvider))) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); System.IFormatProvider arg0 = (System.IFormatProvider)ToLua.ToObject(L, 2); string o = obj.ToString(arg0); LuaDLL.lua_pushstring(L, o); return(1); } else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue), typeof(string))) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); string o = obj.ToString(arg0); LuaDLL.lua_pushstring(L, o); return(1); } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue), typeof(string), typeof(System.IFormatProvider))) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); string arg0 = ToLua.ToString(L, 2); System.IFormatProvider arg1 = (System.IFormatProvider)ToLua.ToObject(L, 3); string o = obj.ToString(arg0, arg1); LuaDLL.lua_pushstring(L, o); return(1); } else if (TypeChecker.CheckTypes(L, 1, typeof(Newtonsoft.Json.Linq.JValue), typeof(Newtonsoft.Json.Formatting)) && TypeChecker.CheckParamsType(L, typeof(Newtonsoft.Json.JsonConverter), 3, count - 2)) { Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.ToObject(L, 1); Newtonsoft.Json.Formatting arg0 = (Newtonsoft.Json.Formatting)ToLua.ToObject(L, 2); Newtonsoft.Json.JsonConverter[] arg1 = ToLua.ToParamsObject <Newtonsoft.Json.JsonConverter>(L, 3, count - 2); string o = obj.ToString(arg0, arg1); LuaDLL.lua_pushstring(L, o); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: Newtonsoft.Json.Linq.JValue.ToString")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public string this[string attName] { get { JToken property = _object[attName]; return property == null ? string.Empty : property.Value<string>(); } set { _object[attName] = new JValue(value); } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Department department = (Department)value; JObject o = new JObject(); o["DepartmentId"] = new JValue(department.DepartmentId.ToString()); o["Name"] = new JValue(new string(department.Name.Reverse().ToArray())); o.WriteTo(writer); }
public void JValueDictionary() { Dictionary<JToken, int> dic = new Dictionary<JToken, int>(JToken.EqualityComparer); JValue v11 = new JValue(1); JValue v12 = new JValue(1); dic[v11] = 1; dic[v12] += 1; Assert.AreEqual(2, dic[v11]); }
public myJValue(JObject root, List<object> path) { _root = root; _path.AddRange(path); JToken jk = _root; foreach(var i in _path) jk = jk[i]; _value = jk as JValue; }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { string name = Enum.GetName(typeof(ProductStatus), (ProductStatus)value); if (string.IsNullOrEmpty(name)) { throw new NoNullAllowedException("Name of a value can't be null"); } JValue jv = new JValue(name.ToLower()); jv.WriteTo(writer); }
/// <summary> /// 获取Int不存在放回null /// </summary> /// <param name="jobject"></param> /// <param name="key"></param> /// <returns></returns> public static Nullable <Int32> GetInt32(this Newtonsoft.Json.Linq.JObject jobject, string key) { Newtonsoft.Json.Linq.JValue jv = jobject[key] as Newtonsoft.Json.Linq.JValue; if (jv != null && jv.Value != null) { return(jobject.Value <Int32>(key)); } else { return(null); } }
/// <summary> /// 获取Guid不存在放回null /// </summary> /// <param name="jobject"></param> /// <param name="key"></param> /// <returns></returns> public static Nullable <Guid> GetGuid(this Newtonsoft.Json.Linq.JObject jobject, string key) { Newtonsoft.Json.Linq.JValue jv = jobject[key] as Newtonsoft.Json.Linq.JValue; if (jv != null && jv.Value != null) { return(Guid.Parse(Convert.ToString(jobject[key]))); } else { return(null); } }
/// <summary> /// 获取String不存在放回null /// </summary> /// <param name="jobject"></param> /// <param name="key"></param> /// <returns></returns> public static string GetString(this Newtonsoft.Json.Linq.JObject jobject, string key) { Newtonsoft.Json.Linq.JValue jv = jobject[key] as Newtonsoft.Json.Linq.JValue; if (jv != null && jv.Value != null) { return(Convert.ToString(jobject[key])); } else { return(null); } }
/// <summary> /// 获取Decimal不存在放回null /// </summary> /// <param name="jobject"></param> /// <param name="key"></param> /// <returns></returns> public static Nullable <Decimal> GetDecimal(this Newtonsoft.Json.Linq.JObject jobject, string key) { Newtonsoft.Json.Linq.JValue jv = jobject[key] as Newtonsoft.Json.Linq.JValue; if (jv != null && jv.Value != null) { return(Convert.ToDecimal(jobject[key])); } else { return(null); } }
private void VisitPrimitive(Newtonsoft.Json.Linq.JValue data) { var key = _currentPath; if (_data.ContainsKey(key)) { throw new FormatException("duplicated key"); } _data[key] = data.ToString(CultureInfo.InvariantCulture); _entities.Add(new ConfigEntity() { Name = key, Value = _data[key] }); }
static int GetHashCode(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.CheckObject(L, 1, typeof(Newtonsoft.Json.Linq.JValue)); int o = obj.GetHashCode(); LuaDLL.lua_pushinteger(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int CreateString(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); string arg0 = ToLua.CheckString(L, 1); Newtonsoft.Json.Linq.JValue o = Newtonsoft.Json.Linq.JValue.CreateString(arg0); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int CompareTo(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.CheckObject(L, 1, typeof(Newtonsoft.Json.Linq.JValue)); Newtonsoft.Json.Linq.JValue arg0 = (Newtonsoft.Json.Linq.JValue)ToLua.CheckObject(L, 2, typeof(Newtonsoft.Json.Linq.JValue)); int o = obj.CompareTo(arg0); LuaDLL.lua_pushinteger(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int WriteTo(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.CheckObject(L, 1, typeof(Newtonsoft.Json.Linq.JValue)); Newtonsoft.Json.JsonWriter arg0 = (Newtonsoft.Json.JsonWriter)ToLua.CheckObject(L, 2, typeof(Newtonsoft.Json.JsonWriter)); Newtonsoft.Json.JsonConverter[] arg1 = ToLua.CheckParamsObject <Newtonsoft.Json.JsonConverter>(L, 3, count - 2); obj.WriteTo(arg0, arg1); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int WriteTo(IntPtr L) { try { ToLua.CheckArgsCount(L, 3); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)ToLua.CheckObject <Newtonsoft.Json.Linq.JValue>(L, 1); Newtonsoft.Json.JsonWriter arg0 = (Newtonsoft.Json.JsonWriter)ToLua.CheckObject <Newtonsoft.Json.JsonWriter>(L, 2); Newtonsoft.Json.JsonConverter[] arg1 = ToLua.CheckObjectArray <Newtonsoft.Json.JsonConverter>(L, 3); obj.WriteTo(arg0, arg1); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int set_Value(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)o; object arg0 = ToLua.ToVarObject(L, 2); obj.Value = arg0; return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Value on a nil value" : e.Message)); } }
static int get_Type(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)o; Newtonsoft.Json.Linq.JTokenType ret = obj.Type; ToLua.Push(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o, "attempt to index Type on a nil value")); } }
static int get_HasValues(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)o; bool ret = obj.HasValues; LuaDLL.lua_pushboolean(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index HasValues on a nil value" : e.Message)); } }
static int get_Value(IntPtr L) { object o = null; try { o = ToLua.ToObject(L, 1); Newtonsoft.Json.Linq.JValue obj = (Newtonsoft.Json.Linq.JValue)o; object ret = obj.Value; ToLua.Push(L, ret); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e, o == null ? "attempt to index Value on a nil value" : e.Message)); } }
private void UpdateList() { items = new List <DataDataList>(); //извлечение данных из 1с начало var mContext = this; DataSetWS dataSetWS = new DataSetWS(); string DatalistResult = string.Empty; try { DatalistResult = dataSetWS.GetList(mRef, AppVariable.Variable.getSessionParametersJSON()); } catch (Exception e) { mContext.RunOnUiThread(() => { Toast.MakeText(mContext, e.Message, ToastLength.Long).Show(); mContext.Finish(); }); return; } JObject jsonResult = JObject.Parse(DatalistResult); if (jsonResult.Property("Error") == null) { foreach (JObject Group in jsonResult["Data"]) { Newtonsoft.Json.Linq.JValue Name = (Newtonsoft.Json.Linq.JValue)Group["Name"]; Newtonsoft.Json.Linq.JValue Ref = (Newtonsoft.Json.Linq.JValue)Group["Ref"]; Newtonsoft.Json.Linq.JValue Description = (Newtonsoft.Json.Linq.JValue)Group["Description"]; items.Add(new DataDataList() { Name = (string)Name.Value, Description = (string)Description.Value, Ref = (string)Ref.Value }); } } else { mContext.RunOnUiThread(() => { Toast.MakeText(mContext, (string)jsonResult.Property("Error").Value, ToastLength.Long).Show(); mContext.Finish(); }); } //извлечение данных из 1с конец Button nButton = new Android.Support.V7.Widget.AppCompatButton(this) { Id = 0 }; nButton.Text = "Очистить"; nButton.Click += clearEquip; mLinearLayout.AddView(nButton); Button nButton2 = new Android.Support.V7.Widget.AppCompatButton(this) { Id = 1 }; nButton2.Text = "Выбрать"; nButton2.Click += finishEquip; mLinearLayout.AddView(nButton2); TableLayout mTableLayout = new TableLayout(this); var param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); mTableLayout.SetColumnStretchable(0, true); mTableLayout.SetColumnShrinkable(0, true); mLinearLayout.AddView(mTableLayout, param); var curId = 2; foreach (var itt in items) { TableRow mNewRow = new TableRow(this); mNewRow.SetGravity(GravityFlags.CenterVertical); mTableLayout.AddView(mNewRow); TextView mTextViewDesc = new TextView(this); mTextViewDesc.Text = itt.Name; mNewRow.AddView(mTextViewDesc); TextView nTextView = new TextView(this) { Id = curId }; nTextView.SetTextSize(Android.Util.ComplexUnitType.Sp, 18); nTextView.Text = getSelItemCount(itt.Ref); mElements.Add(curId, nTextView); mNewRow.AddView(nTextView); ImageButton myImageButton1 = new ImageButton(this) { Id = curId + 1000 }; myImageButton1.SetImageResource(Resource.Drawable.ic_action_new); myImageButton1.Click += plusButtonClicked; mNewRow.AddView(myImageButton1); ImageButton myImageButton2 = new ImageButton(this) { Id = curId + 2000 }; myImageButton2.SetImageResource(Resource.Drawable.ic_action_minus); myImageButton2.Click += minusButtonClicked; mNewRow.AddView(myImageButton2); curId++; } }
/// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(JValue other) { return(other != null && JValue.ValuesEquals(this, other)); }
internal static int Compare(JTokenType valueType, object objA, object objB) { if (objA == null && objB == null) { return(0); } if (objA != null && objB == null) { return(1); } if (objA == null && objB != null) { return(-1); } switch (valueType) { case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: return(string.CompareOrdinal(Convert.ToString(objA, (IFormatProvider)CultureInfo.InvariantCulture), Convert.ToString(objB, (IFormatProvider)CultureInfo.InvariantCulture))); case JTokenType.Integer: if (objA is ulong || objB is ulong || (objA is Decimal || objB is Decimal)) { return(Convert.ToDecimal(objA, (IFormatProvider)CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, (IFormatProvider)CultureInfo.InvariantCulture))); } return(objA is float || objB is float || (objA is double || objB is double) ? JValue.CompareFloat(objA, objB) : Convert.ToInt64(objA, (IFormatProvider)CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, (IFormatProvider)CultureInfo.InvariantCulture))); case JTokenType.Float: return(JValue.CompareFloat(objA, objB)); case JTokenType.Boolean: return(Convert.ToBoolean(objA, (IFormatProvider)CultureInfo.InvariantCulture).CompareTo(Convert.ToBoolean(objB, (IFormatProvider)CultureInfo.InvariantCulture))); case JTokenType.Date: if (objA is DateTime dateTime) { DateTime dateTime = !(objB is DateTimeOffset dateTimeOffset2) ? Convert.ToDateTime(objB, (IFormatProvider)CultureInfo.InvariantCulture) : dateTimeOffset2.DateTime; return(dateTime.CompareTo(dateTime)); } DateTimeOffset dateTimeOffset1 = (DateTimeOffset)objA; if (!(objB is DateTimeOffset other)) { other = new DateTimeOffset(Convert.ToDateTime(objB, (IFormatProvider)CultureInfo.InvariantCulture)); } return(dateTimeOffset1.CompareTo(other)); case JTokenType.Bytes: if (!(objB is byte[])) { throw new ArgumentException("Object must be of type byte[]."); } byte[] a1 = objA as byte[]; byte[] a2 = objB as byte[]; if (a1 == null) { return(-1); } return(a2 == null ? 1 : MiscellaneousUtils.ByteArrayCompare(a1, a2)); case JTokenType.Guid: if (!(objB is Guid guid)) { throw new ArgumentException("Object must be of type Guid."); } return(((Guid)objA).CompareTo(guid)); case JTokenType.Uri: if ((object)(objB as Uri) == null) { throw new ArgumentException("Object must be of type Uri."); } return(Comparer <string> .Default.Compare(((Uri)objA).ToString(), ((Uri)objB).ToString())); case JTokenType.TimeSpan: if (!(objB is TimeSpan timeSpan)) { throw new ArgumentException("Object must be of type TimeSpan."); } return(((TimeSpan)objA).CompareTo(timeSpan)); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), (object)valueType, "Unexpected value type: {0}".FormatWith((IFormatProvider)CultureInfo.InvariantCulture, (object)valueType)); } }
private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) { IJsonLineInfo lineInfo = reader as IJsonLineInfo; JContainer parent = this; do { if (parent is JProperty p && p.Value != null) { if (parent == this) { return; } parent = parent.Parent; } switch (reader.TokenType) { case JsonToken.None: // new reader. move to actual content break; case JsonToken.StartArray: JArray a = new JArray(); a.SetLineInfo(lineInfo, settings); parent.Add(a); parent = a; break; case JsonToken.EndArray: if (parent == this) { return; } parent = parent.Parent; break; case JsonToken.StartObject: JObject o = new JObject(); o.SetLineInfo(lineInfo, settings); parent.Add(o); parent = o; break; case JsonToken.EndObject: if (parent == this) { return; } parent = parent.Parent; break; case JsonToken.StartConstructor: JConstructor constructor = new JConstructor(reader.Value.ToString()); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; break; case JsonToken.EndConstructor: if (parent == this) { return; } parent = parent.Parent; break; case JsonToken.String: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Date: case JsonToken.Boolean: case JsonToken.Bytes: JValue v = new JValue(reader.Value); v.SetLineInfo(lineInfo, settings); parent.Add(v); break; case JsonToken.Comment: if (settings != null && settings.CommentHandling == CommentHandling.Load) { v = JValue.CreateComment(reader.Value.ToString()); v.SetLineInfo(lineInfo, settings); parent.Add(v); } break; case JsonToken.Null: v = JValue.CreateNull(); v.SetLineInfo(lineInfo, settings); parent.Add(v); break; case JsonToken.Undefined: v = JValue.CreateUndefined(); v.SetLineInfo(lineInfo, settings); parent.Add(v); break; case JsonToken.PropertyName: JProperty property = ReadProperty(reader, settings, lineInfo, parent); if (property != null) { parent = property; } else { await reader.SkipAsync(); } break; default: throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)); }
internal void ReadContentFrom(JsonReader r) { ValidationUtils.ArgumentNotNull(r, "r"); IJsonLineInfo lineInfo = r as IJsonLineInfo; JContainer parent = this; do { if (parent is JProperty && ((JProperty)parent).Value != null) { if (parent == this) { return; } parent = parent.Parent; } switch (r.TokenType) { case JsonToken.None: // new reader. move to actual content break; case JsonToken.StartArray: JArray a = new JArray(); a.SetLineInfo(lineInfo); parent.Add(a); parent = a; break; case JsonToken.EndArray: if (parent == this) { return; } parent = parent.Parent; break; case JsonToken.StartObject: JObject o = new JObject(); o.SetLineInfo(lineInfo); parent.Add(o); parent = o; break; case JsonToken.EndObject: if (parent == this) { return; } parent = parent.Parent; break; case JsonToken.StartConstructor: JConstructor constructor = new JConstructor(r.Value.ToString()); constructor.SetLineInfo(constructor); parent.Add(constructor); parent = constructor; break; case JsonToken.EndConstructor: if (parent == this) { return; } parent = parent.Parent; break; case JsonToken.String: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Date: case JsonToken.Boolean: case JsonToken.Bytes: JValue v = new JValue(r.Value); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.Comment: v = JValue.CreateComment(r.Value.ToString()); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.Null: v = new JValue(null, JTokenType.Null); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.Undefined: v = new JValue(null, JTokenType.Undefined); v.SetLineInfo(lineInfo); parent.Add(v); break; case JsonToken.PropertyName: string propertyName = r.Value.ToString(); JProperty property = new JProperty(propertyName); property.SetLineInfo(lineInfo); JObject parentObject = (JObject)parent; // handle multiple properties with the same name in JSON JProperty existingPropertyWithName = parentObject.Property(propertyName); if (existingPropertyWithName == null) { parent.Add(property); } else { existingPropertyWithName.Replace(property); } parent = property; break; default: throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType)); } }while (r.Read()); }
/// <summary> /// Writes a comment <c>/*...*/</c> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public override void WriteComment(string text) { base.WriteComment(text); AddValue(JValue.CreateComment(text), JsonToken.Comment); }
public static string GetJSON() { IList <Earthquake> earthquakes = new List <Earthquake>(); Country Chile = new Country("CHILE"); Country Argentina = new Country("ARGENTINA"); var usgs = "http://earthquake.usgs.gov/earthquakes/feed/v0.1/summary/1.0_hour.geojson"; var urlInpres = "http://www.inpres.gov.ar/seismology/xultimos.php"; var ssuch = "http://www.sismologia.cl/links/ultimos_sismos.html"; string filename = "http://www.emsc-csem.org/service/rss/rss.php"; var urlInpres1 = "J:\\Instituto Nacional de Prevención Sísmica.htm"; var ssuch1 = "J:\\Ultimos Sismos.mht"; var usgs1 = "J:\\earthquake\\2.5_day.csv"; //----------------------------------------------------------------------------------------- while (true) { if (earthquakes.Count > 0) { Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); var earthquakesArgentina = earthquakes.Where(e => e.Place.Country.CountryName.Equals("ARGENTINA")).OrderByDescending(e => e.UTCDateTime); var earthquakesChile = earthquakes.Where(e => e.Place.Country.CountryName.Equals("CHILE")).OrderByDescending(e => e.UTCDateTime); var earthquakesWorld = earthquakes.Except(earthquakesArgentina).Except(earthquakesChile).OrderByDescending(e => e.UTCDateTime); foreach (var earthquake in earthquakesArgentina) { if (earthquake.IsSensible) { Console.ForegroundColor = ConsoleColor.Red; if (earthquake.Place.PlaceName.Contains("MENDOZA")) { PlayAlertSound(); } } else { Console.ForegroundColor = ConsoleColor.Green; } Console.WriteLine(earthquake); Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------"); Thread.Sleep(1000); } foreach (var earthquake in earthquakesChile) { if (earthquake.IsSensible) { Console.ForegroundColor = ConsoleColor.Red; } else { Console.ForegroundColor = ConsoleColor.Green; } Console.WriteLine(earthquake); Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------"); Thread.Sleep(1000); } foreach (var earthquake in earthquakesWorld) { if (earthquake.IsSensible) { Console.ForegroundColor = ConsoleColor.Red; } else { Console.ForegroundColor = ConsoleColor.Green; } Console.WriteLine(earthquake); Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------"); Thread.Sleep(1000); } } earthquakes = new List <Earthquake>(); try { #region ARGENTINA //Console.WriteLine("#################################ARGENTINA###################################ARGENTINA#################################ARGENTINA#######################################"); // Load the html document HtmlWeb webArgentina = new HtmlWeb(); HtmlDocument docArgentina = webArgentina.Load(urlInpres); // Get all tables in the document HtmlNodeCollection tables = docArgentina.DocumentNode.SelectNodes("//table"); var earthquakeTable = tables.Where(tb => tb.Id.Equals("sismos")).Single(); // Iterate all rows in the first table HtmlNodeCollection rows1 = earthquakeTable.SelectNodes(".//tr"); for (int i = 1; 6 > i; ++i) { // Iterate all columns in this row HtmlNodeCollection cols = rows1[i].SelectNodes(".//td"); var sensible1 = cols[8]; bool isSensible = sensible1.OuterHtml.Contains("#D40000"); string LocalDateTimeHour = string.Empty; string LocalDateTimeYear = string.Empty; DateTime LocalDateTime = new DateTime(); Coordenate Latitude = null; Coordenate Longitude = null; Depth Depth = null; Magnitude Magnitude = null; decimal decimalValue = 0; Source Source = null; Place Place = null; for (int j = 1; j < cols.Count; ++j) { string value = cols[j].InnerText; switch (j) { //Local time case (1): LocalDateTimeYear = value; break; case (2): LocalDateTimeHour = value; DateTime.TryParse(LocalDateTimeYear + " " + LocalDateTimeHour, out LocalDateTime); break; //Latitude case (3): string[] coord1 = value.Split('�'); string[] coord2 = coord1[1].Split('\''); var degrees = Convert.ToDecimal(coord1[0], CultureInfo.InvariantCulture); var minutes = Convert.ToDecimal(coord2[0], CultureInfo.InvariantCulture); var seconds = Convert.ToDecimal(coord2[1], CultureInfo.InvariantCulture); Latitude = new Coordenate(degrees, minutes, seconds); break; //Longitude case (4): string[] coord3 = value.Split('�'); string[] coord4 = coord3[1].Split('\''); var degrees1 = Convert.ToDecimal(coord3[0], CultureInfo.InvariantCulture); var minutes1 = Convert.ToDecimal(coord4[0], CultureInfo.InvariantCulture); var seconds1 = Convert.ToDecimal(coord4[1], CultureInfo.InvariantCulture); Longitude = new Coordenate(degrees1, minutes1, seconds1); break; //Depth case (5): string[] depthArray = value.Split(' '); decimalValue = Convert.ToDecimal(depthArray[0], CultureInfo.InvariantCulture); Depth = new Depth(decimalValue, depthArray[1]); break; //Magnitude case (6): string[] magnitudArray = value.Split(' '); decimalValue = Convert.ToDecimal(magnitudArray[0], CultureInfo.InvariantCulture); Magnitude = new Magnitude(decimalValue, "??"); break; //Place case (7): Place = new Place(value, Argentina, -3); Source = new Source("INPRES", ""); break; } } earthquakes.Add(new Earthquake(LocalDateTime, Latitude, Longitude, Depth, Magnitude, isSensible, Place, Source)); } #endregion } catch (Exception ex) { if (ex.InnerException != null) { Console.WriteLine("ARGENTINA REGION ERROR:" + ex.InnerException.Message); } else { Console.WriteLine("ARGENTINA REGION ERROR:" + ex.Message); } } try{ //--------------------------------------------------------------------------------------------------------------------------------------------------------------- #region Twitter /* * The Twitter REST API v1 will soon stop functioning. Please migrate to API v1.1. * https://dev.twitter.com/docs/api/1.1/overview */ var twitter = new Twitter("xNBdzXy7tkyD1kstIDcg", "0nSriIwDZkFR7qcf6nsnQh3bqecn7IGoTqpIr8Xk6gc", "1451422718-kwIAaVppRGys6dltQXKIUt39vNbIg5e4PFD1Rgu", "1LPbBbwYcAELk3dl50WIwZMp38gt2wWGwkOkzVQGQM"); var responseTwitter = twitter.GetTweets("sismo argentina"); JObject jobjectTwitter1 = JObject.Parse(responseTwitter); var resultado12 = jobjectTwitter1["statuses"]; var twittsList2 = resultado12.ToList(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("--------------------Twitter---------------Twitter----------------Twitter------------------Twitter--------------------Twitter-----------------Twitter"); foreach (var twitt in twittsList2) { Console.ForegroundColor = ConsoleColor.Blue; //Wed, 22 May 2013 14:01:58 +0000 DateTime timestamp; //var rrrr = twitt.First.First.ToString().Replace(",", "").Replace("\\", "").Replace("\"",""); // DateTime.TryParseExact(rrrr, "ddd MMM dd HH:mm:ss K yyyy", null, DateTimeStyles.None, out timestamp); var text = twitt["text"]; var date = twitt["created_at"].ToString().Replace("\\", "").Replace("\"", ""); const string format = "ddd MMM dd HH:mm:ss zzzz yyyy"; var realtime = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture); if (text.ToString().Contains("gol") || text.ToString().Contains("futbol") || text.ToString().Contains("jugador")) { Console.ForegroundColor = ConsoleColor.Yellow; } Console.WriteLine(string.Concat(realtime.ToString(), " ", text)); Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------"); Thread.Sleep(500); } #endregion } catch (Exception ex) { if (ex.InnerException != null) { Console.WriteLine("TWITTER ERROR:" + ex.InnerException.Message); } else { Console.WriteLine("TWITTER ERROR:" + ex.Message); } Thread.Sleep(3000); } try{ //--------------------------------------------------------------------------------------------------------------------------------------------------------------- #region Chile //Console.WriteLine("########################CHILE######################CHILE########################CHILE####################################################"); // Load the html document HtmlWeb webChile = new HtmlWeb(); HtmlDocument docChile = webChile.Load(ssuch); // Get all tables in the document HtmlNodeCollection tables1 = docChile.DocumentNode.SelectNodes("//table"); var earthquakeTable1 = tables1[0]; // Iterate all rows in the first table HtmlNodeCollection rows = earthquakeTable1.SelectNodes(".//tr"); for (int i = 1; 6 > i; ++i) { bool IsSensible = false; //determina si fue percibido string sensible = rows[i].Attributes[0].Value; if (sensible.Contains("sensible")) { IsSensible = true; } // Iterate all columns in this row HtmlNodeCollection cols = rows[i].SelectNodes(".//th"); if (cols == null) { cols = rows[i].SelectNodes(".//td"); } DateTime LocalDateTime = new DateTime(); Coordenate Latitude = null; Coordenate Longitude = null; Depth Depth = null; Magnitude Magnitude = null; decimal decimalValue = 0; Source Source = null; Place Place = null; for (int j = 0; j < cols.Count; ++j) { string value = cols[j].InnerText; switch (j) { //Local time : ignore case (0): break; //UTC time case (1): DateTime.TryParse(value, out LocalDateTime); break; //Latitude case (2): decimalValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture); Latitude = new Coordenate(decimalValue); break; //Longitude case (3): decimalValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture); Longitude = new Coordenate(decimalValue); break; //Depth case (4): decimalValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture); Depth = new Depth(decimalValue, "KM."); break; //Magnitude case (5): string[] magnitudArray = value.Trim().Split(' '); decimalValue = Convert.ToDecimal(magnitudArray[0], CultureInfo.InvariantCulture); Magnitude = new Magnitude(decimalValue, magnitudArray[1]); break; //Source case (6): Source = new Source(value, ""); break; //Place case (7): Place = new Place(value, Chile, -4); break; } } earthquakes.Add(new Earthquake(LocalDateTime, Latitude, Longitude, Depth, Magnitude, IsSensible, Place, Source)); } #endregion } catch (Exception ex) { Thread.Sleep(3000); if (ex.InnerException != null) { Console.WriteLine("CHILE REGION ERROR:" + ex.InnerException.Message); } else { Console.WriteLine("CHILE REGION ERROR:" + ex.Message); } } //--------------------------------------------------------------------------------------------------------------------------------------------------------------- try{ #region EMS XDocument doc = XDocument.Load(filename); IEnumerable <XElement> query = from c in doc.Descendants("item") select c; IEnumerable <XElement> query5 = from d in query.Descendants("title") /*.Where(d => d.Value.Contains("ARGENTINA"))*/ select d.Parent; /* * ML 2.3 WESTERN TURKEY * ML 2.3 CRETE, GREECE * Mw 5.8 EASTERN UZBEKISTAN * ML 4.3 JUJUY, ARGENTINA * ML 3.5 SOUTHERN IRAN * M 4.1 POTOSI, BOLIVIA * ML 3.2 OFF COAST OF ATACAMA, CHILE * ML 2.8 FYR OF MACEDONIA * ML 3.8 OFFSHORE COQUIMBO, CHILE * mb 4.8 PAPUA, INDONESIA * mb 4.1 SEA OF OKHOTSK * ML 3.0 ALBANIA * M 4.6 OFF COAST OF SOUTHEASTERN ALASKA" */ foreach (var aaa in query5) { var cantidad = query5.Count(); string[] asdf = aaa.ToString().Split(new Char[] { '\n' }); string LocalDateTimeHour = string.Empty; string LocalDateTimeYear = string.Empty; DateTime LocalDateTime = new DateTime(); Coordenate Latitude = null; Coordenate Longitude = null; Depth Depth = null; Magnitude Magnitude = null; decimal decimalValue = 0; Source Source = null; Place Place = null; bool IsSensible = false; for (int j = 1; j < asdf.Length; ++j) { var value = asdf[j]; switch (j) { //Local time case (1): var haber = value.Replace("<title>", "").Replace("</title>", "").Trim(); string[] ololo = haber.Split(','); if (ololo.Length == 2) { var carac = ololo[0].ToCharArray(); int cantidadEspacios = 0; StringBuilder sbs = new StringBuilder(); bool anteriorSpace = false; for (int i = 0; i < carac.Length; ++i) { if (cantidadEspacios == 2) { sbs.Append(carac[i]); } if (cantidadEspacios < 2 && carac[i].Equals(' ') && !anteriorSpace) { cantidadEspacios++; anteriorSpace = true; } else { anteriorSpace = false; } } var locationTemp = sbs.ToString().Trim(); var location = locationTemp.ToString(); var pais = ololo[1].Trim(); var country = new Country(pais); Place = new Place(location, country, 0); } else { char[] carac = ololo[0].ToCharArray(); int cantidadEspacios = 0; StringBuilder sbs = new StringBuilder(); bool anteriorSpace = false; for (int i = 0; i < carac.Length; ++i) { if (cantidadEspacios == 2) { sbs.Append(carac[i]); } if (cantidadEspacios < 2 && carac[i].Equals(' ') && !anteriorSpace) { cantidadEspacios++; anteriorSpace = true; } else { anteriorSpace = false; } } if (!sbs.ToString().Equals(string.Empty)) { var locationTemp = sbs.ToString().Trim(); string[] side = new string[6] { "EASTERN", "SOUTHERN", "WESTERN", "NORTHEM", "CENTRAL", "GULF OF" }; string[] aaasas = locationTemp.Split(' '); var pais = aaasas[aaasas.Length - 1].Trim();; var location = locationTemp.ToString(); if (side.Contains(pais)) { var country = new Country(pais); Place = new Place(location, country, 0); } else { var country = new Country(location); Place = new Place(location, country, 0); } } } break; //ignore, id earthquake case (2): break; //Latitude case (3): var decimalString = value.Replace("<geo:lat xmlns:geo=\"http://www.w3.org/2003/01/geo/\">", "").Replace("</geo:lat>", "").Trim(); var val = Convert.ToDecimal(decimalString, CultureInfo.InvariantCulture); Latitude = new Coordenate(val); break; //Longitude case (4): var decimalString1 = value.Replace("<geo:long xmlns:geo=\"http://www.w3.org/2003/01/geo/\">", "").Replace("</geo:long>", "").Trim(); var val1 = Convert.ToDecimal(decimalString1, CultureInfo.InvariantCulture); Longitude = new Coordenate(val1); break; //Depth case (5): var decimalString2 = value.Replace("<emsc:depth xmlns:emsc=\"http://www.emsc-csem.org\">", "").Replace("</emsc:depth>", "").Trim(); string[] tempString = decimalString2.Split(' '); var val2 = Convert.ToDecimal(tempString[0], CultureInfo.InvariantCulture); Depth = new Depth(val2, "Km."); break; //Magnitude case (6): var decimalString3 = value.Replace("<emsc:magnitude xmlns:emsc=\"http://www.emsc-csem.org\">", "").Replace("</emsc:magnitude>", "").Trim(); string[] magnitudArray = decimalString3.Split(' '); decimalValue = Convert.ToDecimal(magnitudArray[magnitudArray.Length - 1], CultureInfo.InvariantCulture); Magnitude = new Magnitude(decimalValue, magnitudArray[0]); break; //DateTime case (7): var decimalString4 = value.Replace("<emsc:time xmlns:emsc=\"http://www.emsc-csem.org\">", "").Replace("</emsc:time>", "").Trim(); string[] a1 = decimalString4.Split('-'); string[] a2 = a1[2].Split(' '); string[] a3 = a2[1].Replace("UTC", "").Split(':'); LocalDateTime = new DateTime(int.Parse(a1[0]), int.Parse(a1[1]), int.Parse(a2[0]), int.Parse(a3[0]), int.Parse(a3[1]), int.Parse(a3[2])); break; } } Source = new Source("emsc-csem.", ""); if (Magnitude.MagnitudeValue > Convert.ToDecimal(4.5)) { IsSensible = true; } earthquakes.Add(new Earthquake(LocalDateTime, Latitude, Longitude, Depth, Magnitude, IsSensible, Place, Source)); } #endregion } catch (Exception ex) { Thread.Sleep(3000); if (ex.InnerException != null) { Console.WriteLine("EMS ERROR:" + ex.InnerException.Message); } else { Console.WriteLine("EMS ERROR:" + ex.Message); } } try { //-------------------------------------------------------------------------------------------------------------------------------------------------------------------- #region USA REGION //Console.WriteLine("########################USA######################WORLD########################USA######################WORDL##############################"); /* Stream str = new FileStream(usgs1, FileMode.Open,FileAccess.Read); * StreamReader sr = new StreamReader(str); * string line = string.Empty; * * int lineNumber= 0; * string[] dataLine = null; * * * DateTime LocalDateTimeUsa = new DateTime(); * Coordenate LatitudeUsa = null; * Coordenate LongitudeUsa = null; * Depth DepthUsa = null; * Magnitude MagnitudeUsa = null; * decimal decimalValueUsa = 0; * Source SourceUsa = null; * Place PlaceUsa = null; * * while (line != null ) * { * line = sr.ReadLine(); * if(lineNumber != 0 && lineNumber != 6){ * * dataLine = line.ToString().Split(','); * * * * decimalValueUsa = Convert.ToDecimal(dataLine[0], CultureInfo.InvariantCulture); * } * else if(lineNumber == 6){ * break; * } * lineNumber++; * }*/ //create the constructor with post type and few data MyWebRequest myRequest = new MyWebRequest(usgs, "POST", ""); //show the response string on the console screen. var response = myRequest.GetResponse(); JObject jobject = JObject.Parse(response); JToken metadata = null; JToken type = null; JToken features = null; jobject.TryGetValue("metadata", out metadata); jobject.TryGetValue("features", out features); jobject.TryGetValue("type", out type); var cantidadIncidentes = features.Count(); var eee = features.ToArray <JToken>(); for (int i = 0; i < cantidadIncidentes; i++) { var incidente = eee[i]; var jTokenIntensity = (JToken)incidente.First.Next.First.First.First; var jTokenTime = (JToken)((incidente.First.Next.First.First).Next).Next.Last; string miliseconds = (string)jTokenTime.Value <Newtonsoft.Json.Linq.JValue>(); Newtonsoft.Json.Linq.JValue valor = jTokenIntensity.Value <Newtonsoft.Json.Linq.JValue>(); JTokenType jtype = jTokenIntensity.Type; Int64 intensidadInteger = 0; double intensidadDouble = 0.0; if (jtype.Equals(JTokenType.Float)) { intensidadDouble = (double)valor.Value; } else if (jtype.Equals(JTokenType.Integer)) { intensidadInteger = (Int64)valor.Value; } bool isSensible = false; if (intensidadInteger != 0 && intensidadDouble == 0.0) { isSensible = intensidadInteger >= 4.5; } else if (intensidadInteger == 0 && intensidadDouble != 0.0) { isSensible = intensidadDouble >= 4.5; } if (isSensible) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(incidente.ToString()); Console.WriteLine(".........................................................................................................................."); Thread.Sleep(2000); } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(incidente.ToString()); Console.WriteLine(".........................................................................................................................."); Thread.Sleep(2000); } } #endregion } catch (Exception ex) { Thread.Sleep(3000); if (ex.InnerException != null) { Console.WriteLine("USA REGION ERROR:" + ex.InnerException.Message); } else { Console.WriteLine("USA REGION ERROR:" + ex.Message); } } //--------------------------------------------------------------------------------------------------------------------------------------------------------------------- Console.WriteLine("ªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª"); Console.WriteLine("ªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª"); Console.WriteLine("ªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª"); } //------------------------------------------------------------------------------------------- while (true) { //create the constructor with post type and few data MyWebRequest myRequest = new MyWebRequest(usgs, "POST", ""); //show the response string on the console screen. var response = myRequest.GetResponse(); JObject jobject = JObject.Parse(response); JToken metadata = null; JToken type = null; JToken features = null; jobject.TryGetValue("metadata", out metadata); jobject.TryGetValue("features", out features); jobject.TryGetValue("type", out type); var cantidadIncidentes = features.Count(); var eee = features.ToArray <JToken>(); for (int i = 0; i < cantidadIncidentes; i++) { var incidente = eee[i]; Console.WriteLine(incidente.ToString()); Console.WriteLine(".........................................................................................................................."); Thread.Sleep(2000); } Console.WriteLine("------------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("------------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("------------------------------------------------------------------------------------------------------------------------"); Thread.Sleep(10000); } /* * { * "type": "FeatureCollection", * "features": [ * { * "geometry": { * "type": "Point", * "coordinates": [6.18218, 45.5949] * }, * "type": "Feature", * "properties": { * "elevation": 1770, * "name": "Col d'Arclusaz" * }, * "id": 472 * }, ... more features... * } * } */ object MyCollection = new MyFeatureCollection { Features = new MyFeature[] { new MyFeature { ID = "472", Geometry = new GeoJSON.Point(6.18218, 45.5949), Properties = new MyProperties { Elevation = "1770", Name = "CollectionBase d'Arclusaz" } }, new MyFeature { ID = "458", Geometry = new GeoJSON.Point(6.27827, 45.6769), Properties = new MyProperties { Elevation = "1831", Name = "Pointe de C\\u00f4te Favre" } } } }; StringBuilder Builder = new System.Text.StringBuilder(); StringWriter Writer = new System.IO.StringWriter(Builder); new Newtonsoft.Json.JsonSerializer().Serialize(Writer, MyCollection); return(Builder.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="T:Newtonsoft.Json.Linq.JValue" /> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(object value) : this(value, JValue.GetValueType(new JTokenType?(), value)) { }
/// <summary> /// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object. /// </summary> /// <param name="other">A <see cref="JValue"/> object to copy from.</param> public JValue(JValue other) : this(other.Value, other.Type) { }
private static bool ValuesEquals(JValue v1, JValue v2) { return(v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0)); }
public static int ToInt(this Newtonsoft.Json.Linq.JValue obj) { return(Convert.ToInt32(obj.Value)); }
int IComparable.CompareTo(object obj) { return(obj == null ? 1 : JValue.Compare(this._valueType, this._value, obj is JValue ? ((JValue)obj).Value : obj)); }
internal void method_11(JsonReader jsonReader_0) { JValue value2; JProperty property; Class203.smethod_2(jsonReader_0, "r"); IJsonLineInfo info = jsonReader_0 as IJsonLineInfo; JContainer parent = this; goto Label_0204; Label_01D8: if (!jsonReader_0.Read()) { return; } Label_0204: if ((parent is JProperty) && (((JProperty)parent).Value != null)) { if (parent == this) { return; } parent = parent.Parent; } switch (jsonReader_0.JsonToken_0) { case JsonToken.None: goto Label_01D8; case JsonToken.StartObject: { JObject content = new JObject(); content.method_0(info); parent.Add(content); parent = content; goto Label_01D8; } case JsonToken.StartArray: { JArray array = new JArray(); array.method_0(info); parent.Add(array); parent = array; goto Label_01D8; } case JsonToken.StartConstructor: { JConstructor constructor = new JConstructor(jsonReader_0.Object_0.ToString()); constructor.method_0(constructor); parent.Add(constructor); parent = constructor; goto Label_01D8; } case JsonToken.PropertyName: { string name = jsonReader_0.Object_0.ToString(); property = new JProperty(name); property.method_0(info); JProperty property2 = ((JObject)parent).Property(name); if (property2 != null) { property2.Replace(property); break; } parent.Add(property); break; } case JsonToken.Comment: value2 = JValue.CreateComment(jsonReader_0.Object_0.ToString()); value2.method_0(info); parent.Add(value2); goto Label_01D8; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: value2 = new JValue(jsonReader_0.Object_0); value2.method_0(info); parent.Add(value2); goto Label_01D8; case JsonToken.Null: value2 = new JValue(null, JTokenType.Null); value2.method_0(info); parent.Add(value2); goto Label_01D8; case JsonToken.Undefined: value2 = new JValue(null, JTokenType.Undefined); value2.method_0(info); parent.Add(value2); goto Label_01D8; case JsonToken.EndObject: if (parent != this) { parent = parent.Parent; goto Label_01D8; } return; case JsonToken.EndArray: if (parent != this) { parent = parent.Parent; goto Label_01D8; } return; case JsonToken.EndConstructor: if (parent != this) { parent = parent.Parent; goto Label_01D8; } return; default: throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".smethod_0(CultureInfo.InvariantCulture, jsonReader_0.JsonToken_0)); } parent = property; goto Label_01D8; }
/// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: /// Value /// Meaning /// Less than zero /// This instance is less than <paramref name="obj" />. /// Zero /// This instance is equal to <paramref name="obj" />. /// Greater than zero /// This instance is greater than <paramref name="obj" />. /// </returns> /// <exception cref="T:System.ArgumentException"> /// <paramref name="obj" /> is not the same type as this instance. /// </exception> public int CompareTo(JValue obj) { return(obj == null ? 1 : JValue.Compare(this._valueType, this._value, obj._value)); }