public JsonReturn ObterPolo(int poloId) { var retorno = new JsonReturn(); var polo = new PoloViewModel(); try { retorno.Object = _envolvimentoService.ObterPoloCadastrado(poloId).Result; return(retorno); } catch (DataNotFoundException dEx) { //loggar erro retorno.Object = dEx; retorno.Status = HttpStatusCode.NoContent; retorno.Message = dEx.Message; return(retorno); } catch (Exception ex) { //loggar erro retorno.Object = ex; retorno.Status = HttpStatusCode.InternalServerError; retorno.Message = ex.Message; return(retorno); } }
public async Task <JsonReturn> CriarUsuario([FromBody] UserViewModel userVM) { var retorno = new JsonReturn(); try { CreateUser(new ApplicationUser() { UserName = userVM.UserID, Email = userVM.Email, EmailConfirmed = true, dtAtivacao = DateTime.Now }, userVM.Password, Roles.ROLE_API); retorno.Object = await _userManager.FindByNameAsync(userVM.UserID); retorno.Message = "Usuário criado com sucesso!"; return(retorno); } catch (ApplicationException aEx) { retorno.Message = aEx.Message; retorno.Status = HttpStatusCode.InternalServerError; return(retorno); } catch (Exception ex) { //logar erro retorno.Message = "Erro ao criar usuário. Erro : " + ex.Message; retorno.Status = HttpStatusCode.InternalServerError; return(retorno); } }
public async Task <JsonReturn> Polo([FromBody] PoloViewModel polo) { var retorno = new JsonReturn(); try { ViewBag.CasoId = polo.IdProcesso; await _envolvimentoService.SalvarParteDoProcesso(polo, new Guid(Helpers.RetrieveUserClaimGuid(HttpContext))); return(retorno); } catch (InvalidDataException e) { ViewBag.ErrorList = e.ErrorList; //loggar erro retorno.Status = HttpStatusCode.InternalServerError; retorno.Message = e.GetBaseException().ToString(); return(retorno); } catch (Exception e) { ViewBag.Message = e.Message; //loggar erro retorno.Status = HttpStatusCode.InternalServerError; retorno.Message = e.GetBaseException().ToString(); return(retorno); } }
public static JsonReturn RunTransactionScope(Func <JsonReturn> method, TransactionScopeOption scopeOption, TimeSpan scopeTimeout) { JsonReturn cr; //开启事务,执行操作(注意,这里一定要开启分布式事务,以便应用多业务 using (TransactionScope scope = new TransactionScope(scopeOption, scopeTimeout)) { try { if (method != null) { cr = method(); } else { cr = JsonReturn.RunFail("未执行实际数据操作方法"); } } catch (Exception ex) { cr = JsonReturn.RunFail(ex.Message, ex); } if (cr.IsSuccess) { scope.Complete(); } }; return(cr); }
public JsonReturn GetBlogList([FromQuery] long authorID, [FromQuery] int pageNo, [FromQuery] int pageSize) { if (pageNo < 1) { pageNo = 1; } if (pageSize < 5) { pageSize = 5; } var skipRows = (pageNo - 1) * pageSize; var blogList = from blog in dbc.Blog where blog.BlogAuthorID == authorID orderby blog.BlogID select new { blog.BlogTitle, blog.BlogID, blog.BlogCreateTime }; var blogNum = blogList.Count(); if (blogNum > skipRows || pageNo == 1) { blogList = blogList.Skip(skipRows).Take(pageSize); var blogListStr = JsonConvert.SerializeObject(blogList); var blogListInfo = new JObject() { ["BlogNum"] = blogNum, ["BlogList"] = JArray.Parse(blogListStr) }; return(JsonReturn.ReturnSuccess(blogListInfo)); } else { return(JsonReturn.ReturnFail("页码超出范围!")); } }
public async Task <JsonReturn> ListaTarefasSemCaso(AtividadeStatusCadastroEnum status = AtividadeStatusCadastroEnum.Todos) { var retorno = new JsonReturn(); try { userGuid = new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)); int domainGuid; if (userGuid != null) { domainGuid = _sessionService.ObterIdEscritorioUsuario(userGuid); } else { throw new NullReferenceException("Erro(1)"); } if (domainGuid != null) { retorno.Object = await _agendaService.ObterTarefasSemProcesso(status, domainGuid); } return(retorno); } catch (Exception ex) { //loggar erro retorno.Message = "Erro ao obter tarefas."; retorno.Object = ex; retorno.Status = HttpStatusCode.InternalServerError; return(retorno); } }
public JsonResult FeeListJson(int page, int limit) { var query = from row in Fee.GetFeeListAll().AsEnumerable() select new Fee { Approver = row.Field <string>("Approver"), ApproverID = row.Field <Guid>("ApproverID"), CrTime = row.Field <DateTime>("CrTime"), CrUser = row.Field <string>("CrUser"), CrUserID = row.Field <Guid>("CrUserID"), ID = row.Field <Guid>("ID"), IsPay = row.Field <bool>("IsPay"), Money = row.Field <decimal>("Money"), OrderID = row.Field <int>("OrderID"), OrderNo = row.Field <string>("OrderNo"), PayeeID = row.Field <Guid>("PayeeID"), PayeeTrueName = row.Field <string>("PayeeTrueName"), PayeeUserName = row.Field <string>("PayeeUserName"), ApproveTime = row.Field <DateTime?>("ApproveTime"), PayDate = row.Field <DateTime?>("PayDate") }; var data = new JsonReturn(query, page, limit); return(Json(data, JsonRequestBehavior.AllowGet)); }
public async Task <JsonReturn> CompromissoAudienciaSemProcesso(AudienciaViewModel audiencia) { audiencia.HoraAtividade = audiencia.HoraAtividade.ToLocalTime(); audiencia.DataAtividade = audiencia.DataAtividade.ToLocalTime(); userGuid = new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)); var retorno = new JsonReturn(); try { audiencia.ExportadoComSucesso = false; if (!audiencia.IdForo.HasValue || audiencia.IdForo.Value < 1) { audiencia.IdForo = audiencia.IDForoDoCaso; } if (audiencia.SubTarefas != null) { foreach (AudienciaViewModel st in audiencia.SubTarefas) { if (!st.IdForo.HasValue || st.IdForo < 1) { st.IdForo = audiencia.IdForo; } } } if (audiencia.IdEscritorio == null) { audiencia.IdEscritorio = _sessionService.ObterIdEscritorioUsuario(userGuid); } await _audienciaService.SalvaAudiencia(audiencia, userGuid); if (audiencia.IdProcesso > 0) { retorno.Message = "Audiência atualizada com sucesso."; } else { retorno.Message = "Audiência criada com sucesso."; } return(retorno); } catch (InvalidDataException e) { //loggar erro retorno.Object = e.ErrorList; retorno.Status = System.Net.HttpStatusCode.InternalServerError; retorno.Message = e.ErrorList.FirstOrDefault(); return(retorno); } catch (Exception e) { //loggar erro retorno.Object = e; retorno.Status = System.Net.HttpStatusCode.InternalServerError; retorno.Message = "Erro"; return(retorno); } }
public JsonResult CustomerListJson(int page, int limit) { var query = Customer.GetCustomerList(); var data = new JsonReturn(query, page, limit); return(Json(data, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 页面没找到异常 /// </summary> /// <param name="filterContext"></param> private void PageNotFindError(ExceptionContext filterContext) { if (filterContext.Exception.GetType() == typeof(PageNotFindException)) { if (!filterContext.HttpContext.Request.IsAjaxRequest()) { Response.Write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\">"); Response.Write("<head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <title></title>"); Response.Write("<script> var thisobj = self.window; var pageIndex = 0; while (!thisobj.TopSystemIndex) { thisobj = thisobj.parent; pageIndex++;if (pageIndex > 5) { break;} } thisobj.window.location ='/Error/PageNotFind'</script> "); Response.Write("</head>"); Response.End(); } else { var json = new JsonReturn { Header = { Success = false, Message = "<script> var thisobj = self.window; var pageIndex = 0; while (!thisobj.TopSystemIndex) { thisobj = thisobj.parent; pageIndex++;if (pageIndex > 5) { break;} } thisobj.window.location ='/Error/PageNotFind'</script> " } }; string jsonString = JsonConvert.SerializeObject(json); Response.Write(jsonString); Response.End(); } } }
public JsonResult _Login(LoginParams loginParams) { JsonReturn jsonReturn = UserManagement._doLogin(loginParams.EMAIL, loginParams.URM00_PASSWD); URM00 loginUser = (URM00)jsonReturn.Data; if (loginUser != null) { Session["loginUser"] = loginUser; if (loginParams.REMEMBER) { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, loginUser.URM00_CODE.ToString(), DateTime.Now, DateTime.Now.AddMinutes(20), true, "", "/" ); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(cookie); } } return(Json(jsonReturn, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Down samples data if necessary to run in low Resource Systems /// </summary> /// <param name="dict">The object that will be returned to the Client</param> public static void DownSample(JsonReturn dict) { if (MaxSampleRate == -1) { return; } int i = 0; double dT = 0; double cycles = 0; double step = 0; for (i = 0; i < dict.Data.Count; i++) { dT = dict.Data[i].DataPoints.Max(pt => pt[0]) - dict.Data[i].DataPoints.Min(pt => pt[0]); cycles = dT * Fbase / 1000.0D; if (cycles * MaxSampleRate > dict.Data[i].DataPoints.Count) { continue; } step = (dict.Data[i].DataPoints.Count - 1) / (cycles * MaxSampleRate); dict.Data[i].DataPoints = Enumerable.Range(0, (int)Math.Floor(cycles * MaxSampleRate)).Select(j => dict.Data[i].DataPoints[((int)Math.Round(j * step))]).ToList(); } }
public bool DeleteDonation(int id) { var retVal = false; try { var client = new RestClient(ConfigurationManager.AppSettings["WebApiBaseUrlV1"]); var request = new RestRequest("api/v1/Donations/" + id + "/", Method.DELETE); request.AddParameter("Authorization", AuthorizationInformation, ParameterType.HttpHeader); var response = client.Execute <JsonReturn>(request); if (response != null && response.Data != null) { JsonReturn jReturn = response.Data; retVal = ( bool )jReturn.Result; } } catch (Exception ex) { //TODO: Log error. } return(retVal); }
public async Task <JsonReturn> ListarAudiencias(string startString, string endString, string assunto = "") { var retorno = new JsonReturn(); var filter = new AtribuicaoFilter(); if (!string.IsNullOrEmpty(startString) && !string.IsNullOrEmpty(endString)) { filter.Start = DateTime.Parse(startString); filter.End = DateTime.Parse(endString); } filter.Assunto = assunto; userGuid = new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)); int domainGuid; if (userGuid != null) { domainGuid = _sessionService.ObterIdEscritorioUsuario(userGuid); } else { throw new NullReferenceException("Erro(1)"); } if (domainGuid != null) { retorno.Object = await _agendaService.ObterAudienciasDistribuicao(domainGuid, filter); } return(retorno); }
public async Task <JsonReturn> ListarPrazos(string assunto, int?cliente, int?area) { var retorno = new JsonReturn(); var filter = new AtribuicaoFilter() { Cliente = cliente, Area = area, Assunto = assunto }; userGuid = new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)); int domainGuid; if (userGuid != null) { domainGuid = _sessionService.ObterIdEscritorioUsuario(userGuid); } else { throw new NullReferenceException("Erro(1)"); } if (domainGuid != null) { retorno.Object = await _agendaService.ObterTarefasDistribuicao(domainGuid, filter); } return(retorno); }
public async Task <JsonReturn> IndexPost([FromBody] int id) { var retorno = new JsonReturn(); try { ViewBag.CasoId = id; retorno.Object = await _casoService.ExportarProcesso(new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)), id); retorno.Message = "Exportado com sucesso."; return(retorno); } catch (InvalidDataException e) { //loggar erro retorno.Status = System.Net.HttpStatusCode.InternalServerError; retorno.Object = e.ErrorList; retorno.Message = e.ErrorList[0]; return(retorno); } catch (Exception e) { //loggar erro retorno.Status = System.Net.HttpStatusCode.InternalServerError; retorno.Object = e; retorno.Message = "Erro ao exportar caso, por favor, contate o suporte."; return(retorno); } }
public async Task <JsonReturn> ListarResponsavelPorArea(int idArea) { var retorno = new JsonReturn(); try { userGuid = new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)); var dados = await _casoService.ListarResponsaveisPorArea(userGuid, idArea); retorno.Object = dados?.Profissionais; return(retorno); } catch (Exception ex) { userGuid = new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)); _logger.Error(ex.GetBaseException(), "ProcessosController - ListarResponsavelPorArea -> {idArea} -> {userGuid}", idArea, userGuid); retorno.Status = HttpStatusCode.InternalServerError; retorno.Message = "Erro ao listar responsaveis"; return(retorno); } }
public JsonReturn UsuarioLogado(string token) { JsonReturn retorno = new JsonReturn(); //Session logado = new Session(); //Guid userGuid = Helpers.ValidateToken(token, _tokenConfigurations); //if (userGuid == Guid.Empty) //{ // retorno.Message = "Token Inválido"; // retorno.Object = false; // return retorno; //} //logado = _newSessionService.ObterSessaoAtiva(userGuid.ToString()); //if (logado != null) //{ // retorno.Object = true; // _sessionService.KeepAlive(userGuid); //} //else //{ // retorno.Message = "Sessão inexistente/expirada"; // retorno.Object = false; //} retorno.Object = true; return(retorno); }
public JsonReturn GetBreakerData() { Dictionary <string, string> query = Request.QueryParameters(); int eventId = int.Parse(query["eventId"]); Event evt = m_dataContext.Table <Event>().QueryRecordWhere("ID = {0}", eventId); Meter meter = m_dataContext.Table <Meter>().QueryRecordWhere("ID = {0}", evt.MeterID); meter.ConnectionFactory = () => new AdoDataConnection(m_dataContext.Connection.Connection, typeof(SqlDataAdapter), false); DateTime epoch = new DateTime(1970, 1, 1); DateTime startTime = (query.ContainsKey("startDate") ? DateTime.Parse(query["startDate"]) : evt.StartTime); DateTime endTime = (query.ContainsKey("endDate") ? DateTime.Parse(query["endDate"]) : evt.EndTime); int pixels = int.Parse(query["pixels"]); DataTable table; int calcCycle = m_dataContext.Connection.ExecuteScalar <int?>("SELECT CalculationCycle FROM FaultSummary WHERE EventID = {0} AND IsSelectedAlgorithm = 1", evt.ID) ?? -1; Dictionary <string, FlotSeries> dict = new Dictionary <string, FlotSeries>(); table = m_dataContext.Connection.RetrieveData("select ID from Event WHERE StartTime <= {0} AND EndTime >= {1} and MeterID = {2} AND LineID = {3}", ToDateTime2(m_dataContext.Connection, endTime), ToDateTime2(m_dataContext.Connection, startTime), evt.MeterID, evt.LineID); foreach (DataRow row in table.Rows) { Dictionary <string, FlotSeries> temp = QueryBreakerData(int.Parse(row["ID"].ToString()), meter); foreach (string key in temp.Keys) { if (dict.ContainsKey(key)) { dict[key].DataPoints = dict[key].DataPoints.Concat(temp[key].DataPoints).ToList(); } else { dict.Add(key, temp[key]); } } } if (dict.Count == 0) { return(null); } double calcTime = (calcCycle >= 0 ? dict.First().Value.DataPoints[calcCycle][0] : 0); List <FlotSeries> returnList = new List <FlotSeries>(); foreach (string key in dict.Keys) { FlotSeries series = new FlotSeries(); series = dict[key]; series.DataPoints = Downsample(dict[key].DataPoints.Where(x => !double.IsNaN(x[1])).OrderBy(x => x[0]).ToList(), pixels, new Range <DateTime>(startTime, endTime)); returnList.Add(series); } JsonReturn returnDict = new JsonReturn(); returnDict.StartDate = evt.StartTime; returnDict.EndDate = evt.EndTime; returnDict.Data = returnList; returnDict.CalculationTime = calcTime; return(returnDict); }
/// <summary> /// 商城支付成功处理 /// /// </summary> /// <param name="model"></param> public static JsonReturn PaySuccessService(PaySuccessServiceModel model) { //查订单 JsonReturn res = new JsonReturn(); res.code = ApiCode.成功; res.msg = "成功"; var tradeno = QueryTradeNo(model.hotelcode, model.trade_no, model.notify, Config.CheckWxPayUrl); if (tradeno.code == StatusCode.成功) { //改状态 var isChange = UpdateOrderState(model.trade_no, "[已支付]微信支付,微信单号:" + tradeno.transaction_id + "," + model.remark, "2", model.bosscard, model.total, "1", model.hotelcode); if (isChange) { var orderlist = QueryOrder(model.hotelcode, model.trade_no); if (orderlist[0].success.Count > 0) { shopname = ""; var isSendTicket = TicketApi.SendTicket(orderlist, model.user, ref shopname); if (isSendTicket) { //var r = service.Setproduct_onsale_single_salenum_json(model.user, model.user, data.onsalecode, data.salenum); SendTempPaySuccess(shopname, model.total, model.tel, model.payway, model.hotelcode, model.openid, "", "您好,您已成功购买"); var list = GetServiceList(model.hotelcode, "3", "GetOpenIdList"); if (list.data.Count > 0) { foreach (var item in list.data) { if (model.name != "" || model.mobile != "") { SendTempPaySuccess(shopname, model.total, model.tel, model.payway, model.hotelcode, item.openid1, "", "您好,商城有一笔新订单\n购买人:" + model.name + "\n联系方式:" + model.mobile); } else { SendTempPaySuccess(shopname, model.total, model.tel, model.payway, model.hotelcode, item.openid1, "", "您好,商城有一笔新订单\n购买人:" + model.name + "\n联系方式:" + orderlist[0].success[0].mobile); } } } } else { res.code = ApiCode.发送产品失败; res.msg = "发送产品失败"; } } } else { res.code = ApiCode.已支付; res.msg = "已支付"; } } else { res.code = ApiCode.没有找到微信支付订单; res.msg = "没有找到微信支付订单"; } return(res); }
public static JsonReturn RunTransactionScope(Action method, TransactionScopeOption scopeOption, TimeSpan scopeTimeout) { JsonReturn jr; //开启事务,执行操作(注意,这里一定要开启分布式事务,以便应用多业务 using (TransactionScope scope = new TransactionScope(scopeOption, scopeTimeout)) { try { if (method != null) { method(); } jr = JsonReturn.RunSuccess(true); } catch (Exception ex) { jr = JsonReturn.RunFail(ex.Message); } if (jr.IsSuccess) { scope.Complete(); } }; return(jr); }
public JsonResult CourseAdd(Project model) { if (LUser != null) { model.UpTime = model.CrTime = DateTime.Now; model.CrUserID = LUser.UserId.ToGuid(); if (ModelState.IsValid) { if (model.ID.IsEmpty()) { //新增 model.ID = GuidHelper.GuidNew(); model.CreateAndFlush(); } else { model.UpdateAndFlush(); } return(Json(JsonReturn.OK())); } else { return(Json(JsonReturn.Error("填写的信息有误请确认。"), JsonRequestBehavior.AllowGet)); } } else { return(Json(JsonReturn.Error("登录超时,请重新登录"), JsonRequestBehavior.AllowGet)); } }
public ActionResult CourseAdd() { if (LUser != null) { if (Request.RequestContext.RouteData.Values["id"] != null) { var model = Project.TryFind(Request.RequestContext.RouteData.Values["id"].ToString().ToGuid()); if (model != null) { ViewBag.Title = "课程修改"; return(View(model)); } else { return(Json(JsonReturn.Error("查询数据失败"), JsonRequestBehavior.AllowGet)); } } else { ViewBag.Title = "课程新增"; var model = new Project(); model.IsUse = true; model.StartDate = model.EndDate = DateTime.Now; model.CrUser = LUser.UserName; model.CrTime = model.UpTime = DateTime.Now; model.UpUser = LUser.UserName; model.Amount = 0; return(View(model)); } } else { return(Json(JsonReturn.Error("登录超时,请重新登录"), JsonRequestBehavior.AllowGet)); } }
protected void Application_Error(Object sender, EventArgs e) { JsonReturn jsonResult = new JsonReturn(); Exception lastError = Server.GetLastError(); if (lastError != null) { //异常信息 string strExceptionMessage = string.Empty; //对HTTP 404做额外处理,其他错误全部当成500服务器错误 HttpException httpError = lastError as HttpException; if (httpError != null) { //获取错误代码 int httpCode = httpError.GetHttpCode(); strExceptionMessage = httpError.Message; if (httpCode == 400 || httpCode == 404) { Response.StatusCode = 404; //跳转到指定的静态404信息页面,根据需求自己更改URL // Response.WriteFile("~/HttpError/404.html"); jsonResult.code = ApiCode.序异常; jsonResult.msg = "找不到相关接口"; Server.ClearError(); return; } } strExceptionMessage = lastError.Message; /*----------------------------------------------------- * 此处代码可根据需求进行日志记录,或者处理其他业务流程 * ---------------------------------------------------*/ this.Logger.WriteLog(string.Concat(new string[] { "----------- 记录程序日志 Log-----------\r\n", strExceptionMessage, "\r\n", "错误地址:\r\n", Request.Url.ToString(), "\r\n", })); /* * 跳转到指定的http 500错误信息页面 * 跳转到静态页面一定要用Response.WriteFile方法 */ Response.StatusCode = 500; // Response.WriteFile("~/HttpError/500.html"); jsonResult.code = ApiCode.序异常; jsonResult.msg = strExceptionMessage; HttpHepler.ReturnJson <JsonReturn>(jsonResult, HttpContext.Current); //一定要调用Server.ClearError()否则会触发错误详情页(就是黄页) Server.ClearError(); //Server.Transfer("~/HttpError/500.aspx"); } }
public async Task <JsonReturn> PossiveisPastas(int idCliente) { var retorno = new JsonReturn(); retorno.Object = await _prazoService.ListaPossiveisPastas(new Guid(Helpers.RetrieveUserClaimGuid(HttpContext)), idCliente); return(retorno); }
public JsonResult CourseListJson(int page, int limit) { var where = GeneralQuery.Get(Request.QueryString); var query = Project.GetList(where); var data = new JsonReturn(query, page, limit); return(Json(data, JsonRequestBehavior.AllowGet)); }
public JsonResult PageList() { int currentPage = Convert.ToInt32(Request.Form["currentPage"]); int pageSize = Convert.ToInt32(Request.Form["pageSize"]); int count = _workFlowRepository.SelectCount(); IEnumerable <WorkFlow> workFlows = _workFlowRepository.SelectByPage(currentPage, pageSize); return(Json(JsonReturn.Success(new { total = count, data = workFlows }))); }
public JsonResult SaveDiagram() { JsonReturn jsonReturn = null; string diagramJson = Request.Form["diagramJson"]; string id = Request.Form["id"]; _workFlowService.SaveDiagram(diagramJson, id); return(Json(jsonReturn)); }
public async Task <JsonReturn> EditarPolo(int id) { var retorno = new JsonReturn(); retorno.Object = await _envolvimentoService.ObterPoloCadastrado(id); //ViewBag.CasoId = retorno.Object.IdProcesso; return(retorno); }
public ActionResult GetAnswerList() { var quizList = from sl in dbc.Quiz select sl; var answerList = from al in dbc.Answer join ql in quizList on al.QuizID equals ql.QuizID select new { AnswerID = al.AnswerID, AnswerBody = al.AnswerBody, AnswerIP = al.AnswerIP, QuizName = ql.QuizName, QuizBody = ql.QuizBody }; return(JsonReturn.ReturnSuccess(answerList)); }