public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); }
public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue((object)null), t)); }
public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); }
private void WriteSettingObject(JsonWriter writer, JObject obj) { writer.WriteStartObject(); foreach (var property in obj.Children<JProperty>()) { writer.WritePropertyName(property.Name); if (property.Value is JObject) this.WriteSettingObject(writer, property.Value as JObject); else writer.WriteValue(property.Value); } writer.WriteEndObject(); }
public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); }
public static void PopulateMissing(JObject serialized, TypeInformation information) { // Remove any additional fields. foreach (var item in serialized.Children <JProperty> ().ToList()) { if (!information.Fields.Keys.Contains(item.Name)) { item.Remove(); } } // Populate missing fields with default values. foreach (var field in information.Fields) { if (!serialized.ContainsKey(field.Key)) { serialized.Add(field.Key, field.Value.DefaultValue); } } }
/// <summary> /// Parses the given JSON string in order to extract the Matomo Analytics data. /// </summary> /// <param name="json">The JSON string to be parsed.</param> /// <returns>A list containing the data for each day.</returns> private List <InfluxDatapoint <InfluxValueField> > ParseJSON(string json) { JObject o = JObject.Parse(json); List <InfluxDatapoint <InfluxValueField> > list = new List <InfluxDatapoint <InfluxValueField> >(); foreach (JToken c in o.Children()) { if (c.First.Count() > 0) { int visits = c.First.SelectToken("nb_visits").Value <int>(); int actions = c.First.SelectToken("nb_actions").Value <int>(); int users = c.First.SelectToken("nb_users").Value <int>(); list.Add(SmartAlarm_Overview.CreateInfluxDatapoint(MeasurementName, DateTime.Parse(c.Path).AddMinutes(TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).TotalMinutes).ToUniversalTime(), visits, actions, users)); } } return(list); }
protected JsonSchemaObject Generate(JObject j) { JToken tokenSchema = j["$schema"]; JObject definitions = (JObject)j.SelectToken("definitions"); if (tokenSchema != null) { this.Id = tokenSchema.ToString(); } if (definitions != null) { foreach (JProperty child in definitions.Children()) { this.Definitions.Add(child.Name, JsonSchemaObject.Generate(this, child.Name, (JObject)definitions.SelectToken(child.Name))); } } return(JsonSchemaObject.Generate(this, "$", j)); }
public Document CombineWith(JObject jobj) { Newtonsoft.Json.JsonWriter jwriter = CreateWriter(); IEnumerator <JToken> en = jobj.Children().GetEnumerator(); while (en.MoveNext()) { if (en.Current.Type != JTokenType.Property) { throw new Json.JsonParseException("Property was expected."); } if (this[((JProperty)en.Current).Name] == null) { Newtonsoft.Json.JsonConverter conv = new Newtonsoft.Json.Converters.KeyValuePairConverter(); en.Current.WriteTo(jwriter, new Newtonsoft.Json.JsonConverter[] { conv }); } } return(this); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { List <TransactionChange> changes = new List <TransactionChange>(); JObject changelog = JObject.Load(reader); foreach (JProperty dateProp in changelog.Children <JProperty>()) { DateTime changeDate = DateTime.ParseExact(dateProp.Name, "yyyy-MMM-dd hh:mm tt", CultureInfo.InvariantCulture); foreach (JProperty fieldProp in dateProp.Value.Children <JProperty>()) { TransactionChange change = new TransactionChange(); change.ChangeDate = changeDate; change.Field = fieldProp.Name; change.From = (string)fieldProp.Value["from"]; change.To = (string)fieldProp.Value["to"]; changes.Add(change); } } return(changes); }
public async Task UpdateReportedPropertiesAsync(JObject reportedObject, LogDelegateType Log) { Log("Updating reported properties..."); TwinCollection azureCollection = new TwinCollection(); foreach (JProperty p in reportedObject.Children()) { azureCollection[p.Name] = p.Value; } try { await _deviceClient.UpdateReportedPropertiesAsync(azureCollection); } catch (Exception e) { Log("Error: failed to update reported properties. " + e.Message); } }
private static void CovnertJObjectToDictionary(JObject obj, Dictionary <string, string> finishedJsonObject, string prefix) { //then convert to a list of string->object mappings JContainer container = obj; JProperty objProp = obj.Properties().FirstOrDefault(); if (obj.Count < 2 && container.First.Count() < 2) { ConvertJPropertyToFormDictionary(objProp, finishedJsonObject, prefix); } else { int childCount = 0; foreach (JProperty child in obj.Children()) { ConvertJPropertyToFormDictionary(child, finishedJsonObject, prefix); childCount++; } } }
/// <summary> /// Convert a random object to a form-postable Dictionary[string,string] /// </summary> /// <param name="obj">The object to convert</param> /// <returns>A dictionary [string,string] suitable for http posting as form data</returns> public static Dictionary <string, string> ConvertObjectToFormDictionary(object obj) { Dictionary <string, string> finishedJsonObject = new Dictionary <string, string>(); //object->json->JObject to iterate, this is then passed to the recursive function string json = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); JObject dj = (JObject)JsonConvert.DeserializeObject(json); foreach (JProperty child in dj.Children()) { ConvertJPropertyToFormDictionary(child, finishedJsonObject, ""); } return(finishedJsonObject); //iterate, and anything that is not a list, store as value }
/// <summary> /// Returns all the resource references (excluding prefab desc) /// </summary> /// <param name="root">The root node to start from</param> /// <returns></returns> protected IEnumerable <JObject> AllResourceRef(JObject root) { var toSearch = new Stack <JToken>(root.Children()); while (toSearch.Count > 0) { var inspected = toSearch.Pop(); if (IsResourceRefNode(inspected)) { yield return((JObject)inspected); } else { foreach (var child in inspected) { toSearch.Push(child); } } } }
private T GetValueFromProperty <T>(JObject jObject, string name) { if (jObject == null) { return(default(T)); } var children = jObject.Children(); foreach (var child in children) { var jProperty = child as JProperty; if (jProperty.Name == name) { return(jProperty.First.ToObject <T>()); } } return(default(T)); }
public static HashJsonBU Parse(string jsonStr) { HashJsonBU _json = new HashJsonBU(); try { JObject obj = JObject.Parse(jsonStr); JEnumerable <JToken> _children = obj.Children(); foreach (JProperty field in _children) { string name = field.Name; string value = field.Value.ToString(); _json.Add(name, value); } } catch (Exception) { } return(_json); }
protected void TestPropetries(Type type, JObject jObject) { var propNames = GetPropertyNames(type); var chSet = jObject.Children(); var msg = new List <string>(); foreach (JProperty jtoken in chSet) { if (!propNames.Contains(jtoken.Name)) { msg.Add($"Missing {jtoken}"); } } if (msg.Any()) { Assert.Fail($"Some properties ({msg.Count}) was missed! {Environment.NewLine} {string.Join(Environment.NewLine, msg)}"); } }
private void AlterJobExperience() { JObject xpRewards = mJson.SelectToken("xp_rewards") as JObject; if (xpRewards != null && !mHasAlteredExperience) { foreach (JToken xp in xpRewards.Children()) { JProperty property = xp as JProperty; JValue xpValue = property.Value as JValue; int value = xpValue.Value <int>(); int newValue = value - 5; xpValue.Value = newValue; } AddError("Needs Save after job experience altered"); mSaveJsonAfterParse = true; mHasAlteredExperience = true; } }
private bool IsMatch(Type type, JObject obj) { bool result = true; foreach (JToken childProperty in obj.Children()) { if (childProperty is JProperty) { if (type.GetProperty(((JProperty)childProperty).Name) == null) { result = false; break; } } if (childProperty is JObject) { } } return(result); }
/// <summary> /// Get specified property name from an entry. /// </summary> /// <param name="entry">An entry.</param> /// <param name="partialPropertyName">A partial property name.</param> /// <returns>A list of results.</returns> public static IEnumerable <string> GetAllSpecifiedPropertyNameFromEntry(JObject entry, string partialPropertyName) { List <string> result = new List <string>(); if (entry != null && entry.Type == JTokenType.Object) { // Get all the properties in current entry. var jProps = entry.Children(); foreach (JProperty jProp in jProps) { if (jProp.Name.Contains(partialPropertyName)) { result.Add(jProp.Name); } } } return(result); }
public void GetInfoDeserializeSparseTest() { IOrderedEnumerable <string> expectedSortedPropertyNames = RequiredPropertyNames.OrderBy(name => name); string json = "{\n" + " \"version\": 1010000,\n" + " \"protocolversion\": 70012,\n" + " \"blocks\": 460828,\n" + " \"timeoffset\": 0,\n" + " \"proxy\": \"\",\n" + " \"difficulty\": 499635929816.6675,\n" + " \"testnet\": false,\n" + " \"relayfee\": 0.00001000,\n" + " \"errors\": \"URGENT: Alert key compromised, upgrade required\"\n" + " }\n"; JObject obj = JObject.Parse(json); IOrderedEnumerable <string> actualSortedPropertyNames = obj.Children().Select(o => (o as JProperty)?.Name).OrderBy(name => name); Assert.Equal(expectedSortedPropertyNames, actualSortedPropertyNames); }
public void Load(string FileName) { try { if (false == System.IO.File.Exists(FileName)) { throw new Exception(string.Format("The file \"{0}\"does not exist.", FileName)); } else {//do nothing } #region Load Tags StreamReader file = File.OpenText(FileName); JsonTextReader reader = new JsonTextReader(file); JObject joSettings = (JObject)JToken.ReadFrom(reader); foreach (JToken jt in joSettings.Children()) { var property = jt as JProperty; if (true == property.Name.ToLower().Equals("testplan_tag")) { LoadTags_Testplan((JObject)joSettings["Testplan_Tag"]); } //else if (true == property.Name.ToLower().Equals("testplan_tag")) //{ //} else //do nothing { } } reader.Close(); file.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } #endregion Load Tags }
public void GetMarketsInfo() { string address = "https://bittrex.com/api/v1.1/public/getmarkets"; string text = GetDownloadString(address); Markets.Clear(); JObject res = (JObject)JsonConvert.DeserializeObject(text); foreach (JProperty prop in res.Children()) { if (prop.Name == "success") { if (prop.Value.Value <bool>() == false) { break; } } if (prop.Name == "message") { continue; } if (prop.Name == "result") { JArray markets = (JArray)prop.Value; foreach (JObject obj in markets) { BittrexMarketInfo m = new BittrexMarketInfo(); m.MarketCurrency = obj.Value <string>("MarketCurrency"); m.BaseCurrency = obj.Value <string>("BaseCurrency"); m.MarketCurrencyLong = obj.Value <string>("MarketCurrencyLong"); m.BaseCurrencyLong = obj.Value <string>("BaseCurrencyLong"); m.MinTradeSize = obj.Value <double>("MinTradeSize"); m.MarketName = obj.Value <string>("MarketName"); m.IsActive = obj.Value <bool>("IsActive"); m.Created = obj.Value <DateTime>("Created"); m.Index = Markets.Count; Markets.Add(m); } } } }
private JObject ProcessSingle(Page page, ISelectable item, int index) { JObject dataObject = new JObject(); foreach (var field in EntityMetadata.Entity.Fields) { var fieldValue = ExtractField(item, page, field, index); if (fieldValue != null) { dataObject.Add(field.Name, fieldValue); } } var result = dataObject.Children().Any() ? dataObject : null; if (result != null) { foreach (var targetUrl in EntityMetadata.Entity.TargetUrls) { Dictionary <string, dynamic> extras = new Dictionary <string, dynamic>(); if (targetUrl.Extras != null) { foreach (var extra in targetUrl.Extras) { extras.Add(extra, result.GetValue(extra)); } } Dictionary <string, dynamic> allExtras = new Dictionary <string, dynamic>(); foreach (var extra in page.Request.Extras.Union(extras)) { allExtras.Add(extra.Key, extra.Value); } var value = result.GetValue(targetUrl.PropertyName); if (value != null) { page.AddTargetRequest(new Request(value.ToString(), page.Request.NextDepth, allExtras)); } } } return(result); }
private static JArray GetRings(JObject j) { JArray jArrayRet = null; JEnumerable <JToken> t = j.Children(); if (j.Count >= 1) { foreach (KeyValuePair <string, JToken> JToken in j) { if (JToken.Key == "rings") { return((JArray)JToken.Value); } if (JToken.Value.Type == JTokenType.Array) { JArray jArray = (JArray)JToken.Value; foreach (JToken JToken2 in jArray) { jArrayRet = GetRings(((Newtonsoft.Json.Linq.JObject)(JToken2))); if (jArrayRet != null) { return(jArrayRet); } } } else if (JToken.Value.Type == JTokenType.Object) { jArrayRet = GetRings(((Newtonsoft.Json.Linq.JObject)(JToken.Value))); if (jArrayRet != null) { return(jArrayRet); } } } } return(jArrayRet); }
/// <summary> /// Loads hub data values. /// </summary> /// <param name="strLightsIP"></param> /// <param name="strUser"></param> /// <param name="iBulbCount"></param> //private void Load(IPAddress strLightsIP, string strUser, int iBulbCount) //{ // m_strLightsIP = strLightsIP; // m_strUser = strUser; // List<int> listIDs = new List<int>(); // for (int i = 0; i < iBulbCount; ++i) // { // m_listLightStates.Add(new LightState()); // listIDs.Add(i); // } // // Add the all set. Don't call the standard method for all lights so there isn't any accidents if there are more lights than the program knows about. // LightGroup group = new LightGroup(0, "All", listIDs.ToArray()); // m_listLightGroup.Add(group); // ResetAllBulbs(); // m_updateTimer.Elapsed += Update; // m_updateTimer.Start(); //} /// <summary> /// Initializes the light states /// </summary> public void Init() { string response = MakeLightRequest("/api/" + m_strUser, "GET"); JObject jobject = JObject.Parse(response); foreach (var topChild in jobject.Children()) { if (topChild.Type == JTokenType.Property && ((JProperty)topChild).Name.Equals("lights")) { if (topChild.Children().Count() != 1) { logger.Log("I don't understand the Hue Bridge response!. Quitting"); return; } var lightList = topChild.Children().First(); foreach (var light in lightList.Children()) { LightState lstate = new LightState(); lstate.Index = int.Parse(((JProperty)light).Name); if (light.Children().Count() != 1) { logger.Log("I don't understand the Hue Bridge response for light object!. Quitting"); return; } var lightDetails = light.Children().First(); lstate.Name = lightDetails["name"].ToString(); lstate.ParseState(lightDetails["state"]); m_listLightStates.Add(lstate); } } } }
private Dictionary <string, Extension> DeserializeExtensions(GLTFRoot root, JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartObject) { throw new GLTFParseException("GLTF extensions must be an object"); } JObject extensions = (JObject)JToken.ReadFrom(reader); var extensionsCollection = new Dictionary <string, Extension>(); foreach (JToken child in extensions.Children()) { if (child.Type != JTokenType.Property) { throw new GLTFParseException("Children token of extensions should be properties"); } JProperty childAsJProperty = (JProperty)child; string extensionName = childAsJProperty.Name; ExtensionFactory extensionFactory; if (_extensionRegistry.TryGetValue(extensionName, out extensionFactory)) { extensionsCollection.Add(extensionName, extensionFactory.Deserialize(root, childAsJProperty)); } else if (extensionName.Equals(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME)) { extensionsCollection.Add(extensionName, _KHRExtensionFactory.Deserialize(root, childAsJProperty)); } else if (extensionName.Equals(ExtTextureTransformExtensionFactory.EXTENSION_NAME)) { extensionsCollection.Add(extensionName, _TexTransformFactory.Deserialize(root, childAsJProperty)); } else { extensionsCollection.Add(extensionName, _defaultExtensionFactory.Deserialize(root, childAsJProperty)); } } return(extensionsCollection); }
private JObject jsonflusher(JObject jsonObject) { JObject newJsonObject = new JObject(); JProperty property; foreach (var token in jsonObject.Children()) { if (token != null) { property = (JProperty)token; if (property.Value.Children().Count() == 0) { newJsonObject.Add(property.Name.Replace(" ", ""), property.Value); } else if (property.Value.GetType().Name == "JArray") { JArray myjarray = new JArray(); foreach (var arr in property.Value) { if (arr.ToString() != "[]") { if (arr.GetType().Name == "JValue") { myjarray.Add(arr); } else { myjarray.Add(jsonflusher((JObject)arr)); } } } newJsonObject.Add(property.Name, myjarray); } else if (property.Value.GetType().Name == "JObject") { newJsonObject.Add(property.Name.Replace(" ", ""), jsonflusher((JObject)property.Value)); } } } return(newJsonObject); }
private static void ParseTopics(Article article, string responseBody) { JObject dynamicResult = (JObject)Newtonsoft.Json.Linq.JObject.Parse(responseBody); var topics = new List <string>(); var tags = new List <string>(); foreach (JToken token in dynamicResult.Children()) { if (token is JProperty) { var prop = token as JProperty; if (prop != null) { var values = prop.Children()["_typeGroup"].Values(); if (values.Count() > 0) { var value = values.FirstOrDefault(); if (value != null && value.Value <string>() == "topics") { var name = prop.Children()["name"].Values().FirstOrDefault().Value <string>(); topics.Add(name); } if (value != null && value.Value <string>() == "socialTag") { var name = prop.Children()["name"].Values().FirstOrDefault().Value <string>(); tags.Add(name); } } } } } article.tags = tags; article.topics = topics; if (article.lctags == null) { article.lctags = new List <string>(); } article.lctags.AddRange(tags.Select(x => x.ToLower())); article.lctags.AddRange(topics.Select(x => x.ToLower())); }
/// <summary> /// Verify if one entry passed this rule /// </summary> /// <param name="entry">One entry object</param> /// <returns>true if rule passes; false otherwise</returns> private bool?VerifyOneEntry(JObject entry, HashSet <string> builtInTypes, List <string> qualitifiedAlias, List <string> qualitifiedNamespace, ODataVersion version = ODataVersion.V4) { if (entry == null || entry.Type != JTokenType.Object) { return(null); } bool? passed = null; string jPropValue = string.Empty; var jProps = entry.Children(); foreach (JProperty jProp in jProps) { if (jProp.Name.Contains(Constants.V4OdataType) && this.IsPrimitiveType(jProp)) { jPropValue = version == ODataVersion.V3 ? jProp.Value.ToString().StripOffDoubleQuotes() : Constants.EdmDotPrefix + jProp.Value.ToString().StripOffDoubleQuotes().TrimStart('#'); if (!builtInTypes.Contains(jPropValue)) { passed = null; if ((this.IsContainsSpecialStrings(qualitifiedAlias, jProp.Value.ToString().StripOffDoubleQuotes()) || this.IsContainsSpecialStrings(qualitifiedNamespace, jProp.Value.ToString().StripOffDoubleQuotes()) && Uri.IsWellFormedUriString(jProp.Value.ToString().StripOffDoubleQuotes().TrimStart('#'), UriKind.RelativeOrAbsolute))) { passed = true; } else { passed = false; break; } } } } return(passed); }
public IHttpActionResult AddJobCard(JObject jsonBody) { JObject materials = (JObject)jsonBody["MaterialsInJobCard"]; // this variable must be present in the javascript JObject products = (JObject)jsonBody["ProductsInJobCard"]; // this variable must be present in the javascript jsonBody.Remove("MaterialsInJobCard"); jsonBody.Remove("ProductsInJobCard"); JobCard jobCard = jsonBody.ToObject <JobCard>(); // the job card object db.JobCards.Add(jobCard); db.SaveChanges(); // save the shit int jobCardId = jobCard.JobCardId; // the foregin key to be used for the -> material in job Cards // Adding materials in job card to table JEnumerable <JToken> materialsJson = (JEnumerable <JToken>)materials.Children <JToken>(); foreach (JToken token in materialsJson) { JToken materialJson = token.Children().First(); MaterialInJobCard materialInstance = materialJson.ToObject <MaterialInJobCard>(); materialInstance.JobCardId = jobCardId; db.MaterialInJobCards.Add(materialInstance); } // Adding products in job card to table JEnumerable <JToken> productsJson = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in productsJson) { JToken productJson = token.Children().First(); ProductInJobCard productInstance = productJson.ToObject <ProductInJobCard>(); productInstance.JobCardId = jobCardId; db.ProductInJobCard.Add(productInstance); } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }
public CompareStruct CompareStruct(JObject originalObject, JObject newObject) { CompareStruct resultStruct = new CompareStruct(); if (originalObject == null && newObject == null) { throw new Exception("Not supported type"); } if (originalObject == null) { foreach (var childNode in newObject.Children()) { var property = childNode as JProperty; string name = property.Name; var value = property.Value; resultStruct.Fields.Add(name, Compare(null, newObject[name])); } } else if (newObject == null) { foreach (var childNode in originalObject.Children()) { var property = childNode as JProperty; string name = property.Name; var value = property.Value; resultStruct.Fields.Add(name, Compare(value, null)); } } else { foreach (var childNode in originalObject.Children()) { var property = childNode as JProperty; string name = property.Name; var value = property.Value; resultStruct.Fields.Add(name, Compare(value, newObject[name])); } } return(resultStruct); }
private JObject ProcessSingle(Page page, ISelectable item, Entity entityDefine, int index) { JObject dataObject = new JObject(); foreach (var field in entityDefine.Fields) { var fieldValue = ExtractField(item, page, field, index); if (fieldValue != null) { dataObject.Add(field.Name, fieldValue); } } var stopping = entityDefine.Stopping; if (stopping != null) { var field = entityDefine.Fields.First(f => f.Name == stopping.PropertyName); var datatype = field.DataType; bool isEntity = VerifyIfEntity(datatype); if (isEntity) { throw new SpiderExceptoin("Can't compare with object."); } stopping.DataType = datatype.ToString().ToLower(); string value = dataObject.SelectToken($"$.{stopping.PropertyName}")?.ToString(); if (string.IsNullOrEmpty(value)) { page.MissTargetUrls = true; } else { if (stopping.NeedStop(value)) { page.MissTargetUrls = true; } } } return(dataObject.Children().Count() > 0 ? dataObject : null); }
public IHttpActionResult Login([FromBody] JObject parameters) { List <JProperty> properties = null; string userName; string password; try { //Getting parameters values properties = parameters.Children().Cast <JProperty>().ToList(); userName = properties.Where(p => p.Name == "userName").FirstOrDefault()?.Value?.ToString(); password = properties.Where(p => p.Name == "password").FirstOrDefault()?.Value?.ToString(); } catch { //returning error response return(Content(HttpStatusCode.BadRequest, "Invalid input parameters")); } try { LoginResult o = new LoginResult(); User tmpUser; //Searching for such user if ((tmpUser = users?.Where(u => u.Username == userName && u.Password == password).FirstOrDefault()) != null) { //If the user is found we will return success response o.UserId = tmpUser.Id; return(Ok(o)); } //Returning error response, because no such user exists or wrong password is entered return(Content(HttpStatusCode.BadRequest, "Invalid username or password")); } catch (Exception) { //returning error response return(Content(HttpStatusCode.InternalServerError, "Unknown error")); } }
private void SetJsonTimeOrDecmail(JObject obj) { foreach (var item in obj.Children()) { if (item is JObject) { SetJsonTimeOrDecmail((JObject)item); } else if (item is JProperty) { JProperty jProperty = (JProperty)item; SetValue(jProperty); if (jProperty.Value.GetType() == typeof(JObject)) { SetJsonTimeOrDecmail((JObject)jProperty.Value); } else if (jProperty.Value.GetType() == typeof(JArray)) { try { var jArraies = ((JArray)jProperty.Value).AsJEnumerable(); foreach (var jToken in jArraies) { SetJsonTimeOrDecmail((JObject)jToken); } } catch (Exception ex) { //SuperGMS.Log.GrantLogTextWriter.Write(ex); var jArraies = ((JArray)jProperty.Value).GetEnumerator(); var jProp = (JProperty)jArraies; if (jProp?.Value != null) { JObject js = (JObject)jProp.Value; SetJsonTimeOrDecmail(js); } } } } } }
public void GenericCollectionAdd() { var o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.Equal(1, (int)o["PropertyNameValue"]); Assert.Equal(1, o.Children().Count()); }
public void GenericDictionaryAdd() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.Equal(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.Equal(2, o.Children().Count()); }
public void GenericCollectionCopyTo() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.Equal(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.Equal(default(KeyValuePair<string, JToken>), a[0]); Assert.Equal("PropertyNameValue", a[1].Key); Assert.Equal(1, (int)a[1].Value); Assert.Equal("PropertyNameValue2", a[2].Key); Assert.Equal(2, (int)a[2].Value); Assert.Equal("PropertyNameValue3", a[3].Key); Assert.Equal(3, (int)a[3].Value); Assert.Equal(default(KeyValuePair<string, JToken>), a[4]); }
public void GenericDictionaryContains() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.Equal(true, contains); }
public void GenericCollectionContains() { JValue v = new JValue(1); var o = new JObject(); o.Add("PropertyNameValue", v); Assert.Equal(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.Equal(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.Equal(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.Equal(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.Equal(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.Equal(false, contains); }
public void GenericCollectionClear() { var o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.Equal(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.Equal(0, o.Children().Count()); Assert.Equal(null, p.Parent); }