public ResponseBase<Data> aa(string UserId, string EncodePassword, string Search, string StartRow, string EndRow) { ResponseBase<Data> ReturnResult = new ResponseBase<Data>(); string SUrl = string.Empty; string content = string.Empty; SUrl = "https://uemployee.api.liontravel.com/api/V1/EmployeeContent?UserId=" + UserId + "&EncodePassword="******"&Search=" + Search + "&StartRow=" + StartRow + "&EndRow=" + EndRow; var request = HttpWebRequest.Create(SUrl); request.ContentType = "application/json"; request.Method = "GET"; request.Headers.Add("Authorization", "basic MjA2OTQ2MzE5NjkzMjU0OTYzMjAxNS81LzI4IKRXpMggMTE6NTE6NTI"); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode); return ReturnResult; } using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { content = reader.ReadToEnd(); ReturnResult = JsonConvert.DeserializeObject<ResponseBase<Data>>(content); } } return ReturnResult; }
public void CheckIntoEvent(string userId, string eventCode) { string json = ParamsToJSON ("user_id", userId, "event_code", eventCode); SayHiRestClient syrc = new SayHiRestClient (SayHiRestClient.HTTPPOSTMETHOD, CreateEndpointURL (CheckInUserPath), json); syrc.OnRestCallCompleted += (RestResult obj) => { ResponseBase ret = null; if (!obj.IsSuccess) { ret = new ResponseBase (obj.IsSuccess, obj.Result); } else { try { bool success = false; string msg = ""; using (JsonTextReader jtr = new JsonTextReader(new StringReader(obj.Result))) { while (jtr.Read()) { if (JsonKeyMatches (jtr, JsonToken.PropertyName, "Success")) { success = jtr.ReadAsInt32 () == 0; } } if (!success) { msg = "Unabled to parse JSON"; } ret = new ResponseBase (success, msg); } } catch (Exception e) { ret = new ResponseBase (false, GenerateParseErrorMessage (e)); } } SafeRaiseEvent (OnCheckIntoEventCompleted, ret); }; syrc.SendRestRequest (); }
/// <summary> /// 創瑞 /// </summary> /// <returns></returns> public ResponseBase<string> Post() { #region 宣告 //參數宣告 ResponseBase<string> RespBaseReturn = new ResponseBase<string>(); //預設值 RespBaseReturn.IsSuccess = true; RespBaseReturn.Msg = ""; RespBaseReturn.Data = null; //DataModel StatusUp StatusUpClass = new StatusUp(); //變數 string strparameter = string.Empty; string client = string.Empty; string strUrltoJson = string.Empty; var httpRequest = System.Web.HttpContext.Current.Request; #endregion try { if (httpRequest.InputStream.CanRead)//將Url轉成Json格式 { var reader = new System.IO.StreamReader(httpRequest.InputStream);//用httpRequsest去讀取InputStream,InputStream的資料是從 strUrltoJson = reader.ReadToEnd();//停止讀取posman的json資料 StatusUpClass = JsonConvert.DeserializeObject<StatusUp>(strUrltoJson); } strparameter = "name=" + StatusUpClass.name + "&pwd=" + StatusUpClass.pwd + "&sendid=" + StatusUpClass.sendid + "&time=" + StatusUpClass.time + "&mobile=" + StatusUpClass.mobile + "&state=" + StatusUpClass.state; client = FunWebClientPost(strparameter, Url); if (string.IsNullOrWhiteSpace(client)) { RespBaseReturn.Msg = "修改資料失敗!"; return RespBaseReturn; } RespBaseReturn = JsonConvert.DeserializeObject<ResponseBase<string>>(client); return RespBaseReturn; } catch (Exception ex) { return RespBaseReturn; } }
public async Task <ResponseBase <Question> > Create(QuestionModel model, string accessToken) { if (accessToken != null) { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } var json = JsonConvert.SerializeObject(model); var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("api/Questions/", httpContent); if (response.IsSuccessStatusCode) { var body = await response.Content.ReadAsStringAsync(); ResponseBase <Question> createResult = JsonConvert.DeserializeObject <ResponseBase <Question> >(body); return(createResult); } else { return(null); } }
private static void CloseNTMiner() { bool isClosed = false; ResponseBase response = RpcRoot.Post <ResponseBase>(NTKeyword.Localhost, NTKeyword.MinerClientPort, _minerClientControllerName, nameof(IMinerClientController.CloseNTMiner), new SignRequest { }); isClosed = response.IsSuccess(); if (!isClosed) { try { string location = NTMinerRegistry.GetLocation(NTMinerAppType.MinerClient); if (!string.IsNullOrEmpty(location) && File.Exists(location)) { string processName = Path.GetFileNameWithoutExtension(location); Windows.TaskKill.Kill(processName); } } catch (Exception e) { Logger.ErrorDebugLine(e); } } }
public ResponseBase SetVirtualMemory(Dictionary <string, int> data) { ResponseBase response; if (data == null || data.Count == 0) { response = ResponseBase.InvalidInput("参数错误"); } else { try { VirtualRoot.DriveSet.SetVirtualMemory(data); response = ResponseBase.Ok("设置虚拟内存,需重启电脑,重启电脑后生效"); } catch (Exception e) { Logger.ErrorDebugLine(e); response = ResponseBase.ServerError(e.Message); } } VirtualRoot.OperationResultSet.Add(response.ToOperationResult()); return(response); }
public async Task <ResponseBase> GetProvince() { try { var areas = await _areaBll.GetProvince(); return(ResponseBase.Success(areas.Select(p => new GetAreaView() { AreaId = p.AreaId, AreaName = p.AreaName, ParentId = p.ParentId, Level = p.Level } ))); } catch (Exception ex) { Log.Error(ex.Message, ex, this.GetType()); return(ResponseBase.CodeError()); } }
public void LoginTest_ReturnsValidCredentials_MobileFault() { RESTAPIProfileController api = new RESTAPIProfileController(); RESTAPILoginCredentials req = new RESTAPILoginCredentials() { UserName = "", Password = "", CallerId = "", Platform = "" }; GetProfileResponse profileRes = new GetProfileResponse() { Credentials = new AccessCredentials() { UserID = 1000, SessionToken = "sessionToken", CallerId = "CallerId" }, CustomerProfileObject = new CustomerProfile() { ActiveHealth = true } }; hpidMock.Setup(x => x.GetCustomerProfileByTestLogin(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <APIMethods>())).Returns(profileRes); // customerMock.Setup(x => x.GetCustomerProfile(It.IsAny<UserAuthenticationInterchange>(), It.IsAny<bool>())).Returns(profileRes); ResponseBase mobileResponse = new ResponseBase() { ErrorList = new HashSet <Fault>() { new Fault("", "", "") } }; RESTAPILoginResponse response = api.Login(req); Assert.IsTrue(response.ErrorList.Count == 0); Assert.IsTrue(response.UserID == 1000); Assert.AreEqual(response.SessionToken, "sessionToken"); Assert.AreEqual(response.CallerId, "CallerId"); }
///// <summary> ///// Function maps Generic Faults from HPP to our Fault object ///// </summary> ///// <param name="r">ResponseBase object - should not be null</param> ///// <param name="hppFaults">Array of GenericFaultType objects</param> //public void MapHPPGenericFaults(ResponseBase r, HPPService.genericFaultType[] hppFaults) //{ // if (hppFaults != null && hppFaults.Length > 0) // { // foreach (HPPService.genericFaultType f in hppFaults) // { // if (f == null) // just to be sure // continue; // // Those are errors that indicates if email was found or not in database // // This kind of response should be hidden because of security issue // // using brute-force checking someone could get list of registered mails // if (f.ruleNumber != 473 && f.ruleNumber != 807) // { // // if other rule occur please add the fault to list in class Faults and use it here // // building Fault using 'new' should be considered only in places where you don't know what type of error can happen // if (Faults.HppErrorMap.ContainsKey(f.ruleNumber)) // r.ErrorList.Add(Faults.HppErrorMap[f.ruleNumber]); // else // r.ErrorList.Add(new Fault("HPP", Faults.GenericError.ReturnCode, Convert.ToString(f.ruleNumber) + ": " + f.desc)); // } // } // } //} public void MapGenericFaults(ResponseBase r, string errXml) { if (!string.IsNullOrEmpty(errXml) && errXml.Length > 0) { XmlDocument xdoc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("ns", "http://isac.hp.com/schema/registrations/CustomeErrorSchema.xsd"); xdoc.LoadXml("<err>" + errXml + "</err>"); XmlNodeList nodeFaults = xdoc.DocumentElement.FirstChild.ChildNodes; foreach (XmlNode nodeFault in nodeFaults) { //this is needed to filter out nodes that dont provide error information if (!string.IsNullOrEmpty(nodeFault.InnerText) && nodeFault.InnerText.Length > 2) { MapReturnCode(nodeFault.OuterXml, r); } } } }
internal static QueryClientsResponse DoQueryClients(QueryClientsRequest request, UserData user) { if (request == null) { return(ResponseBase.InvalidInput <QueryClientsResponse>("参数错误")); } request.PagingTrim(); try { var data = WebApiRoot.ClientDataSet.QueryClients( user, request, out int total, out CoinSnapshotData[] latestSnapshots, out int totalOnlineCount, out int totalMiningCount) ?? new List <ClientData>(); return(QueryClientsResponse.Ok(data, total, latestSnapshots, totalMiningCount, totalOnlineCount)); } catch (Exception e) { Logger.ErrorDebugLine(e); return(ResponseBase.ServerError <QueryClientsResponse>(e.Message)); } }
public ResponseBase Delete(int Id) { var rs = new ResponseBase(); try { using (var db = new PMSEntities()) { var obj = db.Errors.FirstOrDefault(x => !x.IsDeleted && x.Id == Id); if (obj != null) { obj.IsDeleted = true; db.SaveChanges(); rs.IsSuccess = true; rs.Messages.Add(new Message() { Title = "Thông Báo", msg = "Xóa Thành công." }); } else { rs.IsSuccess = false; rs.Messages.Add(new Message() { Title = "Lỗi", msg = "không tìm thấy lỗi." }); } } } catch (Exception) { rs.IsSuccess = false; rs.Messages.Add(new Message() { Title = "Lỗi", msg = "không tìm thấy lỗi." }); } return(rs); }
public JsonResult Delete(MuaAoModel m) { ResponseBase res = new ResponseBase(); try { var dt = (from a in db.MuaAos where a.ID == m.ID select a).FirstOrDefault(); dt.IDDoanVien = m.IDDoanVien; dt.TrangThai = 3; db.SubmitChanges(); res.Status = StatusID.Success; res.Message = "Đã huỷ đơn hàng"; } catch (Exception e) { res.Status = StatusID.InternalServer; res.Message = e.Message; } return(Json(res, JsonRequestBehavior.AllowGet)); }
public ResponseBase UpdateSystem(CategoryModel menuCategory, int userId) { using (var db = new IEDEntities()) { ResponseBase result = null; try { result = new ResponseBase(); SCategory category = db.SCategories.FirstOrDefault(x => x.Id == menuCategory.Id && !x.IsDeleted); if (category != null) { category.Position = menuCategory.Position; category.OrderIndex = menuCategory.OrderIndex; if (menuCategory.Icon != "0" && menuCategory.Icon != null) { category.Icon = menuCategory.Icon.Split(',').ToList().FirstOrDefault(); } category.UpdatedUser = userId; category.UpdatedDate = DateTime.Now; db.Entry <SCategory>(category).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); result.IsSuccess = true; } else { result.IsSuccess = false; result.Errors.Add(new Error() { MemberName = "Cập Nhật Nhóm Danh Mục", Message = "Nhóm Danh Mục đang thao tác không tồn tại. Vui lòng kiểm tra lại!" }); } } catch (Exception ex) { throw ex; } return(result); } }
public ResponseBase <AnuncioDTO> Read(int id) { var response = new ResponseBase <AnuncioDTO>(); try { var keys = new Dictionary <string, object>(); keys.Add("ID", id); var anuncio = _anuncioRepository.Get(keys); response.Data = _mapper.Map(anuncio, new AnuncioDTO()); } catch (Exception ex) { response.Success = false; response.Message = $"{ex.Message}"; response.Exception = ex; } return(response); }
public JsonResult Update(DeXuatModel m) { ResponseBase res = new ResponseBase(); try { var dt = (from a in db.DeXuats where a.ID == m.ID select a).FirstOrDefault(); dt.IDDoanVien = m.IDDoanVien; dt.NoiDung = m.NoiDung; dt.NgayThang = DateTime.Parse(m.NgayThang); db.SubmitChanges(); res.Status = StatusID.Success; res.Message = "Thông tin đã cập nhật thành công"; } catch (Exception e) { res.Status = StatusID.InternalServer; res.Message = e.Message; } return Json(res, JsonRequestBehavior.AllowGet); }
/// <summary> /// 同步租户 /// </summary> /// <param name="token"></param> /// <param name="dto"></param> /// <returns></returns> public ResponseBase SyncMemberInfos() { var response = new ResponseBase(); try { GetSyncMember(out response); } catch (Exception ex) { response.IsSuccess = false; response.OperationDesc = "请求错误"; WriteLogException(ex); // 记录日志信息 } if (response.IsSuccess) { response.OperationDesc = "会员同步成功,共" + _syncSUM + "条数据"; } _syncCount = 0; _syncSUM = 0; return(response); }
public async Task <ResponseBase <List <OrderModel> > > GetOrders() { var response = new ResponseBase <List <OrderModel> >(); response = await httpService.Send <List <OrderModel> >(UriMethod.Get); return(await Task.Run(() => response)); //var response = new ResponseBase<List<OrderModel>>(); //var search = new List<OrderModel>(); //var lst = new List<OrderModel>(); //lst = GetList(); //response.Code = 200; //response.Data = lst; //Thread.Sleep(500); //return await Task.Run(() => response); }
public ResponseBase <UsuarioDTO> Obter(int id) { ResponseBase <UsuarioDTO> br = new ResponseBase <UsuarioDTO>(); if (UsuarioLogado.Id != id) { br.Mensagens.Add("Não encontrado."); return(br); } var usuario = _contexto.Usuario.Find(id); if (usuario == null) { br.Mensagens.Add("Não encontrado."); return(br); } br.Objeto = usuario.TraduzirParaDTO(); return(br); }
public async Task <ResponseBase <bool> > DeleteCustomer(long id) { var response = new ResponseBase <bool>(); var service = new CustomerClient(); try { var callback = await service.DeleteCustomerAsync(id); response.Code = callback.Code; response.Data = callback.Data; response.Message = callback.Message; } catch (Exception ex) { response.Code = StatusCode.ServiceUnavailable; response.Message = $"Ups! no se pudo crear el usuario: {ex.Message}"; } service.Close(); return(response); }
public async Task <ResponseBase <bool> > InsertOrder(OrderModel data) { var response = new ResponseBase <bool>(); var validate = ValidateMiddle.Result(data); if (validate.Status) { IRepository <OracleParameterCollection> repository = new OracleRepository(); repository.Status.Code = Status.Ok; if (repository.Status.Code == Status.Ok) { var OrdId = 1; foreach (var item in data.LItems) { item.OrdId = OrdId; item.IdEstado = 1; InsertItem(item); } ; response.Data = true; response.Message = "Orden insertada correctamente"; } else { response.Data = false; response.Message = repository.Status.Message; } response.Code = repository.Status.Code; } else { response.Code = Status.InvalidData; response.Message = validate.Message; } return(await Task.Run(() => response)); }
public ResponseBase DeleteSecondLevelSafetyAssessmentReport(ManualInspectionSafetyAssementReportUploadRequest req) { ResponseBase resp = new ResponseBase(); IList <Func <ManualInspectionSafetyAssessmentReportTable, bool> > ps = new List <Func <ManualInspectionSafetyAssessmentReportTable, bool> >(); DealWithDeleteConditon(req, ps); try { var source = _getManualInspectionSafetyAssessmentReportDAL.FindBy(ps).SingleOrDefault(); _getManualInspectionSafetyAssessmentReportDAL.Remove(source); resp.Succeed = true; resp.Message = "删除报告成功"; } catch (Exception ex) { resp.Succeed = false; resp.Message = "删除报告失败!"; Log(ex); } return(resp); }
public ResponseBase StopMine() { ResponseBase response; try { if (!IsNTMinerOpened()) { response = ResponseBase.Ok(); } else { RpcRoot.Post <ResponseBase>(NTKeyword.Localhost, NTKeyword.MinerClientPort, _minerClientControllerName, nameof(IMinerClientController.StopMine), new SignRequest()); response = ResponseBase.Ok("停止挖矿"); } } catch (Exception e) { Logger.ErrorDebugLine(e); response = ResponseBase.ServerError(e.Message); } VirtualRoot.OperationResultSet.Add(response.ToOperationResult()); return(response); }
public async Task <ResponseBase> InsertarIngreso(Ingreso ingreso) { var response = new ResponseBase(); try { using (var connection = new SqlConnection(con.getConnection())) { using (var command = new SqlCommand("Reporte.spInsertarIngreso", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.Clear(); command.Parameters.AddWithValue("@idIngreso", 0); command.Parameters.AddWithValue("@idEmpresa", ingreso.idEmpresa); command.Parameters.AddWithValue("@concepto", ingreso.concepto); command.Parameters.AddWithValue("@descripcion", ingreso.descripcion); command.Parameters.AddWithValue("@cantidad", ingreso.cantidad); command.Parameters.AddWithValue("@fecha", ingreso.fecha); command.Parameters.AddWithValue("@hora", ingreso.hora); command.Parameters["@idIngreso"].Direction = ParameterDirection.Output; connection.Open(); var result = await command.ExecuteNonQueryAsync(); if (result > 0) { response.success = true; response.message = "Datos insertados correctamente"; response.id = Convert.ToInt32(command.Parameters["@idIngreso"].Value); } } } } catch (Exception ex) { response.success = false; response.message = ex.Message; } return(response); }
public ResponseBase DeleteBook(DeleteBookRequest request) { var response = new ResponseBase(); try { var book = _bookRepository.GetById(request.Id); _bookRepository.Delete(book); _bookUnitOfWork.Commit(); response.TransactionMessage = "Book deleted Successfully"; response.TransactionStatus = true; } catch (InvalidBookException ex) { response.TransactionMessage = "Book deletion failed"; response.TransactionStatus = false; LoggingFactory.GetLogger().Log(ex.Message.ToString()); } return(response); }
public JsonResult Index(LoadWebCommandQueueListRequest req) { ViewBag.CommandQueueCreateTimeRange = req.CommandQueueCreateTimeRange; ViewBag.CommandId = req.CommandId.ToString(); ViewBag.ExecuteStatus = req.CommandStatus.ToString(); ViewBag.NodeId = req.NodeId.ToString(); ViewBag.TaskId = req.TaskId.ToString(); ViewBag.CommandQueueId = req.CommandQueueId.ToString(); ResponseBase <PageInfoResponse <List <WebCommandQueueListDto> > > tasklist = PostToServer <PageInfoResponse <List <WebCommandQueueListDto> >, LoadWebCommandQueueListRequest>(ClientProxy.LoadWebCommandQueueList_Url, req); if (tasklist.Status != ResponesStatus.Success) { return(Json(new { sEcho = 0, iTotalRecords = 0, iTotalDisplayRecords = 0, aaData = new List <string>() })); } return(Json(tasklist.Data)); }
public async Task <ResponseBase <bool> > Create(ExampleModel data) { IRepository <SqlParameterCollection> repository = new SqlServerRepository(connString); var response = new ResponseBase <bool>() { Data = true, Message = "Datos registrados" }; repository.Parameters.Add("@name", SqlDbType.NVarChar, 100).Value = data.Name; repository.Parameters.Add("@date", SqlDbType.DateTime).Value = data.Date; repository.SaveChanges("usp_toures_create"); if (repository.Status.Code != Status.Ok) { response.Data = false; response.Message = repository.Status.Message; } response.Code = repository.Status.Code; return(await Task.Run(() => response)); }
public ResponseBase ExportMineWork([FromBody] ExportMineWorkRequest request) { if (request == null) { return(ResponseBase.InvalidInput <ResponseBase>("参数错误")); } try { if (!request.IsValid(HostRoot.Instance.UserSet.GetUser, ClientIp, out ResponseBase response)) { return(response); } string localJsonFileFullName = SpecialPath.GetMineWorkLocalJsonFileFullName(request.MineWorkId); string serverJsonFileFullName = SpecialPath.GetMineWorkServerJsonFileFullName(request.MineWorkId); File.WriteAllText(localJsonFileFullName, request.LocalJson); File.WriteAllText(serverJsonFileFullName, request.ServerJson); return(ResponseBase.Ok()); } catch (Exception e) { Logger.ErrorDebugLine(e.Message, e); return(ResponseBase.ServerError <ResponseBase>(e.Message)); } }
public GetCoinSnapshotsResponse LatestSnapshots([FromBody] GetCoinSnapshotsRequest request) { if (request == null) { return(ResponseBase.InvalidInput <GetCoinSnapshotsResponse>("参数错误")); } try { if (!request.IsValid(HostRoot.Instance.UserSet.GetUser, ClientIp, out GetCoinSnapshotsResponse response)) { return(response); } List <CoinSnapshotData> data = HostRoot.Instance.CoinSnapshotSet.GetLatestSnapshots( request.Limit, out int totalMiningCount, out int totalOnlineCount) ?? new List <CoinSnapshotData>(); return(GetCoinSnapshotsResponse.Ok(data, totalMiningCount, totalOnlineCount)); } catch (Exception e) { Logger.ErrorDebugLine(e.Message, e); return(ResponseBase.ServerError <GetCoinSnapshotsResponse>(e.Message)); } }
public void IsDownloadFailsAfterMaxRetries() { var configSetting = new ConfigurationSetting() { NumberOfTrial = 10, LocalFilePath = "C:\\temp", MinSizeSegment = 200000, RetrialDelay = 10, NumberOfSegments = 5, Timeout = -1, LogFilePath = "C:\\temp\\log.txt" }; var rd = new ResourceDetail() { Url = "http://testutl.example/file.txt" }; FileDownloader fileDownloader = new FileDownloader(_mockSegementProcessorDownloadSegmentRetries.Object, _mockProtcolDownloadSegmentRetries.Object, new InitializeDownload()); ResponseBase response = fileDownloader.StartDownload(rd, configSetting); Assert.IsTrue(response.Denied); _mockSegementProcessorDownloadSegmentRetries.Verify(m => m.ProcessSegment(It.IsAny <ResourceDetail>(), It.IsAny <IProtocolDownloader>(), It.IsAny <Segment>())); }
public Task <HttpResponseMessage> CheckLogin(string uuid) { ResponseBase <CheckLoginResponse> response = new ResponseBase <CheckLoginResponse>(); var result = _wechat.CheckLoginQRCode(uuid); CheckLoginResponse checkLoginResponse = new CheckLoginResponse(); checkLoginResponse.State = result.State; checkLoginResponse.Uuid = result.Uuid; checkLoginResponse.WxId = result.WxId; checkLoginResponse.NickName = result.NickName; checkLoginResponse.Device = result.Device; checkLoginResponse.HeadUrl = result.HeadUrl; checkLoginResponse.Mobile = result.BindMobile; checkLoginResponse.Email = result.BindEmail; checkLoginResponse.Alias = result.Alias; checkLoginResponse.Data62 = result.Remark; response.Data = checkLoginResponse; return(response.ToHttpResponseAsync()); }
public ResponseBase saveSizesBase(List <DatabaseSizesModelRequest> listSizes) { var response = new ResponseBase(); var listModel = new List <DatabaseSizesModel>(); try { foreach (var sizes in listSizes) { var model = new DatabaseSizesModel(); model.Instance = sizes.Instance; model.Base = sizes.Base; model.SizeMB = sizes.SizeMB; model.FreeSpaceMB = sizes.FreeSpaceMB; model.MaxSize = sizes.MaxSize; model.Growth = sizes.Growth; model.IsPercentGrowth = sizes.IsPercentGrowth ? 1 : 0; model.LogicName = sizes.LogicName; model.PhysicName = sizes.PhysicName; model.Type = sizes.Type; model.Fecha = sizes.Fecha; listModel.Add(model); } _sizesService.saveBasesSizes(listModel); response.Success = true; } catch (Exception ex) { response.Message = ex.Message.ToString(); Elmah.ErrorSignal.FromCurrentContext().Raise(ex); } return(response); }
public virtual ResponseBase Delete(TKey id) { var resp = new ResponseBase { Type = ResponseType.Fail }; var entity = Repository.GetById(id); if (entity == null) { resp.ErrorCode = ErrorCode.RecordNotFound; return(resp); } if (ValidateEntityOwner) { //client wants to check for an IDOR attack if (!IsEntityOwnerValid(entity)) { resp.ErrorCode = ErrorCode.NotAuthorized; return(resp); } } Repository.Delete(entity); Uow.Save(); var type = typeof(TEntity); //log db record deletion as an info Logger.LogInformation($"'{type}' entity has been hard-deleted."); resp.Type = ResponseType.Success; return(resp); }
public void UpdateAfterStateCommon(ResponseBase rb, int index) { this.black = rb.black; if (rb.handi != 0) { handicapLabel.text = "Handicap: " + rb.handi; } if (rb.black == 0) { this.firstPlayerColor.spriteName = BoardStateParser.GetSprite(Stone.BLACK); this.secondPlayerColor.spriteName = BoardStateParser.GetSprite(Stone.WHITE); } else { this.firstPlayerColor.spriteName = BoardStateParser.GetSprite(Stone.WHITE); this.secondPlayerColor.spriteName = BoardStateParser.GetSprite(Stone.BLACK); } if (rb.komi1 != 0) { this.firstPlayerKomi.text = "Komi: " + rb.komi1 + ""; } if (rb.komi2 != 0) { this.secondPlayerKomi.text = "Komi: " + rb.komi2 + ""; } if (rb.me == MeEnum.OBSERVER) { resignButton.isEnabled = false; } if (rb.me == MeEnum.OBSERVER) { chatButton.isEnabled = false; } controller.SetState(rb); }
public SendResponse(ResponseBase response) { if (response == null) throw new ArgumentNullException("response"); Response = response; }
public void CreateEvent(string userId, string eventName, string address, string city, string venue, string date, string startTime, string endTime, string summary, int maxAttendants, bool recurring) { string json = ParamsToJSON ("user_id", userId, "name", eventName, "address", address, "city", city, "venue", venue, "date", date, "start_time", startTime, "end_time", endTime, "summary", summary, "max_attendants", maxAttendants, "recurring", recurring); SayHiRestClient syrc = new SayHiRestClient (SayHiRestClient.HTTPPOSTMETHOD, CreateEndpointURL (CreateEventPath), json); syrc.OnRestCallCompleted += (RestResult obj) => { ResponseBase ret = null; if (!obj.IsSuccess) { ret = new ResponseBase (obj.IsSuccess, obj.Result); } else { try { bool success = false; string msg = string.Empty; using (JsonTextReader jtr = new JsonTextReader(new StringReader(obj.Result))) { while (jtr.Read()) { if (JsonKeyMatches (jtr, JsonToken.PropertyName, "good")) { success = CompareStrings (jtr, "good"); } } ret = new ResponseBase (success, msg); } } catch (Exception e) { ret = new ResponseBase (false, GenerateParseErrorMessage (e)); } } SafeRaiseEvent (OnCreateEventCompleted, ret); }; syrc.SendRestRequest (); }
public ResponseBase<string> SmsStatusUp(StatusUp StatusUpClass) { #region 宣告 //參數宣告 ResponseBase<string> RespBaseReturn = new ResponseBase<string>(); //預設值 RespBaseReturn.IsSuccess = true; RespBaseReturn.Data = null; RespBaseReturn.Msg = ""; //變數 string client = string.Empty; string strparameter = string.Empty; //查詢結果 string strResult = string.Empty; string strQuery = string.Empty; //是否更新成功 int intIsVaild = 0; //SQL 條件判斷 string strWhere = string.Empty; //計算Mobile數量 int intMobileCount = 0; string[] strarrMobile; #endregion try { #region SQL 參數 DynamicParameters sqlParm = new DynamicParameters(); sqlParm.Add("@Status", StatusUpClass.state); sqlParm.Add("@Sendid", StatusUpClass.sendid); sqlParm.Add("@Mobile", StatusUpClass.mobile); #endregion intMobileCount = StatusUpClass.mobile.Split(',').Count(); if (intMobileCount > 1) { int intN = 0; string strIn = string.Empty; foreach (string item in StatusUpClass.mobile.Split(',')) { SqlParameter parameter = new SqlParameter("@dd" + intN, SqlDbType.NVarChar, 50, item); parameter.IsNullable = true; parameter.Direction = ParameterDirection.Output; sqlParm.Add("@dd" + intN, item, System.Data.DbType.String); strIn += "@dd" + intN + ","; intN++; } strWhere = string.Format(" And Mobile in ({0} ) ", strIn.TrimEnd(',')); } else { strWhere = " And Mobile=@Mobile "; } #region SQL 語法 strQuery = @"UPDATE SMSCNStatus SET [Status] =@Status WHERE Sendid=@Sendid {0} "; strQuery = string.Format(strQuery, strWhere); #endregion #region SQL 執行 //using (SqlConnection conn = new SqlConnection(DBList.LionExAPI)) //{ // intIsVaild = conn.Execute(strQuery, sqlParm); //} //if (intIsVaild == 0) //{ // //Proj.send_ErrorEmail("更新失敗", string.Format("<h4>SQLUpdate:</h4><ul><li>{0};</li></ul><h4>StatusUpClass:</h4><ul><li>{1}</li></ul>", strQuery, JsonConvert.SerializeObject(StatusUpClass))); //} #endregion RespBaseReturn.Data = intIsVaild.ToString(); return RespBaseReturn; } catch (Exception ex) { RespBaseReturn.IsSuccess = false; RespBaseReturn.Data = null; RespBaseReturn.Msg = "API System error"; //new Log().ErrorLog(strThisPageName + "/SmsStatusUp", ex.Message); #region 記錄LOG //SmsCNLogs LogData = new SmsCNLogs(); //LogData.ActionData = strThisPageName + "/SmsStatusUp"; //LogData.SourceJsonString = JsonConvert.SerializeObject(StatusUpClass); //LogData.ReturnJsonString = string.Format("SQLUpdate={0};RespBaseReturn={1}", strQuery, RespBaseReturn); //LogData.CreateDateTime = DateTime.Now; //LogData.MagData = ex.Message; //LogData.Sort = "1"; //ProjectFun.FunAddLogData(LogData); #endregion return RespBaseReturn; } }
private void AssertResponse(ResponseBase response) { if (null == response) throw new ArgumentNullException(nameof(response)); if (string.IsNullOrEmpty(response.status)) return; var stringCode = response.status.Substring(0, 3); int responseCode = int.Parse(stringCode); if (responseCode >= 400) throw new OpenSubtitlesHttpException($"HTTP {responseCode} - {response.status}"); }
/// <summary> /// Adds a response to the stub. /// </summary> /// <param name="response">The response object designating what the stub will return</param> /// <returns>The stub that the response was added to</returns> public TcpStub Returns(ResponseBase response) { Responses.Add(response); return this; }