private IEnumerable <ISkillFact> ParseSkillFacts(JArray facts) { return (facts? .Children() .Select(x => _skillFactFactory.CreateFact(x)) .ToArray()); }
/// <summary> /// Converts the injested data into a collection of the specified <see cref="Type"/>. /// </summary> /// <param name="name">The name of the node that constains the items.</param> /// <param name="replaceAllShorthandGuids">Indicates whether to recursively replaces all '^n' values where 'n' is an integer with n.ToGuid() equivalent.</param> /// <param name="initializeCreatedChangeLog">Indicates whether to set the <see cref="ChangeLog.CreatedBy"/> and <see cref="ChangeLog.CreatedDate"/> where <typeparamref name="T"/> implements <see cref="IChangeLog"/>.</param> /// <param name="initializeReferenceData">Indicates where to set the </param> /// <param name="itemAction">An action to allow further updating to each item.</param> /// <returns>The corresponding collection.</returns> public IEnumerable <T> Convert <T>(string name, bool replaceAllShorthandGuids = true, bool initializeCreatedChangeLog = true, bool initializeReferenceData = true, Action <JObject, int, T> itemAction = null) where T : class, new() { Check.NotEmpty(name, nameof(name)); var json = _json?.Children().OfType <JObject>()?.Children().OfType <JProperty>().Where(x => x.Name == name)?.FirstOrDefault()?.Value; if (json == null || json.Type != JTokenType.Array) { return(default);
private List <string> getUsernamesWithList(JArray response) { List <string> handles = new List <string>(); JArray responseArray = response; foreach (JObject o in responseArray.Children <JObject>()) { foreach (JProperty p in o.Properties()) { string name = p.Name; string value = (string)p.Value; if (name == "username") { handles.Add(value); } } } return(handles); }
//set up environment public static void Init() { //load json to create dictionary string json = System.IO.File.ReadAllText("..\\..\\verbs-dictionaries.json"); JsonSerializer serializer = new JsonSerializer(); JArray values = JsonConvert.DeserializeObject <JArray>(json); foreach (var item in values.Children()) { dict.Add((string)item[0], (string)item[3]); } // Path to models extracted from `stanford-parser-3.9.1-models.jar` jarRoot = "D:\\MSRA\\Txt2Vis\\Parser\\nlp.stanford.edu\\stanford-corenlp-full-2018-02-27"; modelsDirectory = jarRoot + "\\edu\\stanford\\nlp\\models"; // We should change current directory, so StanfordCoreNLP could find all the model files automatically var curDir = Environment.CurrentDirectory; System.IO.Directory.SetCurrentDirectory(jarRoot); }
internal async Task <List <HomeAssistentEntity> > GetEntities() { if (_cachedEntitites == null) { var json = await GetStates(); JArray states = JArray.Parse(json); //_cachedDomains = new List<HomeAssistentDomain>(); _cachedEntitites = new List <HomeAssistentEntity>(); foreach (var state in states.Children <JObject>()) { var e = new HomeAssistentEntity(); e.EntityId = state["entity_id"].Value <string>(); e.FriendlyName = state["attributes"]?["friendly_name"]?.Value <string>(); _cachedEntitites.Add(e); // var s = service; // var entity = new HomeAssistentDomain(); // entity.Domain = service["domain"].Value<string>(); // //var sservices = service["services"].Values(); // var sservices = service["services"]; // //var x = sservices.Children(); // foreach (var child in sservices.Value<JObject>()) // { // HomeAssistentDomainFeature feature = new HomeAssistentDomainFeature(); // feature.Name = child.Key; // feature.Description = ""; // entity.AddFeature(feature); // } // _cachedDomains.Add(entity); } } return(_cachedEntitites); }
public IEnumerator login() { string send = "{ \"Email\": \"" + user + "\", \"Password\": \"" + pass + "\", \"RememberMe\": \"false\" }"; Debug.Log(send); byte[] myData = System.Text.Encoding.UTF8.GetBytes(send); UnityWebRequest www = UnityWebRequest.Put("https://cis174gamewebsite.azurewebsites.net/api/user/login", myData); www.SetRequestHeader("Content-Type", "application/json"); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.LogError(www.error); Error("Login Failed. Please try again."); } else { Debug.Log("Upload complete!"); errorText.text = ""; string json = www.downloadHandler.text; JArray parsedArray = JArray.Parse(json); foreach (JObject parsedObject in parsedArray.Children <JObject>()) { foreach (JProperty parsedProperty in parsedObject.Properties()) { string propertyName = parsedProperty.Name; if (propertyName.Equals("id")) { string propertyValue = (string)parsedProperty.Value; UserId = propertyValue; Debug.Log(UserId); break; } } } SceneManager.LoadScene("main"); } }
public virtual string ExecuteHtml(string viewTemplate, string json) { string date = $"{DateTime.Now:dd.MM.yy HH:mm:ss}"; TemplateServiceConfiguration templateConfig = new TemplateServiceConfiguration(); templateConfig.DisableTempFileLocking = true; templateConfig.CachingProvider = new DefaultCachingProvider(t => { }); //templateConfig.Namespaces.Add("PagedList"); var serv = RazorEngineService.Create(templateConfig); Engine.Razor = serv; Engine.Razor.Compile(viewTemplate, "somekey"); JArray jObj = JArray.Parse(json); List <string> headers = new List <string>(); foreach (JProperty p in JObject.Parse(jObj.First.ToString()).Properties()) { headers.Add(p.Name); } List <List <string> > content = new List <List <string> >(); foreach (JObject j in jObj.Children <JObject>()) { List <string> prop = new List <string>(); foreach (JProperty p in j.Properties()) { prop.Add(p.Value.ToString()); } content.Add(prop); } // var pagedList = content.ToPagedList(2,3); var model = new { Headers = headers, Content = content, Date = date }; return(Engine.Razor.Run("somekey", null, model)); }
/// <summary> /// Returns the ZipSettings from a Stream /// </summary> /// <param name="stream">The stream with the ZipSettings</param> /// <returns>A ZipSettings object</returns> public static ZipSettings FromStream(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { try { string jsonstr = reader.ReadToEnd(); ZipSettings zs = new ZipSettings(); JObject obj = JsonConvert.DeserializeObject <JObject>(jsonstr); JArray foldersarray = obj.Value <JArray>("Subfolders"); foreach (JObject subdir in foldersarray.Children <JObject>()) { SubFolder sub = new SubFolder(); foreach (var dict in subdir) { sub.Name = dict.Key; foreach (JToken token in dict.Value.Children <JToken>().ToList()) { Utils.ZipType ztype = Utils.FileOrDir(token.Value <string>()); if (ztype == Utils.ZipType.File) { sub.Files.Add(token.Value <string>()); } else if (ztype == Utils.ZipType.Directory) { sub.Directories.Add(token.Value <string>()); } } } zs.Subfolders.Add(sub); } return(zs); } catch (Exception ex) { MainWindow.Instance.WriteLog("There was an error while reading the ZipSettings! => " + ex.Message); return(null); } } }
public List <User> ObtenerUsers() { List <User> list = new List <User>(); User user = new User(); List <SqlParameter> _Parametros = new List <SqlParameter>(); try { sql.PrepararProcedimiento("dbo.[USER.GetAllJSON]", _Parametros); DataTableReader dtr = sql.EjecutarTableReader(CommandType.StoredProcedure); if (dtr.HasRows) { while (dtr.Read()) { var Json = dtr["Usuario"].ToString(); if (Json != string.Empty) { JArray arr = JArray.Parse(Json); foreach (JObject jsonOperaciones in arr.Children <JObject>()) { list.Add(new User() { ID = Convert.ToInt32(jsonOperaciones["Id"].ToString()), FirstName = jsonOperaciones["Name"].ToString(), CreateDate = DateTime.Parse(jsonOperaciones["CreateDate"].ToString()) }); } } } } }catch (SqlException sqlEx) { throw new Exception(sqlEx.Message, sqlEx); } catch (Exception ex) { throw new Exception(ex.Message, ex); } return(list); }
private static void parseJSON(string A, string B, List <KeyValuePair <string, string> > jsonlist) { jsonlist.Add(new KeyValuePair <string, string>(A, B)); if (B.StartsWith("[")) { JArray arr = null; try { arr = JArray.Parse(B); } catch { return; } foreach (var i in arr.Children()) { parseJSON("", i.ToString(), jsonlist); } } if (B.Contains("{")) { JObject obj = null; try { obj = JObject.Parse(B); } catch { return; } foreach (var o in obj) { parseJSON(o.Key, o.Value.ToString(), jsonlist); } } }
private void HandleAzureStorageInsert(string value) { try { JArray items = JArray.Parse(value); int rows = 0; foreach (var json in items.Children()) { try { StorageTwitterItem item = new StorageTwitterItem(); item.Path = eventHubClient.Path; item.RowKey = string.Concat(Guid.NewGuid().ToString(), "-", json["id"].Value <string>()); item.Id = json["id"].Value <string>(); item.PartitionKey = json["id"].Value <string>(); item.Text = json["text"].Value <string>(); item.CreatedAt = json["created_at"].Value <DateTime>(); item.UserId = json["userid"].Value <string>(); item.ProfileImageUrl = json["profile_image_url"].Value <string>(); item.UserName = json["name"].Value <string>(); item.Source = json["source"].Value <string>(); TableOperation insertOperation = TableOperation.Insert(item); table.Execute(insertOperation); rows++; } catch (Exception jsonException) { Trace.WriteLine(jsonException.ToString()); Trace.WriteLine(json); } } Trace.WriteLine(string.Format("Azure Storage rows inserted {0}", rows), "Information"); } catch (Exception eX) { Trace.WriteLine(eX.ToString()); Trace.WriteLine(value); } }
public void Shift_API_Thread(string URI) { RestRequest request; request = new RestRequest(URI, Method.GET); request.AddHeader("Content-type", "application/json"); request.AddHeader("User-Agent", user_agent); request.RequestFormat = DataFormat.Json; var response = client.Execute(request); JArray obj = JArray.Parse(response.Content); if (obj.Count > 0) { foreach (JObject o in obj.Children <JObject>()) { Shifts ajout = new Shifts(); try { ajout.Id = (string)o["id"]; ajout.Full = (bool)o["full"]; ajout.Debut = (DateTime)o["starts_at"]; ajout.Fin = (DateTime)o["ends_at"]; if (gestion_interval.Check_Shift_In_Interval(ajout, listInterval) && !ajout.Full) { if (!list_shifts.Exists(x => x.Id == ajout.Id)) { list_shifts.Add(ajout); shiftComplet = false; } } } catch (Exception) { } } } }
public async Task <JsonResult> AddItem([FromBody] PurchaseReturnOrder pro) { try { try { if (string.IsNullOrEmpty(pro.ItemNo)) { return(await _purchaseReturnOrderLogic.SendRespose("False", "Blank Item No").ConfigureAwait(false)); } JArray item_info = await _purchaseReturnOrderLogic.AddItem(pro).ConfigureAwait(false); JObject jo = item_info.Children <JObject>().FirstOrDefault(o => o["condition"] != null); if (jo.Value <string>("condition") == "True") { decimal cost_per_unit, gst_percentage; cost_per_unit = jo.Value <decimal>("cost_per_unit"); gst_percentage = jo.Value <decimal>("gst_percentage"); jo.Add(new JProperty("quantity", pro.Quantity)); jo.Add(new JProperty("amount_without_tax", decimal.Round((cost_per_unit * pro.Quantity), 2))); jo.Add(new JProperty("gst_amount", decimal.Round((jo.Value <decimal>("amount_without_tax") * gst_percentage) / 100, 2))); jo.Add(new JProperty("amount_with_tax", decimal.Round(jo.Value <decimal>("amount_without_tax") + jo.Value <decimal>("gst_amount"), 2))); JArray response = new JArray(jo); return(new JsonResult(response)); } else { return(new JsonResult(item_info)); } } catch (Exception ee) { return(await _purchaseReturnOrderLogic.SendRespose("False", ee.Message).ConfigureAwait(false)); } } catch (Exception ee) { return(await _purchaseReturnOrderLogic.SendRespose("False", ee.Message).ConfigureAwait(false)); } }
public void TransformMaskedAndConditional() { JToken source = GetJSONObject(@"JSON\Source\nestedNested.json"); JToken transform = GetJSONObject(@"JSON\Transform\maskedAndConditional.json"); JToken result = Transformer.TransformJSON(source, transform); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(JArray)); JArray resultArray = ((JArray)result); Assert.AreEqual(resultArray.Count, 2); bool passingThere = false; bool failingThere = false; foreach (JToken entry in resultArray.Children()) { Assert.IsInstanceOfType(entry, typeof(JObject)); JObject child = (JObject)entry; if (child["passing"] != null) { if (((string)child["passing"]["item"]) == "questionPassing") { passingThere = true; Assert.AreEqual("How are you doing?", (string)child["passing"]["text"]); } } if (child["failing"] != null) { failingThere = true; } } Assert.IsTrue(passingThere); Assert.IsFalse(failingThere); }
public static void Read(string filename = "") { Entries.Clear(); if (String.IsNullOrEmpty(filename)) { string executable = System.Reflection.Assembly.GetEntryAssembly().Location; filename = Path.GetDirectoryName(executable) + "\\" + LocalFilename; if (!File.Exists(filename)) { return; } } if (!Helper.IsFileValid(filename)) { return; } using (FileStream stream = File.Open(filename, FileMode.Open)) { using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); JArray entries = (JArray)JsonConvert.DeserializeObject(json); if (entries == null) { return; } foreach (JToken token in entries.Children()) { WulinshuRaymonfAPIEntry entry = new WulinshuRaymonfAPIEntry { Path = token.SelectToken("Path").Value <string>(), Hash = token.SelectToken("Hash").Value <string>(), Matches = token.SelectToken("Matches").Value <int>(), Game = token.SelectToken("Game").Value <string>() }; Entries.Add(entry); } } } }
internal static IEnumerable <int> GetListPersonAliasIds(string apiKey, int listId, int listCount) { var personAliasIds = new List <int>(); int page = 1; for ( ; listCount > 0; listCount -= 1000) { var parameters = new Dictionary <string, string> { { "page_size", "1000" }, { "page", page.ToString() } }; var response = CreatePersonListRequest(apiKey, listId, Method.GET, null, parameters); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Unable to fetch list people " + response.Content); } dynamic payload = JObject.Parse(response.Content); dynamic listPeople = payload.recipients; foreach (var person in listPeople) { JArray customFields = person.custom_fields; JObject personAliasField = customFields.Children <JObject>() .FirstOrDefault(o => o["name"] != null && o["name"].ToString() == "person_alias_id"); if (personAliasField?["value"] != null && !string.IsNullOrWhiteSpace(personAliasField["value"].ToString())) { string personAlisFieldValue = personAliasField["value"].ToString(); int personAliasId; bool succesfulParse = int.TryParse(personAlisFieldValue, out personAliasId); if (succesfulParse) { personAliasIds.Add(personAliasId); } } } listCount = listCount - 1000; page++; } return(personAliasIds); }
/// <summary>Returns whether the given array contains each of the patterns specified in the 'expected' array in order.</summary> /// <returns>True if matching, false otherwise</returns> /// <remarks>The 'expected' array contains a list of elements that are searched in the actual array /// The actual array can have more elements. The order of elements in the 'actual' array must /// match the order found in the expected array</remarks> private static bool CompareArraysInOrder(JArray expected, JArray actual) { int currentExpectedIndex = 0; int currentActualIndex = 0; JToken[] expectedChildren = expected.Children().ToArray(); JToken[] actualChildren = actual.Children().ToArray(); while (currentExpectedIndex < expectedChildren.Length) { JToken expectedMember = expectedChildren[currentExpectedIndex]; bool foundMatching = false; while (currentActualIndex < actualChildren.Length) { JToken actualMember = actualChildren[currentActualIndex]; if (!CompareObjects(expectedMember.Value <object>(), actualMember.Value <object>(), ignoreOrder: false)) { currentActualIndex++; } else { foundMatching = true; break; } } if (!foundMatching) { return(false); } currentActualIndex++; currentExpectedIndex++; } return(true); }
private Hanzi parseHanzi(JArray jsonChar) { Hanzi hanzi = new Hanzi { Char = jsonChar[0].ToObject <string>()[0], StrokeCount = jsonChar[1].ToObject <int>(), SubStrokes = new List <SubStroke>(), }; JArray jsonSubStrokes = jsonChar[2] as JArray; foreach (var x in jsonSubStrokes.Children()) { JArray jsonSS = x as JArray; SubStroke ss = new SubStroke { Dir = jsonSS[0].ToObject <double>(), Len = jsonSS[1].ToObject <double>(), }; hanzi.SubStrokes.Add(ss); } return(hanzi); }
public override List <BaseValidatorRule> ReadJson(JsonReader reader, Type objectType, List <BaseValidatorRule> existingValue, bool hasExistingValue, JsonSerializer serializer) { JsonSerializerSettings settings = ValidatorRulesSerializationSettings.GetSettings(); if (reader.TokenType == JsonToken.StartArray) { JArray arrayEntry = JArray.Load(reader); int count = arrayEntry.Count; List <BaseValidatorRule> ruleList = new List <BaseValidatorRule>(count); foreach (JObject item in arrayEntry.Children()) { string jsonString = item.ToString(); BaseValidatorRule rule = JsonConvert.DeserializeObject <BaseValidatorRule>(jsonString, settings); ruleList.Add(rule); } return(ruleList); } return(null); }
static void createFiles() { JObject o1 = JObject.Parse(File.ReadAllText(@"C:\Users\john\Documents\Visual Studio 2017\Projects\CreateChunckedAlphabetizedCityLists\CreateChunckedAlphabetizedCityLists\TextFile1.txt")); string[] alphabet = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; foreach (var alpha in alphabet) { // read JSON directly from a file using (StreamReader file = File.OpenText(@"C:\Users\joselowpc\Documents\Visual Studio 2017\Projects\CreateChunckedAlphabetizedCityLists\CreateChunckedAlphabetizedCityLists\TextFile1.txt")) { using (JsonTextReader reader = new JsonTextReader(file)) { JObject o2 = (JObject)JToken.ReadFrom(reader); foreach (var obj in o2) { JArray array = JArray.Parse(obj.Value.ToString()); string buildFile = "["; foreach (JObject content in array.Children <JObject>()) { foreach (JProperty prop in content.Properties()) { string myVal = prop.Value.ToString(); if (myVal.StartsWith(alpha)) { buildFile += "{citystate:'" + prop.Value.ToString() + "'},"; } //Console.WriteLine(prop.Value); //Console.WriteLine(prop.Name); } } buildFile += "]"; //remove last comma from created file buildFile = buildFile.Remove(buildFile.Length - 2, 1); File.WriteAllText(@"C:\Users\john\Documents\Visual Studio 2017\Projects\CreateChunckedAlphabetizedCityLists\CreateChunckedAlphabetizedCityLists\AlphaFilter\" + alpha + "States.txt", buildFile); } } } } }
// Busca cliente em cliente.detalhes por email e retorna id. Retorna -1 se não encontrado. private int get_cliente_id(SqlConnection connection, string email) { StringBuilder get_cliente_id_str = new StringBuilder(); get_cliente_id_str.Append("SELECT cliente.detalhes.cliente_id as id "); get_cliente_id_str.Append("FROM cliente.detalhes "); get_cliente_id_str.Append("WHERE cliente.detalhes.cliente_email = @email "); get_cliente_id_str.Append("FOR JSON PATH"); SqlCommand input_command = new SqlCommand(get_cliente_id_str.ToString(), connection); SqlParameter input_nome = input_command.Parameters.Add("@email", System.Data.SqlDbType.VarChar); input_nome.Value = email; SqlDataReader reader = input_command.ExecuteReader(); StringBuilder sb = new StringBuilder(); while (reader.Read()) { sb.Append(reader.GetString(0)); } reader.Close(); JArray result = JArray.Parse(sb.ToString()); foreach (JObject result_obj in result.Children <JObject>()) { foreach (JProperty result_property in result_obj.Properties()) { Debug.WriteLine(result_property.Name + " | " + (string)result_property.Value); if (result_property.Name == "id") { return((int)result_property.Value); } } } return(-1); }
public List <ShoppingCart> getShoppingCart(int id_user) { List <ShoppingCart> list = new List <ShoppingCart>(); List <SqlParameter> _Parametros = new List <SqlParameter>(); try{ _Parametros.Add(new SqlParameter("@Id", id_user)); sql.PrepararProcedimiento("dbo.[ShoppingCart.GetJSONByIdUser]", _Parametros); DataTableReader dtr = sql.EjecutarTableReader(CommandType.StoredProcedure); if (dtr.HasRows) { while (dtr.Read()) { var Json = dtr["ShoppingCart"].ToString(); if (Json != string.Empty) { JArray arr = JArray.Parse(Json); foreach (JObject jsonOperaciones in arr.Children <JObject>()) { list.Add(new ShoppingCart { ID_Product = Convert.ToInt32(jsonOperaciones["ID_Product"].ToString()), Quantity = Convert.ToInt32(jsonOperaciones["Quantity"].ToString()) }); } } } } } catch (SqlException sqlEx) { throw new Exception(sqlEx.Message, sqlEx); } catch (Exception ex) { throw new Exception(ex.Message, ex); } return(list); }
private void button3_Click(object sender, EventArgs e) { Path = @"D:\Work\Phd\Data Sciences\rumoureval-2019-training-data\rumoureval-2019-training-data\twitter-english"; GetDir(Path); foreach (string s in paths) { string text = File.ReadAllText(s); JArray parsedArray = JArray.Parse(text); foreach (JObject parsedObject in parsedArray.Children <JObject>()) { foreach (JProperty parsedProperty in parsedObject.Properties()) { string propertyName = parsedProperty.Name; if (propertyName.Equals("p")) { string propertyValue = (string)parsedProperty.Value; Console.WriteLine("Name: {0}, Value: {1}", propertyName, propertyValue); } } } } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject obj = JObject.Load(reader); IDictionary <K, V> dict = (IDictionary <K, V>)Activator.CreateInstance(objectType); foreach (PropertyInfo prop in GetReadWriteProperties(objectType)) { JToken token = obj[prop.Name]; object val = token != null?token.ToObject(prop.PropertyType, serializer) : null; prop.SetValue(dict, val); } JArray array = (JArray)obj["KVPs"]; foreach (JObject kvp in array.Children <JObject>()) { K key = kvp["Key"].ToObject <K>(serializer); V val = kvp["Value"].ToObject <V>(serializer); dict.Add(key, val); } return(dict); }
public static void parseHotKeys() { hotKeys = new HotKeyDict(); JArray keys_arr = JArray.Parse(Properties.Settings.Default.HotKeys); foreach (JObject obj in keys_arr.Children <JObject>()) { KeyPair key_pairs = new KeyPair(); JArray key_pairs_tmp = (JArray)obj["key_pairs"]; foreach (int key in key_pairs_tmp) { key_pairs.Add((Keys)key); } ConfigClass.CommandType _type; if (!Enum.TryParse(obj["type"].ToString(), out _type)) { continue; } hotKeys.Add(key_pairs.GetHashCode(), new ConfigClass(obj["name"].ToString(), key_pairs, _type , obj["exe_file"].ToString(), obj["exe_arg"].ToString(), (Keys)((int)obj["target_key"]), obj["cmd_line"].ToString())); } }
public void Get_User_Gorgeade() { user_agent = username; try { client_w.Authenticator = new HttpBasicAuthenticator(cle_client, secret_client); var request = new RestRequest("wp-json/wc/v1/customers?email=" + username + "&consumer_key=" + cle_client + "&consumer_secret=" + secret_client + "&role=all", Method.GET); var response = client_w.Execute(request); JArray obj = JArray.Parse(response.Content); foreach (JObject o in obj.Children <JObject>()) { id_customer = (string)o["id"]; } Ajout_Log("User Shiftbot recuperer"); } catch { Ajout_Text(false, "Mauvais identifiants ShiftBot.fr"); } }
public SearchResult[] GetAutocompleteResults(string search) { if (search.IsNullOrWhiteSpace()) { return(new SearchResult[0]); } var searchResults = new List <SearchResult>(); using (var webClient = new WebClient()) { string suggestionJson = webClient.DownloadString("http://suggestqueries.google.com/complete/search?client=firefox&q=" + Uri.EscapeDataString(search)); JArray suggestions = (JArray)JsonConvert.DeserializeObject <object[]>(suggestionJson)[1]; foreach (string suggestion in suggestions.Children <JToken>().Select(x => x.ToString()).Except(new[] { search }).Distinct()) { searchResults.Add(new SearchResult(suggestion, 0, new StringIndexable(suggestion), ImmutableHashSet.Create <int>())); } } return(searchResults.ToArray()); }
private void launchWithNKHook() { //Auto download latest nkhook exe <3 ~DisabledMallis ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; WebClient client = new WebClient(); client.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0"); //spoof using firefox so we dont get 403 forbidden error JArray parsedArray = JArray.Parse(client.DownloadString("https://api.github.com/repos/DisabledMallis/NKHook5/releases")); string downloadLink = ""; JObject o = parsedArray.Children <JObject>().First(); foreach (JProperty p in o.Properties()) { string name = p.Name; if (name == "assets") { JObject assets = p.Value.Children <JObject>().First(); foreach (JProperty np in assets.Properties()) { string dlname = np.Name; if (dlname == "browser_download_url") { downloadLink = np.Value.ToString(); } } } } PrintToConsole("\nDownloading latest version of NKHook"); client.DownloadFile(downloadLink, livePath + "\\NKHook5.exe"); try { Process.Start(livePath + "\\NKHook5.exe"); PrintToConsole("\nLaunching NKHook"); } catch (System.ComponentModel.Win32Exception) { PrintToConsole("\nNKHook was cancelled..."); } }
public async Task <IList <Location> > GetLocations(string searchString, ApiSettings apiSettings) { string url = BuildUri(searchString, apiSettings); var response = await _httpClient.GetAsync(url); string apiResponseText = await response.Content.ReadAsStringAsync(); JArray apiResponse = JArray.Parse(apiResponseText); IList <JToken> results = apiResponse.Children().ToList(); IList <Location> locations = new List <Location>(); foreach (JToken result in results) { Location location = new Location(); location.LocationKey = result.Value <string>("Key"); location.LocationName = result.Value <string>("EnglishName"); locations.Add(location); } return(locations); }
private void BuildObjectStatusesConditional(JObject conditionalObject) { Main.LogDebug("[BuildObjectStatusesConditional] Building 'ObjectStatusesConditional' conditional"); bool notInContractObjectivesAreSuccesses = conditionalObject.ContainsKey("NotInContractObjectivesAreSuccesses") ? (bool)conditionalObject["NotInContractObjectivesAreSuccesses"] : true; JArray statusesArray = (JArray)conditionalObject["Statuses"]; Dictionary <string, ObjectiveStatusEvaluationType> statuses = new Dictionary <string, ObjectiveStatusEvaluationType>(); foreach (JObject status in statusesArray.Children <JObject>()) { string childGuid = status["Guid"].ToString(); string childStatus = status["Status"].ToString(); ObjectiveStatusEvaluationType childStatusType = (ObjectiveStatusEvaluationType)Enum.Parse(typeof(ObjectiveStatusEvaluationType), childStatus); statuses.Add(childGuid, childStatusType); } ObjectiveStatusesConditional conditional = ScriptableObject.CreateInstance <ObjectiveStatusesConditional>(); conditional.NotInContractObjectivesAreSuccesses = notInContractObjectivesAreSuccesses; conditional.Statuses = statuses; conditionalList.Add(new EncounterConditionalBox(conditional)); }
public void Children() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.AreEqual(4, a.Count()); Assert.AreEqual(3, a.Children<JArray>().Count()); }