public static Models.Metadata GetMetadata(string path) { var client = new GRPCServer.GRPCServer.GRPCServerClient(channel); StringResponse response = null; bool retry = true; while (retry) { try { response = client.GetMetadata(new PathRequest { SessionId = _SessionId, Path = path }); } catch (RpcException) { Thread.Sleep(5000); continue; } retry = false; } return(Models.Metadata.FromJson(response.PayLoad)); }
public bool DeleteField(string index, string type, string id, List <string> fields) { bool flag = false; StringResponse resStr = null; try { var fieldScripts = fields.ConvertAll(x => $"ctx._source.remove(\\\"{x}\\\")"); resStr = client.Update <StringResponse>(index, type, id, PostData.String($"{{\"script\":\"{string.Join(";", fieldScripts)}\"}}")); var resObj = JObject.Parse(resStr.Body); if ((int)resObj["_shards"]["total"] == 0 || (int)resObj["_shards"]["successful"] > 0) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
/// <summary> /// 删除文档 /// </summary> /// <param name="index"></param> /// <param name="type"></param> /// <param name="id"></param> public bool DeleteDocument(string index, string type, string id) { bool flag = false; StringResponse resStr = null; try { resStr = client.Delete <StringResponse>(index, type, id); var resObj = JObject.Parse(resStr.Body); if ((int)resObj["_shards"]["total"] == 0 || (int)resObj["_shards"]["successful"] > 0) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
private static void CheckReponseSuccess(StringResponse response, string index) { if (response.Success == false) { Console.WriteLine($"[{DateTimeOffset.UtcNow}] An error occured when logging on ElasticSearch, index '{index}'. {response.OriginalException.Message}"); } }
/// <summary> /// 插入文档 /// </summary> /// <param name="index"></param> /// <param name="type"></param> /// <param name="doc"></param> public bool InsertDocument(string index, string type, string id, BsonDocument doc) { bool flag = false; StringResponse resStr = null; try { resStr = client.Index <StringResponse>(index, type, id, PostData.String(doc.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }))); var resObj = JObject.Parse(resStr.Body); if ((int)resObj["_shards"]["successful"] > 0) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
/// <summary> /// Returns the cargo capacity of your ship /// </summary> /// <returns>Capacity or -1 on error</returns> public double getShipCapacity() { StringResponse tresp = (StringResponse)com.sendCall(FunctionCallFactory.CALLS.GETSHIPCAPACITY, Response.RESPONSES.STRINGRESPONSE); if (tresp == null) { Console.WriteLine("Couldn't retrieve selected item"); return(-1); } Regex reg = new Regex(@"/" + "[0-9]*,*[0-9]+" + @"." + "[0-9]+"); string result = reg.Match((string)tresp.Data).Value; if (result.Length > 0) { try { result = result.Substring(1, result.Length - 1); return(Convert.ToDouble(result)); } catch (Exception e) { Console.WriteLine(e.ToString()); return(-1); } } return(-1); }
private static BaseResponse SerializeResponse(HttpContext context, StringResponse stringResponse) { context.Response.Write(stringResponse.NotJson ? stringResponse.Response : new JavaScriptSerializer().Serialize(stringResponse.Response)); return(stringResponse); }
public StringResponse Create(string storeName, Dictionary <string, string> values) { var response = new StringResponse { Success = false }; logger.Debug("Create started"); var newItem = this.storeService.Create(storeName, values); if (newItem != null) { response.Response = newItem.Id.ToString(); response.Success = true; response.NotJson = true; } else { response.StatusCode = 500; response.Response = "Could not create row!"; logger.Debug("Create failed - Could not create row!"); } logger.Debug("Create finished"); return(response); }
public StringResponse Delete(string storeName, string identityId) { var response = new StringResponse { Success = false }; logger.Debug("Delete started"); Identity identity; if (Identity.TryParse(identityId, out identity) && identity != null) { if (this.storeService.Delete(storeName, identity)) { response.Response = "ok"; response.Success = true; response.NotJson = true; } else { response.StatusCode = 500; response.Response = "Could not delete row!"; } } else { response.StatusCode = 500; response.Response = "Could not interpret Id!"; } logger.Debug("Delete finished"); return(response); }
public StringResponse Update(OrderUpdate orderUpdate) { try { var shop = ServiceContainer.GetService <ShopService>().GetById(orderUpdate.ShopId).First; var functionType = popService.GetOrderGetFunction(shop.PopType); StringResponse ret = null; if (functionType == PopOrderGetFunction.PAYED) { var nor = popService.GetOrderState(shop, orderUpdate.PopOrderId); ret = ServiceContainer.GetService <OrderService>().UpdateOrderState(nor, orderUpdate, shop); } else { var nor = popService.GetOrder(shop, orderUpdate.PopOrderId); ret = ServiceContainer.GetService <OrderService>().UpdateOrderStateWithGoods(nor.Order, orderUpdate, shop); } return(ret); } catch (WebFaultException) { throw; } catch (Exception e) { throw new WebFaultException <ResponseBase>(new ResponseBase(e.Message), HttpStatusCode.OK); } }
public StringResponse Update(string storeName, int columnId, string value, string id, string columnName) { var response = new StringResponse { Success = false }; logger.DebugFormat("Update started"); Identity identity; if (Identity.TryParse(id, out identity) && identity != null) { if (this.storeService.UpdateCell(storeName, identity, columnId, columnName, value)) { response.Response = value; response.Success = true; } else { response.StatusCode = 500; response.Response = "Could not save cell!"; logger.Error("Update failed - Could not save cell!"); } } else { response.StatusCode = 500; response.Response = "Could not interpret Id!"; logger.Error("Update failed - Could not interpret Id!"); } logger.Debug("Update finished"); return(response); }
public async Task <StringResponse> SaveNOCByCitizen(NOCModel model) { StringResponse resp = new StringResponse(); try { using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(baseAddress); //httpClient1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken); //httpClient.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token.AccessToken)); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("Referer", "http://localhost:1843"); StringContent content = new StringContent(JsonConvert.SerializeObject(model)); HttpResponseMessage response = await httpClient.PostAsync("api/NOCModule/SaveNOCByCitizen", content); if (response.IsSuccessStatusCode) { string str = response.Content.ReadAsStringAsync().Result; resp = Newtonsoft.Json.JsonConvert.DeserializeObject <StringResponse>(str); } string message = response.Content.ReadAsStringAsync().Result; System.Console.WriteLine("URL responese : " + message); } } catch (Exception ex) { } return(resp); }
private async Task CreateIndexIfNeededAsync(IElasticLowLevelClient client) { if (!_seederConfiguration.CreateIndexIfNotExists) { return; } StringResponse result = await client.Indices.ExistsAsync <StringResponse>(_elasticsearchConfiguration.IndexName); if (result.HttpStatusCode == (int)HttpStatusCode.NotFound) { string json = await File.ReadAllTextAsync(_seederConfiguration.CreateIndexRequestBodyContentFilePath); StringResponse response = await client.Indices.CreateAsync <StringResponse>( _elasticsearchConfiguration.IndexName, PostData.String(json)); if (!response.Success) { const string messageConst = "Unable to create index. Response from server: "; ServerError error; var message = response.TryGetServerError(out error) ? $"{messageConst}{error.Error.Reason}" : $"{messageConst}{response.Body}"; throw new SystemException(message); } Log.Logger.Information($"Index '{_elasticsearchConfiguration.IndexName}' created"); } else if (!result.Success) { Log.Logger.Warning($"Unable to check if index exists. Server response: [{result.HttpStatusCode}] {result.Body}"); } }
public static List <Models.Metadata> ListFolder(string path) { var client = new GRPCServer.GRPCServer.GRPCServerClient(channel); StringResponse response = null; bool retry = true; while (retry) { try { response = client.ListFolder(new PathRequest { SessionId = _SessionId, Path = path }); } catch (RpcException) { Thread.Sleep(5000); continue; } retry = false; } List <Models.Metadata> metadataList = new List <Models.Metadata>(); JObject obj = JObject.Parse(response.PayLoad); JArray MetadataArray = (JArray)obj["entries"]; foreach (var item in MetadataArray) { metadataList.Add(Models.Metadata.FromJson(item)); } return(metadataList); }
public StringResponse SaveNOCbyCitizen(NOCModel model) { StringResponse response = new StringResponse(); try { // var list = new EntityCall.NOCRepository(_Companyinformation).SaveNOCbyCitizen(); if (model != null) { string str = Newtonsoft.Json.JsonConvert.SerializeObject(model); //response.Data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DropDownValue>>(str); } else { throw new Exception("No Data Available in Place List"); } } catch (Exception ex) { //var errorRequest = "authenticatedCustomerId:" + customerId; //response = Response.Failed(response, ex, errorRequest, MethodBase.GetCurrentMethod().Name, _companyinfo.PrivateConnectionString, _companyinfo.CompanyID); } return(response); }
public T GetItem <T>(string indexName, FilterCondition filter, List <string> columns = null) { PageCondition page = new PageCondition(1, 1); string body = FilterToQueryString(indexName, filter, ref page); if (body == null) { return(default(T)); } StringResponse res = conn.LowLevel.Search <StringResponse>(PostData.String(body)); if (!res.Success) { return(default(T)); } ELSearchResponse <T> sr = JsonConvert.DeserializeObject <ELSearchResponse <T> >(res.Body); if (sr == null || sr.hits.total.value == 0) { return(default(T)); } T data = sr.hits.hits[0]._source; return(data); }
/// <summary> /// Get our ship's current speed /// </summary> /// <returns>The speed of the ship in m/s</returns> public int getSpeed() { int speed = -1; StringResponse iresp = (StringResponse)com.sendCall(FunctionCallFactory.CALLS.GETSHIPSPEED, Response.RESPONSES.STRINGRESPONSE); if (iresp == null) { Console.WriteLine("Response is null"); return(speed); } Regex regex = new Regex("Warping"); if (regex.Match((String)iresp.Data).Value != "") { Console.WriteLine("We're warping"); speed = WARPSPEED; } else { regex = new Regex("[0-9]+" + @"\." + "*[0-9]*"); String match = regex.Match((String)iresp.Data).Value; try { speed = (int)Convert.ToDouble(match); } catch (Exception e) { Console.WriteLine(e.ToString()); } } return(speed); }
/// <summary> /// 创建索引 /// </summary> /// <param name="index"></param> /// <param name="shards"></param> /// <returns></returns> public bool CreateIndex(string index, int shards = 5) { bool flag = false; StringResponse resStr = null; try { resStr = client.IndicesCreate <StringResponse>(index, PostData.String($"{{\"settings\" : {{\"index\" : {{\"number_of_replicas\" : 0, \"number_of_shards\":\"{shards}\",\"refresh_interval\":\"-1\"}}}}}}")); var resObj = JObject.Parse(resStr.Body); if ((bool)resObj["acknowledged"]) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
internal async Task <StringResponse> UrlGetToString(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) { if (string.IsNullOrEmpty(request) || (maxTries == 0)) { return(null); } StringResponse result = null; for (byte i = 0; i < maxTries; i++) { using HttpResponseMessage response = await InternalGet(request, referer).ConfigureAwait(false); if (response?.StatusCode.IsClientErrorCode() == true) { if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { result = new StringResponse(response); } break; } if (response?.Content == null) { continue; } return(new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false))); } return(result); }
public override Task <StringResponse> HealthProve(StringResponse request, ServerCallContext context) { return(Task.FromResult(new StringResponse { Message = "OK" })); }
/// <summary> /// 优化写入性能 /// </summary> /// <param name="index"></param> /// <param name="refresh"></param> /// <param name="replia"></param> /// <returns></returns> public bool SetIndexRefreshAndReplia(string index, string refresh = "30s", int replia = 1) { bool flag = false; StringResponse resStr = null; try { resStr = client.IndicesPutSettings <StringResponse>(index, PostData.String($"{{\"index\" : {{\"number_of_replicas\" : {replia},\"refresh_interval\":\"{refresh}\"}}}}")); var resObj = JObject.Parse(resStr.Body); if ((bool)resObj["acknowledged"]) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
public static Models.Metadata CreateFolder(string path) { var client = new GRPCServer.GRPCServer.GRPCServerClient(channel); StringResponse response = null; bool retry = true; while (retry) { try { response = client.CreateFolder(new PathRequest { SessionId = _SessionId, Path = path, ModifiedTime = (new DirectoryInfo(Util.Utils.CloudPathtoLocalPath(path)).LastWriteTimeUtc.Ticks - 621355968000000000) / 10000 }); } catch (RpcException) { Thread.Sleep(5000); continue; } retry = false; } return(Models.Metadata.FromJson(response.PayLoad)); }
/// <summary> /// 批量插入文档 /// </summary> /// <param name="docs"></param> /// <returns></returns> public bool InsertBatchDocument(IEnumerable <string> docs) { bool flag = false; StringResponse resStr = null; try { resStr = client.Bulk <StringResponse>(PostData.MultiJson(docs)); var resObj = JObject.Parse(resStr.Body); if (!(bool)resObj["errors"]) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
public bool DeleteIndex(string index) { bool flag = false; StringResponse resStr = null; try { resStr = client.IndicesDelete <StringResponse>(index); var resObj = JObject.Parse(resStr.Body); if ((bool)resObj["acknowledged"]) { flag = true; } else { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } } catch (Exception ex) { if (resStr != null) { LogUtil.LogInfo(logger, resStr.DebugInformation, nodeId); } LogUtil.LogError(logger, ex.ToString(), nodeId); } return(flag); }
public void GetChoice(string question, List <string> options, StringResponse callback, TimeSpan expiration) { SendCustomKeyboardList(question, options, (string result) => { callback(result); return(""); }, expiration); }
public override Task <StringResponse> GetWorkerStatus(IntegerRequest request, ServerCallContext context) { var response = new StringResponse(); var user = _activeMembers.Find(member => member.ID == IntegerRequest.NumberFieldNumber); response.Resp = user.ID == -1 ? "absent" : user.Status; return(System.Threading.Tasks.Task.FromResult(response)); }
public void Process(ISemanticProcessor proc, IMembrane membrane, StringResponse resp) { resp.Context.Response.StatusCode = resp.StatusCode; resp.Context.Response.ContentType = "text/text"; resp.Context.Response.ContentEncoding = Encoding.UTF8; resp.Context.Response.ContentLength64 = resp.Message.Length; resp.Context.Response.OutputStream.Write(resp.Message.to_Utf8(), 0, resp.Message.Length); resp.Context.Response.Close(); }
public static async Task <ConcurrentBag <ProductModel> > GetEsSearchableProducts() { EsClient client = new EsClient(); StringResponse searchResponse = new StringResponse(); try { searchResponse = await client.Client.SearchAsync <StringResponse>("product_search", PostData.Serializable( new { from = 0, size = 10000, query = new { match = new { type = "product" } } })); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); Debug.WriteLine(ex.InnerException.ToString()); } string responseJson = searchResponse.Body; using JsonDocument document = JsonDocument.Parse(responseJson); JsonElement root = document.RootElement; JsonElement sourceElement = root.GetProperty("hits").GetProperty("hits"); ConcurrentBag <ProductModel> products = new ConcurrentBag <ProductModel>(); Parallel.ForEach(sourceElement.EnumerateArray().AsParallel(), source => { if (source.TryGetProperty("_source", out JsonElement rec)) { ProductModel product = new ProductModel { Type = rec.GetProperty("type").GetString(), Sku = rec.GetProperty("sku").GetString(), Image = rec.GetProperty("image").GetString(), Url = rec.GetProperty("url").GetString(), Price = rec.GetProperty("price").GetDecimal(), Name = rec.GetProperty("name").GetString(), Description = rec.GetProperty("description").GetString() }; products.Add(product); } }); return(products); }
public async Task <string> ResponseData(string search) { StringResponse searchResponse = await client.SearchAsync <StringResponse>(search); bool successful = searchResponse.Success; string responseJson = searchResponse.Body; return(successful ? responseJson : searchResponse.ApiCall.DebugInformation); }
public async Task Get() { string query = "shap"; EsClient client = new EsClient(); StringResponse searchResponse = await client.Client.SearchAsync <StringResponse>("product_search", PostData.Serializable(new { query = new { @bool = new { should = new { @bool = new { must = new { match_phrase_prefix = new { name = new { query = $"{query}", slop = 3, max_expansions = 10 } } }, should = new { multi_match = new { query = $"{query}", fields = @"[""name"",""url"", ""image""]", fuzziness = "auto", @operator = "or" } } } }, filter = new { term = new { type = "product" } } } }, size = 50, _source = @"[""name"", ""price"", ""sku""]", })); var jsonDoc = JsonDocument.Parse(searchResponse.Body).RootElement.GetProperty("hits").GetProperty("hits"); var count = jsonDoc.EnumerateArray().Count(); Debug.WriteLine($"Get Count: {count}"); }