// Retrieves all bus stops that contain a given route with route short name // Returns a tuple of the route and the associated stops in a 1800-meter radius public (Route, List <Stop>) FindStopsForRoute(string routeShortName, string json) { JObject jobject = JObject.Parse(json); if (jobject["code"].ToString() == "200") { JEnumerable <JToken> routes = jobject["data"]["references"]["routes"].Children(); JToken targetRoute = routes.FirstOrDefault(x => x["shortName"].ToString() == routeShortName); if (targetRoute != null) { Route route = targetRoute.ToObject <Route>(); JEnumerable <JToken> stops = jobject["data"]["list"].Children(); List <Stop> stopsForRoute = new List <Stop>(); foreach (JToken s in stops) { JToken routeIds = s["routeIds"]; foreach (JToken rId in routeIds) { if (rId.ToString() == route.Id) { stopsForRoute.Add(s.ToObject <Stop>()); stopsForRoute.Add(s.ToObject <Stop>()); } } } return(route, stopsForRoute); } } return(null, null); }
public IHttpActionResult RequestQuotation(JObject jsonBody) { // set quotations status to request // add Request for Quotation JObject products = (JObject)jsonBody["ProductsInQuotation"]; // this variable must be present in the javascript jsonBody.Remove("ProductsInQuotation"); Quotation quotation = jsonBody.ToObject <Quotation>(); // the job card object\ quotation.Status = "Request"; db.Quotations.Add(quotation); db.SaveChanges(); // save the shit int quotationId = quotation.QuotationId; // the foregin key to be used for the -> products JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInQuotation productInstance = productJson.ToObject <ProductInQuotation>(); productInstance.QuotationId = quotationId; db.ProductsInQuotations.Add(productInstance); } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }
// // GET: /RabbitMQ/ public ActionResult Index() { RabbitMqQueueModel model = new RabbitMqQueueModel(); // Connect to Rabbit MQ and grab basic queue counts. HttpWebRequest request = HttpWebRequest.CreateHttp("http://localhost:15672/api/queues"); request.Credentials = new NetworkCredential(MtaParameters.RabbitMQ.Username, MtaParameters.RabbitMQ.Password); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { string json = new StreamReader(response.GetResponseStream()).ReadToEnd(); JArray rabbitQueues = JArray.Parse(json); foreach (JToken q in rabbitQueues.Children()) { JEnumerable <JProperty> qProperties = q.Children <JProperty>(); string queueName = (string)qProperties.First(x => x.Name.Equals("name")).Value; if (queueName.StartsWith("manta_mta_")) { model.Add(new RabbitMqQueue { Name = queueName, Messages = (long)qProperties.First(x => x.Name.Equals("messages")).Value, State = (string)qProperties.First(x => x.Name.Equals("state")).Value }); } } } return(View(model)); }
private static void SetCurrencies(JEnumerable <JToken> jsonCurrencies) { if (_currenciesSet) { return; } lock (_currenciesLock) { _currencies = new HashSet <Currency>(); _currencyPairs = new HashSet <CurrencyPair>(); foreach (var symbol in jsonCurrencies) { if (symbol["status"].ToObject <string>() != "TRADING") { continue; } Enum.TryParse(symbol["baseAsset"].ToObject <string>(), out Currency baseCurrency); _currencies.Add(baseCurrency); Enum.TryParse(symbol["quoteAsset"].ToObject <string>(), out Currency quoteCurrency); _currencies.Add(quoteCurrency); var currencyPair = new CurrencyPair(baseCurrency, quoteCurrency); _currencyPairs.Add(currencyPair); } _currenciesSet = true; } }
public MaxPageAndListResult <basePost> listSubPost(long pn, bool reflush = true) { JToken tiejt; if (pn > 1 || reflush) { tiejt = JSON.parse(_stbapi.sendTieba("/c/f/pb/floor", "kz=" + tid + "&pid=" + id + "&pn=" + pn, "")); } else { tiejt = pinfo; } JEnumerable <JToken> suli = tiejt["subpost_list"].Children(); List <basePost> lbc = new List <basePost>(); foreach (JToken pjt in suli) { JEnumerable <JToken> jejt = pjt["content"].Children(); List <postContent> lpc = new List <postContent>(); foreach (JToken conjte in jejt) { lpc.Add(postContent.byJtoken(conjte)); } postContent[] pce = lpc.ToArray(); lbc.Add(new basePost(new userInBar(pjt["author"]["id"].Value <long>(), pjt["author"]["name"].Value <String>(), false, 0, pjt["author"]["portrait"].Value <String>()), pce, 0, pjt["id"].Value <long>(), 0, pjt["time"].Value <long>(), "")); } return(new MaxPageAndListResult <basePost>(lbc, tiejt["page"]["total_page"].Value <long>())); }
public IHttpActionResult AddPurchaseOrder(JObject jsonBody) { JObject materials = (JObject)jsonBody["MaterialsInPurchaseOrder"]; // this variable must be present in the javascript jsonBody.Remove("MaterialsInPurchaseOrder"); PurchaseOrder purchaseOrder = jsonBody.ToObject <PurchaseOrder>(); // the job card object db.PurchaseOrder.Add(purchaseOrder); db.SaveChanges(); // save the shit int purchaseOrderId = purchaseOrder.PurchaseOrderId; // the foregin key to be used for the -> proudcts JEnumerable <JToken> tokens = (JEnumerable <JToken>)materials.Children <JToken>(); foreach (JToken token in tokens) { JToken materialsJson = token.Children().First(); MaterialInPurchaseOrder materialInstance = materialsJson.ToObject <MaterialInPurchaseOrder>(); materialInstance.PurchaseOrderId = purchaseOrderId; db.MaterialInPurchaseOrders.Add(materialInstance); } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }
public IHttpActionResult AddStocks(JObject jsonBody) { JObject products = (JObject)jsonBody["ProductsInStocks"]; // this variable must be present in the javascript jsonBody.Remove("ProductsInStocks"); ProductStocks productStocks = jsonBody.ToObject <ProductStocks>(); // the job card object\ JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInProductStocks productInstance = productJson.ToObject <ProductInProductStocks>(); // get the product and update it Product product = db.Products.Find(productInstance.ProductId); if (product == null) { return(NotFound()); } product.StocksQuantity = productInstance.QuantityRecieved + product.StocksQuantity; db.Entry(product).State = EntityState.Modified; } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }
/// <summary> /// Requesting a Quotation. /// Save Quotation information in the local database. /// Send the object to the IS to route to the Enterprise /// TODO : Authorization /// </summary> /// <param name="jsonBody"></param> /// <returns></returns> public IHttpActionResult RequestQuotation(JObject jsonBody) { using (var dbTransaction = db.Database.BeginTransaction()){ try { // Deserializing the json and gettting Quotation object JObject products = (JObject)jsonBody["ProductsInQuotation"]; // this variable must be present in the javascript jsonBody.Remove("ProductsInQuotation"); Quotation quotation = jsonBody.ToObject <Quotation>(); quotation.Status = "Request"; db.Quotations.Add(quotation); db.SaveChanges(); int quotationId = quotation.QuotationId; // saving this in a seperate variable to make the code look simple //Deserializing the object and getting Produts in Quotation JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInQuotation productInstance = productJson.ToObject <ProductInQuotation>(); productInstance.QuotationId = quotationId; db.ProductsInQuotations.Add(productInstance); } db.SaveChanges(); // lets send this to the IS Integrator integrator = new Integrator(); Setting setting = db.Settings.Find(1); //reconstructing the jsonBody to send to the IS jsonBody.Add("ProductsInQuotation", products); // adding routing information. Some of these might be usefull at the Enterprise system too. jsonBody.Add("ServiceId", setting.SystemIdNumber); jsonBody.Add("SellingEnterpriseId", jsonBody["SellingEnterpriseId"]); jsonBody.Add("BuyingEnterpriseId", jsonBody["BuyingEnterpriseId"]); HttpWebResponse response = integrator.sendJsonObject(jsonBody, "/api/Enterprises/RequestQuotation"); if (response != null && response.StatusCode != HttpStatusCode.Conflict) { dbTransaction.Commit(); return(StatusCode(response.StatusCode)); } else { dbTransaction.Rollback(); return(StatusCode(HttpStatusCode.Conflict)); } }catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex); dbTransaction.Rollback(); return(StatusCode(HttpStatusCode.Conflict)); } } }
public static List <TabPages> GetJsonList(JEnumerable <JToken> jToken, string key) { JObject jsonObj = JsonHelper.readJson(); //foreach the JObject add the value List <TabPages> tabpageindexlist = new List <TabPages>() { }; //List<string> tabpageindexlist = new List<string>(); foreach (JToken child in jToken) { if (child.Count() != 0) { string tabpageid = JsonHelper.GetJsonValue(child.Children(), "tabpageid"); string tabpagename = JsonHelper.GetJsonValue(child.Children(), "tabpagename"); int tabpageindex = int.Parse(JsonHelper.GetJsonValue(child.Children(), "tabpageindex")); tabpageindexlist.Add(new TabPages() { tabpageid = tabpageid, tabpagename = tabpagename, tabpageindex = tabpageindex }); //tabpageindexlist.Add(JsonHelper.GetJsonValue(child.Children(), "tabpageindex")); } } return(tabpageindexlist); }
/// <summary> /// Gets the breed list from the raw API response message body /// </summary> /// <param name="breedJsonArray">The object containing the breed array</param> /// <returns>List of breeds</returns> private List <Breed> GetBreedList(JObject breedJsonArray) { List <Breed> breedList = new List <Breed>(); try { foreach (JProperty breedObject in breedJsonArray.Children()) { if (breedObject != null) { Breed nextBreed = new Breed(breedObject.Name); JEnumerable <JToken> variations = breedObject.Children(); foreach (JValue variation in variations.Children()) { nextBreed.Variations.Add(new BreedVariation(variation.ToString())); } breedList.Add(nextBreed); } } return(breedList); } catch (Exception ex) { Console.WriteLine("Error: Unable generate BreedList\n{0}", ex.StackTrace); return(breedList); } }
public async Task GetAccounts_PerformsNetworkInstanceDiscovery_IfUnknownRtEnvironment_Async() { // Arrange - modify an existing account to have an unknown environment string tokenCacheAsString = File.ReadAllText( ResourceHelper.GetTestResourceRelativePath("MultiCloudTokenCache.json")); var cacheJson = JObject.Parse(tokenCacheAsString); JEnumerable <JToken> tokens = cacheJson["RefreshToken"].Children(); foreach (JToken token in tokens) { var obj = token.Children().Single() as JObject; if (string.Equals( obj["environment"].ToString(), "login.microsoftonline.de", StringComparison.InvariantCulture)) { obj["environment"] = new Uri(TestConstants.AuthorityNotKnownTenanted).Host; } } tokenCacheAsString = cacheJson.ToString(); await ValidateGetAccountsWithDiscoveryAsync(tokenCacheAsString).ConfigureAwait(false); }
/// <inheritdoc/> public override IWolfResponse Deserialize(Type responseType, SerializedMessageData responseData) { // if body contains an object that contains yet another body, means it's nested, so treat it as normal // otherwise, it's just one group, and we need to nest it deeper so this serializer works // yes. This protocol is damn stupid. "What is consistency? We don't know, unless it's consistently bad!" SerializedMessageData data = responseData; IEnumerable <JToken> nestedGroupBodies = GetResponseJson(responseData).SelectTokens("body.*.body"); if (nestedGroupBodies?.Any() != true) { JToken newJson = responseData.Payload.DeepClone(); JObject newBody = GetResponseJson(newJson).SelectToken("body") as JObject; JEnumerable <JToken> children = newBody.Children(); JObject groupBody = new JObject(); foreach (JToken obj in children) { groupBody.Add(obj); } newBody.RemoveAll(); newBody.Add(new JProperty("0", new JObject(new JProperty("body", groupBody)))); data = new SerializedMessageData(newJson, responseData.BinaryMessages); } GroupProfileResponse result = (GroupProfileResponse)base.Deserialize(responseType, data); return(result); }
public static List <T> DeserializeTokens <T>(JsonReader reader) { JObject jsonObject = JObject.Load(reader); JEnumerable <JToken> tokens = jsonObject.Children(); return(tokens.Select(token => token.First.ToObject <T>()).ToList()); }
public void SetupExpectedOutputFiles(JEnumerable <JObject> masterObjects, IPublisher publisherObject) { foreach (JObject masterObject in masterObjects) { JEnumerable <JObject> detailObjects = GetDetailedTrackingRecords(masterObject); foreach (JObject detailObject in detailObjects) { string masterId = masterObject.Property("ID").Value.ToString(); string detailId = detailObject.Property("ID").Value.ToString(); string postTransformFilepath = detailObject.Property("FilePath").Value.ToString(); try { var payLoadObject = GetPayload(postTransformFilepath); if ((payLoadObject.Stream != null) && (payLoadObject.Stream.Length > 0)) { payLoadObject.FileName = string.Format("{0}_{1}", masterId, detailId); TraceProvider.WriteLine("Executing test suit run id {0}, Setting up expected file {1}", testSuiteRunId, payLoadObject.FileName); publisherObject.Publish(payLoadObject); } } catch (Exception ex) { TraceProvider.WriteLine("Executing test suit run id {0}, error while setting up expected files {1}", testSuiteRunId, ex.Message); } } } }
internal async Task ParseAsync() { if (!File.Exists(LocalCachePath)) { return; } try { using (StreamReader reader = new StreamReader(LocalCachePath)) { string json = await reader.ReadToEndAsync(); JObject root = JObject.Parse(json); foreach (JProperty obj in root.Children <JProperty>()) { JEnumerable <JProperty> child = obj.Children <JProperty>(); ExtensionEntry entry = new ExtensionEntry { Name = obj.Name, Id = (string)root[obj.Name]["id"], MinVersion = new Version((string)root[obj.Name]["minVersion"] ?? "15.0"), MaxVersion = new Version((string)root[obj.Name]["maxVersion"] ?? "16.0") }; Extensions.Add(entry); } } } catch (Exception ex) { Debug.Write(ex); } }
private void OutputPath(JEnumerable <JToken> children) { foreach (var child in children) { if (child.Children().Any()) { OutputPath(child.Children()); } else { var message = @" { ""from"": ""{from}"", ""to"":"""" },"; if (child.Path.Contains("[")) { Console.WriteLine(RemoveArrayIndexNumbers(message.Replace("{from}", child.Path))); } else { Console.WriteLine(message.Replace("{from}", child.Path)); } } } }
private void BuildThisNode(JEnumerable <JToken> JTl) { foreach (JToken XN in JTl) { ChildNodes.Add(new JsonExtended(this, XN)); } }
public HttpResponseMessage AddOrder(JObject jsonBody) { JObject products = (JObject)jsonBody["ProductsRetailOrder"]; // this variable must be present in the javascript jsonBody.Remove("ProductsRetailOrder"); RetailSale retailOrder = jsonBody.ToObject <RetailSale>(); // the job card object retailOrder.AccountId = User.Identity.GetUserId(); db.RetailSales.Add(retailOrder); db.SaveChanges(); int retailOrderId = retailOrder.OrderId; // the foregin key to be used for the -> proudcts JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInRetailSale productInstance = productJson.ToObject <ProductInRetailSale>(); productInstance.RetailSaleId = retailOrderId; db.ProductsInRetailSales.Add(productInstance); } db.SaveChanges(); return(this.Request.CreateResponse(HttpStatusCode.Created, retailOrderId)); }
public static IList BuildIEnumerable(DeserializationContext context, Type type, JEnumerable<JToken> elements, IEnumerable<TypeMapping> typeMappings, int nestingLevel) { typeMappings = typeMappings.ToArray(); var itemType = type.GetGenericArguments().Single(); var listType = typeof(List<>).MakeGenericType(itemType); var list = (IList)Activator.CreateInstance(listType); foreach (var element in elements) { if (itemType.IsPrimitive) { var value = element as JValue; if (value != null) { list.Add(Convert.ChangeType(value.Value, itemType)); } } else if (itemType == typeof (string)) { list.Add(element.AsString()); } else { var item = CreateAndMap(context, itemType, element, typeMappings, nestingLevel + 1); list.Add(item); } } return list; }
public IHttpActionResult AddCustomerOrder(JObject jsonBody) { JObject products = (JObject)jsonBody["ProductsInCustomerOrder"]; // this variable must be present in the javascript jsonBody.Remove("ProductsInCustomerOrder"); CustomerOrder customerOrder = jsonBody.ToObject <CustomerOrder>(); // the job card object db.CustomerOrders.Add(customerOrder); db.SaveChanges(); // save the shit int CustomerOrderId = customerOrder.CustomerOrderId; // the foregin key to be used for the -> proudcts JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInCustomerOrder productInstance = productJson.ToObject <ProductInCustomerOrder>(); productInstance.CustomerOrderId = CustomerOrderId; db.ProductInCustomerOrder.Add(productInstance); } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }
/// <summary> /// /// </summary> /// <returns></returns> public List <OrderItem> GetOrderItems(JArray orderItemsJArray, string filterName = "ORDER_ITEMS") { List <OrderItem> items = new List <OrderItem>(); if (orderItemsJArray == null) { return(null); } JEnumerable <JToken> children = orderItemsJArray.Children(); List <JToken> properties = GetSubArray(children, filterName); //loop through the arrray list foreach (var property in properties) { OrderItem item = property.ToObject <OrderItem>(); //add to list array items.Add(item); } Console.WriteLine(items.Count); return(items); }
static async void MakeRequest(string imageFilePath) { var client = new HttpClient(); // Request headers - replace this example key with your valid key. client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "SUA_CHAVE_AQUI"); // // NOTE: You must use the same region in your REST call as you used to obtain your subscription keys. // For example, if you obtained your subscription keys from westcentralus, replace "westus" in the // URI below with "westcentralus". string uri = "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize?"; HttpResponseMessage response; string responseContent; string caminhoImagem = ""; using (var client2 = new WebClient()) { client2.DownloadFile(imageFilePath, "imagem.jpg"); } // Request body. Try this sample with a locally stored JPEG image. byte[] byteData = GetImageAsByteArray("imagem.jpg"); using (var content = new ByteArrayContent(byteData)) { // This example uses content type "application/octet-stream". // The other content types you can use are "application/json" and "multipart/form-data". content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(uri, content); responseContent = response.Content.ReadAsStringAsync().Result; } // A peak at the raw JSON response. //Console.WriteLine(responseContent); // Processing the JSON into manageable objects. JToken rootToken = JArray.Parse(responseContent).First; // First token is always the faceRectangle identified by the API. JToken faceRectangleToken = rootToken.First; // Second token is all emotion scores. JToken scoresToken = rootToken.Last; // Show all face rectangle dimensions JEnumerable <JToken> faceRectangleSizeList = faceRectangleToken.First.Children(); foreach (var size in faceRectangleSizeList) { Console.WriteLine(size); } // Show all scores JEnumerable <JToken> scoreList = scoresToken.First.Children(); foreach (var score in scoreList) { Console.WriteLine(score); } }
public List <AqiParam> ParseParam(byte[] data) { List <AqiParam> listParam = new List <AqiParam>(); string json = Encoding.UTF8.GetString(data); JArray ja = JArray.Parse(json); JEnumerable <JToken> je = ja.Children(); foreach (JToken j in je) { if (!(j is JObject)) { throw new DataDifferentException("与预期的数据不一致(JSON数组子元素应该是对象),可能数据源已经发生变化"); } JObject joOne = j as JObject; JToken jttf = joOne.GetValue("tfid"); if (jttf == null) { throw new DataDifferentException("与预期的数据不一致(JSON数组对象应该包含tfid属性),可能数据源已经发生变化"); } AqiParam ap = new AqiParam(jttf.ToString() + "号台风"); ap.Add("", jttf.ToString()); listParam.Add(ap); } return(listParam); }
/// <summary> /// Transforms the raw party_answer table data into an array of Party instances. /// </summary> /// <param name="objectList"></param> /// <returns></returns> public static Party[] LoadParties(JEnumerable <JObject> objectList) { List <Parties> partyList = new List <Parties>(); List <Party> results = new List <Party>(); foreach (JObject obj in objectList) { partyList.Add(obj.ToObject <Parties>()); } //x Vai pa onde com essa ideia de iterar dado multiplicado em batch? //! guess ill partyList to do it var ids = partyList.GroupBy(c => c.party_id).Select(g => g.First()).Select(x => x.party_id).ToList(); foreach (string id in ids) { var party = new Party(); var singlePartyAnswers = partyList.Where(x => x.party_id == id).ToArray(); party.party_id = singlePartyAnswers[0].party_id; party.party_name = singlePartyAnswers[0].party_name; foreach (Parties parties in singlePartyAnswers) { party.Answers.Add(parties.question_id, parties.answer); } results.Add(party); } return(results.ToArray()); }
private IList BuildList(Type type, JEnumerable <JToken> elements) { var list = (IList)Activator.CreateInstance(type); var itemType = type.GetGenericArguments()[0]; foreach (var element in elements) { if (itemType.IsPrimitive) { var value = element as JValue; if (value != null) { list.Add(value.Value.ChangeType(itemType)); } } else if (itemType == typeof(string)) { list.Add(element.AsString()); } else { var item = CreateAndMap(itemType, element); list.Add(item); } } return(list); }
public bar(BDUSS b, String kw) { this.kw = kw; String jon = _stbapi.sendTieba("/c/f/frs/page", "kw=" + _.encodeURIComponent(kw) + "&is_good=0&pn=1", b.bduss); barinfo = JSON.parse(jon); if (barinfo["error_code"].Value <int>() != 0) { throw new SeeBarField(kw, barinfo["error_code"].Value <int>(), barinfo["error_msg"].Value <String>()); } maxPage = barinfo["page"]["total_page"].Value <long>(); JEnumerable <JToken> fromgr = barinfo["forum"]["managers"].Children(); foreach (JToken jt in fromgr) { Managers.Add(new user(jt["id"].Value <long>(), jt["name"].Value <String>())); } JEnumerable <JToken> frgc = barinfo["forum"]["good_classify"].Children(); foreach (JToken jt in frgc) { gdclasses.Add(new goodclassflyItem(kw, jt["class_name"].Value <String>(), jt["class_id"].Value <Int16>())); } fid = barinfo["forum"]["id"].Value <long>(); this.sb = b; }
public static IList BuildList(DeserializationContext context, Type type, JEnumerable <JToken> elements, IEnumerable <TypeMapping> typeMappings, int nestingLevel) { typeMappings = typeMappings.ToArray(); var list = (IList)Activator.CreateInstance(type); var itemType = type .GetInterfaces() .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList <>)) .Select(i => i.GetGenericArguments().First()) .Single(); foreach (var element in elements) { if (itemType.IsPrimitive) { var value = element as JValue; if (value != null) { list.Add(Convert.ChangeType(value.Value, itemType)); } } else if (itemType == typeof(string)) { list.Add(element.AsString()); } else { var item = CreateAndMap(context, itemType, element, typeMappings, nestingLevel + 1); list.Add(item); } } return(list); }
/// <summary> /// 列出该吧所有主题 /// </summary> /// <param name="page">页数</param> /// <returns>一个basethread组成的List组</returns> public MaxPageAndListResult <basethread> listThreads(long page) { String bduss = ""; if (sb != null) { bduss = sb.bduss; } String jon = _stbapi.sendTieba("/c/f/frs/page", "kw=" + _.encodeURIComponent(kw) + "&is_good=0&pn=" + page, bduss); JObject jot = JSON.parse(jon); JEnumerable <JToken> threadlist = jot["thread_list"].Children(); List <basethread> lt = new List <basethread>(); foreach (JToken jt in threadlist) { List <userWithPic> likerList = new List <userWithPic>(); foreach (JToken t in jt["zan"]["liker_list"].Children()) { likerList.Add(new userWithPic(t["id"].Value <long>(), t["name"].Value <String>(), t["portrait"].Value <String>())); } bool isb = false; if (jt["zan"]["is_liked"] != null) { isb = jt["zan"]["is_liked"].Value <int>() > 0; } lt.Add(new basethread(jt["tid"].Value <long>(), jt["title"].Value <String>(), jt["reply_num"].Value <long>(), jt["last_time_int"].Value <long>(), (jt["is_top"] == null ? false : jt["is_top"].Value <int>() == 1), (jt["is_good"] == null ? false : jt["is_good"].Value <int>() == 1), new userWithPic(jt["author"]["id"].Value <int>(), jt["author"]["name"].Value <String>(), jt["author"]["portrait"].Value <String>()), kw, jt["zan"]["num"].Value <long>(), likerList, isb, jt["first_post_id"].Value <long>())); } return(new MaxPageAndListResult <basethread>(lt, jot["page"]["total_page"].Value <long>())); }
public static bool SetShortcutKeyJsonValue(JObject jobject, string key, string value) { try { JEnumerable <JToken> jToken = jobject["Settings"].Children(); IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken)enumerator.Current; if (jc is JObject || ((JProperty)jc).Value is JObject) { SetShortcutKeyJsonValue((JObject)jc, key, value); } else { if (((JProperty)jc).Name == key) { ((JProperty)jc).Value = value; } } } Console.WriteLine(jobject.ToString()); File.WriteAllText(jsonPath, jobject.ToString()); return(true); } catch (Exception e) { Console.WriteLine("e.Message: " + e.Message + ";e.StackTrace: " + e.StackTrace); return(false); } }
public List <basePost> listpost(long page, bool reflash = true) { JToken jo; if (page < 2 && (!reflash)) { jo = tinfo; } else { jo = JSON.parse(_stbapi.sendTieba("/c/f/pb/page", "kz=" + tid + "&pn=" + page, "")); } JEnumerable <JToken> posts = jo["post_list"].Children(); List <basePost> lbp = new List <basePost>(); foreach (JToken pt in posts) { List <postContent> pc = new List <postContent>(); JEnumerable <JToken> jecon = pt["content"].Children(); foreach (JToken conjt in jecon) { pc.Add(postContent.byJtoken(conjt)); } lbp.Add(new basePost(new userInBar(pt["author"]["id"].Value <long>(), pt["author"]["name"].Value <String>(), pt["author"]["is_like"].Value <int>() == 1, pt["author"]["level_id"].Value <int>(), pt["author"]["portrait"].Value <String>()) , pc.ToArray(), pt["floor"].Value <long>(), pt["id"].Value <long>(), pt["sub_post_number"].Value <long>(), pt["time"].Value <long>(), pt["title"].Value <String>())); } return(lbp); }
private void getChildValue(JToken j, DataTable dt) { JEnumerable <JToken> je = j.Children(); if (je.Count <JToken>() > 0) { foreach (JToken jt in je) { getChildValue(jt, dt); Console.WriteLine("HasChildren.I am " + jt.Path); } } else { //retList.Add(j.Path +":" + j.CreateReader().ReadAsString()); Regex reg = new Regex("\\[[0-9]*\\]"); String columnName = reg.Replace(j.Path, ""); if (!dt.Columns.Contains(columnName)) { dt.Columns.Add(j.Path); } DataRow dr = dt.NewRow(); dr[columnName] = j.CreateReader().ReadAsString(); } }
public void EmptyJEnumerableEquals() { JEnumerable<JToken> tokens1 = new JEnumerable<JToken>(); JEnumerable<JToken> tokens2 = new JEnumerable<JToken>(); Assert.True(tokens1.Equals(tokens2)); object o1 = new JEnumerable<JToken>(); object o2 = new JEnumerable<JToken>(); Assert.True(o1.Equals(o2)); }
public static IDictionary BuildDictionary(DeserializationContext context, Type type, JEnumerable<JToken> elements, IEnumerable<TypeMapping> typeMappings, int nestingLevel) { typeMappings = typeMappings.ToArray(); var dict = (IDictionary)Activator.CreateInstance(type); var valueType = type.GetGenericArguments()[1]; foreach (JProperty child in elements) { var key = child.Name; var item = CreateAndMap(context, valueType, child.Value, typeMappings, nestingLevel + 1); dict.Add(key, item); } return dict; }
static void StripSystemProperties(JEnumerable<JToken> children) { foreach (JToken child in children) { if (child.Type.ToString().Equals("Property")) { } else if (child.Type.ToString().Equals("Array")) { } else if (child.Type.ToString().Equals("Object")) { JObject obj = (JObject)child; obj.Remove("__permissions"); obj.Remove("__effectiveRights"); bool retVal = obj.Remove("__roles"); obj.Remove("__type"); obj.Remove("__id"); //If there was a roles object then replace it. if (retVal) { //Set contributor equal to "Everyone" on all nodes. This allows them to be updated by others later. Ideally we would preserve the contributor but that requires //a special platform to enable it. JToken contributor = JObject.Parse("{'role': 'Contributor','members': [{'objectId': '00000000-0000-0000-0000-000000000201'}]}"); JArray roles = new JArray(); roles.Add(contributor); obj.Add("__roles", roles); } if ((obj["__creatorId"] != null) && (obj["__creatorId"].ToString().Contains("@"))) { obj["__creatorId"] = "imported_" + obj["__creatorId"].ToString(); } } else { return; } StripSystemProperties(child.Children()); } }
public override void LoadFile() { // get doc size _streamReader = File.OpenText(SourceFileName); while (_streamReader.ReadLine() != null) TotalRecordCount++; // load first and last pages into cache _cache[First] = GetPageAt(DefaultStartRowIndex, PageSize); var lastPageStart = TotalRecordCount - (TotalRecordCount % PageSize == 0 ? PageSize : TotalRecordCount % PageSize); _cache[Last] = GetPageAt(lastPageStart, TotalRecordCount - lastPageStart); // instantiate the rest _cache[Next] = new JEnumerable<JObject>(); _cache[Previous] = new JEnumerable<JObject>(); _lastRequestPage = First; _refreshTask = new Task(RefreshCache); _refreshTask.Start(); }
public static IEnumerable<ResultProperty> FromJson(JEnumerable<JToken> tokens) { foreach (var token in tokens) { var property = token as JProperty; var child = token.Children().FirstOrDefault(); var value = child?.ToString(); if (String.Equals(property.Name, "_ObjectIdentity_", StringComparison.InvariantCultureIgnoreCase)) { var identity = IdentityParameter.FromIdentityString(value); yield return new ResultProperty(property.Name, identity); } else { yield return new ResultProperty(property.Name, value); } } }
private void ConstructCombox() { if (string.IsNullOrEmpty(seatAndTicketType)) { return; } try { JObject json = JObject.Parse(seatAndTicketType); seatList = json["seat_type_codes"].Children(); ticketList = json["ticket_type_codes"].Children(); } catch { } }
public void EmptyJEnumerableCount() { JEnumerable<JToken> tokens = new JEnumerable<JToken>(); Assert.AreEqual(0, tokens.Count()); }
public void EmptyJEnumerableAsEnumerable() { IEnumerable tokens = new JEnumerable<JToken>(); Assert.AreEqual(0, tokens.Cast<JToken>().Count()); }
public void EmptyJEnumerableGetHashCode() { JEnumerable<JToken> tokens = new JEnumerable<JToken>(); Assert.AreEqual(0, tokens.GetHashCode()); }
public JToken FindJObject(JEnumerable<JToken> children, string key) { foreach (var child in children) { if (child.Path.Contains(key)) return child; JEnumerable<JToken> descendants = child.Children(); if (descendants.Any()) { JToken found = FindJObject(descendants, key); if (found != null) return found; } } return null; }
public string GetJsonValue(JEnumerable<JToken> jToken, string key) { IEnumerator enumerator = jToken.GetEnumerator(); while (enumerator.MoveNext()) { JToken jc = (JToken)enumerator.Current; if (jc is JObject || ((JProperty)jc).Value is JObject) { return GetJsonValue(jc.Children(), key); } else { if (((JProperty)jc).Name == key) { return ((JProperty)jc).Value.ToString(); } } } return null; }