public static Tuple <string, string> FetchAgencyImage(JObject majorSegment, JArray agencies) { var segmentAgencies = majorSegment["agencies"] as JArray; if (segmentAgencies == null) { return(new Tuple <string, string>(string.Empty, string.Empty)); } var index = (int)segmentAgencies.ElementAt(0)["agency"]; var agencyName = (string)agencies.ElementAt(index)["name"]; var agencyUrl = new Uri((string)agencies.ElementAt(index)["url"]).Host.Replace("www.", ""); agencyUrl = FixAgencyUrls(agencyUrl); var fixedUrl = ClearbitNoLogo(agencyUrl); if (!string.IsNullOrWhiteSpace(fixedUrl)) { return(new Tuple <string, string>(agencyName, fixedUrl)); } using (var client = new WebClient()) { var url = $"https://autocomplete.clearbit.com/v1/companies/suggest?query={agencyUrl}"; var companiesArray = JArray.Parse(client.DownloadString(url)); return(new Tuple <string, string>(agencyName, companiesArray.Any() ? (string)companiesArray[0]["logo"] + "?size=220" : "www.rome2rio.com/" + (string)agencies.ElementAt(index)["icon"]["url"])); } }
private static Segment HandleAirSegment(JObject segment, JArray airlines, JArray places, JArray vehicles) { var indicativePrices = segment["indicativePrices"] as JArray; var pLow = indicativePrices != null ? (int?)indicativePrices[0]["priceLow"] : 0; var pHigh = indicativePrices != null ? (int?)indicativePrices[0]["priceHigh"] : 0; var vehicleJson = (JObject)vehicles.ElementAt((int)segment["vehicle"]); var kind = (string)vehicleJson["kind"]; var duration = (int)segment["transitDuration"] + (int)segment["transferDuration"]; var distance = (double)segment["distance"]; var tuple = RoutesHandler.FetchAirlineImage(segment, airlines); var image = tuple.Item2; var segName = tuple.Item1; var from = (string)((JObject)places.ElementAt((int)segment["depPlace"]))["shortName"]; var to = (string)((JObject)places.ElementAt((int)segment["arrPlace"]))["shortName"]; pLow = pLow ?? 0; pHigh = pHigh ?? 0; int?price = 0; if (pLow == 0 && pHigh == 0) { price = indicativePrices != null ? (int?)indicativePrices[0]["price"] : 0; } return(new AirSegment(segName, from, to, (int)pLow, (int)pHigh, duration, distance, image, "", kind, price ?? 0)); }
public static string GetCoinOfTheWeek() { string JSONString = HTTPMethod.Get("https://api.coinmarketcap.com/v1/ticker/?limit=100"); JArray Array = JArray.Parse(JSONString); int Index = -1; double BiggestChange = 0; for (int i = 0; i < 100; i++) { double Change24HoursComparison = (double)Array.ElementAt(i)["percent_change_7d"]; if (Change24HoursComparison > BiggestChange) { Index = i; BiggestChange = Change24HoursComparison; } } if (Index == -1) { return("Coin not found."); } JObject JObj = (JObject)Array.ElementAt(Index); string Coin = (string)JObj["name"]; string Change7Days = (string)JObj["percent_change_7d"]; string UpOrDown = ((Func <string>)(() => { if (Double.Parse(Change7Days) < 0) { return("down"); } return("up"); }))(); return($"This weeks coin of of the week is {Coin}.\n\nIt's gone {UpOrDown} by {Change7Days} percent in the last 7 days!"); }
public bool GetBlackListFromConfig() { try { using (System.IO.StreamReader file = System.IO.File.OpenText(ProcConfigPath)) { using (JsonTextReader reader = new JsonTextReader(file)) { JObject o = (JObject)JToken.ReadFrom(reader); if (o.ContainsKey("BlackList")) { JArray ja = ((JArray)o["BlackList"]); for (int i = 0; i < ja.Count; i++) { string procName = ((JObject)(ja.ElementAt(i)))["name"].ToString(); long memLimit = Convert.ToInt64(((JObject)(ja.ElementAt(i)))["memLimit"].ToString()); BlackProcDict.Add(procName, memLimit); } } else { Console.WriteLine("黑名单为空"); } return(true); } } } catch (Exception exp) { Console.WriteLine("读取黑名单进程异常,异常为:" + exp.Message); return(false); } }
public static BloqueoTarjetaModel FromJsonArray(JArray array) { try { return(new BloqueoTarjetaModel() { Tarjetas = ChooseTarjetaItem.FromJsonArray((JArray)array.ElementAt(0)), TiposBloqueos = ChooseTipoBloqueoItem.FromJsonArray((JArray)array.ElementAt(1)) }); } catch { return(null); } }
public override void InnerRun(Dictionary <string, object> vars, Dictionary <string, object> outputVars, Dictionary <string, object> InvertedInputVars, Message message) { try { // get index var indexParam = vars["Index"]; int index = indexParam is JValue ? ((JValue)indexParam).ToObject <int>() : Convert.ToInt32(indexParam); // get value if (vars["List"] is JArray) { JArray list = (JArray)vars["List"]; outputVars["Result"] = list.ElementAt(index); } else { List <Object> list = (List <Object>)vars["List"]; outputVars["Result"] = list.ElementAt(index); } outputVars["Error"] = false; } catch (Exception) { outputVars["Error"] = true; outputVars["Result"] = null; } }
public static async void GetTrendingGIF(Channel channel) { using (var client = new HttpClient()) { try { string response = await client.GetStringAsync(string.Format("http://api.giphy.com/v1/gifs/trending?api_key={0}&limit={1}" , Bot.Config.GiphyAPIKey , Bot.Config.GiphySearchLimit)); var requestObject = Newtonsoft.Json.Linq.JObject.Parse(response); var dataString = requestObject.GetValue("data").ToString(); JArray dataObject = Newtonsoft.Json.Linq.JArray.Parse(dataString); var arrayString = dataObject.ElementAt(Supporter.GetRandom(Bot.Config.GiphySearchLimit)).ToString(); var arrayObject = Newtonsoft.Json.Linq.JObject.Parse(arrayString); var imagesString = arrayObject.GetValue("images").ToString(); var imagesObject = Newtonsoft.Json.Linq.JObject.Parse(imagesString); var fixedHeightString = imagesObject.GetValue("fixed_height").ToString(); var fixedHeightObject = Newtonsoft.Json.Linq.JObject.Parse(fixedHeightString); string gifURL = fixedHeightObject.GetValue("url").ToString(); await channel.SendMessage(gifURL); } catch (Exception e) { Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "GetTrendingGIF()")); } } }
private SGCategoryAxis GetJSONCategoryAxis(Dictionary <string, object> file) { SGCategoryAxis x_axis = new SGCategoryAxis(); x_axis.Title = Convert.ToString(jo_parsed_file["encoding"]["x"]["axis"]["title"]); // STUBBED x_axis.Origin = 0.0; x_axis.Width = 500; x_axis.PosX = 1; x_axis.PrimaryCategoryType = CategoryUnit.MONTH; x_axis.CategoriesTypeAxis = TypeAxis.CONTINUOS; x_axis.Categories = new List <String>(); // empty list of categories string x_axis_labels_str = Convert.ToString(jo_parsed_file["encoding"]["x"]["scale"]["labels"]); object x_axis_labels = JsonConvert.DeserializeObject(x_axis_labels_str); JArray labels_array = (JArray)x_axis_labels; // Add each categoryto our list of categories foreach (var category in labels_array.Children()) { x_axis.Categories.Add(category.Value <string>()); } x_axis.StartsAt = x_axis.Categories.First(); x_axis.EndsAt = x_axis.Categories.Last(); x_axis.Stepping = Convert.ToString((Double)labels_array.ElementAt(1) - (Double)labels_array.ElementAt(0)); return(x_axis); }
/// <summary> /// Method for getting all the RunIDs for a specific Project and Specific to Milestone /// </summary> /// <param name="MilestoneId"></param> /// <returns></returns> public List <string> GetRunIdsForProjectAndMileStone(String MilestoneId) { string ProjectId = GetProjectID(); Gurock.TestRail.APIClient client = GetTestRailClientConfig(); JArray response = null; List <string> runs = new List <string>(); try { response = (JArray)client.SendGet("get_runs/" + ProjectId); for (int i = 0; i < response.LongCount(); i++) { JObject sections = (JObject)response.ElementAt(i); Object milestone_id = sections.GetValue("milestone_id"); if (milestone_id != null) { if (sections.GetValue("milestone_id").ToString().Equals(MilestoneId)) { runs.Add(sections.GetValue("id").ToString()); continue; } } } } catch (Exception ex) { _testRailUtilsLog.Error(ex); } return(runs); }
string[] InlineLookupFields(JArray lookupParams) { if (lookupParams == null) { return(null); } string inlineLookupFields = ""; for (int lkpIdx = 0; lkpIdx < lookupParams.Count; lkpIdx++) { JObject lkp = (JObject)lookupParams.ElementAt(lkpIdx); inlineLookupFields += ((inlineLookupFields.Length != 0 ? "," : "") + lkp["displayField"].ToString()); // split sub lookup field list and add to inlineLookupFields collection string[] dspSubArr = (lkp["displayFieldSub"].ToString()).Split(SQLJoinChars.ARGUMENTS_SEPARATOR); if (dspSubArr.Length != 0) { for (int dspSubIdx = 0; dspSubIdx < dspSubArr.Length; dspSubIdx++) { string dspFld = dspSubArr[dspSubIdx].Trim(); if (dspFld == "") { continue; } inlineLookupFields += "," + dspFld; } } } return(inlineLookupFields.Split(SQLJoinChars.ARGUMENTS_SEPARATOR)); }
public static string PegarVenda(string idVenda, string canal) { string retorno = "Fail"; try { string response = Vivo.Common.Before.Main.PegarVenda(idVenda, canal); Newtonsoft.Json.Linq.JObject result = Newtonsoft.Json.Linq.JObject.Parse(response); string value = result.GetValue("codigo").ToString(); if (value != "0") { retorno = response; } else if (value == "0") { Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("vendaJson", response); JArray dataReader = JArray.Parse(ORM.DBConnection.ExecuteReader("operador_Virtual.addVenda_PendAut", null, parameters)); JObject dbResponse = dataReader.ElementAt(0).ToObject <JObject>(); retorno = dbResponse["idVenda"].ToString(); } } catch (Exception err) { retorno = retorno + err; } return(retorno); }
public static Dictionary <string, object> JSONStringToMap(string JSONString) { object JObject = JsonConvert.DeserializeObject(JSONString); if (JObject.GetType().Equals(typeof(JArray))) { JArray ObjList = (JArray)JObject; Dictionary <string, object> ArrayMap = new Dictionary <string, object>(); List <Dictionary <string, object> > Array = new List <Dictionary <string, object> >(); for (int i = 0; i < ObjList.Count; i++) { JToken Element = ObjList.ElementAt(i); // Gui.App.Controls.CustomConsole.Write("element to String " + Element.ToString()); Dictionary <string, object> ElementMap = JSONStringToMap(Element.ToString()); Array.Add(ElementMap); } ArrayMap.Add("Array", Array); return(ArrayMap); } else { JObject JSONObj = (JObject)JObject; Gui.App.Controls.CustomConsole.WriteLine("==========BEGIN::JSONObject to MAP======="); Dictionary <string, object> Dict = new Dictionary <string, object>(); foreach (JProperty key in JSONObj.Properties()) { Gui.App.Controls.CustomConsole.WriteLine(key.Name.ToString() + "-> " + key.Value + " | " + key.Value.GetType()); Dict.Add(key.Name, key.Value); } Gui.App.Controls.CustomConsole.WriteLine("==========END::JSONObject to MAP======="); return(Dict); } }
public static string PendenciarVenda(string idVenda, string canal, string idPendencia) { string retorno = "Fail"; //Carregando Pendencia Pendencia pendencia = new Pendencia(); pendencia = Pendencia.getPendencia(idPendencia); //Chamando método da dll commmon JObject response = JObject.Parse(Vivo.Common.Before.Main.PendenciarVenda(idVenda, canal, pendencia.api, pendencia.observacao)); try { retorno = response["dados"]["mensagem"].ToString(); Dictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("idVenda", idVenda); parameters.Add("canal", canal); parameters.Add("status", pendencia.api); parameters.Add("idPendencia", idPendencia); parameters.Add("motivo", pendencia.observacao); JArray dbResponse = JArray.Parse(ORM.DBConnection.ExecuteReader("operador_Virtual.registraPendencia_PendAut", null, parameters)); JObject dbParser = dbResponse.ElementAt(0).ToObject <JObject>(); retorno = retorno + "idPendencia: " + dbParser["idPendencia"].ToString(); } catch { retorno = retorno + response["mensagem"].ToString(); } return(retorno); }
void Awake() { beatData = JObject.Parse(beatTimingsForSong.text); //Loop over all the timings and store the beat data! float bpm = float.Parse(beatData["rhythm"]["bpm"].ToString()); Debug.Log("BPM: " + bpm); //Debug.Log(((JArray)beatData["lowlevel"]["barkbands_kurtosis"]).Count); //Debug.Log(((JArray)beatData["rhythm"]["beats_loudness"]).Count); JArray bpmLoudness = (JArray)beatData["rhythm"]["beats_loudness"]; JArray bpmTimings = (JArray)beatData["rhythm"]["beats_position"]; for (int i = 0; i < bpmLoudness.Count; i++) { timings.Add(new BeatTiming( float.Parse(bpmTimings.ElementAt(i).ToString()), float.Parse(bpmLoudness.ElementAt(i).ToString()))); } //Get the first time and set it as the first amount! timer = timings.First().timing; loudness = timings.First().loudness; //Debug.Log(beatData["lowlevel"]["average_loudness"]); //JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]"); //Debug.Log(acme.ToString()); }
/// <summary> /// Method for getting all the Test Cases for a Project for all the suites /// </summary> /// <returns></returns> public Dictionary <string, string> GetAllTestCasesFromAllSuites() { Gurock.TestRail.APIClient client = GetTestRailClientConfig(); string ProjectId = GetProjectID(); List <string> SuiteIds = GetAllSuiteIds(); Dictionary <string, string> AllTestCases = new Dictionary <string, string>(); try { foreach (string SuiteId in SuiteIds) { _testRailUtilsLog.Info("===fetching test cases for suite:=>" + SuiteId); JArray response = (JArray)client.SendGet("get_cases/" + ProjectId + "&suite_id=" + SuiteId); for (int i = 0; i < response.LongCount(); i++) { JObject Case = (JObject)response.ElementAt(i); AllTestCases.Add(Case.GetValue("id").ToString(), Case.GetValue("title").ToString()); } } } catch (Exception ex) { _testRailUtilsLog.Error(ex); } return(AllTestCases); }
/// <summary> /// Reads an array of doubles and creates a Position object /// </summary> /// <param name="reader"></param> /// <param name="objectType"></param> /// <param name="existingValue"></param> /// <param name="serializer"></param> /// <returns></returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // This is an array of doubles JArray token = JArray.Load(reader); double longitude = token.ElementAt(0).ToObject <double>(serializer); double latitude = token.ElementAt(1).ToObject <double>(serializer); double elevation = double.NaN; if (token.Count == 3) { elevation = token.ElementAt(2).ToObject <double>(serializer); } return(new Position(longitude, latitude, elevation)); }
public async override Task <OtimizacaoRota> obterOtimizacaoRota(Local[] locais) { List <String> enderecos = new List <string>(); foreach (var local in locais) { enderecos.Add(prepararEndereco(local)); } using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://www.mapquestapi.com/directions/v2/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsJsonAsync("optimizedroute?key=" + key, new { locations = enderecos }); if (response.IsSuccessStatusCode) { dynamic resultado = await response.Content.ReadAsAsync <dynamic>(); float distanciaTotal = ((float)resultado.route.distance) * coeficienteConversãoKm; JArray sequencia = resultado.route.locationSequence; int[] sequenciaReordenada = new int[sequencia.Count]; int i = 0; foreach (var indice in sequencia) { sequenciaReordenada[i] = (int)indice; i++; } JArray trechos = resultado.route.legs; float[] distanciasTrechos = new float[trechos.Count]; for (int t = 0; t < trechos.Count; t++) { float distanciaTrecho; dynamic trecho = trechos.ElementAt(t); distanciaTrecho = ((float)trecho.distance) * coeficienteConversãoKm; distanciasTrechos[t] = distanciaTrecho; } OtimizacaoRota o = new OtimizacaoRota() { DistanciasTrechos = distanciasTrechos, DistanciaTotal = distanciaTotal, SequenciaLocais = sequenciaReordenada }; return(o); } } return(null); }
private async Task callAPI() { UserDialogs.Instance.ShowLoading("Please wait...", MaskType.Black); try { var astros = new List <Astro>(); HttpClient client = new HttpClient(); var uri = new Uri("http://mobixapp.com/loto_canada_api/Api/getAllQuebec_Astro"); var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); var responseJson = JsonConvert.DeserializeObject(content); JArray output = JArray.Parse(responseJson.ToString()); for (int i = 0; i < output.Count; i++) { string n1 = output.ElementAt(i)["n1"].ToString(); string n2 = output.ElementAt(i)["n2"].ToString(); string n3 = output.ElementAt(i)["n3"].ToString(); string n4 = output.ElementAt(i)["n4"].ToString(); string tirage_du = output.ElementAt(i)["tirage_du"].ToString(); astros.Add(new Astro { n1 = n1, n2 = n2, n3 = n3, n4 = n4, tirage_du = tirage_du }); } listView.ItemsSource = astros; UserDialogs.Instance.HideLoading(); } } catch (Exception ex) { UserDialogs.Instance.HideLoading(); await DisplayAlert("Error", "An error has occurred, please try again.", "OK"); //Debug.WriteLine(@"ERROR {0}", ex.Message); } }
public async Task <bool> PublishAsync(JArray events) { if (events == null || events.Count == 0) { return(true); } //Build the POST body of the request var body = new JObject(); try { var loglines = new JArray(); for (var i = 0; i < events.Count; i++) { var eventToPublish = events.ElementAt(i); if (eventToPublish != null) { var trackingInfo = new JObject { { CODE, AILTN } }; var data = new JObject(); var schemaType = eventToPublish[InstrumentationEvent.SCHEMA_TYPE_KEY]; data.Add(InstrumentationEvent.SCHEMA_TYPE_KEY, schemaType); var property = eventToPublish.Children <JProperty>() .FirstOrDefault(p => p.Name == InstrumentationEvent.SCHEMA_TYPE_KEY); property?.Remove(); data.Add(PAYLOAD, eventToPublish.ToString(Newtonsoft.Json.Formatting.None)); trackingInfo.Add(DATA, data); loglines.Add(trackingInfo); } } body.Add(LOG_LINES, loglines); } catch (Exception ex) { return(false); } var path = string.Format(API_PATH, ApiVersionStrings.VersionNumber); var headers = new Dictionary <string, string>(); var request = new RestRequest(HttpMethod.Post, path, body.ToString(Newtonsoft.Json.Formatting.None), ContentTypeValues.Gzip, headers); var restClient = SDKManager.GlobalClientManager.PeekRestClient(); var response = await restClient.SendAsync(request); if (response.Success) { return(true); } return(false); }
private void loadHullPrefabInfosAndWeaponDict() { TextAsset jsonText = Resources.Load("PartPrefabConfs") as TextAsset; JObject root = JObject.Parse(jsonText.text); foreach (var info in root.Value <JObject>("hulls")) { string name = info.Key; JObject jObj = (JObject)info.Value; GameObject hullPrefab = prefabDict[jObj.Value <string>("hull")]; GameObject wheelPrefab = prefabDict[jObj.Value <string>("wheels")]; float wheelOffset = jObj.Value <float>("wheel_offset"); Dictionary <string, Vector2> jetOffsets = new Dictionary <string, Vector2>(); foreach (var val in jObj.Value <JObject>("jet_offsets")) { Vector2 vec = new Vector2(); JArray arr = (JArray)val.Value; vec.x = (float)arr.ElementAt(0); vec.y = (float)arr.ElementAt(1); jetOffsets.Add(val.Key, vec); } nameToHullPrefabInfo.Add(name, new HullPrefabInfo(hullPrefab, wheelPrefab, wheelOffset, jetOffsets)); } foreach (var info in root.Value <JObject>("weapons")) { string name = info.Key; GameObject prefab = prefabDict[(string)info.Value]; nameToPrefabDict.Add(name, prefab); } }
public static Tuple <string, string> FetchAirlineImage(JObject majorSegment, JArray airlines) { var hops = (JArray)((JArray)majorSegment["outbound"]).ElementAt(0)["hops"]; var index = (int)hops.ElementAt(0)["airline"]; var airlineName = (string)airlines.ElementAt(index)["name"]; var airlineCode = (string)airlines.ElementAt(index)["code"]; var fixedUrl = FixAirlineUrls(airlineCode); if (!string.IsNullOrEmpty(fixedUrl)) { return(new Tuple <string, string>(airlineName, fixedUrl)); } using (var client = new WebClient()) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; var companiesArray = JArray.Parse(client.DownloadString($"https://autocomplete.clearbit.com/v1/companies/suggest?query={airlineName}")); return(new Tuple <string, string>(airlineName, companiesArray.Any() ? (string)companiesArray[0]["logo"] + "?size=220" : $"http://pics.avs.io/200/200/{airlineCode}.png")); } }
/// <summary> /// Method for getting All the test cases which is under a Project and a Suite /// </summary> /// <returns>Dictionary<string,string></returns> public Dictionary <string, string> GetAllTestCases() { Gurock.TestRail.APIClient client = GetTestRailClientConfig(); string ProjectId = GetProjectID(); string SuiteId = GetSuiteId(); Dictionary <string, string> AllTestCases = new Dictionary <string, string>(); JArray response = (JArray)client.SendGet("get_cases/" + ProjectId + "&suite_id=" + SuiteId); for (int i = 0; i < response.LongCount(); i++) { JObject Case = (JObject)response.ElementAt(i); AllTestCases.Add(Case.GetValue("id").ToString(), Case.GetValue("title").ToString()); } return(AllTestCases); }
} // end of Start function // updates Host movement void updateHost(int arrayNumber) { if (arrayNumber < hostSpeed.Count) { if (prevMainCount == arrayNumber) { shouldMove = false; } else { shouldMove = true; zeroSpeed = (float)hostSpeed.ElementAt <JToken>(arrayNumber); // get host speed float convertedSpeed = (float)Math.Ceiling((float)zeroSpeed / 4.0f * 9.0f); speedText.GetComponent <Text>().text = convertedSpeed.ToString(); } prevMainCount = arrayNumber; } } // end of update host function
public static async void GetGIF(string keyword, Channel channel) { using (var client = new HttpClient()) { try { string response = await client.GetStringAsync(string.Format("http://api.giphy.com/v1/gifs/search?q={0}&api_key={1}&limit={2}" , keyword , Bot.Config.GiphyAPIKey , Bot.Config.GiphySearchLimit)); var requestObject = Newtonsoft.Json.Linq.JObject.Parse(response); var dataString = requestObject.GetValue("data").ToString(); JArray dataObject = Newtonsoft.Json.Linq.JArray.Parse(dataString); if (dataObject.Count == 0) { await channel.SendMessage(string.Format("There are no results for **{0}** :(" , keyword)); return; } var arrayString = dataObject.ElementAt(Supporter.GetRandom(dataObject.Count)).ToString(); var arrayObject = Newtonsoft.Json.Linq.JObject.Parse(arrayString); var imagesString = arrayObject.GetValue("images").ToString(); var imagesObject = Newtonsoft.Json.Linq.JObject.Parse(imagesString); var fixedHeightString = imagesObject.GetValue("fixed_height").ToString(); var fixedHeightObject = Newtonsoft.Json.Linq.JObject.Parse(fixedHeightString); string gifURL = fixedHeightObject.GetValue("url").ToString(); await channel.SendMessage(string.Format("**#{0}**\r\n{1}" , keyword , gifURL)); } catch (Exception e) { if (e.Message.Equals("Sequence contains no elements") || e.Message.Equals("Die Sequenz enthält keine Elemente") || e.Data.ToString() == "System.Collections.ListDictionaryInternal") { return; } Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "GetGIF()", keyword)); } } }
/// <summary> /// 对应AddArrayItem()。key不存在返回长度为零的array /// </summary> /// <param name="key"></param> /// <returns></returns> public JsonString[] GetArray(string key) { JArray items = (JArray)GetObject(key); if (items == null) { return(new JsonString[0]); } if (items.Count == 0) { return(new JsonString[0]); } JsonString[] ret = new JsonString[items.Count]; for (int i = 0; i < items.Count; i++) { Dictionary <string, object> dic = items.ElementAt(i).ToObject <Dictionary <string, object> >(); ret[i] = new JsonString(dic); } return(ret); }
/// <summary> /// Method for all the Projects Name and their unique IDs for TestRail Client. /// </summary> /// <returns></returns> public Dictionary <string, string> GetAllProjects() { Gurock.TestRail.APIClient client = GetTestRailClientConfig(); Dictionary <string, string> AllProjects = new Dictionary <string, string>(); try { JArray response = (JArray)client.SendGet("get_projects"); for (int i = 0; i < response.LongCount(); i++) { JObject project = (JObject)response.ElementAt(i); AllProjects.Add(project.GetValue("id").ToString(), project.GetValue("name").ToString()); } } catch (Exception ex) { _testRailUtilsLog.Error(ex); } return(AllProjects); }
/// <summary> /// Method for getting all the TestRuns for Certain ProjectID /// </summary> /// <param name="ProjectId"></param> /// <returns></returns> public Dictionary <string, string> GetAllRunsForAProject(string ProjectId) { Gurock.TestRail.APIClient client = GetTestRailClientConfig(); Dictionary <string, string> AllRuns = new Dictionary <string, string>(); try { JArray response = (JArray)client.SendGet("get_runs/" + ProjectId + ""); for (int i = 0; i < response.LongCount(); i++) { JObject Run = (JObject)response.ElementAt(i); AllRuns.Add(Run.GetValue("id").ToString(), Run.GetValue("name").ToString()); } } catch (Exception ex) { _testRailUtilsLog.Error(ex); } return(AllRuns); }
public ActionResult GetContactWithContactKey(string tenantKey, string authToken, string contactName) { JArray contactArray = (JArray)HLGetRequest(tenantKey, authToken, "api/v1.0/Contacts/GetMyContacts"); List <string> contactList = new List <string>(); foreach (JObject j in contactArray) { contactList.Add(j.Property("FirstName").Value + " " + j.Property("LastName").Value); } ViewData["contacts"] = contactList; JObject first = (JObject)contactArray.First; if (contactName == null) { ViewData["contactKey"] = first.Properties().ElementAt <JProperty>(2).Value; } else { int index = contactList.IndexOf(contactName); JObject contact; if (index == -1) { contact = first; } else { contact = (JObject)contactArray.ElementAt <JToken>(index); } ViewData["contactKey"] = contact.Properties().ElementAt <JProperty>(2).Value; } JObject results = (JObject)HLGetRequest(tenantKey, authToken, "api/v1.0/Contacts/GetContact?contactKey=" + ViewData["contactKey"]); if (results != null) { ViewData["results"] = results; ViewData["getContact"] = JsonConvert.SerializeObject(results, Formatting.Indented); return(View()); } return(RedirectToAction("UserSignIn", "Domain", new { preView = "GetContactWithContactName" })); }
/// <summary> /// Method for getting all the Test Case IDs for a particular Test Run /// </summary> /// <param name="RunId"></param> /// <returns></returns> public List <String> getCaseIdsForRun(String RunId) { Gurock.TestRail.APIClient client = GetTestRailClientConfig(); List <String> caseIds = new List <String>(); JArray response = null; try { response = (JArray)client.SendGet("get_tests/" + RunId); for (int i = 0; i < response.LongCount(); i++) { JObject obj = (JObject)response.ElementAt(i); caseIds.Add(obj.GetValue("case_id").ToString()); } } catch (Exception ex) { _testRailUtilsLog.Error(ex); } return(caseIds); }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedIndex >= 0) { int index = listBox1.SelectedIndex; place_holder_bell_lable.Visible = false; listBox2.Visible = true; listBox2.Items.Clear(); int[] arr = new int[6]; JObject temp = (JObject)jarray.ElementAt(index); int i = 0; foreach (int x in temp.GetValue("days")) { if (x != 0) { listBox2.Items.Add(Enum.Parse(typeof(Data_Manipulation.DaysOfWeek), i.ToString())); } i++; } } }