public async Task ReadSource(string source) { //this is not best practice! HttpClient instance should be created as singelton per source url try { System.Console.WriteLine("**** PriceUrlSourceReader scan started *** "); using (var httpClient = new HttpClient()) { var urlSourceResp = await httpClient.GetAsync(source); urlSourceResp.EnsureSuccessStatusCode(); var contentAsText = await urlSourceResp.Content.ReadAsStringAsync(); JArray arrayOfStock = (JArray)JToken.Parse(contentAsText); foreach (var token in arrayOfStock.AsJEnumerable()) { await _repo.AddStock(token.ToObject <Stock>()); // await Task.Delay(10); // for testing purpose } System.Console.WriteLine("**** PriceUrlSourceReader scan done *** "); } } catch (Exception ex) { _logger.LogError($"PriceUrlSourceReader: Couldnt read from source {source} : {ex}"); throw new StockServerException($"PriceUrlSourceReader: Couldnt read from source {source}"); } }
private void ConvertToTN(TreeNode node, JToken token) { switch (token.Type) { case JTokenType.String: if (string.IsNullOrEmpty(node.Text)) { node.Text = token.ToObject <string>(); } else { node.Text += " : " + token.ToObject <string>(); } break; case JTokenType.Object: var body = token as JObject; node.Text = string.IsNullOrEmpty(node.Text) ? "Object" : node.Text; foreach (var item in body) { if (item.Value.Type == JTokenType.String || item.Value.Type == JTokenType.Integer) { string key = string.IsNullOrEmpty(item.Key) ? "Object" : item.Key; TreeNode child = new TreeNode(key + " : " + item.Value.ToString()); node.Nodes.Add(child); } else { TreeNode child = new TreeNode(item.Key); node.Nodes.Add(child); ConvertToTN(child, item.Value); } } break; case JTokenType.Array: JArray jarr = token as JArray; TreeNode array = new TreeNode("array-items"); node.Nodes.Add(array); foreach (var item in jarr.AsJEnumerable()) { ConvertToTN(array, item); } break; default: //不存在 break; } }
/// <summary> /// Maps the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns>Mapped <see cref="object" />.</returns> public override object Map(Type type, object value) { Type elementType = type.GetElementType(); List <System.Linq.Expressions.Expression> values = new List <System.Linq.Expressions.Expression>(); if (value.GetType() == typeof(JArray)) { JArray jsonArray = (JArray)value; foreach (JValue item in jsonArray.AsJEnumerable()) { UnaryExpression valueCast = (!elementType.IsValueType) ? Expression.TypeAs(Expression.Constant(item.ToString(CultureInfo.CurrentCulture)), elementType) : Expression.Convert(Expression.Constant(item.ToString(CultureInfo.CurrentCulture)), elementType); values.Add(valueCast); } } else if (value.GetType() == typeof(IEnumerable)) { IEnumerable enumerable = (IEnumerable)value; foreach (var item in enumerable) { UnaryExpression valueCast = (!elementType.IsValueType) ? Expression.TypeAs(Expression.Constant(item.ToString()), elementType) : Expression.Convert(Expression.Constant(item.ToString()), elementType); values.Add(valueCast); } } System.Linq.Expressions.NewArrayExpression newArrayExpression = System.Linq.Expressions.Expression.NewArrayInit(elementType, values); var func = Expression.Lambda <Func <object> >(newArrayExpression).Compile(); return(func()); }
protected void rblMandateModes_SelectedIndexChanged(object sender, EventArgs e) { ClearAccountDetails(); DataTable dt = new DataTable(); dt.Columns.Add("BankCode", typeof(string)); dt.Columns.Add("BankName", typeof(string)); JArray BanksList = (JArray)Session["BanksList"]; foreach (var option in BanksList.AsJEnumerable().Where(a => a["MandateMode"].ToString() == rblMandateModes.SelectedValue)) { dt.Rows.Add(new object[] { option["BankCode"].ToString(), option["BankName"].ToString() }); } ListItem InitItem = new ListItem("--Select--", ""); BankDD.DataSource = dt; BankDD.DataBind(); BankDD.Items.Insert(0, InitItem); BankDD.Enabled = true; }
/// <summary> /// Loads the repository from whatever backing data store is most appropriate /// </summary> public void Load() { var client = new RestClient(Config.DeltaApiRoot); var request = new RestRequest("Change", Method.GET); request.AddParameter("channel", SettingsRepository.PushChannelUri); client.ExecuteAsync(request, resp => { _repository = new ChangeList(); if (resp.StatusCode == HttpStatusCode.OK) { JArray jsonArray = JArray.Parse(resp.Content); _repository.AddRange(from ch in jsonArray.AsJEnumerable() select CreateChangeEntity(ch)); } if (LoadCompleted != null) { LoadCompleted(this, new EventArgs()); } }); }
public async Task ReadSource(string source) { try { while (safeGuradOnFileSource.TryGetValue(source, out bool safe)) { _logger.LogWarning($"File {source} already under process"); //todo: need to write once. not every 100 ms await Task.Delay(100); } if (safeGuradOnFileSource.TryAdd(source, true)) { await Task.Run(async() => { Console.WriteLine("**** PriceJsonSourceReader scan started *** "); using (StreamReader reader = File.OpenText(source)) { JArray arrayOfStock = (JArray)JToken.ReadFrom(new JsonTextReader(reader)); foreach (var token in arrayOfStock.AsJEnumerable()) { await _repo.AddStock(token.ToObject <Stock>()); //await Task.Delay(10); // for testing purpose } } safeGuradOnFileSource.TryRemove(source, out bool _); //enable next scan on same file }); Console.WriteLine("**** PriceJsonSourceReader scan done *** "); } } catch (Exception ex) { _logger.LogError($"PriceJsonSourceReader: Couldnt read from source {source} : {ex}"); throw new StockServerException($"PriceJsonSourceReader: Couldnt read from source {source}"); } }
/// <summary> /// Gets the primary email address contained in the given array. /// </summary> public static string GetEmail([NotNull] JArray array) { return((from address in array.AsJEnumerable() where address.Value <bool>("primary") select address.Value <string>("email")).FirstOrDefault()); }
protected void btnCreateSIP_Click(object sender, EventArgs e) { string OrderID = string.Empty; string ServerURL = string.Empty; string TxnAmount = string.Empty; string Mobile = string.Empty; string Email = string.Empty; string CallbackUrl = string.Empty; string SubsRequestBodyJSON = string.Empty; string checksum = string.Empty; string SubsRequestJSON = string.Empty; string SubsInitResponseJSON = string.Empty; string PaymentOptions = string.Empty; UserMaster Owner = db.UserMasters.Where(a => a.ID == 2).FirstOrDefault(); SIPData SubsData = new SIPData(); string[] SIPStartDate = txtSIPStartDate.Text.Split('/'); string[] SIPEnddate = txtSIPEndDate.Text.Split('/'); SubsData.StartDate = SIPStartDate[2] + "-" + SIPStartDate[1] + "-" + SIPStartDate[0]; SubsData.EndDate = SIPEnddate[2] + "-" + SIPEnddate[1] + "-" + SIPEnddate[0]; SubsData.Frequency = Convert.ToInt32(drpFrequency.SelectedValue); SubsData.FrequencyUnit = db.FrequencyUnitMasters.Where(a => a.FrequencyUnit == drpSIPFrequencyUnit.SelectedValue).Select(b => b.ID).SingleOrDefault(); SubsData.Amount = Convert.ToDecimal(txtAmount.Text); SubsData.CustomerID = Owner.ID; db.SIPDatas.Add(SubsData); db.SaveChanges(); OrderID = "ON" + SubsData.ID; ServerURL = "https://securegw-stage.paytm.in/subscription/create?mid=" + PaytmCreds.MID + "&orderId=" + OrderID; TxnAmount = Convert.ToDouble(txtAmount.Text).ToString("0.00"); Mobile = Owner.Mobile; Email = Owner.Email; CallbackUrl = "https://localhost:44300/CallBack.aspx"; SubsRequestBodyJSON = "{\"requestType\":\"NATIVE_SUBSCRIPTION\",\"mid\":\"" + PaytmCreds.MID + "\",\"orderId\":\"" + OrderID + "\",\"websiteName\":\"" + PaytmCreds.WEBSITE + "\",\"subscriptionAmountType\":\"VARIABLE\",\"subscriptionMaxAmount\":\"" + TxnAmount + "\",\"subscriptionEnableRetry\":\"0\",\"subscriptionRetryCount\":\"5\",\"subscriptionFrequencyUnit\":\"MONTH\",\"subscriptionFrequency\":\"" + SubsData.Frequency.ToString() + "\",\"subscriptionStartDate\":\"" + SubsData.StartDate + "\",\"subscriptionExpiryDate\":\"" + SubsData.EndDate + "\",\"subscriptionGraceDays\":\"0\",\"callbackUrl\":\"" + CallbackUrl + "\",\"txnAmount\":{\"value\":\"0\",\"currency\":\"INR\"},\"userInfo\":{\"custId\":\"" + SubsData.CustomerID.ToString() + "\"}}"; //Newtonsoft.Json.JsonConvert.SerializeObject(SubsRequestBody); checksum = paytm.CheckSum.generateCheckSumByJson(PaytmCreds.MerchantKey, SubsRequestBodyJSON); //JObject SubsRequest = new JObject(new JProperty("head", new JObject(new JProperty("clientId", PaytmCreds.MerchantKey.ToString()), new JProperty("version", "v1"), new JProperty("channelId", PaytmCreds.CHANNEL_ID), new JProperty("signature", checksum))), new JProperty("body", SubsRequestBody)); SubsRequestJSON = "{\"head\":{\"clientId\":\"" + PaytmCreds.MerchantKey + "\",\"version\":\"v1\",\"channelId\":\"" + PaytmCreds.CHANNEL_ID + "\",\"signature\":\"" + checksum + "\"},\"body\":" + SubsRequestBodyJSON + "}"; //Newtonsoft.Json.JsonConvert.SerializeObject(SubsRequest); SubsInitResponseJSON = utils.CommunicateToServer(ServerURL, SubsRequestJSON, "application/json"); if (!string.IsNullOrEmpty(SubsInitResponseJSON)) { JObject SubsInitResponse = JObject.Parse(SubsInitResponseJSON); SIPRegistrationData sIPRegData = new SIPRegistrationData(); sIPRegData.SIPID = SubsData.ID; sIPRegData.InsertDate = System.DateTime.Now; sIPRegData.InsertUserID = SubsData.CustomerID; sIPRegData.OrderID = OrderID; sIPRegData.UpdateDate = System.DateTime.Now; sIPRegData.UpdateUserID = Owner.ID; sIPRegData.TranInitResultCode = Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultCode"]); sIPRegData.TranInitResultStatus = Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultCode"]) != "0000" ? Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultStatus"]) + "(" + Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultMsg"]) + ")" : Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultStatus"]); if (Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultCode"]) == "0000" && Convert.ToString(SubsInitResponse["body"]["resultInfo"]["resultStatus"]) == "S") { ScriptManager.RegisterStartupScript(this, this.GetType(), "subsinitsuccess", "javascript: alert('Subscription initiated successfully, please enter bank details to proceed further');", true); sIPRegData.SubsID = Convert.ToString(SubsInitResponse["body"]["subscriptionId"]); sIPRegData.txnToken = Convert.ToString(SubsInitResponse["body"]["txnToken"]); sIPRegData.IsTransactionInit = true; PaymentOptions = this.GetPaymentOptions(Convert.ToString(SubsInitResponse["body"]["txnToken"]), OrderID); if (!string.IsNullOrEmpty(PaymentOptions)) { JObject Options = JObject.Parse(PaymentOptions); JArray PayModes = JArray.Parse(Options["body"]["merchantPayOption"]["paymentModes"].ToString()); JArray ChannelOptions = JArray.Parse(PayModes.AsJEnumerable().Where(a => a["displayName"].ToString() == "BANK_MANDATE").Select(b => b["payChannelOptions"]).First().ToString()); JArray MandateAuthModes = new JArray(); JObject obj; foreach (var option in ChannelOptions.AsJEnumerable().Where(a => a["mandateMode"].ToString() == "E_MANDATE" && Convert.ToBoolean(a["isDisabled"]["status"]) == false && Convert.ToBoolean(a["hasLowSuccess"]["status"]) == false)) { obj = new JObject(); obj.Add("BankCode", option["channelCode"]); obj.Add("AuthModes", option["mandateAuthMode"]); MandateAuthModes.Add(obj); } Session["MandateAuthModes"] = MandateAuthModes; JArray BanksList = new JArray(); foreach (var option in ChannelOptions.AsJEnumerable().Where(a => Convert.ToBoolean(a["isDisabled"]["status"]) == false && Convert.ToBoolean(a["hasLowSuccess"]["status"]) == false)) { obj = new JObject(); obj.Add("MandateMode", option["mandateMode"]); obj.Add("BankCode", option["channelCode"].ToString()); obj.Add("BankName", option["channelName"].ToString()); BanksList.Add(obj); } Session["BanksList"] = BanksList; db.SIPRegistrationDatas.Add(sIPRegData); db.SaveChanges(); hdfOrderID.Value = OrderID; hdfSubsID.Value = sIPRegData.SubsID; hdfTxnToken.Value = sIPRegData.txnToken; hdfRegData.Value = sIPRegData.ID.ToString(); mpeBankDetails.Show(); } else { sIPRegData.IsTransactionInit = false; ScriptManager.RegisterStartupScript(this, this.GetType(), "subsfail", "javascript: alert('Subscription registration failed due to technical reasons');", true); } } else { sIPRegData.IsTransactionInit = false; ScriptManager.RegisterStartupScript(this, this.GetType(), "subsfail", "javascript: alert('Subscription registration failed due to technical reasons');", true); } } else { db.SIPDatas.Remove(SubsData); db.SaveChanges(); ScriptManager.RegisterStartupScript(this, this.GetType(), "subsfail", "javascript: alert('Subscription registration failed due to technical reasons');", true); } }
public static IEnumerable <string> GetRoles(JArray roles) { return(roles.AsJEnumerable().Select(x => x.Value <string>("role"))); }
public async Task <(ulong, ulong, string)> GetAnswerAsync(string game) { ulong newAuthor = _commandService.Message.Author.Id + 1; // Needs to make sure authors don't match at the first iteration SocketUser newAuthorAsSocketUser = _commandService.Message.Author; ulong originalAuthor = 0; string originalMessage = ""; string newMessage = ""; int index = 0; string reply = ""; ulong firstDisposableMessage = 0; ulong secondDisposableMessage = 0; // Searches for possible matches on steam and returns them as a json string string searchResult = await _api.GetResult(game); JArray jsonResult = await _handler.Parse(searchResult); while (true) { // Sets newAuthor to the author of the newest message if (originalAuthor != 0 && !originalMessage.Equals(newMessage)) { newAuthor = _commandService.Message.Author.Id; newMessage = _commandService.Message.Content; } // Only executes once so that it sets the user who originally initialized the command if (!_commandService.Message.Author.IsBot && originalAuthor == 0 && string.IsNullOrEmpty(originalMessage)) { originalAuthor = _commandService.Message.Author.Id; originalMessage = _commandService.Message.Content; } // Builds the embed and sends it to the channel if (index.Equals(0) && !jsonResult.Count.Equals(0)) { List <(string, string)> list = new List <(string, string)>(); int listIterator = 0; foreach (var o in jsonResult) { string name = o.SelectToken("pagemap").SelectToken("product")[0].SelectToken("name").ToString(); list.Add(($"{++listIterator}", name)); } Embed embed = await _embed.Build(list, "Result of steam search:"); await _commandService.Message.Channel.SendMessageAsync(text : "Which one?", embed : embed); firstDisposableMessage = _commandService.Message.Id; index = 1; } // Checks if there's nothing in the result, break out of the loop if (jsonResult.ToString().Equals(searchResult)) { reply = "Game not found. Weird."; break; } // Will only execute if we got a reply from the same user if (originalAuthor != 0 && originalAuthor.Equals(newAuthor) && !newAuthorAsSocketUser.IsBot && !originalMessage.Equals(newMessage)) { // Checks if it's a number and if the number is in the list if (int.TryParse(_commandService.Message.Content, out int answer)) { secondDisposableMessage = _commandService.Message.Id; if (answer < jsonResult.Count) { reply = jsonResult.AsJEnumerable().ElementAt(answer - 1).SelectToken("formattedUrl").ToString(); break; } else { reply = "That number is not in the list."; break; } } else { reply = "Not a number."; break; } } } return(firstDisposableMessage, secondDisposableMessage, reply); }