private void SetupClient(Mock<IClient> clientMock, int? timeToReply = null) { clientMock.Setup(c => c.Request(It.IsAny<RequestData>(), It.IsAny<CancellationToken>())) .Returns( (RequestData request, CancellationToken token) => { Task<ResponseData> responseTask; if (request.Operation == "Sum") { var data = new TestService().Sum((int)request.Arguments[0], (int)request.Arguments[1]); var response = new ResponseData(data); responseTask = Task.FromResult(response); } else if (request.Operation == "Concatenate") { var dataTask = new TestService().Concatenate(request.Arguments[0] as string[]); responseTask = dataTask.ContinueWith(t => new ResponseData(t.Result)); } else { throw new NotSupportedException("Only sum and Concatenate are supported in this mock"); } if (timeToReply.HasValue) { return Task.Delay(timeToReply.Value).ContinueWith(t => responseTask).Unwrap(); } else { return responseTask; } }); }
public ActionResult ClearAnyLog() { var responseResult = new ResponseData { success = false }; GetRequiredService<ILoggingService>().ClearAnyLog(); responseResult.success = true; return this.JsonResult(responseResult); }
public static ResponseData Generate() { var responseData = new ResponseData {Results = new ResponseResult[8]}; for (int i = 0; i < responseData.Results.Length; i++) { responseData.Results[i] = ResponseResult.Generate(); } return responseData; }
public BasicOcspResponse( ResponseData tbsResponseData, AlgorithmIdentifier signatureAlgorithm, DerBitString signature, Asn1Sequence certs) { this.tbsResponseData = tbsResponseData; this.signatureAlgorithm = signatureAlgorithm; this.signature = signature; this.certs = certs; }
public ApiResponseException(string message, IRestResponse response) : base(message) { HttpResponseData = new ResponseData { ErrorMessage = response.ErrorMessage, Content = response.Content, ResponseUri = response.ResponseUri, StatusCode = response.StatusCode, ErrorException = response.ErrorException }; }
public static int CreateResponse(FlatBufferBuilder builder, uint id = 0, ResponseData response_data_type = 0, int response_data = 0) { builder.StartObject(3); Response.AddResponseData(builder, response_data); Response.AddId(builder, id); Response.AddResponseDataType(builder, response_data_type); return Response.EndResponse(builder); }
private BasicOcspResponse( Asn1Sequence seq) { this.tbsResponseData = ResponseData.GetInstance(seq[0]); this.signatureAlgorithm = AlgorithmIdentifier.GetInstance(seq[1]); this.signature = (DerBitString)seq[2]; if (seq.Count > 3) { this.certs = Asn1Sequence.GetInstance((Asn1TaggedObject)seq[3], true); } }
private bool IsResponseDataFormatOK() { try { responseData = ResponseData.Parse(data); } catch (Exception e) { logger.Info("�s���ȃt�H�[�}�b�g��ResponseData����܂����B", e); return false; } return true; }
public ResponseData Auth(RequestData rData) { // Call BLL here var data = rData.details.Split('|'); var response = new ResponseData { Name = data[0], Age = data[1], Exp = data[2], Technology = data[3] }; return response; }
/// <summary> /// 发送, /// 命令行模式 /// </summary> /// <param name="cmd"></param> /// <returns></returns> internal ResponseData RequestWithConsole(string cmd) { ResponseData result = new ResponseData() { Type = ResponseType.Empty, Data = "未知的命令" }; try { if (!string.IsNullOrWhiteSpace(cmd)) { var @params = cmd.Split(" ", StringSplitOptions.RemoveEmptyEntries); if (@params != null && @params.Length > 0) { var redisCmd = @params[0].ToUpper(); if (EnumHelper.GetEnum(redisCmd, out RequestType requestType)) { var sendData = RedisCoder.Coder(requestType, @params); Request(sendData); result = RedisCoder.Decoder(); } else { result.Type = ResponseType.Error; result.Data = "未知的命令 cmd:" + cmd; } } } } catch (Exception ex) { result.Type = ResponseType.Error; result.Data = ex.Message; } return(result); }
public ResponseData DoMultiLineWithList(RequestType type, string id, IEnumerable <string> list) { ResponseData result = new ResponseData() { Type = ResponseType.Empty, Data = "未知的命令" }; try { result = TaskHelper.Run((token) => { lock (SyncRoot) { RedisCoder.RequestForList(type, id, list); var sresult = RedisCoder.Decoder(type, token); if (sresult.Type == ResponseType.Redirect) { return((ResponseData)OnRedirect.Invoke(sresult.Data, OperationType.DoBatchWithList, type, list)); } else { return(sresult); } } }, _actionTimeout).Result; } catch (TaskCanceledException tex) { result.Type = ResponseType.Error; result.Data = "Action Timeout"; } catch (Exception ex) { result.Type = ResponseType.Error; result.Data = ex.Message; } return(result); }
public void GetLogList() { var msg = new ResponseData(); string keyword = null; int page = 1; int limit = 10; int count = 0; try { if (!string.IsNullOrWhiteSpace(Request["keyword"])) { keyword = Request["keyword"]; // 搜索关键词 } // 当前页码 if (!string.IsNullOrWhiteSpace(Request["page"])) { int.TryParse(Request["page"], out page); page = page > 0 ? page : 1; } // 每页数量 if (!string.IsNullOrWhiteSpace(Request["limit"])) { int.TryParse(Request["limit"], out limit); limit = limit > 0 ? limit : 10; } msg.data = new DbHelper.Logs().GetByPages(page, limit, ref count, keyword); // 获取列表 msg.count = count; Response.Write(msg.ToJson()); Response.End(); } catch (Exception) { throw; } }
private async void btnSignIn_Click(object sender, EventArgs e) { String email = txtEmail.Text; String password = txtPassword.Text; var userLogin = new User() { Email = email, Password = password }; loadingView.Visible = true; Task <ResponseData <User> > newUser = _authentication.SignIn(FirebaseAuthType.EmailAndPassword, userLogin, null); ResponseData <User> responseData = await newUser; loadingView.Visible = false; if (responseData.statusCode == Constants.CODE_SUCCESS) { // MessageBox.Show("Hi " + responseData.data.DisplayName); new FormMain().Show(); } else { MessageBox.Show(responseData.Msg); } //Task < ResponseData < bool >> signUpUser = _authentication.ForgotPassword("*****@*****.**"); //ResponseData<bool> responseDataSignUp = await signUpUser; //loadingView.Visible = false; //if (responseDataSignUp.statusCode == Constants.CODE_SUCCESS) //{ // MessageBox.Show("Hi " + responseDataSignUp.data); //} //else //{ // MessageBox.Show(responseDataSignUp.Msg); //} }
/// <summary> /// 发送命令 /// </summary> /// <param name="cmd"></param> public ResponseData Do(RequestType type) { ResponseData result = new ResponseData() { Type = ResponseType.Empty, Data = "未知的命令" }; try { result = TaskHelper.Run((token) => { lock (SyncRoot) { RedisCoder.RequestOnlyParams(type.ToString()); var sresult = RedisCoder.Decoder(type, token); if (sresult.Type == ResponseType.Redirect) { return((ResponseData)OnRedirect.Invoke(sresult.Data, OperationType.Do, null)); } else { return(sresult); } } }, _actionTimeout).Result; } catch (TaskCanceledException tex) { result.Type = ResponseType.Error; result.Data = "Action Timeout"; } catch (Exception ex) { result.Type = ResponseType.Error; result.Data = ex.Message; } return(result); }
public ResponseData DoExpireInsert(RequestType type, string key, string value, int seconds) { key.KeyCheck(); ResponseData result = new ResponseData() { Type = ResponseType.Empty, Data = "未知的命令" }; try { result = TaskHelper.Run((token) => { lock (SyncRoot) { RedisCoder.Request(type, key, value); var sresult = RedisCoder.Decoder(type, token); if (sresult.Type == ResponseType.Redirect) { return((ResponseData)OnRedirect.Invoke(sresult.Data, OperationType.DoExpireInsert, key, value, seconds)); } RedisCoder.Request(RequestType.EXPIRE, string.Format("{0} {1}", key, seconds)); return(RedisCoder.Decoder(RequestType.EXPIRE, token)); } }, _actionTimeout).Result; } catch (TaskCanceledException tex) { result.Type = ResponseType.Error; result.Data = "Action Timeout"; } catch (Exception ex) { result.Type = ResponseType.Error; result.Data = ex.Message; } return(result); }
public ResponseData <string> DoMultiLineWithDic(RequestType type, Dictionary <string, string> dic) { ResponseData <string> result = new ResponseData <string>() { Type = ResponseType.Empty, Data = "未知的命令" }; try { result = TaskHelper.Run((token) => { lock (SyncRoot) { RedisCoder.RequestForDic(type, dic); var sresult = RedisCoder.Decoder <string>(type, token); if (sresult != null && sresult.Type == ResponseType.Redirect) { return((ResponseData <string>)OnRedirect.Invoke(sresult.Data, OperationType.DoBatchWithDic, type, dic)); } else { return(sresult); } } }, _actionTimeout).Result; } catch (TaskCanceledException tex) { result.Type = ResponseType.Error; result.Data = "Action Timeout"; } catch (Exception ex) { result.Type = ResponseType.Error; result.Data = ex.Message; } return(result); }
public ContentResult EditToCart(Product product) { List <Product> ProductList = new List <Product>(); var unitofwork = new UnitOfWork(new QLBHDienThoaiEntities()); int amountInDb = unitofwork.Product.Get(product.ProductID).Amount.GetValueOrDefault(); if (Session["Cart"] != null) { ProductList = (List <Product>)Session["Cart"]; if (amountInDb < product.Amount) { return(Content(ResponseData.ToJson(new ResponseData(ProductList, 0, false, null, "<p></p>Không thể thêm! Số lượng " + product.Name + " chỉ còn " + amountInDb.ToString() + " sản phẩm!")))); } var pro = ProductList.Single(x => x.ProductID == product.ProductID); pro.Amount = product.Amount; Session["Cart"] = ProductList; return(Content(ResponseData.ToJson(new ResponseData(ProductList, ProductList.Sum(x => x.Amount * x.PriceProduct).GetValueOrDefault(), true, null, "<p></p>" + pro.Name + " được sửa vào giỏ hàng thành công!")))); } else { return(Content(ResponseData.ToJson(new ResponseData(ProductList, ProductList.Sum(x => x.Amount * x.PriceProduct).GetValueOrDefault(), true, null, "Giỏ hàng trống!")))); } }
public ResponseData <IDictionary <string, object> > GetAll() { ResponseData <IDictionary <string, object> > responseData = new ResponseData <IDictionary <string, object> >(); try { IList <string> keys = GetCacheKeys(); IDictionary <string, object> dict = new Dictionary <string, object>(); foreach (string key in keys) { dict.Add(key, cache.Get(key)); } responseData.Data = dict; } catch (Exception exception) { responseData.ErrorNumber = 1000; responseData.ErrorMessage = Properties.Resources.Error_1000; responseData.Exception = exception; logger.Error(exception); } return(responseData); }
public async Task <IHttpActionResult> Update([FromBody] Advertising advertising) { var query = from a in ModelContext.DatabaseContext.Advertising where a.Id == advertising.Id select a; var data = query.FirstOrDefault(); var responseData = new ResponseData <Advertising>() { Message = data == null ? "未找到该条广告数据" : "", Data = data }; if (data != null) { ReflectionHelper.CopyProperties(advertising, data, new string[] { "Id" }); ModelContext.DatabaseContext.Entry(data).State = System.Data.Entity.EntityState.Modified; await ModelContext.DatabaseContext.SaveChangesAsync(); } return(Json(responseData)); }
public async Task <ActionResult> GetCCARateCellListByConAsync([FromBody] CCARateCellListRequestDto request) { string searchRateCell = String.IsNullOrEmpty(request.CCARateCell) ? "" : request.CCARateCell; string searchProduct = String.IsNullOrEmpty(request.Product) ? "" : request.Product; int eventUserID = Request.GetUserID(); var response = new ResponseData <ResponseDataList <CCARateCells> > { IsSuccess = true, Code = Constants.ResponseCode.Success, Message = "Success", }; var query = _context.Query <CCARateCells>().FromSql($"dbo.spGetCCARateCells {eventUserID}, {searchRateCell}, {searchProduct}"); var ccatRateCellList = await query.AsNoTracking().ToArrayAsync(); response.Data = new ResponseDataList <CCARateCells> { List = ccatRateCellList, }; return(Ok(response)); }
public async Task<ResponseData<string>> Login(string username, string password) { ResponseData<string> res = new ResponseData<string>(); User user = await _context.Users.FirstOrDefaultAsync(u => u.Username.ToLower().Equals(username.ToLower())); if(user==null) { res.Message = "user not found"; res.success = false; } else if(!VerifyPasswordHash(password,user.PasswordHash,user.PasswordSalt)) { res.Message = "password donot match"; res.success = false; } else { res.Data = CreateToken(user); } return res; }
public async Task <IHttpActionResult> Update([FromBody] MembershipType membershipType) { var resp = new ResponseData <MembershipType>(); var mQuery = from m in DataContext.MembershipType where m.Id == membershipType.Id select m; var mEntity = mQuery.FirstOrDefault(); if (mEntity == null) { resp.Message = "没有找到这个套餐类型"; } else { Utils.CopyProperties(membershipType, mEntity, ID_EXCEPTION); DataContext.Entry(mEntity).State = System.Data.Entity.EntityState.Modified; await DataContext.SaveChangesAsync(); resp.Data = membershipType; } return(Json(resp)); }
public ResponseData consulta2(string loginUsuario, string password) { ResponseData respuesta = new ResponseData(); List <usuarios> usuario = new List <usuarios>(); try { var consulta = (from usu in this.context.usuarios where usu.login == loginUsuario && usu.password == password select usu).First(); //usuario = consulta; usuario.Add((usuarios)consulta); respuesta.objeto = usuario; respuesta.mensaje = "Usuario encontrado con exito"; respuesta.resultado = "OK"; } catch (Exception ex) { respuesta.mensaje = "Ocurrio un error interno"; respuesta.resultado = "Fallo"; } return(respuesta); }
public async Task <ActionResult> GetMonthlySummaryRecordMemberYearsByConAsync(int MasterPatientId) { int MasterPatientID = MasterPatientId; int eventUserID = Request.GetUserID(); var response = new ResponseData <ResponseDataList <MonthlySummaryRecordMemberYearsForListDto> > { IsSuccess = true, Code = Constants.ResponseCode.Success, Message = "Success", }; var query = _context.Query <MonthlySummaryRecordMemberYearsPaged>().FromSql($"dbo.spGetMonthlySummaryRecordMemberYears {eventUserID},{MasterPatientID}"); var summaryYearsInfo = await query.AsNoTracking().ToArrayAsync(); response.Data = new ResponseDataList <MonthlySummaryRecordMemberYearsForListDto> { //Count = discrepancyInfo.Any() ? discrepancyInfo[0].ResultCount : 0, List = _mapper.Map <IEnumerable <MonthlySummaryRecordMemberYearsForListDto> >(summaryYearsInfo) }; return(Ok(response)); }
public async Task <ResponseData> UpdateProfile(ApplicationUser currentUser, UserForProfileEditDTO editUser) { ResponseData responseData = new ResponseData { isSuccessful = false, Message = "Error updating profile", }; currentUser.Address = editUser.Address; currentUser.Company = editUser.Company; currentUser.FirstName = editUser.FirstName; currentUser.LastName = editUser.LastName; currentUser.PhoneNumber = editUser.PhoneNumber; currentUser.City = editUser.City; currentUser.Country = editUser.Country; currentUser.UserName = editUser.UserName; currentUser.Email = editUser.Email; await _context.SaveChangesAsync(); responseData.isSuccessful = true; responseData.Message = "Successfuly updated profile!"; return(responseData); }
public IHttpActionResult Query([FromUri] long apointmentId, long userid, DateTime date) { var resp = new ResponseData <IEnumerable <InfraredData> >(); try { var query = from a in DataContext.InfraredData where (userid == 0 || a.UserId == userid) && (date.Date == DateTime.MinValue || (a.CreateTime > date.Date && a.CreateTime < date.Date.AddDays(1))) && (apointmentId == 0 || a.ApointmentId == apointmentId) select a; resp.Data = query; //Logger.Log("shitererer"); } catch (Exception ex) { resp.Message = ex.Message; Logger.LogError("query Infrared Datas error", ex); } return(Json(resp)); }
public IActionResult UpdateEvaluation([FromBody] EvaluationData evaluationData) { ResponseData responseData = new ResponseData { Status = Ok().StatusCode, IsError = false, Text = "Evaluation saved successfully" }; if (ModelState.IsValid) { try { evaluationsService.UpdateEvaluationData(evaluationData); } catch (Exception e) { responseData = new ResponseData { Status = (int)HttpStatusCode.NotModified, IsError = true, Text = "Failed to save evaluation." }; } return(Ok(responseData)); } return(BadRequest()); }
// POST: api/User public ResponseData <UserModelResponse> Post([FromBody] UserModelPost user) { ResponseData <UserModelResponse> resp = new ResponseData <UserModelResponse>(); try { if (BaseRepository <User> .getAll().Where(u => u.Login == user.Login).Count() > 0) { throw new InvalidOperationException("Este login já está sendo utilizado por outro jogador!"); } string ip = Helpers.GetVisitorIPAddress(HttpContext.Current.Request); string encrypted = StringCipher.Encrypt(user.Password, StringCipher.SecretMessage); RegisterUserCommandData data = new RegisterUserCommandData(user.Login, encrypted, ip); resp.Data = AutoMapperFacade.Map <UserModelResponse>(this.RegisterUser.Handle(data).user); resp.Message = "Registro efetuado com sucesso!"; resp.Success = true; } catch (Exception e) { resp.Message = e.Message; } return(resp); }
public async Task <IActionResult> GetAsync( [FromQuery(Name = "search")] string searchRequest, [FromQuery(Name = "ids")] string idsRequest, [FromQuery] ICPC2Groups?groupId, [FromQuery] bool?isActive, [FromQuery] int page = 1, [FromQuery] int?limit = 30) { var ids = new HashSet <string>(); if (!string.IsNullOrEmpty(idsRequest)) { ids = idsRequest.Split(',', StringSplitOptions.RemoveEmptyEntries) .ToHashSet(); } var elements = await GetCodesAsync(searchRequest, ids, groupId, isActive, page, limit); var response = new ResponseData(elements.data); response.AddPaginationData(elements.count, page, limit.Value); return(Ok(response)); }
public ResponseData ForgotPassword(ForgotPasswordRequest forgotPassword) { try { ResponseData responseData = null; var userData = _context.Users.FirstOrDefault(user => user.Email == forgotPassword.Email); if (userData != null) { responseData = new ResponseData() { ID = userData.ID, FirstName = userData.FirstName, LastName = userData.LastName, Email = userData.Email }; } return(responseData); } catch (Exception ex) { throw new Exception(ex.Message); } }
private static ResponseData ExtractResponseData(Response response) { var responseData = new ResponseData { Header = new Dictionary <string, string[]>(), Content = new byte[] {} }; if (response != null) { responseData.StatusCode = (int)response.StatusCode; responseData.ReasonPhrase = response.ReasonPhrase; responseData.Header = response.Headers.ToDictionary(x => x.Key, y => new[] { y.Value }); using (var ms = new MemoryStream()) { response.Contents(ms); responseData.Content = ms.ToArray(); } } return(responseData); }
// [Audit] public JsonResult SaveInventory(InventoryDetailModel model) { IResponseData <int> response = new ResponseData <int>(); try { var service = IoC.Container.Resolve <IInventoryAdjustmentService>(); var nhaThuoc = this.GetNhaThuoc(); var maNhaThuocCha = nhaThuoc.MaNhaThuocCha; int currentUserId = WebSessionManager.Instance.CurrentUserId; // khởi tạo biến data = -1, sau khi lưu thành công set data = Mã Phiếu Kiểm Kê int data = -1; data = service.SaveInventory(MedSessionManager.CurrentDrugStoreCode, maNhaThuocCha, currentUserId, model); response.SetData(data); } catch (ValidationException ex) { response.SetErrors(ex.Errors); response.SetStatus(HttpStatusCode.PreconditionFailed); } return(Json(response)); }
public async Task <IList <OrderDto> > GetMyOrders(string orderId, string getMethod) { var result = ""; IList <OrderDto> orderList = null; try { HttpClient client = await GetClient(); result = await client.GetStringAsync(Url + "/api/order/" + getMethod + "/" + orderId); ResponseData mobilResult = JsonConvert.DeserializeObject <ResponseData>(result); orderList = JsonConvert.DeserializeObject <IList <OrderDto> >(mobilResult.data.ToString()); } catch (Exception exc) { throw; } return(orderList); }
/// <summary> /// 获取单个实例 /// </summary> /// <param name="id">标识</param> /// <returns></returns> protected override ResponseData <T> DoGet <T>(TKey id) where T : class { ResponseData <T> responseData = new ResponseData <T>(); try { string merchantId = merchantService.MerchantId; TEntity entity = manager.Get(id); if (entity != null && entity.MerchantId == merchantId) { responseData.Data = mapper.Map <T>(entity); } } catch (Exception exception) { responseData.ErrorNumber = 1000; responseData.ErrorMessage = Properties.Resources.Error_1000; responseData.Exception = exception; logger.Error(exception); } return(responseData); }
// GET: api/User/5 public ResponseData <UserModelResponse> Get(string login, string password) { ResponseData <UserModelResponse> resp = new ResponseData <UserModelResponse>(); try { string encrypted = StringCipher.Encrypt(password, StringCipher.SecretMessage); User users = BaseRepository <User> .getAll().Where(u => u.Login == login && u.Password == encrypted).FirstOrDefault(); if (users == null) { throw new InvalidOperationException("Login e/ou Senha incorreto(s)!"); } resp.Data = AutoMapperFacade.Map <UserModelResponse>(users); resp.Message = "Login efetuado com sucesso!"; resp.Success = true; } catch (Exception e) { resp.Message = e.Message ?? "Not treated exception!"; } return(resp); }
public async Task <ActionResult> CancelSubscription() { try { var response = new ResponseData <Dashboard>(); string url = _appSettings.ApiUrl + "/Home/CancelSubscription"; client.BaseAddress = new Uri(url); HttpResponseMessage responseMessage = await client.GetAsync(url + "?applianceId=" + current_ApplianceId + "&accountId=" + current_UserID); var responseData = new ResponseData <Dashboard>(); if (responseMessage.IsSuccessStatusCode) { responseData = responseMessage.Content.ReadAsAsync <ResponseData <Dashboard> >().Result; return(Json(new { success = responseData.Status, responseText = responseData.Message })); } return(Json(new { success = ResponseStatus.Error, responseText = ResponseMessage.Error })); } catch (Exception ex) { return(Json(new { success = ResponseStatus.Error, responseText = ex.Message })); } }
public IHttpActionResult Query([FromUri] long userid, long machineryId, sbyte isValid) { var resp = new ResponseData <IEnumerable <Membership> >(); try { var query = from c in DataContext.Membership where (userid == 0 || c.Userid == userid) && (machineryId == 0 || c.MachineryId == machineryId) && c.IsValid == isValid select c; resp.Data = query; //Logger.Log("shitererer"); } catch (Exception ex) { resp.Message = ex.Message; Logger.LogError("query Member ship error", ex); } return(Json(resp)); }
/// <summary> /// 制作饮品回调 /// </summary> /// <param name="req"></param> /// <returns></returns> public ResponseData <string> MakeCallBack(MakeDrinkReq req) { var result = new ResponseData <string> { Code = "0", Data = "成功", Message = "成功", Success = true }; var context = new CoffeeOrderContext(); var materials = JsonConvert.SerializeObject(req.Drink.Materials); var ordDetail = context.BM_COFFEE_DETAIL.Where(o => o.ORDER_ID == req.OrderId && o.COFFEE_TYPE == req.Drink.Value && o.MATERIALS == materials).FirstOrDefault(); ordDetail.ISSUED += req.Drink.Number; context.SaveChanges(); //判断是否已出完咖啡 var ordDetailList = context.BM_COFFEE_DETAIL.Where(o => o.ORDER_ID == req.OrderId).ToList(); if (ordDetailList.Sum(o => o.QUANTITY) == ordDetailList.Sum(o => o.ISSUED)) { FinishCallBack(req.OrderId); } return(result); }
public async Task <ActionResult> GetMonthlySummaryRecordMemberMonthsByConAsync([FromBody] MonthlySummaryRecordMemberMonthsListRequestDto request) { int MasterPatientID = request.MasterPatientID; string Year = request.MemberYear; int eventUserID = Request.GetUserID(); var response = new ResponseData <ResponseDataListPaged <MonthlySummaryRecordMemberMonthsForListDto> > { IsSuccess = true, Code = Constants.ResponseCode.Success, Message = "Success", }; var query = _context.Query <MonthlySummaryRecordMemberMonthsPaged>().FromSql($"dbo.spGetMonthlySummaryRecordMemberMonths {eventUserID},{MasterPatientID},{Year}"); var summaryYearsInfo = await query.AsNoTracking().ToArrayAsync(); response.Data = new ResponseDataListPaged <MonthlySummaryRecordMemberMonthsForListDto> { List = _mapper.Map <IEnumerable <MonthlySummaryRecordMemberMonthsForListDto> >(summaryYearsInfo) }; return(Ok(response)); }
public ActionResult Refresh() { var result = new ResponseData { success = true }; if (!AcSession.IsDeveloper()) { result.success = false; result.msg = "对不起,您不是开发人员,不能执行本功能"; } else { GetRequiredService<IFunctionListImport>().Import(AcDomain, AcSession, AcDomain.Config.SelfAppSystemCode); } return this.JsonResult(result); }
/// <summary> /// Обновляет, опрашивает состояние и получает данные с терминала /// Тип терминала задается в конструкторе класса переменной _TermType /// </summary> public void Refresh(SPort cPort) { //IDevice cDevice = null; switch (_TermType) { case "IMP01": case "TEM05M": Tem05 cTem05 = new Tem05(); //cDevice.Refresh(cPort); cTem05._TimeDelay = _TimeDelay; cTem05._TimeWait = _TimeWait; cTem05._TermId = _TermId; cTem05.Refresh(cPort); ResData = cTem05.ResData; break; case "SPT961": SPT961 cSPT961 = new SPT961(); cSPT961._TimeDelay = _TimeDelay; cSPT961._TimeWait = _TimeWait; cSPT961._TermId = _TermId; cSPT961.RequestParam = _RequestParam; cSPT961.Refresh(cPort); ResData = cSPT961.ResData; break; case "TEM104": TEM104 cTEM104 = new TEM104(); cTEM104._TimeDelay = _TimeDelay; cTEM104._TimeWait = _TimeWait; cTEM104._TermId = _TermId; cTEM104.RequestParam = _RequestParam; cTEM104.Refresh(cPort); ResData = cTEM104.ResData; break; default: throw new ArgumentException("Терминала типа '" + _TermType+"' в системе не описано."); break; } }
public TimeoutClient(IClient client, TimeSpan timeout) { this.client = client; this.timeout = timeout; this.timeoutResponse = new ResponseData(new TimeoutException()); }
public static void LogReply(ServiceMessage Msg, ResponseData Response) { Stopwatch timer = ((Tag)Msg.Tag).Timer; timer.Stop(); Debug.WriteLine( "[" + GetFormattedTime(DateTime.Now) + "] " + string.Format("Replied Message {0} with {1} . Processed in {2} ms \n", Msg.Tag, Response.ResponseType.Name, timer.ElapsedMilliseconds ), "MESSAGING"); }
public static void LogSend(ServiceSocket socket, ResponseData Response) { Debug.WriteLine( "[" + GetFormattedTime(DateTime.Now) + "] " + string.Format("Sent {0} to {1}\n", Response.ResponseType.Name, socket.RemoteIP), "MESSAGING"); }
public static void AddResponseDataType(FlatBufferBuilder builder, ResponseData responseDataType) { builder.AddByte(1, (byte)(responseDataType), 0); }
/// <summary> /// Sends data via the socket asynchronously /// </summary> /// <param name="Message">Data to transmit</param> public void Send(ResponseData Message) { IBuffer sendBuffer = null; //TODO: ENHANCEMENT: Log consecutive bad request response types and use that information to disconnect socket after 3 try { lock (syncSocket) { if (sentMsgs.Count > 1) { sentMsgs.Dequeue(); } sentMsgs.Enqueue(Message); //Log error if .Data is null -- this will help raise a flag if the message is being resent after .ClearData was called Diags.Assert(Message.Data != null, "ASSERTION FAILED: Message Data is null", new System.Diagnostics.StackTrace().ToString()); sendBuffer = bufferPool.GetBuffer(Message.Data.LongLength); sendBuffer.CopyFrom(Message.Data); socket.BeginSend(sendBuffer.GetSegments(), SocketFlags.None, CompleteSend, sendBuffer); Message.ClearData(); //free some memory } } catch (Exception ex) { Diags.LogSocketException(ex); if (sendBuffer != null) { sendBuffer.Dispose(); sendBuffer = null; } } }
/// <summary> /// Process a new response from the license server. /// We call this to guarantee that we fetch a fresh policy from the /// server. This is to be used if the URL is invalid. /// This data will be used for computing future policy decisions. /// The following parameters are processed: /// <ul> /// <li>VT: the timestamp that the client should consider the response valid until</li> /// <li>GT: the timestamp that the client should ignore retry errors until</li> /// <li>GR: the number of retry errors that the client should ignore</li> /// </ul> /// </summary> /// <param name="response"> /// the result from validating the server response /// </param> /// <param name="rawData"> /// the raw server response data /// </param> public void ProcessServerResponse(PolicyServerResponse response, ResponseData rawData) { // Update retry counter if (response == PolicyServerResponse.Retry) { this.RetryCount = this.RetryCount + 1; } else { this.RetryCount = 0; } if (response == PolicyServerResponse.Licensed) { // Update server policy data var extras = new Dictionary<string, string>(); try { extras = PolicyExtensions.DecodeExtras(rawData.Extra); } catch (Exception) { Debug.WriteLine("Invalid syntax error while decoding extras data from server."); } // If no response or not parseable, expire in one minute. this.ValidityTimestamp = PolicyExtensions.GetCurrentMilliseconds() + PolicyExtensions.MillisPerMinute; foreach (var pair in extras) { this.ProcessResponseExtra(pair); } } else if (response == PolicyServerResponse.NotLicensed) { // Clear out stale policy data this.ValidityTimestamp = 0; this.RetryUntil = 0; this.MaxRetries = 0; } this.LastResponse = response; this.obfuscator.Commit(); }
public ActionResult DeleteEntity(string ontologyCode, string id/*infoID*/) { var response = new ResponseData { success = true, id = id }; OntologyDescriptor ontology; if (!AcDomain.NodeHost.Ontologies.TryGetOntology(ontologyCode, out ontology)) { throw new ValidationException("非法的本体码"); } string[] infoIDs = id.Split(','); foreach (var item in infoIDs) { if (id != "-1") { var commandResult = this.DeleteEntity(ontology, new Guid(item)); if (commandResult.Body.Event.Status == (int)Status.ToAudit) { response.success = false; response.msg = commandResult.Body.Event.Description; response.Info(); } if (commandResult.Body.Event.Status < 200 || commandResult.Body.Event.Status >= 300) { response.success = false; response.msg = commandResult.Body.Event.Description; response.Warning(); } } } return this.JsonResult(response); }
public ActionResult AuditApproved(string ontologyCode, string id) { var response = new ResponseData { id = id, success = true }; OntologyDescriptor ontology; if (!AcDomain.NodeHost.Ontologies.TryGetOntology(ontologyCode, out ontology)) { throw new ValidationException("非法的本体码"); } string[] ids = id.Split(','); var localEventIDs = new Guid[ids.Length]; for (int i = 0; i < ids.Length; i++) { Guid tmp; if (Guid.TryParse(ids[i], out tmp)) { localEventIDs[i] = tmp; } else { throw new ValidationException("意外的本地事件标识" + ids[i]); } } foreach (var localEventId in localEventIDs) { MessageEntity evnt = ontology.MessageProvider.GetCommand(MessageTypeKind.LocalEvent, ontology, localEventId); if (evnt != null) { if (evnt.Status == (int)Status.ToAudit && evnt.EventSourceType.Equals("Command", StringComparison.OrdinalIgnoreCase)) { var node = AcDomain.NodeHost.Nodes.ThisNode; var ticks = DateTime.UtcNow.Ticks; var cmd = new Message() { Version = ApiVersion.V1.ToName(), IsDumb = false, MessageType = MessageType.Event.ToName(), Credential = new CredentialData { ClientType = ClientType.Node.ToName(), UserType = UserType.None.ToName(), CredentialType = CredentialType.Token.ToName(), ClientId = node.Node.PublicKey.ToString(), UserName = evnt.UserName,// UserName Password = TokenObject.Token(node.Node.Id.ToString(), ticks, node.Node.SecretKey), Ticks = ticks }, TimeStamp = DateTime.UtcNow.Ticks, MessageId = evnt.Id.ToString(), Verb = evnt.Verb.Code, Ontology = evnt.Ontology, Body = new BodyData(new KeyValue[] { new KeyValue("Id", evnt.LocalEntityId) }, evnt.DataTuple.ValueItems.Items.ToDto()) { Event = new EventData { Status = (int)Status.AuditApproved, ReasonPhrase = Status.AuditApproved.ToName(), SourceType = evnt.EventSourceType, Subject = evnt.EventSubjectCode } } }; var result = AnyMessage.Create(HecpRequest.Create(AcDomain, cmd), AcDomain.NodeHost.Nodes.ThisNode).Response(); if (result.Body.Event.Status == (int)Status.NotExist) { ontology.MessageProvider.DeleteCommand(MessageTypeKind.LocalEvent, ontology, evnt.Id, evnt.IsDumb); } else { if (result.Body.Event.Status < 200 || result.Body.Event.Status >= 400) { response.success = false; response.msg = result.Body.Event.Description; response.Warning(); } } } } else { response.success = false; response.msg = "给定标识的本地事件不存在"; response.Warning(); } } return this.JsonResult(response); }
public ActionResult AddOrUpdate(string ontologyCode) { OntologyDescriptor ontology; if (!AcDomain.NodeHost.Ontologies.TryGetOntology(ontologyCode, out ontology)) { throw new ValidationException("非法的本体码"); } NameValueCollection form = Request.Form; bool isCreate = string.IsNullOrEmpty(form["id"]); IList<InfoItem> infoValues = new List<InfoItem>(); IList<InfoItem> infoIDs = new List<InfoItem>(); foreach (string k in form.Keys) { if (!k.Equals("id", StringComparison.OrdinalIgnoreCase)) { ElementDescriptor element; if (ontology.Elements.TryGetValue(k, out element)) { if (element.Element.IsEnabled != 1) { continue; } if (isCreate) { if (!string.IsNullOrEmpty(form[k]) && form[k] != "undefined") { infoValues.Add(InfoItem.Create(element, form[k])); } } else { if (form["__" + k] != form[k]) { infoValues.Add(InfoItem.Create(element, form[k])); } } } } } string id = form["Id"]; infoIDs.Add(InfoItem.Create(ontology.IdElement, form["Id"])); var response = new ResponseData { success = true }; if (infoValues.Count > 0) { IMessageDto commandResult; if (isCreate) { infoIDs.Add(InfoItem.Create(ontology.Elements["ZZJGM"], form["ZZJGM"])); infoIDs.Add(InfoItem.Create(ontology.Elements["XM"], form["XM"])); commandResult = this.Save(ontology, infoIDs, infoValues, out id); if (commandResult.Body.Event.Status == (int)Status.ToAudit) { response.success = false; response.msg = commandResult.Body.Event.Description; response.Warning(); } } else { commandResult = this.Update(ontology, infoIDs, infoValues); if (commandResult.Body.Event.Status == (int)Status.ToAudit) { response.success = false; response.msg = commandResult.Body.Event.Description; response.Warning(); } } if (commandResult.Body.Event.Status < 200 || commandResult.Body.Event.Status >= 300) { response.success = false; response.msg = commandResult.Body.Event.Description; response.Warning(); if (commandResult.Body.Event.Status == (int)Status.AlreadyExist) { response.msg = "本目录下已经存在重名的用户"; } } } else { response.success = false; response.msg = "数据无变化"; response.Warning(); } response.id = id; return this.JsonResult(response); }
/// <summary> /// Process a new response from the license server. /// This data will be used for computing future policy decisions. The /// following parameters are processed: /// <ul> /// <li>VT: the timestamp that the client should consider the response valid until</li> /// <li>GT: the timestamp that the client should ignore retry errors until</li> /// <li>GR: the number of retry errors that the client should ignore</li> /// </ul> /// </summary> /// <param name="response"> /// the result from validating the server response /// </param> /// <param name="rawData"> /// the raw server response data /// </param> public virtual void ProcessServerResponse(PolicyServerResponse response, ResponseData rawData) { // Update retry counter this.RetryCount = response == PolicyServerResponse.Retry ? this.RetryCount + 1 : 0; switch (response) { case PolicyServerResponse.Licensed: // Update server policy data Dictionary<string, string> extras; if (!PolicyExtensions.TryDecodeExtras(rawData.Extra, out extras)) { Debug.WriteLine("Invalid syntax error while decoding extras data from server."); } // If no response or not parseable, expire in one minute. this.ValidityTimestamp = PolicyExtensions.GetCurrentMilliseconds() + PolicyExtensions.MillisPerMinute; foreach (var pair in extras) { this.ProcessResponseExtra(pair); } break; case PolicyServerResponse.NotLicensed: this.ValidityTimestamp = Preferences.DefaultValidityTimestamp; this.RetryUntil = Preferences.DefaultRetryUntil; this.MaxRetries = Preferences.DefaultMaxRetries; break; } this.LastResponse = response; this.Obfuscator.Commit(); }
public ResponseData PortQuery_() { ResponseData resData = new ResponseData(); return resData; }
public ResponseData GetData(NetReader reader) { ResponseData data = new ResponseData(); data.ActionId = reader.ActionId; data.ErrorCode = reader.StatusCode; data.ErrorMsg = reader.Description; IResponse ret = null; if (data.ErrorCode == Net.Instance.NetSuccess) { ret = GetResponse(reader, data.ActionId); } data.Resonse = ret; return data; }
public RedisResponse(string requestId, ResponseData response) { this.RequestId = requestId; this.Response = response; }
/// <summary> /// Process a new response from the license server. Since we aren't /// performing any caching, this equates to reading the LicenseResponse. Any /// ResponseData provided is ignored. /// </summary> /// <param name="response"> /// the result from validating the server response /// </param> /// <param name="rawData"> /// the raw server response data /// </param> public void ProcessServerResponse(PolicyServerResponse response, ResponseData rawData) { this.lastResponse = response; }
/// <summary> /// Gets the response data /// </summary> /// <returns>ResponseData</returns> /// <seealso cref="SiLADevice.ExecuteAsync"/> public ResponseData GetResponseData() { if (_responseData == null) { _responseData = new ResponseData(); } return _responseData; }
void DoRespond(EventHttpRequest req, ResponseData resp) { req.Respond((System.Net.HttpStatusCode) resp.Code, resp.Headers ?? new Dictionary<string, string>(), resp.Data ?? new byte[0]); }
/// <summary> /// Sets the response data /// </summary> /// <param name="data">The data.</param> /// <seealso cref="SiLADevice.ExecuteAsync"/> public void SetResponseData(ResponseData data) { _responseData = data; }
private void RequestHandler(EventHttpRequest req) { if (req.Uri == null) { req.Respond(System.Net.HttpStatusCode.BadRequest, new Dictionary<string, string>(), new byte[0]); return; } ThreadPool.QueueUserWorkItem(_ => { Request nreq; try { PreProcessRequest(req); var pairs = req.Uri.Split(new[] {'?'}, 2); var path = Uri.UnescapeDataString(pairs[0]); var query = pairs.Length == 2 ? pairs[1] : string.Empty; nreq = CreateRequest(req.Method, req.Host, path, req.Headers, RequestStream.FromStream(new MemoryStream(req.RequestBody)), "http", query, req.UserHostAddress); } catch(Exception e) { DoRespond(req, GetExceptionResponse(e)); return; } try { _engine.HandleRequest( nreq, ctx => { ResponseData resp; try { var ms = new MemoryStream(); PostProcessNancyResponse(nreq, ctx.Response); ctx.Response.Contents(ms); resp = new ResponseData(ctx.Response.StatusCode, ms.ToArray(), ctx.Response.Headers); } catch (Exception e) { resp = GetExceptionResponse(e); } DoRespond(req, resp); }, exception => DoRespond(req, GetExceptionResponse(exception))); } catch (Exception e) { DoRespond(req, GetExceptionResponse(e)); } }); }
/// <summary> /// Process a new response from the license server. /// This data will be used for computing future policy decisions. The /// following parameters are processed: /// <ul> /// <li>VT: the timestamp that the client should consider the response valid until</li> /// <li>GT: the timestamp that the client should ignore retry errors until</li> /// <li>GR: the number of retry errors that the client should ignore</li> /// </ul> /// </summary> /// <param name="response"> /// the result from validating the server response /// </param> /// <param name="rawData"> /// the raw server response data /// </param> public void ProcessServerResponse(PolicyServerResponse response, ResponseData rawData) { // Update retry counter this.RetryCount = response == PolicyServerResponse.Retry ? this.RetryCount + 1 : 0; switch (response) { case PolicyServerResponse.Licensed: // Update server policy data Dictionary<string, string> extras; if (!PolicyExtensions.TryDecodeExtras(rawData.Extra, out extras)) { Debug.WriteLine("Invalid syntax error while decoding extras data from server."); } else { this.SetValidityTimestamp(extras.ContainsKey("VT") ? extras["VT"] : DefaultValidityTimestamp); this.SetRetryUntil(extras.ContainsKey("GT") ? extras["GT"] : DefaultRetryUntil); this.SetMaxRetries(extras.ContainsKey("GR") ? extras["GR"] : DefaultMaxRetries); } break; case PolicyServerResponse.NotLicensed: this.SetValidityTimestamp(DefaultValidityTimestamp); this.SetRetryUntil(DefaultRetryUntil); this.SetMaxRetries(DefaultMaxRetries); break; } this.LastResponse = response; this.preferences.Commit(); }