/// <summary> /// 加载表格 /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="content">The content.</param> /// <param name="datetime1">The datetime1.</param> /// <param name="datetime2">The datetime2.</param> /// <param name="rows">The rows.</param> /// <param name="page">The page.</param> /// Author : Napoleon /// Created : 2015-01-17 11:00:34 public ActionResult LoadDataGrid(string userName, string content, string datetime1, string datetime2, int rows, int page) { SystemLog log = new SystemLog(); log.UserName = userName; log.OperateContent = content; datetime1 = string.IsNullOrWhiteSpace(datetime1) ? SqlDateTime.MinValue.ToString() : datetime1; datetime2 = string.IsNullOrWhiteSpace(datetime2) ? SqlDateTime.MaxValue.ToString() : datetime2; DataTable dt = log.SelectLog(datetime1, datetime2, rows * (page - 1), rows * page); int count = log.LogCount(datetime1, datetime2); string json = dt.ConvertTableToGridJson(count); return Content(json); }
public void Save(SystemLogModel model) { vmsServerLinqDataContext datacontext = new vmsServerLinqDataContext(); SystemLog log = new SystemLog(); log.LogID = GetLongID(); log.LogValue = model.LogValue; log.Type = model.LogType; log.Time = model.LogTime; log.Source = model.Source; log.StackTrace = model.StackTrace; datacontext.SystemLogs.InsertOnSubmit(log); datacontext.SubmitChanges(); }
/// <summary> /// action异常捕获 /// </summary> /// <param name="filterContext">有关当前请求和操作的信息。</param> /// Author : Napoleon /// Created : 2015-06-05 11:10:24 protected override void OnException(ExceptionContext filterContext) { filterContext.ExceptionHandled = true;//已经处理异常 SystemLog log = new SystemLog(); log.IpAddress = IpFunc.GetIp(); log.OperateTime = DateTime.Now; log.OperateUrl = System.Web.HttpContext.Current.Request.Url.ToString(); log.UserName = "******"; log.OperateType = "DAL层错误"; log.OperateContent = filterContext.Exception.Message; log.InsertLog(LogType.Error, InsertType.All); //页面跳转 filterContext.Result = RedirectToRoute("Default", new { Controller = "Error", Action = "Index" }); base.OnException(filterContext); }
public void LogOperationAddOKInfo(SystemUser systemUser, SystemMoudle systemMoudle, string recordName, int relateID,string source,string requestInfo) { SystemLog log = new SystemLog(); log.LogDate = System.DateTime.Now; log.LogDescrption = GenerateOperationAddOKInfo(systemUser, systemMoudle.MoudleNameCn, recordName, relateID); log.LogLevel = LogLevel.Info.ToString(); log.LogType = LogType.BussnessOperation.ToString(); log.LogRelateDateTime = null; log.LogRelateMoudleDataID = relateID; log.LogRelateMoudleDataID = systemMoudle.MoudleID; log.LogRelateUserID = systemUser.UserID; log.LogUser = systemUser.UserName; log.LogSource = source; log.LogRequestInfo = requestInfo; this.Create(log); }
/// <summary> /// 导出Excel /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="content">The content.</param> /// <param name="datetime1">The datetime1.</param> /// <param name="datetime2">The datetime2.</param> /// Author : Napoleon /// Created : 2015-01-14 14:15:33 public FileResult ExcelLog(string userName, string content, string datetime1, string datetime2) { SystemLog log = new SystemLog(); log.UserName = userName; log.OperateContent = content; datetime1 = string.IsNullOrWhiteSpace(datetime1) ? SqlDateTime.MinValue.ToString() : datetime1; datetime2 = string.IsNullOrWhiteSpace(datetime2) ? SqlDateTime.MaxValue.ToString() : datetime2; DataTable dt = log.SelectLogTable(datetime1, datetime2); string[] titles = { "ID", "操作用户", "IP地址", "日志时间", "日志类型", "错误地址", "日志内容" }; string[] columns = { "Id", "UserName", "IpAddress", "OperateTime", "OperateType", "OperateUrl", "OperateContent" }; //string excel = dt.Excel("", columns, titles, false, null, ""); //MemoryStream fileStream = new MemoryStream(Encoding.Default.GetBytes(excel)); //return File(fileStream, "application/ms-excel", PublicFields.LogExcelName); MemoryStream fileStream = dt.CreateSheet(titles, columns); fileStream.Seek(0, SeekOrigin.Begin); return File(fileStream, "application/vnd.ms-excel", PublicFields.LogExcelName); }
/// <summary> /// 导出Excel /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="content">The content.</param> /// <param name="datetime1">The datetime1.</param> /// <param name="datetime2">The datetime2.</param> /// Author : Napoleon /// Created : 2015-01-14 14:15:33 public ActionResult ExcelLog(string userName, string content, string datetime1, string datetime2) { string fileName = "系统日志" + DateTime.Now.ToString("yyyyMMddhhmmssff") + ".xls"; string filePath = Server.MapPath("../Export/"); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } SystemLog log = new SystemLog(); log.UserName = userName; log.OperateContent = content; datetime1 = string.IsNullOrWhiteSpace(datetime1) ? SqlDateTime.MinValue.ToString() : datetime1; datetime2 = string.IsNullOrWhiteSpace(datetime2) ? SqlDateTime.MaxValue.ToString() : datetime2; DataTable dt = log.SelectLogTable(datetime1, datetime2); string[] titles = { "ID", "操作用户", "IP地址", "日志时间", "日志类型", "错误地址", "日志内容" }; string[] columns = { "Id", "UserName", "IpAddress", "OperateTime", "OperateType", "OperateUrl", "OperateContent" }; MemoryStream fileStream = dt.CreateSheet(titles, columns); fileStream.Seek(0, SeekOrigin.Begin); fileStream.StreamToFile(filePath + fileName); return Content("../Export/" + fileName); //return File(fileStream, "application/vnd.ms-excel", PublicFields.LogExcelName); }
public bool validateCode([FromBody] string code) { bool solicitudRol = false; try { if (!string.IsNullOrWhiteSpace(code)) { //verificacion de existencia y estado del codigo Expression<Func<SolicitudRegistro, bool>> query = u => u.codigo == code && u.estado == true; SolicitudRegistro solicitud = _repositorio.Get<SolicitudRegistro>(query); //Si la solicitud existe y no se ha usado subo a session el codigo if (solicitud != null) { return true; } } } catch (Exception ex) { SystemLog mSystemLog = new SystemLog(); mSystemLog.ErrorLog(ex.Message); } return false; }
/// <summary> /// 绑定日志列表 /// </summary> /// <param name="pageIndex"></param> private void BindLogList(int pageIndex) { string sourceID = rblSource.SelectedValue; string typeName = (rblType.SelectedItem == null) ? "" : rblType.SelectedItem.Text; int size = pGrid.PageSize; IList<LogInfo> list = new List<LogInfo>(); if (typeName != "" && null != typeName) { EventLogEntryType type = (EventLogEntryType)Enum.Parse(typeof(EventLogEntryType), typeName); list = new SystemLog().GetLogInfoList(DateTime.MinValue, DateTime.MaxValue, type, sourceID, size, pageIndex); } else { list = new SystemLog().GetLogInfoList(DateTime.MinValue, DateTime.MaxValue, sourceID, size, pageIndex); } gvLogInfoList.DataSource = list; gvLogInfoList.DataBind(); CustomList<LogInfo> cList = list as CustomList<LogInfo>; if (null != cList) { pGrid.PageSize = size; pGrid.TotalAmout = cList.TotalAmout; } }
protected void Page_Load(object sender, EventArgs e) { int order_id = RequestTool.RequestInt("order_id", 0); order = B_Lebi_Order.GetModel(order_id); if (order == null) { Response.Write("ERROR"); Response.End(); return; } Lebi_Language language = B_Lebi_Language.GetModel(order.Language_id); if (order.IsPaid == 1) { Response.Write(Language.Tag("已付款", language.Code)); Response.End(); return; } order.Site_id_pay = CurrentSite.id; order.Language_id = CurrentLanguage.id; Lebi_OnlinePay pay = B_Lebi_OnlinePay.GetModel("id = " + order.OnlinePay_id + ""); if (pay == null) { Log.Add("在线支付接口 weixinpay 配置错误"); return; } Lebi_Currency currendy = B_Lebi_Currency.GetModel(pay.Currency_id); if (pay.FeeRate > 0) { order.Money_OnlinepayFee = order.Money_Pay * pay.FeeRate / 100; } if (order.OnlinePay_id != pay.id) { order.OnlinePay_id = pay.id; order.OnlinePay_Code = pay.Code; order.OnlinePay = pay.Name; } B_Lebi_Order.Update(order); Lebi_User user = B_Lebi_User.GetModel(order.User_id); if (user == null) { Response.Write("订单错误"); Response.End(); return; } returnurl = URL("P_UserOrderDetails", order.id); TenpayUtil tu = new TenpayUtil(order); appId = tu.appid; timeStamp = TenpayUtil.getTimestamp(); nonceStr = TenpayUtil.getNoncestr(); string order_price = (order.Money_Pay * currendy.ExchangeRate * 100 * (1 + (pay.FeeRate / 100))).ToString("0"); string sp_billno = order.Code; shopname = Lang(CurrentSite.Name); string prepayId = order.weixin_prepay_id; if (prepayId == "" || prepayId == "INVALID_REQUEST") { //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(Context); //初始化 packageReqHandler.init(); //设置package订单参数 packageReqHandler.setParameter("body", order.Code); //商品信息 127字符 packageReqHandler.setParameter("appid", tu.appid); packageReqHandler.setParameter("mch_id", tu.mch_id); packageReqHandler.setParameter("nonce_str", nonceStr); packageReqHandler.setParameter("openid", user.bind_weixin_id); packageReqHandler.setParameter("out_trade_no", sp_billno); //商家订单号 packageReqHandler.setParameter("spbill_create_ip", RequestTool.GetClientIP()); //Page.Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.setParameter("total_fee", order_price); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.setParameter("trade_type", "MWEB"); //packageReqHandler.setParameter("notify_url", HttpUtility.UrlEncode(tu.tenpay_notify)); packageReqHandler.setParameter("notify_url", tu.tenpay_notify); //Response.Write("body:" + order.Code + ",appid:" + tu.appid + ",mch_id:" + tu.mch_id + ",nonce_str:" + nonceStr + ",notify_url:" + HttpUtility.UrlEncode(tu.tenpay_notify) + ",openid:" + user.bind_weixin_id + ",out_trade_no:" + sp_billno + ",spbill_create_ip:" + RequestTool.GetClientIP() + ",total_fee:" + order_price + ",key:" + tu.key + ""); string sign = packageReqHandler.createMd5Sign("key", tu.key); packageReqHandler.setParameter("sign", sign); string data = packageReqHandler.parseXML(); string prepayXml = HttpUtil.Send(data, "https://api.mch.weixin.qq.com/pay/unifiedorder"); SystemLog.Add(prepayXml); Response.Write(prepayXml); return; //获取预支付ID var xdoc = new XmlDocument(); xdoc.LoadXml(prepayXml); XmlNode xn = xdoc.SelectSingleNode("xml"); XmlNodeList xnl = xn.ChildNodes; //Response.Write("<br/>xml:" + xnl[0].InnerText + "|" + xnl[1].InnerText + "|" + xnl[2].InnerText + "|" + xnl[3].InnerText + "|" + xnl[4].InnerText + "|" + xnl[5].InnerText + "|" + xnl[6].InnerText + "|" + xnl[7].InnerText + "|" + xnl[8].InnerText + ""); if (xnl.Count > 7) { prepayId = xnl[7].InnerText; order.weixin_prepay_id = prepayId; B_Lebi_Order.Update(order); } } //Response.Write("prepayId:" + prepayId + ""); packageValue = string.Format("prepay_id={0}", prepayId); var paySignReqHandler = new RequestHandler(Context); paySignReqHandler.setParameter("appId", appId); paySignReqHandler.setParameter("timeStamp", timeStamp); paySignReqHandler.setParameter("nonceStr", nonceStr); paySignReqHandler.setParameter("package", packageValue); paySignReqHandler.setParameter("signType", "MD5"); paySign = paySignReqHandler.createMd5Sign("key", tu.key); //获取debug信息,建议把请求和debug信息写入日志,方便定位问题 //string pakcageDebuginfo = packageReqHandler.getDebugInfo(); //Response.Write("<br/>pakcageDebuginfo:" + pakcageDebuginfo + "<br/>"); //string paySignDebuginfo = paySignReqHandler.getDebugInfo(); //Response.Write("<br/>paySignDebuginfo:" + paySignDebuginfo + "<br/>"); }
private void bt确认_Click(object sender, System.EventArgs e) { DataTable myTb = (DataTable)this.myDataGrid1.DataSource; // if(!myOldTb.Equals(myTb)) // { // MessageBox.Show("网格已经更新,请重新确认!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); // return; // } int nrow = this.myDataGrid1.CurrentCell.RowNumber; string sSql = ""; if (MessageBox.Show(this, "确认该项目不执行了吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) { return; } //Modify By Tany 2010-06-08 是否使用密码确认 0=使用 1=不使用 if (new SystemCfg(7066).Config == "0") { frmInPassword f1 = new frmInPassword(); f1.ShowDialog(); if (f1.isLogin == false) { return; } f1.Close(); } InstanceForm.BDatabase.BeginTransaction(); try { string _lisGroup = "-1"; switch (Convert.ToInt16(myTb.Rows[nrow]["xh"])) { case 1: //未安排 安排表cancel //看看是否有lis组合 //sSql="select lis_group from yj_applyrecord "+ // " where id="+myTb.Rows[nrow]["id"].ToString()+" and isarrange=0"; //_lisGroup=InstanceForm.BDatabase.GetDataResult(sSql).ToString().Trim(); //if(_lisGroup!="-1" && _lisGroup!="") //{ // sSql="update yj_applyrecord set lis_group=-1 where lis_group="+_lisGroup; // InstanceForm.BDatabase.DoCommand(sSql); //} sSql = "update YJ_ZYSQ " + " set bscbz=1,scsj=getdate() ,scr=" + InstanceForm.BCurrentUser.EmployeeId + " where yjsqid='" + myTb.Rows[nrow]["id"].ToString() + "' and bjsbz=0"; if (InstanceForm.BDatabase.DoCommand(sSql) == 0) { throw new Exception("未找到需要更新的记录,请重新确认!"); } sSql = "update zy_fee_speci " + " set delete_bit= " + " (select 1 from zy_fee_speci a,VI_jc_ITEMS b " + " where a.hditem_id=b.itemid and a.tcid=b.tcid " + " and a.hditem_id=" + myTb.Rows[nrow]["hditem_id"].ToString() + " ) where prescription_id='" + myTb.Rows[nrow]["applycode"].ToString() + "' and charge_bit=0"; if (InstanceForm.BDatabase.DoCommand(sSql) == 0) { throw new Exception("未找到需要更新的记录,请重新确认!"); } break; case 2: //已安排,未记帐 //sSql="update yj_arrangequeue set affirm_user=-2 where id="+myTb.Rows[nrow]["id"].ToString(); //if(InstanceForm.BDatabase.DoCommand(sSql)==0) // throw new Exception("未找到需要更新的记录,请重新确认!"); sSql = "update zy_fee_speci " + " set delete_bit= " + " (select 1 from zy_fee_speci a,VI_jc_ITEMS b " + " where a.hditem_id=b.itemid and a.tcid=b.tcid " + " and a.hditem_id=" + myTb.Rows[nrow]["hditem_id"].ToString() + " ) where prescription_id='" + myTb.Rows[nrow]["applycode"].ToString() + "' and charge_bit=0"; if (InstanceForm.BDatabase.DoCommand(sSql) == 0) { throw new Exception("未找到需要更新的记录,请重新确认!"); } break; case 3: //冲正 //sSql="update yj_arrangequeue set affirm_user=-2 where id="+myTb.Rows[nrow]["id"].ToString(); //if(InstanceForm.BDatabase.DoCommand(sSql)==0) // throw new Exception("未找到需要更新的记录,请重新确认!"); sSql = "update zy_fee_speci " + " set charge_bit=1,charge_date=getdate(),charge_user="******" " + " from zy_fee_speci a,VI_jc_ITEMS b " + " where a.hditem_id=b.itemid and a.tcid=b.tcid " + " and a.hditem_id=" + myTb.Rows[nrow]["hditem_id"].ToString() + " and a.cz_flag=2 and a.prescription_id='" + myTb.Rows[nrow]["applycode"].ToString() + "' and a.charge_bit=0"; if (InstanceForm.BDatabase.DoCommand(sSql) == 0) { throw new Exception("未找到需要更新的记录,请重新确认!"); } break; } if (Convert.ToInt16(myTb.Rows[nrow]["xh"]) == 1 || Convert.ToInt16(myTb.Rows[nrow]["xh"]) == 2) { //如果是临嘱,且不是冲账,均打上未执行标志 if (Convert.ToInt16(myTb.Rows[nrow]["mngtype"]) == 1 || Convert.ToInt16(myTb.Rows[nrow]["mngtype"]) == 5) { //Modify by Tany 2005-02-21 order_edate=getdate() sSql = "update zy_orderrecord set wzx_flag=" + InstanceForm.BCurrentUser.EmployeeId + ",order_edate=getdate() where order_id='" + myTb.Rows[nrow]["order_id"].ToString() + "'"; if (InstanceForm.BDatabase.DoCommand(sSql) == 0) { throw new Exception("未找到需要更新的记录,请重新确认!"); } } //取消检查打印 Add By Tany 2004-12-02 sSql = "update zy_jy_print set delete_bit=1 where order_id='" + myTb.Rows[nrow]["order_id"].ToString() + "'"; InstanceForm.BDatabase.DoCommand(sSql);//Modify By Tany 2004-12-08 } InstanceForm.BDatabase.CommitTransaction(); //更新lis条形码表 暂时没有lis连接屏蔽 Modify By Tany 2006-12-04 // if(_lisGroup!="-1" && _lisGroup!="") // { // sSql="update ls_as_txm set delete_bit=1 where id="+_lisGroup; // InstanceForm.BDatabase.DoCommand(sSql); // } } catch (Exception err) { InstanceForm.BDatabase.RollbackTransaction(); // database.Close(); //写错误日志 Add By Tany 2005-01-12 SystemLog _systemErrLog = new SystemLog(-1, InstanceForm.BCurrentDept.DeptId, InstanceForm.BCurrentUser.EmployeeId, "程序错误", "取消医技检查错误:" + err.Message + " Source:" + err.Source, DateManager.ServerDateTimeByDBType(InstanceForm.BDatabase), 1, "主机名:" + System.Environment.MachineName, 39); _systemErrLog.Save(); _systemErrLog = null; MessageBox.Show("错误:" + err.Message + "\n" + "Source:" + err.Source + "\n\n数据已经回滚,请检查后重新执行!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); myDataGrid1.DataSource = null; return; } // database.Close(); MessageBox.Show("取消成功!"); myDataGrid1.DataSource = null; }
public void ExportToTemplateMQCDefectDaily(string PathTemplate, string pathSaveExcel, List <string> listHeaderRw25, List <DefectRateData> defectRates, DateTime From, DateTime To) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; //sheet 2 //Excel.Worksheet xlWorkSheet1; //sheet 1 object misValue = System.Reflection.Missing.Value; try { xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(PathTemplate, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); #region Sheet 1 //Add data in Sheet 1 xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add data sheet1 //xlWorkSheet.Cells[6, 1] = "BackLog Report on " + DateTime.Now.ToString("MMM/dd/yyyy"); //Line string strWorksheetName = xlWorkSheet.Name; //Get the name of worksheet. xlWorkSheet.Cells[1, "A"] = "MQC Report from [" + From.ToString("dd/MMM/yyyy HH:mm") + "] to [" + To.ToString("dd/MMM/yyyy HH:mm") + "]"; //Fill ngay thang nam //xlWorkSheet.Cells[2, 11] = usersend; //Model //xlWorkSheet.Cells[1, 11] = dateupdate; //Line string date = DateTime.Now.ToString("dd-MM-yyyy"); for (int j = 0; j < 16; j++) { xlWorkSheet.Cells[3, 47 + j] = listHeaderRw25[j]; // countDefect += defectRates[i].defectItems[j].Quantity; } for (int i = 0; i < defectRates.Count; i++) { double countDefect = 0; double countRework = 0; xlWorkSheet.Cells[4 + i, "A"] = defectRates[i].Product; //xlWorkSheet.Cells[3, 11] = version; //User // xlWorkSheet.Cells[4 + i, "B"] = defectRates[i].DateTime_from + "-" + defectRates[i].DateTime_to;//xlWorkSheet.Cells[3, 11] = version; //User // xlWorkSheet.Cells[4 + i, "C"] = defectRates[i].Product;//xlWorkSheet.Cells[3, 11] = version; //User // xlWorkSheet.Cells[4 + i, "D"] = defectRates[i].Lot; xlWorkSheet.Cells[4 + i, "E"] = defectRates[i].TargetMQC.TargetOutput; // xlWorkSheet.Cells[4 + i, "F"] = defectRates[i].TotalQuantity; xlWorkSheet.Cells[4 + i, "F"] = defectRates[i].OutputQuantity; xlWorkSheet.Cells[4 + i, "AF"] = defectRates[i].DefectQuantity; xlWorkSheet.Cells[4 + i, "BL"] = defectRates[i].ReworkQuantity; // xlWorkSheet.Cells[2, 31] = DateTime.Now.ToString("MM"); for (int j = 0; j < defectRates[i].defectItems.Count; j++) { if (defectRates[i].defectItems[j].Note == (j + 1)) { xlWorkSheet.Cells[4 + i, 18 + j] = defectRates[i].defectItems[j].Quantity; countDefect += defectRates[i].defectItems[j].Quantity; } } xlWorkSheet.Cells[4 + i, 31] = defectRates[i].DefectQuantity - countDefect; for (int j = 0; j < defectRates[i].ReworkItems.Count; j++) { for (int k = 0; k < 16; k++) { if (defectRates[i].ReworkItems[j].DefectSFTName == (string)xlWorkSheet.Cells[3, 47 + k].Value2.ToString()) { xlWorkSheet.Cells[4 + i, 47 + k] = defectRates[i].ReworkItems[j].Quantity; countRework += defectRates[i].ReworkItems[j].Quantity; } } } xlWorkSheet.Cells[4 + i, 31] = defectRates[i].DefectQuantity - countDefect; xlWorkSheet.Cells[4 + i, 62] = defectRates[i].ReworkQuantity - countRework; } xlWorkSheet.Name = date; #endregion xlWorkBook.SaveAs(pathSaveExcel, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(); xlApp.Quit(); reOject(xlWorkSheet); reOject(xlWorkBook); reOject(xlApp); } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "ExportToTemplateMQCDefectDaily : An error happened in the process.", ex.Message); } }
public IQueryable<UtilsJson.AInstitucion> getCadenaValorFilter([FromBody] UtilsJson.ACadenaValor cadena_valor) { IQueryable<UtilsJson.AInstitucion> listado=null; try { string tipo_ente=cadena_valor.tipo_institucion; string nombre_institucion=cadena_valor.nombre_institucion; long[] id_tipo_biotecnologia =cadena_valor.ids_tipo_biotecnologia; long id_sector = cadena_valor.id_sector; SqlParameter[] param = new SqlParameter[4]; if (tipo_ente == null) { param[0] = new SqlParameter("tipo", DBNull.Value); } else { param[0] = new SqlParameter("tipo", tipo_ente); } if (nombre_institucion == null) { param[1] = new SqlParameter("nombre", DBNull.Value); } else { param[1] = new SqlParameter("nombre", nombre_institucion); } if (id_tipo_biotecnologia == null) { param[2] = new SqlParameter("biotecnologia", DBNull.Value); } else { string stringids = string.Empty; for (int i = 0; i < id_tipo_biotecnologia.Length; i++) { stringids += id_tipo_biotecnologia[i] + "|"; } param[2] = new SqlParameter("biotecnologia", stringids); } if (id_sector == 0) { param[3] = new SqlParameter("sector", DBNull.Value); } else { param[3] = new SqlParameter("sector", id_sector); } listado = _repositorio.executeStored<UtilsJson.AInstitucion>("getFilterCadenaValor", param).Cast<UtilsJson.AInstitucion>().AsQueryable<UtilsJson.AInstitucion>(); } catch (Exception ex) { SystemLog log = new SystemLog(); log.ErrorLog(ex.Message); } return listado; }
protected void ExcelGenButton1_Click(object sender, EventArgs e) { try { IList<LogInfo> list = new List<LogInfo>(); list = new SystemLog().GetLogInfoList(5000, 0, true); gvLogInfoList.DataSource = list; gvLogInfoList.DataBind(); gvLogInfoList.Columns[0].Visible = false; } catch (ArgumentNullException ane) { this.ShowMsg(ane.Message); } catch (Exception ex) { ShowMsg(ex.Message); LogEntry.Log.Write(ex.ToString(), EventLogEntryType.Error, LogSourceType.其他); } }
private void LogToDataBase() { // create a system log business object and save to the database SystemLog log = new SystemLog( _systemLogType, _application, _source, _message, _details ).Save(); }
public Mensaje editCronograma([FromBody]UtilsJson.ACronograma cronograma) { Mensaje mensaje = null; try { if (cronograma != null) { if (!string.IsNullOrWhiteSpace(cronograma.token_string)) { if (AutenticacionToken.validateToken(cronograma.token_string) == 1) { Institucion institucion = _repositorio.Get<Institucion>(cronograma.institucionId); Cronograma cronogramaDB = _repositorio.Get<Cronograma>(cronograma.id); if (institucion != null && cronogramaDB != null) { if (AutenticacionToken.validateUserToken(cronograma.token_string, institucion.logueo.correo_electronico)) { string nombre = cronograma.nombre; string tema = cronograma.tema; string descripcion = cronograma.descripcion; string color = cronograma.color; long id_sala = cronograma.salaMesaId; bool estado = cronograma.estado; long id_evento = cronograma.eventoId; if (!string.IsNullOrWhiteSpace(cronograma.hora_inicio) && !string.IsNullOrWhiteSpace(cronograma.hora_fin)) { DateTime hora_inicio = Convert.ToDateTime(cronograma.hora_inicio); DateTime hora_fin = Convert.ToDateTime(cronograma.hora_fin); Publicacion publicacion = _repositorio.Get<Publicacion>(id_evento); SalaMesa salaMesa = _repositorio.Get<SalaMesa>(id_sala); if (DateTime.Compare(hora_inicio, hora_fin) < 0) { if (publicacion != null && salaMesa != null) { cronogramaDB.evento = publicacion; cronogramaDB.sala = salaMesa; cronogramaDB.nombre = nombre; cronogramaDB.tema = tema; cronogramaDB.descripcion = descripcion; cronogramaDB.hora_inicio = hora_inicio; cronogramaDB.hora_fin = hora_fin; cronogramaDB.estado = estado; cronogramaDB.fecha_ult_modificacion = DateTime.Now; _repositorio.SaveOrUpdate<Cronograma>(cronogramaDB); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Cronograma editado exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "El evento o la sala solicitada no existe. verifique"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "La hora de inicio es posterior a la hora de finalizacion. verifique"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "La hora de inicio es posterior a la hora de finalizacion. verifique"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se encontro la sala solicitada o esta asociada a otra institucion."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se puede insertar un objeto nulo"); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
//----------------------------------------------------------------------------------------------------- private void ShowLog(SystemLog log) { Logger.Info(log.Content); }
public bool UpdateDataDBForFinishedGoods(FinishedGoodsItems fgItems, out string ERPDoc, out string SFTDoc) { try { GetdataSFTToDataTable getdataSFTToDataTable = new GetdataSFTToDataTable(); DataTable dtLotMODETAL = getdataSFTToDataTable.GetDataTableLOTMODETAIL(fgItems.productCode); ERPDataUpdate eRPDataUpdate = new ERPDataUpdate(); string TB002 = eRPDataUpdate.getTB002(Class.valiballecommon.GetStorage().DocNo); SFTDataUpdate sFTDataUpdate = new SFTDataUpdate(); string TransNo = sFTDataUpdate.getTransnoOfSFT(Class.valiballecommon.GetStorage().DocNo); Database.ADMMFUpdate aDMMF = new ADMMFUpdate(); DataTable dtADMMF = aDMMF.GetDtADMFFByUser(Class.valiballecommon.GetStorage().UserName); var Update2SFT = sFTDataUpdate.SFTdataUpdate(fgItems, dtLotMODETAL, TB002, TransNo); if (Update2SFT == false) { SystemLog.Output(SystemLog.MSG_TYPE.War, "sFTDataUpdate.SFTdataUpdate(fgItems, TB002, TransNo)", "false"); } else { SystemLog.Output(SystemLog.MSG_TYPE.War, Class.valiballecommon.GetStorage().DocNo + "-" + TransNo + " is created !", ""); } var Update2ERP = eRPDataUpdate.UploadtoERPDBForFinishedGoods(fgItems, dtADMMF, dtLotMODETAL, TB002, TransNo); if (Update2ERP == false) { SystemLog.Output(SystemLog.MSG_TYPE.War, "eRPDataUpdate.UploadtoERPDBForFinishedGoods(fgItems, TB002, TransNo)", "false"); } else { SystemLog.Output(SystemLog.MSG_TYPE.War, Class.valiballecommon.GetStorage().DocNo + "-" + TB002 + " is created !", ""); } Database.Model.INVItems iNVItems = new Database.Model.INVItems(); iNVItems.Product = fgItems.product; iNVItems.ProductCode = fgItems.productCode; iNVItems.Lot = fgItems.lot; iNVItems.Create_Date = fgItems.ImportDate; iNVItems.TypeDoccument = Class.valiballecommon.GetStorage().DocNo; iNVItems.DoccumentNo = TB002; iNVItems.STTDoc = "0001"; iNVItems.Warehouse = fgItems.Warehouse; iNVItems.TypeInportExport = "1"; iNVItems.TypeChange = "1"; iNVItems.Quantity = fgItems.TotalQty; iNVItems.PackageQty = 0; iNVItems.Note = iNVItems.ProductCode; iNVItems.Location = fgItems.location; iNVItems.ImportDate = fgItems.ImportDate; iNVItems.MainLocation = fgItems.location; Database.INVMFUpdate iNVMFUpdate = new INVMFUpdate(); var UpdateINVMF = iNVMFUpdate.InsertINVMF(iNVItems, dtADMMF); Database.INVMEUpdate iNVMEUpdate = new INVMEUpdate(); var UpdateINVME = iNVMEUpdate.InsertINVME(iNVItems, dtADMMF); INVLAUpdate iNVLAUpdate = new INVLAUpdate(); var UpdateINVLA = iNVLAUpdate.InsertINVLA(iNVItems, dtADMMF); INVLFUpdate iNVLFUpdate = new INVLFUpdate(); var UpdateINVLF = iNVLFUpdate.InsertINVLF(iNVItems, dtADMMF); INVMCUpdate iNVMCUpdate = new INVMCUpdate(); var UpdateINVMC = iNVMCUpdate.UpdateOrInsertINVMC(iNVItems, dtADMMF); INVMMUpdate iNVMMUpdate = new INVMMUpdate(); var UpdateINVMM = iNVMMUpdate.UpdateOrInsertINVMM(iNVItems, dtADMMF); ERPDoc = TB002; SFTDoc = TransNo; } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "UpdateData2DBForFinishedGoods(FinishedGoodsItems fgItems)", ex.Message); ERPDoc = ""; SFTDoc = ""; return(false); } return(true); }
public bool InsertData(DataTable dtdata) { try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(" insert into t_TL_BuyerInfo ( "); for (int i = 0; i < dtdata.Columns.Count; i++) { if (i < dtdata.Columns.Count - 1) { stringBuilder.Append(dtdata.Columns[i].ColumnName + ","); } else { stringBuilder.Append(dtdata.Columns[i].ColumnName + ") values ( "); } } for (int i = 0; i < dtdata.Rows.Count; i++) { StringBuilder stringFun = new StringBuilder(); for (int j = 0; j < dtdata.Columns.Count; j++) { string valueCell = "NULL"; if (dtdata.Rows[i][dtdata.Columns[j].ColumnName] != null) { if (dtdata.Columns[j].DataType == typeof(DateTime)) { if (dtdata.Columns[j].ColumnName == "Date_Update") { valueCell = "NULL"; } else { valueCell = DateTime.Now.ToString("yyyyMMdd HH:mm:ss"); } } else if (dtdata.Rows[i][dtdata.Columns[j].ColumnName].GetType() == typeof(DBNull)) { valueCell = "NULL"; } else { valueCell = dtdata.Rows[i][dtdata.Columns[j].ColumnName].ToString(); } } if (j < dtdata.Columns.Count - 1) { if (valueCell == "NULL") { stringFun.Append(" " + valueCell + " ,"); } else { stringFun.Append(" '" + valueCell + "',"); } } else { if (valueCell == "NULL") { stringFun.Append(" " + valueCell + ")"); } else { stringFun.Append(" '" + valueCell + "')"); } } } string sqlInsert = stringBuilder.ToString() + stringFun.ToString(); sqlCON sql = new sqlCON(); var result = sql.sqlExecuteNonQuery(sqlInsert, false); //if (result == false) //{ // return false; //} } return(true); } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "insert data t_TL_BuyerInfor", ex.Message); } return(false); }
public override void ProcessNotify() { WxPayData notifyData = GetNotifyData(); //检查openid和product_id是否返回 if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "回调数据异常"); SystemLog.Add(this.GetType().ToString() + "The data WeChat post is error : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //调统一下单接口,获得下单结果 string openid = notifyData.GetValue("openid").ToString(); string product_id = notifyData.GetValue("product_id").ToString(); string Order_Code = notifyData.GetValue("out_trade_no").ToString(); Lebi_Order order = B_Lebi_Order.GetModel("Code = lbsql{'" + Order_Code + "'}"); if (order == null) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL Order"); res.SetValue("return_msg", "统一下单失败"); SystemLog.Add(this.GetType().ToString() + "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } WxPayData unifiedOrderResult = new WxPayData(); try { unifiedOrderResult = UnifiedOrder(openid, product_id); } catch (Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台 { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); SystemLog.Add(this.GetType().ToString() + "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } //若下单失败,则立即返回结果给微信支付后台 if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id")) { WxPayData res = new WxPayData(); res.SetValue("return_code", "FAIL"); res.SetValue("return_msg", "统一下单失败"); SystemLog.Add(this.GetType().ToString() + "UnifiedOrder failure : " + res.ToXml()); page.Response.Write(res.ToXml()); page.Response.End(); } WxPayConfig conf = new WxPayConfig(order); //统一下单成功,则返回成功结果给微信支付后台 WxPayData data = new WxPayData(); data.SetValue("return_code", "SUCCESS"); data.SetValue("return_msg", "OK"); data.SetValue("appid", conf.APPID); data.SetValue("mch_id", conf.MCHID); data.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id")); data.SetValue("result_code", "SUCCESS"); data.SetValue("err_code_des", "OK"); data.SetValue("sign", data.MakeSign(order)); //SystemLog.Add(this.GetType().ToString() + "UnifiedOrder success , send data to WeChat : " + data.ToXml()); page.Response.Write(data.ToXml()); page.Response.End(); }
protected void Page_Load(object sender, EventArgs e) { SortedDictionary <string, string> sPara = GetRequestPost(); if (sPara.Count == 0) { sPara = GetRequestGet(); } //商户订单号 string out_trade_no = RequestTool.RequestString("out_trade_no"); Lebi_Order order = B_Lebi_Order.GetModel("Code=lbsql{'" + out_trade_no + "'}"); if (order == null) { SystemLog.Add(out_trade_no + "系统错误"); Response.Write("系统错误"); Response.End(); return; } if (sPara.Count > 0)//判断是否有带返回参数 { Notify aliNotify = new Notify(order); bool verifyResult = aliNotify.Verify(sPara, RequestTool.RequestString("notify_id"), RequestTool.RequestString("sign")); if (verifyResult)//验证成功 { ///////////////////////////////////////////////////////////////////////////////////////////////////////////// //请在这里加上商户的业务逻辑程序代码 //——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— //获取支付宝的通知返回参数,可参考技术文档中服务器异步通知参数列表 //支付宝交易号 string trade_no = RequestTool.RequestString("trade_no"); //交易状态 string trade_status = RequestTool.RequestString("trade_status"); if (trade_status == "TRADE_FINISHED") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 //注意: //该种交易状态只在两种情况下出现 //1、开通了普通即时到账,买家付款成功后。 //2、开通了高级即时到账,从该笔交易成功时间算起,过了签约时的可退款时限(如:三个月以内可退款、一年以内可退款等)后。 Order.OnlinePaySuccess("alipayJSDZ", out_trade_no, trade_no); Response.Write("success"); //请不要修改或删除 } else if (trade_status == "TRADE_SUCCESS") { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 //注意: //该种交易状态只在一种情况下出现——开通了高级即时到账,买家付款成功后。 Order.OnlinePaySuccess("alipayJSDZ", out_trade_no, trade_no); Response.Write("success"); //请不要修改或删除 } else { Response.Write("fail"); SystemLog.Add("单号付款" + trade_no + " | " + trade_status); } //Response.Write("success"); //Order.PaySuccess(out_trade_no, trade_no); } else//验证失败 { Response.Write("fail"); SystemLog.Add(out_trade_no + "验证fail"); } } else { Response.Write("无通知参数"); SystemLog.Add(out_trade_no + "无通知参数"); } }
public bool InsertData(DataTable dtdata) { try { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(" insert into MOCTF ( "); for (int i = 0; i < dtdata.Columns.Count - 1; i++) { if (i < dtdata.Columns.Count - 2) { if (dtdata.Columns[i].ColumnName != "CFIELD01") { stringBuilder.Append(dtdata.Columns[i].ColumnName + ","); } } else { stringBuilder.Append(dtdata.Columns[i].ColumnName + ") values ( "); } } for (int i = 0; i < dtdata.Rows.Count; i++) { StringBuilder stringFun = new StringBuilder(); for (int j = 0; j < dtdata.Columns.Count - 1; j++) { string valueCell = "NULL"; if (dtdata.Rows[i][dtdata.Columns[j].ColumnName] != null) { if (dtdata.Rows[i][dtdata.Columns[j].ColumnName].GetType() == typeof(DBNull)) { valueCell = "NULL"; } else { valueCell = dtdata.Rows[i][dtdata.Columns[j].ColumnName].ToString(); } } if (j < dtdata.Columns.Count - 2) { if (dtdata.Columns[j].ColumnName != "CFIELD01") { if (valueCell == "NULL") { stringFun.Append(" " + valueCell + " ,"); } else { stringFun.Append(" '" + valueCell + "',"); } } } else { if (valueCell == "NULL") { stringFun.Append(" " + valueCell + ")"); } else { stringFun.Append(" '" + valueCell + "')"); } } } string sqlInsert = stringBuilder.ToString() + stringFun.ToString(); SqlTLVN2 sqlTLVN2 = new SqlTLVN2(); var result = sqlTLVN2.sqlExecuteNonQuery(sqlInsert, false); if (result == false) { return(false); } } return(true); } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "MOCTF", ex.Message); } return(false); }
/// <summary> /// 获取或更新报表11,12源数据 /// </summary> /// <param name="dt"></param> /// <param name="HourPer"></param> public void Update(DateTime dt, int HourPer) { try { string startTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); SystemLog.GetInstance().Log.Info(string.Format("{0}:开始获取11,12报表数据", startTime)); using (DataSubmittedEntities db = new DataSubmittedEntities()) { //获取报表12配置的假期信息 List <OT_HDayConfig> pdayconfigs = db.OT_HDayConfig.Where(s => s.Id == 12).ToList(); OT_HDayConfig pdayconfig = new OT_HDayConfig(); if (pdayconfigs.Count > 0) { pdayconfig = pdayconfigs.First(); } DateTime pDt = DateTime.Parse(dt.ToShortDateString()); //报表11,12收费站 List <int> TJStation = StationConfiguration.GetStaionList(); //获取今年当日数据//p.VehType == 0 表示合计数据, IEnumerable <DS_DataSource> pCollection = db.DS_DataSource.Where(p => DbFunctions.TruncateTime(p.CalcuTime) == DbFunctions.TruncateTime(dt) && p.VehType == 0 && TJStation.Contains(p.StaID.Value)); //今年数据 IEnumerable <DS_DataSource> pHdayCollection = db.DS_DataSource.Where(p => (DbFunctions.TruncateTime(p.CalcuTime) <= pdayconfig.HDayEnd.Value && DbFunctions.TruncateTime(p.CalcuTime) >= pdayconfig.HDayStart.Value) && p.VehType == 0 && TJStation.Contains(p.StaID.Value)); //每日数据 List <RP_HDayAADT> pList = db.RP_HDayAADT.Where(p => p.CalcuTime == pDt).ToList(); RP_HDayAADT pAADTInfo = null; bool pIsHas = false; if (pList.Count > 0) { pAADTInfo = pList.FirstOrDefault(); pIsHas = true; } else { pAADTInfo = new RP_HDayAADT(); } //更新实体 UpdateInfo(pCollection, pAADTInfo, pDt, pIsHas, pHdayCollection); using (TransactionScope transaction = new TransactionScope()) { //如果不存在,则添加,否则则更新 if (!pIsHas) { db.RP_HDayAADT.Add(pAADTInfo); } db.SaveChanges(); transaction.Complete(); } } string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); SystemLog.GetInstance().Log.Info(string.Format("{0}:结束获取11,12报表数据", endTime)); SystemLog.GetInstance().Log.Info(string.Format("统计11,12报表数据耗时{0}秒", (DateTime.Parse(endTime) - DateTime.Parse(startTime)).TotalSeconds)); //显示执行该方法的线程ID //SystemLog.GetInstance().Log.Info(string.Format("调用11,12Update的线程ID为:{0}", Thread.CurrentThread.ManagedThreadId)); Thread.Sleep(1000); } catch (Exception ex) { throw ex; } }
/// <summary> /// 登录 /// </summary> protected void LogIn() { try { //new Mac().GetMac(); string userName = txtUserName.Text.Trim(); //用户名 string passWord = txtPassword.Text.Trim(); //密码 //用户名和密码均不为空 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passWord)) { //加密密码 passWord = AES.Encrypt(passWord, "0512000000000512"); } UserProfile user0 = UserProfile.GetUserProfileByUserIDNew(userName, passWord); if (user0 != null) { //user0 = UserProfile.GetUserProfileByUserID(userName); UserProfile.instance = user0; GetClientIP(); string Mac = string.Empty; string userIP = string.Empty; GetMac(out Mac, out userIP); string physicalAddress = Common.GetMacByIPConfig().Count > 0 ? Common.GetMacByIPConfig()[0] : null; SystemLog log = new SystemLog(); log.ID = Guid.NewGuid().ToString(); log.EMPLOYEEID = user0.ID; log.OPERATETYPE = null; log.OPERATECONTENT = "登录"; log.CREATEDATE = DateTime.Now; log.IPADDRESS = userIP; log.PHYSICALADDRESS = Mac; SystemLogDAL slogDal = new SystemLogDAL(); slogDal.Add(log); if (!string.IsNullOrEmpty(Request.QueryString["returnurl"])) { Response.Redirect(Request.QueryString["returnurl"].ToString()); } else { Response.Redirect("~/Pages/Account/WebPageRedirect.aspx", true); //原来用重定向非常耗时 注意哦 Response.End(); //ExecuteScript("window.location.href='/Pages/Account/WebPageRedidrect.aspx"); } Response.End(); //ExecuteScript("window.location.href='WebPageRedirect.aspx';"); } else { Alert("用户名或密码不正确,或者您不具备访问任何模块的权限!"); return; } ////获得用户dt //System.Data.DataTable dt = UserProfile.GetUserProfileByUserIDandPwd(userName, passWord); //UserProfile user = null; //if (dt != null) //{ // user = UserProfile.GetUserProfileByUserID(userName); // UserProfile.instance = user; // GetClientIP(); // string Mac = string.Empty; // string userIP = string.Empty; // GetMac(out Mac, out userIP); // string physicalAddress = Common.GetMacByIPConfig().Count > 0 ? Common.GetMacByIPConfig()[0] : null; // SystemLog log = new SystemLog(); // log.ID = Guid.NewGuid().ToString(); // log.EMPLOYEEID = user.ID; // log.OPERATETYPE = null; // log.OPERATECONTENT = "登录"; // log.CREATEDATE = DateTime.Now; // log.IPADDRESS = userIP; // log.PHYSICALADDRESS = Mac; // SystemLogDAL slogDal = new SystemLogDAL(); // slogDal.Add(log); // Response.Redirect("/WebPageRedirect.aspx"); //} //else //{ // Alert("用户名或密码不正确,或者您不具备访问任何模块的权限!"); // return; //} } catch (Exception ex) { LogHelper.WriteLine("登录异常。" + ex.Message + "\r\n" + ex.StackTrace); Alert("登录出现异常!"); return; } }
/// <summary> /// [Tuanngoc Dev] For update all data to all department. /// </summary> /// <param name="dtERPPQC"></param> /// <param name="ERPDoc"></param> /// <returns></returns> public sql_CheckCondition.QueryResult UpdateDataDBForAllDeparment(DataTable dtERPPQC, out string ERPDoc) { ERPDoc = null; sql_CheckCondition.QueryResult ttReturn = sql_CheckCondition.QueryResult.Exception; var ischeckSFCTA = false; try { ERPDoc = ""; ERPDataUpdate eRPDataUpdate = new ERPDataUpdate(); string TB002 = eRPDataUpdate.getTB002(Class.valiballecommon.GetStorage().DocNo); // Done update query from Mr.An guidelines. sql_CheckCondition.QueryResult CheckNoConfirmTotal = sql_CheckCondition.CheckConditionAllItemQRCodeInsert(dtERPPQC); if (CheckNoConfirmTotal == sql_CheckCondition.QueryResult.Exception) { return(sql_CheckCondition.QueryResult.Exception); } for (int i = 0; i < dtERPPQC.Rows.Count; i++) { string productOrder = dtERPPQC.Rows[i]["ProductOrder"].ToString(); string product = dtERPPQC.Rows[i]["Product"].ToString().Trim(); if (!Database.SFC.SFCTA.IsExistSFCTA(productOrder) && sql_CheckCondition.Is_stageManagement(product) == sql_CheckCondition.QueryResult.OK) { MessageBox.Show("Vui lòng kiểm tra không tồn tại mã sản phẩm này trong bảng SFCTA: " + productOrder, "Warning", MessageBoxButtons.OK); /// Consider break; } double Quantity = double.Parse(dtERPPQC.Rows[i]["Quantity"].ToString()); double SLDongGoi = Database.INV.INVMD.ConvertToWeightKg(product, Quantity); // convert quality to Kg string WareHouse = dtERPPQC.Rows[i]["Warehouse"].ToString(); /// sql_CheckCondition.QueryResult statusStage = sql_CheckCondition.Is_stageManagement(product); sql_CheckCondition.QueryResult statusLocationManagement = sql_CheckCondition.Is_LocationManagement(WareHouse); /// if (statusStage == sql_CheckCondition.QueryResult.OK) // phai quan ly cong doan moi kiem tra { ischeckSFCTA = Database.SFC.SFCTA.IscheckQantityAndWeight(productOrder, Quantity, SLDongGoi); // chi cho quan ly cong doan } var ischeckMOCTA = Database.MOC.MOCTA.IscheckQantityAndWeight(product, productOrder, Quantity, SLDongGoi); //we have check more sql_CheckCondition.QueryResult statusLot = sql_CheckCondition.Is_lotManagement(product); /// stage OK if (statusStage == sql_CheckCondition.QueryResult.OK && statusLot == sql_CheckCondition.QueryResult.OK && statusLocationManagement == sql_CheckCondition.QueryResult.OK) //_07_111 { if (ischeckMOCTA == true && ischeckSFCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_07(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_07(dtERPPQC.Rows[i], i, TB002, false); } } else if (statusStage == sql_CheckCondition.QueryResult.OK && statusLot == sql_CheckCondition.QueryResult.OK && statusLocationManagement == sql_CheckCondition.QueryResult.NG) ///_06_110 { if (ischeckMOCTA == true && ischeckSFCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_06(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_06(dtERPPQC.Rows[i], i, TB002, false); } } else if (statusStage == sql_CheckCondition.QueryResult.OK && statusLot == sql_CheckCondition.QueryResult.NG && statusLocationManagement == sql_CheckCondition.QueryResult.OK) /// _05_101 { if (ischeckMOCTA == true && ischeckSFCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_05(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_05(dtERPPQC.Rows[i], i, TB002, false); } } else if (statusStage == sql_CheckCondition.QueryResult.OK && statusLot == sql_CheckCondition.QueryResult.NG && statusLocationManagement == sql_CheckCondition.QueryResult.NG) //_04_100 { if (ischeckMOCTA == true && ischeckSFCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_04(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_04(dtERPPQC.Rows[i], i, TB002, false); } } /////////stage NG else if (statusStage == sql_CheckCondition.QueryResult.NG && statusLot == sql_CheckCondition.QueryResult.OK && statusLocationManagement == sql_CheckCondition.QueryResult.OK) //_03_011 { if (ischeckMOCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_03(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_03(dtERPPQC.Rows[i], i, TB002, false); } } else if (statusStage == sql_CheckCondition.QueryResult.NG && statusLot == sql_CheckCondition.QueryResult.OK && statusLocationManagement == sql_CheckCondition.QueryResult.NG) //_02_010 { if (ischeckMOCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_02(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_02(dtERPPQC.Rows[i], i, TB002, false); } } else if (statusStage == sql_CheckCondition.QueryResult.NG && statusLot == sql_CheckCondition.QueryResult.NG && statusLocationManagement == sql_CheckCondition.QueryResult.OK) //_01_001 { if (ischeckMOCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_01(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_01(dtERPPQC.Rows[i], i, TB002, false); } } else if (statusStage == sql_CheckCondition.QueryResult.NG && statusLot == sql_CheckCondition.QueryResult.NG && statusLocationManagement == sql_CheckCondition.QueryResult.NG) //_00_000 { if (ischeckMOCTA == true && CheckNoConfirmTotal == sql_CheckCondition.QueryResult.OK) { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_00(dtERPPQC.Rows[i], i, TB002, true); } else { ttReturn = NewQRcode.sql_QueryFromFileSQL.managestage_managelot_managelocation_00(dtERPPQC.Rows[i], i, TB002, false); } } else { ttReturn = sql_CheckCondition.QueryResult.Exception; } //// if (ttReturn != sql_CheckCondition.QueryResult.Exception) // Add for call trigger for check status product. { sql_QueryFromFileSQL.Updatestatus_Product(productOrder); } } ERPDoc = TB002; } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "Exception message", "UpdateDataDBForAllDeparment :" + ex.Message); return(sql_CheckCondition.QueryResult.Exception); } return(ttReturn); }
public Mensaje deleteInstitution([FromBody]UtilsJson.AInstitucion institution) { Mensaje mensaje = null; object[] infoLogin = getExternalIp(); try { if (institution != null) { if (!string.IsNullOrWhiteSpace(institution.token_string)) { if (AutenticacionToken.validateToken(institution.token_string) == 1 && AutenticacionToken.validateUserToken(institution.token_string, institution.logueo.correo_electronico)) { //datos logueo string correo_electronico_l = institution.logueo.correo_electronico; string password1 = institution.logueo.contrasena1; string password2 = institution.logueo.contrasena2; if (!string.IsNullOrEmpty(correo_electronico_l) && !string.IsNullOrEmpty(password1) && !string.IsNullOrEmpty(password2)) { if (password1.Equals(password2)) { //Cifrado de la contrasena string contrasena = CifradoDatos.cifrarPassword(password1); //Busco la institucion asociada al usuario y a la contrasena Expression<Func<Institucion, bool>> query = (u => u.logueo.correo_electronico == correo_electronico_l && u.logueo.contrasena == password1); List<Institucion> institucion = _repositorio.Filter<Institucion>(query); institucion[0].estado = false; institucion[0].fecha_ult_modificacion = DateTime.Now; _repositorio.SaveOrUpdate<Institucion>(institucion[0]); //Creo un token de autenticacion para deshabilitar el perfil string codigo = CifradoDatos.cifrarRSA(institucion[0].logueo.correo_electronico); //Envio email confirmacion para deshabilitar el perfil StringBuilder bodyMail = new StringBuilder(); bodyMail.AppendLine("Para eliminar el perfil de la institucion " + institucion[0].nombre + " dirijase al siguiente enlace."); string informacionHost = UtilsHost.serverInfoCurrent(); bodyMail.AppendLine("<a href=\"" + informacionHost + "/Institucion/ConfirmationDelete?tokenString=" + codigo + "\">Eliminar perfil.</a>" + "</br>"); bodyMail.AppendLine("Informacion Adicional:" + "</br>"); if (infoLogin != null) { bodyMail.AppendLine("Pais:" + infoLogin[2].ToString() + "</br>"); bodyMail.AppendLine("Departamento:" + infoLogin[4].ToString() + "</br>"); bodyMail.AppendLine("Ciudad:" + infoLogin[5].ToString() + "</br>"); bodyMail.AppendLine("Ip Address:" + infoLogin[0].ToString() + "</br>"); } bodyMail.AppendLine("Fecha:" + DateTime.Now.ToString() + "</br>"); string subject = "Confirmación cancelación de perfil."; Mail mail = new Mail(institucion[0].logueo.correo_electronico, subject, bodyMail); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificacion", "Envio de correo electronico para continuar con el proceso realizado."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "passwords son diferentes."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "passwords son obligatorios."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "Token de autenticación requerido."); } } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(); mensaje.titulo = "Error en tipo de dato"; mensaje.tipo = "Error"; mensaje.cuerpo = "Error en la lectura de parametros, verifique que los parametros cumplan con el tipo de dato"; SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
public bool UpdateDataDBForFinishedGoodsNotConfirm(DataTable dtERPPQC, string Location, out string ERPDoc, out string SFTDoc) { try { ERPDoc = ""; SFTDoc = ""; ERPDataUpdate eRPDataUpdate = new ERPDataUpdate(); string TB002 = eRPDataUpdate.getTB002(Class.valiballecommon.GetStorage().DocNo); SFTDataUpdate sFTDataUpdate = new SFTDataUpdate(); string TransNo = sFTDataUpdate.getTransnoOfSFT(Class.valiballecommon.GetStorage().DocNo); Database.SFT.SFT_TRANSORDER_LINE sFT_TRANSORDER_LINE = new Database.SFT.SFT_TRANSORDER_LINE(); ConvertDataTable convertDataTable = new ConvertDataTable(); DataTable dtTRANSORDER_LINE = convertDataTable.ERPPQCtoSFTTRANSORDERLINE(dtERPPQC, TransNo, TB002, Location); DataTable dtTRANSORDER = convertDataTable.GetDataSFTTRANSORDER(dtERPPQC, dtTRANSORDER_LINE); DataTable dtWSRUN = convertDataTable.GetDataTableSFT_WS_RUN(dtERPPQC, dtTRANSORDER_LINE); ConvertDataERP convertDataERP = new ConvertDataERP(); DataTable dtSFCTC = convertDataERP.GetDataTableSFCTC(dtERPPQC, TB002, "N"); //// DataTable dtSFCTB = convertDataERP.GetDataTableSFCTB(dtSFCTC, dtERPPQC, TransNo, "N"); /// if (dtTRANSORDER_LINE.Rows.Count > 0 && dtTRANSORDER.Rows.Count > 0 && dtWSRUN.Rows.Count > 0 && dtSFCTC.Rows.Count > 0 && dtSFCTB.Rows.Count > 0) { var Result = sFT_TRANSORDER_LINE.InsertData(dtTRANSORDER_LINE); if (Result == false) { MessageBox.Show("Insert TransOrder_Line fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFT.SFT_TRANSORDER sFT_TRANSORDER = new Database.SFT.SFT_TRANSORDER(); var resultTransOrder = sFT_TRANSORDER.InsertData(dtTRANSORDER); if (resultTransOrder == false) { MessageBox.Show("Insert TransOrder fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } int[] sequence = new int[dtERPPQC.Rows.Count]; Database.SFT.SFT_WS_RUN sFT_WS_RUN = new Database.SFT.SFT_WS_RUN(); var resultWs_run = sFT_WS_RUN.InsertData(dtWSRUN, out sequence); if (resultWs_run == false) { MessageBox.Show("Insert SFT_WS_RUN fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFT.MODETAIL mODETAIL = new Database.SFT.MODETAIL(); var resultUpdate = mODETAIL.UpdateMODETAIL(dtTRANSORDER_LINE); //MOC027 ko biet la gi ? if (resultUpdate == false) { MessageBox.Show("update Modetail fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFT.SFT_LOT sFT_LOT = new Database.SFT.SFT_LOT(); var InsertOrUpdate = sFT_LOT.InsertUpdateLot(dtTRANSORDER_LINE); if (InsertOrUpdate == false) { MessageBox.Show("Insert Lot fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFC.SFCTC sFCTC = new Database.SFC.SFCTC(); /// var InsertSFCTC = sFCTC.InsertData(dtSFCTC); ///// if (InsertSFCTC == false) { MessageBox.Show("Insert SFCTC fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFC.SFCTB sFCTB = new Database.SFC.SFCTB(); ///// var InsertSFCTB = sFCTB.InsertData(dtSFCTB); if (InsertSFCTB == false) { MessageBox.Show("Insert SFCTB fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFC.SFCTA sFCTA = new Database.SFC.SFCTA(); ///// var UpdateSFCTA = sFCTA.UpdateSFCTAForFinishedGoodsNotConfirm(dtERPPQC); if (UpdateSFCTA == false) { MessageBox.Show("Insert SFCTA fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.ERPSOFT.ERPOutPQCQR eRPOutPQCQR = new Database.ERPSOFT.ERPOutPQCQR(); ////function kho var updateOutPQC = eRPOutPQCQR.UpdateImportWarehouse(dtERPPQC, Class.valiballecommon.GetStorage().DocNo + "-" + TB002); if (updateOutPQC == false) { MessageBox.Show("Insert import status fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } } ERPDoc = TB002; SFTDoc = TransNo; } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "UpdateData2DBForFinishedGoods(FinishedGoodsItems fgItems)", ex.Message); ERPDoc = ""; SFTDoc = ""; return(false); } return(true); }
/// <summary> /// 保存系统日志 /// </summary> /// <param name="Title">日志信息</param> /// <returns></returns> public bool SaveSystemLog(string Title) { SystemLog log = new SystemLog(); log.AddTime = DateTime.Now; log.Title = Title; //获取远程ip地址 log.Url = HttpContext.Current.Request.Url.Authority; Web_User user = (Web_User)HttpContext.Current.Session["User"]; log.UserName = user.LOGNAME; return dal.AddNew(log); }
public bool UpdateDataDBForFinishedGoods(DataTable dtERPPQC, out string ERPDoc) { try { ERPDoc = ""; //Class.valiballecommon.GetStorage().DocNo ERPDataUpdate eRPDataUpdate = new ERPDataUpdate(); string TB002 = eRPDataUpdate.getTB002(Class.valiballecommon.GetStorage().DocNo); //fix //string TB002 = eRPDataUpdate.getTF002(Class.valiballecommon.GetStorage().DocNo);//fix disable 22/12/2020 ConvertDataTable convertDataTable = new ConvertDataTable(); ConvertDataERP convertDataERP = new ConvertDataERP(); DataTable dtSFCTC = convertDataERP.GetDataTableSFCTC(dtERPPQC, TB002, "Y"); DataTable dtSFCTB = convertDataERP.GetDataTableSFCTB(dtSFCTC, dtERPPQC, "", "Y");// NO SFT DataTable dtMOCTG = convertDataERP.GetDataTableMOCTG(dtERPPQC, TB002); DataTable dtMOCTF = convertDataERP.GetDataTableMOCTF(dtMOCTG, TB002); if (dtSFCTC.Rows.Count > 0 && dtMOCTG.Rows.Count > 0 && dtMOCTF.Rows.Count > 0) { Database.SFC.SFCTC sFCTC = new Database.SFC.SFCTC(); var InsertSFCTC = sFCTC.InsertData(dtSFCTC); if (InsertSFCTC == false) { MessageBox.Show("Insert SFCTC fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFC.SFCTB sFCTB = new Database.SFC.SFCTB(); var InsertSFCTB = sFCTB.InsertData(dtSFCTB); if (InsertSFCTB == false) { MessageBox.Show("Insert SFCTB fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.SFC.SFCTA sFCTA = new Database.SFC.SFCTA(); var UpdateSFCTA = sFCTA.UpdateSFCTAForFinishedGoods(dtERPPQC); // UPDATE SO LUONG if (UpdateSFCTA == false) { MessageBox.Show("Insert SFCTA fail ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } Database.MOC.MOCTG mOCTG = new Database.MOC.MOCTG(); var insertMoctg = mOCTG.InsertData(dtMOCTG); if (insertMoctg == false) { ClassMessageBoxUI.Show("Insert MOCTG fail ", false); return(false); } Database.MOC.MOCTF mOCTF = new Database.MOC.MOCTF(); var insertMOCTF = mOCTF.InsertData(dtMOCTF); if (insertMOCTF == false) { ClassMessageBoxUI.Show("Insert MOCTF fail ", false); return(false); } Database.MOC.MOCTA mOCTA = new Database.MOC.MOCTA(); var updateMOCTA = mOCTA.UpdateMOCTAForFinishedGoods(dtERPPQC); if (updateMOCTA == false) { ClassMessageBoxUI.Show("update MOCTA fail ", false); return(false); } UpdateWarehouseForFinishedGoods updateWarehouseForFinishedGoods = new UpdateWarehouseForFinishedGoods(); var UpdateWarehouse = updateWarehouseForFinishedGoods.UpdateWarehouse(dtERPPQC, TB002); if (UpdateWarehouse == false) { ClassMessageBoxUI.Show("update stock warehouse fail ", false); } } ERPDoc = TB002; } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "UpdateData2DBForFinishedGoods(FinishedGoodsItems fgItems)", ex.Message); ERPDoc = ""; return(false); } return(true); }
public async Task<Mensaje> editInstitution([FromBody]UtilsJson.AInstitucion institution) { Mensaje mensaje = new Mensaje(); try { if (institution != null) { if (!string.IsNullOrWhiteSpace(institution.token_string)) { if (AutenticacionToken.validateToken(institution.token_string) == 1 && AutenticacionToken.validateUserToken(institution.token_string, institution.logueo.correo_electronico)) { string n_correo_electronico_l = string.Empty; string n_password1 = string.Empty; string n_password2 = string.Empty; string contrasena = string.Empty; if (institution.logueo != null) { n_correo_electronico_l = institution.logueo.correo_electronico; n_password1 = institution.logueo.contrasena1; n_password2 = institution.logueo.contrasena2; if (!string.IsNullOrWhiteSpace(n_password1) && !string.IsNullOrWhiteSpace(n_password2)) { contrasena = CifradoDatos.cifrarPassword(n_password1); } } //datos representante string nombre_r = institution.representante.nombre; string apellido_r = institution.representante.nombre; string tipo_identificacion = institution.representante.tipo_identificacion; string identificacion = institution.representante.identificacion; string urlCvlac = institution.representante.urlCvlac; string correo_electronico_r = institution.representante.correo_electronico; //datos institucion string nombre = institution.nombre; string descripcion = institution.descripcion; string correo_electronico = institution.correo_electronico; string direccion_postal = institution.direccion_postal; string facebook = institution.facebook; string fax = institution.fax; string impacto = institution.impacto; string linkedin = institution.linkedin; string naturaleza = institution.naturaleza; string pagina_web = institution.pagina_web; int tamano = institution.tamano; string telefono = institution.telefono; string tipo_institucion = institution.tipo_institucion; string twitter = institution.twitter; string constitucion = institution.constitucion; string fecha_creacion = institution.fecha_creacion; string imagen_base64 = institution.imagen_base64; long municipio_id = institution.municipio.id; UtilsJson.ASector[] sectores = institution.sectores; List<Sector> lstSectores = convertToSector(sectores); UtilsJson.ATipoBiotecnologia[] tipo_biote = institution.Tipos_Biotecnologia; List<TipoBiotecnologia> lstTipoBiotecnologia = convertToTipoBiotecnologia(tipo_biote); //Busco la institucion y el representante asociada al usuario y a la contrasena Expression<Func<Persona, bool>> query = (u => u.institucion.logueo.correo_electronico == institution.logueo.correo_electronico && u.institucion.estado == true); List<Persona> institucion = _repositorio.Filter<Persona>(query); //Si el correo_electronico y la contrasena son validas subo a session la institucion if (institucion != null) { if (institucion.Count > 0) { Municipio municipioDb = _repositorio.Get<Municipio>(municipio_id); if (!string.IsNullOrWhiteSpace(contrasena)) { institucion[0].institucion.logueo.contrasena = contrasena; institucion[0].institucion.logueo.fecha_ult_modificacion = DateTime.Now; } institucion[0].institucion.descripcion = descripcion; institucion[0].institucion.impacto = impacto; institucion[0].institucion.correo_electronico = correo_electronico; institucion[0].institucion.linkedin = linkedin; institucion[0].institucion.municipio = municipioDb; institucion[0].institucion.naturaleza = naturaleza; institucion[0].institucion.constitucion = constitucion; institucion[0].institucion.nombre = nombre; institucion[0].institucion.pagina_web = pagina_web; institucion[0].institucion.tamano = tamano; institucion[0].institucion.telefono = telefono; institucion[0].institucion.fax = fax; institucion[0].institucion.direccion_postal = direccion_postal; institucion[0].institucion.facebook = facebook; institucion[0].institucion.tipo_institucion = tipo_institucion; institucion[0].institucion.twitter = twitter; institucion[0].institucion.fecha_creacion = (!string.IsNullOrWhiteSpace(fecha_creacion)) ? Convert.ToDateTime(fecha_creacion) : (DateTime?)null; institucion[0].institucion.fecha_ult_modificacion = DateTime.Now; if (institucion[0].institucion.banner == null) { if (!string.IsNullOrWhiteSpace(imagen_base64)) { institucion[0].institucion.banner = new Imagen { imagenBase64 = imagen_base64, fecha_ult_modificacion = DateTime.Now }; //Redimension de la imagen y creacion de icono string extension = imagen_base64.Split(',')[0]; imagen_base64 = imagen_base64.Split(',')[1]; byte[] bytes = Convert.FromBase64String(imagen_base64); if (bytes.Length > 0) { byte[] filebytesIcon = UtilsHost.Redimensionar(Image.FromStream(new MemoryStream(bytes)), 100, 100, 32); string encodedDataIcon = extension + "," + Convert.ToBase64String(filebytesIcon, Base64FormattingOptions.None); institucion[0].institucion.icono = new Imagen { imagenBase64 = encodedDataIcon, fecha_ult_modificacion = DateTime.Now }; } } } else { if (!string.IsNullOrWhiteSpace(imagen_base64)) { institucion[0].institucion.banner.imagenBase64 = imagen_base64; institucion[0].institucion.banner.fecha_ult_modificacion = DateTime.Now; //Redimension de la imagen y creacion de icono string extension = imagen_base64.Split(',')[0]; imagen_base64 = imagen_base64.Split(',')[1]; byte[] bytes = Convert.FromBase64String(imagen_base64); if (bytes.Length > 0) { byte[] filebytesIcon = UtilsHost.Redimensionar(Image.FromStream(new MemoryStream(bytes)), 100, 100, 32); string encodedDataIcon = extension + "," + Convert.ToBase64String(filebytesIcon, Base64FormattingOptions.None); institucion[0].institucion.icono.imagenBase64 = encodedDataIcon; institucion[0].institucion.icono.fecha_ult_modificacion = DateTime.Now; } } } //datos del representante institucion[0].nombre = nombre_r; institucion[0].apellido = apellido_r; institucion[0].tipo_identificacion = tipo_identificacion; institucion[0].identificacion = identificacion; institucion[0].urlCvlac = urlCvlac; institucion[0].correo_electronico = correo_electronico_r; institucion[0].fecha_ult_modificacion = DateTime.Now; //Envio email confirmacion edicion perfil StringBuilder bodyMail = new StringBuilder(); bodyMail.AppendLine("Su Perfil ha sido editado exitosamente en biotecred.com ."); bodyMail.AppendLine("Lo invitamos a que inicie sesión y continúe disfrutando de nuestra plataforma."); string subject = "Confirmación Edición de perfil."; Mail mail = new Mail(institucion[0].institucion.logueo.correo_electronico, subject, bodyMail); //Verifico si la institucion existe en el sistema List<Mensaje> lstVerificaExiste = existeInstitucion(institucion[0]); List<Mensaje> lstVerificaExisteEmail = mail.existeEmail(); if (lstVerificaExiste.Count == 0 && lstVerificaExisteEmail.Count == 0) { institucion[0].fecha_ult_modificacion = DateTime.Now; _repositorio.SaveOrUpdate<Persona>(institucion[0]); long id_inst = institucion[0].id; //Elimino las relaciones de la entidad institucion con sectores y tipoBiotecnologia Expression<Func<InstitucionSector, bool>> query3 = (u => u.institucion.id == id_inst); _repositorio.DeleteFilter<InstitucionSector>(query3); Expression<Func<InstitucionTipoBiotec, bool>> query4 = (u => u.institucion.id == id_inst); _repositorio.DeleteFilter<InstitucionTipoBiotec>(query4); //almaceno las relaciones de la entidad institucion con sectores y tipoBiotecnologia foreach (Sector sector in lstSectores) { _repositorio.SaveOrUpdate(new InstitucionSector { institucion = institucion[0].institucion, sector = sector, fecha_ult_modificacion = DateTime.Now }); } foreach (TipoBiotecnologia tipo in lstTipoBiotecnologia) { _repositorio.SaveOrUpdate(new InstitucionTipoBiotec { institucion = institucion[0].institucion, tipoBiotecnologia = tipo, fecha_ult_modificacion = DateTime.Now }); } //Envio el correo de confirmacion if (mail.sendMail()) { mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Institución editada exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "Se produjo un error mientras se enviaba el correo. Correo invalido"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error validacion", "Existen campos que ya existen en el sistema."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "Institucion no encontrada."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "Institución no encontrada."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "Token de autenticación requerido."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error Autenticación", "institucón no encontrada."); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
/// <summary> /// 分发器 /// </summary> /// <param name="stream"></param> /// <returns></returns> public Message Action(string method, Stream stream) { try { int operation_user; string token; Dictionary <string, string> param = Utilities.GetQueryParam(stream); operation_user = param.ContainsKey("operation_user") ? Convert.ToInt32(param["operation_user"]) : 0; token = param.ContainsKey("token") ? param["token"] : ""; string str_result = ""; if (!Token.ValidToken(operation_user, token)) { GeneralResult <string> result = new GeneralResult <string>("token过期,请重新登录"); str_result = JsonConvert.SerializeObject(result); } else { switch (method) { case "login1": { string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string pin = param.ContainsKey("pin") ? param["pin"] : ""; string error = ""; int id = Login1(out error, mobile, pin); GeneralResult <int> result = new GeneralResult <int>(); result.data = id; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "login2": { string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string code = param.ContainsKey("code") ? param["code"] : ""; string error = ""; UserLogin ul = Login2(out error, mobile, code); GeneralResult <UserLogin> result = new GeneralResult <UserLogin>(); result.data = ul; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "login3": { string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string password = param.ContainsKey("password") ? param["password"] : ""; string error = ""; UserLogin ul = Login3(out error, mobile, password); GeneralResult <UserLogin> result = new GeneralResult <UserLogin>(); result.data = ul; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "no_login": { string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string error = ""; GeneralResult <int> result = new GeneralResult <int>(); result.data = NoLogin(out error, mobile); if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "register": { Register(); break; } case "add_user": { string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string name = param.ContainsKey("name") ? param["name"] : ""; string identity = param.ContainsKey("identity") ? param["identity"] : ""; string sex = param.ContainsKey("sex") ? param["sex"] : ""; int age = param.ContainsKey("age") ? Convert.ToInt32(param["age"]) : 0; string photo = param.ContainsKey("photo") ? param["photo"] : ""; int role = param.ContainsKey("role") ? Convert.ToInt32(param["role"]) : 0; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; int admin = param.ContainsKey("admin") ? Convert.ToInt32(param["admin"]) : 0; string error = ""; bool flag = AddUser(out error, name, identity, mobile, age, sex, photo, role, dep, admin); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_user": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string name = param.ContainsKey("name") ? param["name"] : ""; string identity = param.ContainsKey("identity") ? param["identity"] : ""; string sex = param.ContainsKey("sex") ? param["sex"] : ""; int age = param.ContainsKey("age") ? Convert.ToInt32(param["age"]) : 0; string photo = param.ContainsKey("photo") ? param["photo"] : ""; int parent = param.ContainsKey("admin") ? Convert.ToInt32(param["admin"]) : 0; string pin = param.ContainsKey("pin") ? param["pin"] : ""; string password = param.ContainsKey("password") ? param["password"] : ""; string authCode = param.ContainsKey("authCode") ? param["authCode"] : ""; string error = ""; bool flag = UpdateUser(out error, id, name, identity, mobile, password, age, sex, photo, pin, parent, authCode); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_user_pin": { string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; string pin = param.ContainsKey("pin") ? param["pin"] : ""; string error = ""; bool flag = UpdateUserPin(out error, mobile, pin); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "clear_user_pin": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = UpdateUserPin2(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_user_dep_relationship": { int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string dep = param.ContainsKey("dep") ? param["dep"].ToString() : ""; string error = ""; bool flag = UpdateUserDepRelationship(out error, user, dep); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_user_role_relationship": { int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string role = param.ContainsKey("role") ? param["role"].ToString() : ""; string error = ""; bool flag = UpdateUserRoleRelationship(out error, user, role); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_user_dep": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; int parent = param.ContainsKey("parent") ? Convert.ToInt32(param["parent"]) : 0; string error = ""; bool flag = UpdateUserDep(out error, id, dep, parent); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "delete_user": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteUser(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_user": { SystemLog.WriteErrorLog2("测试日志", "0000", "1"); int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string name = param.ContainsKey("name") ? param["name"] : ""; string code = param.ContainsKey("code") ? param["code"] : ""; string sex = param.ContainsKey("sex") ? param["sex"] : ""; string mobile = param.ContainsKey("mobile") ? param["mobile"] : ""; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; int role = param.ContainsKey("role") ? Convert.ToInt32(param["role"]) : 0; int age = param.ContainsKey("age") ? Convert.ToInt32(param["age"]) : 0; string level = param.ContainsKey("level") ? param["level"] : ""; string error = ""; User[] users = QueryUser(out error, id, name, code, sex, age, mobile, dep, role, level); GeneralResult <User[]> result = new GeneralResult <User[]>(); result.data = users; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_adminuser_by_dep": { int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; string error = ""; User[] users = QueryAdminUserByDep(out error, dep); GeneralResult <User[]> result = new GeneralResult <User[]>(); result.data = users; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_subuser_by_id": { int userId = param.ContainsKey("user_id") ? Convert.ToInt32(param["user_id"]) : 0; string error = ""; User[] users = QuerySubImportantUserById(out error, userId); GeneralResult <User[]> result = new GeneralResult <User[]>(); result.data = users; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_contacts_by_dep": { int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; int role = param.ContainsKey("role") ? Convert.ToInt32(param["role"]) : 0; int user = param.ContainsKey("user") ? Convert.ToInt32(param["user"]) : 0; string error = ""; User[] users = QueryContactsByDep(out error, dep, role, user); GeneralResult <User[]> result = new GeneralResult <User[]>(); result.data = users; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "add_role": { string name = param.ContainsKey("name") ? param["name"] : ""; int level = param.ContainsKey("level") ? Convert.ToInt32(param["level"]) : 0; string error = ""; bool flag = AddRole(out error, name, level); GeneralResult <bool> result = new GeneralResult <bool>(); if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_role": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string name = param.ContainsKey("name") ? param["name"] : ""; int level = param.ContainsKey("level") ? Convert.ToInt32(param["level"]) : 0; string error = ""; bool flag = UpdateRole(id, name, level); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_role_menu_relationship": { int roleId = param.ContainsKey("roleId") ? Convert.ToInt32(param["roleId"]) : 0; string menuId = param.ContainsKey("menuId") ? param["menuId"] : ""; string error = ""; bool flag = UpdateRoleMenuRelationship(out error, roleId, menuId); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_role_dep_relationship": { int role = param.ContainsKey("role") ? Convert.ToInt32(param["role"]) : 0; string deps = param.ContainsKey("deps") ? param["deps"] : ""; string error = ""; bool flag = UpdateRoleDepRelationship(out error, role, deps); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "delete_role": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteRole(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_role": { string name = param.ContainsKey("name") ? param["name"] : ""; string level = param.ContainsKey("level") ? param["level"] : ""; string error = ""; Role[] roles = QueryRoles(out error, name, level); GeneralResult <Role[]> result = new GeneralResult <Role[]>(); result.data = roles; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_role2": { string level = param.ContainsKey("level") ? param["level"] : ""; int dep = param.ContainsKey("dep") ? Convert.ToInt32(param["dep"]) : 0; string error = ""; Role[] roles = QueryRole2(out error, dep, level); GeneralResult <Role[]> result = new GeneralResult <Role[]>(); result.data = roles; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "add_department": { string name = param.ContainsKey("name") ? param["name"] : ""; int order = param.ContainsKey("order") ? Convert.ToInt32(param["order"]) : 0; int parent = param.ContainsKey("parent") ? Convert.ToInt32(param["parent"]) : 0; int level = param.ContainsKey("level") ? Convert.ToInt32(param["level"]) : 0; string alias = param.ContainsKey("alias") ? param["alias"] : ""; string code = param.ContainsKey("code") ? param["code"] : ""; string error = ""; Department dep = AddDepartment(out error, name, order, parent, level, alias, code); GeneralResult <Department> result = new GeneralResult <Department>(); result.data = dep; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "update_department": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string name = param.ContainsKey("name") ? param["name"] : ""; string alias = param.ContainsKey("alias") ? param["alias"] : ""; string code = param.ContainsKey("code") ? param["code"] : ""; string error = ""; Department dep = UpdateDepartment(out error, id, name, alias, code); GeneralResult <Department> result = new GeneralResult <Department>(); result.data = dep; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "delete_department": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string error = ""; bool flag = DeleteDepartment(out error, id); GeneralResult <bool> result = new GeneralResult <bool>(); result.data = flag; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_department": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string name = param.ContainsKey("name") ? param["name"] : ""; int parent = param.ContainsKey("parent") ? Convert.ToInt32(param["parent"]) : 0; string error = ""; Department[] deps = QueryDepartments(out error, id, name, parent); GeneralResult <Department[]> result = new GeneralResult <Department[]>(); result.data = deps; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_department2": { int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; string name = param.ContainsKey("name") ? param["name"] : ""; int parent = param.ContainsKey("parent") ? Convert.ToInt32(param["parent"]) : 0; string error = ""; Department[] deps = QueryDepartments(out error, id, name, parent); DepartmentVue[] deps2 = SerializeDepTree(parent, deps); GeneralResult <DepartmentVue[]> result = new GeneralResult <DepartmentVue[]>(); result.data = deps2; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_role_dep_relationship": { int role = param.ContainsKey("role") ? Convert.ToInt32(param["role"]) : 0; string error = ""; Department[] deps = QueryRoleDepRelationship(out error, role); GeneralResult <Department[]> result = new GeneralResult <Department[]>(); result.data = deps; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } //case "query_sub_dep": // { // int parent = param.ContainsKey("parent") ? Convert.ToInt32(param["parent"]) : 0; // string error = ""; // Department[] deps = QuerySubDepartment(out error, parent); // GeneralResult<Department[]> result = new GeneralResult<Department[]>(); // result.data = deps; // if (error == "") // { // result.success = true; // } // else // { // result.message = error; // } // str_result = JsonConvert.SerializeObject(result); // break; // } //case "query_deparentment_contacts": // { // int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; // string name = param.ContainsKey("name") ? param["name"] : ""; // int parent = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : -1; // string error = ""; // Department[] deps = QueryDepartments(out error, id, name, parent); // GeneralResult<Department[]> result = new GeneralResult<Department[]>(); // result.data = deps; // if (error == "") // { // result.success = true; // } // str_result = JsonConvert.SerializeObject(result); // break; // } //case "addMenu": // { // AddMenu(); // break; // } //case "updateMenu": // { // int id = 0; // UpdateMenu(); // break; // } //case "deleteMenu": // { // int id = 0; // DeleteMenu(); // break; // } case "query_menu": { string error = ""; Menu[] menus = QueryMenus(out error); GeneralResult <Menu[]> result = new GeneralResult <Menu[]>(); result.data = menus; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "query_role_menu_relationship": { string roleIds = param.ContainsKey("roles") ? param["roles"] : ""; string error = ""; string[] codes = QueryRoleMenuRelationship(out error, roleIds); GeneralResult <string[]> result = new GeneralResult <string[]>(); result.data = codes; if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "service_config": { str_result = "{"; str_result += string.Format("\"level1\":{0},", ConfCenter.ImportantUserRoleLevel); str_result += string.Format("\"level2\":{0},", ConfCenter.AdministratorUserRoleLevel); str_result += string.Format("\"level3\":{0}", ConfCenter.LoginAdminRoleLevel); str_result += "}"; break; } case "get_map_data": { string error = ""; string base_path = "config/mapjson/"; GeneralResult <string> result = new GeneralResult <string>(); int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; Department dep = QueryRegionByDepID(out error, id); if (dep.code != "") { using (FileStream fs = File.Open(AppHome.BaseDirectory + base_path + dep.code + ".json", FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) { result.data = sr.ReadToEnd(); result.success = true; } } } if (error != "") { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "stat_region_data": { string error = ""; GeneralResult <StatisticResult[]> result = new GeneralResult <StatisticResult[]>(); int id = param.ContainsKey("id") ? Convert.ToInt32(param["id"]) : 0; result.data = StatRegionData(out error, id); if (error == "") { result.success = true; } else { result.message = error; } str_result = JsonConvert.SerializeObject(result); break; } case "create_partial_table": { bool flag = false; try { string sql = "exec CreateSegmentTable"; string error = ""; DataBaseHelper.ExecuteNonQuery(sql, out error); if (error == "") { flag = true; } } catch (Exception ex) { SystemLog.WriteErrorLog("分表创建失败", "1099", ex.Message, ex.StackTrace); } str_result = flag.ToString(); break; } default: { GeneralResult <string> result = new GeneralResult <string>("没有该方法,请检查参数"); str_result = JsonConvert.SerializeObject(result); break; } } } byte[] bytes = Encoding.UTF8.GetBytes(str_result); MemoryStream ms = new MemoryStream(bytes); return(WebOperationContext.Current.CreateStreamResponse(ms, "application/json; charset=utf-8")); } catch (Exception ex) { SystemLog.WriteErrorLog("请求失败", "2002", ex.Message, ex.StackTrace); } return(null); }
/// <summary> /// There are no comments for SystemLog in the schema. /// </summary> public void AddToSystemLog(SystemLog systemLog) { base.AddObject("SystemLog", systemLog); }
public void DoActivities() { EntityGlobal.transactionId = "0001"; //int businessTrails = 3; //for (int i = 0; i < businessTrails; i++) //{ EntityGlobal.isTransactionComplete = false; SystemLog.LogAuditMessage(MethodBase.GetCurrentMethod().Name, DiagnosticLevel.level1, EntityGlobal.TRANSACTION_START, EntityGlobal.transactionId); //Thread.Sleep(EntityGlobal.pageLoadWaitTime); //MainFrameAdapter.WaitForCursor(3, 15); try { /*new ScreenTSO().DoActivities(); * new ScreenUserId().DoActivities(); * new ScreenPwd().DoActivities(); * new ScreenIspf().DoActivities();*/ //new ScreenWebMailTCS().DoActivities(); new ScreenWebTeller().DoActivities(); EntityGlobal.isTransactionComplete = true; //break; } catch (AppException e) { count_AppException++; SystemLog.LogExceptionMessage(e.Message, EntityGlobal.transactionId, EntityGlobal.lastScreenName); if (count_AppException > 5) { throw new TcsRpaException("Maximum limit reached for Application Exception"); } } catch (TcsRpaException e) { count_TcsRpaException++; SystemLog.LogErrorMessage(e, EntityGlobal.transactionId, EntityGlobal.lastScreenName); if (count_TcsRpaException > 5) { throw new TcsRpaException("Maximum limit reached for TCSRPA Exception"); } } catch (COMException e) { count_ComExceptiom++; SystemLog.LogErrorMessage(e, EntityGlobal.transactionId, EntityGlobal.lastScreenName); if (count_ComExceptiom > 5) { throw new TcsRpaException("Maximum limit reached for COM Exception"); } } catch (Exception e) { count_UnknownErrors++; SystemLog.LogErrorMessage(e, EntityGlobal.transactionId, EntityGlobal.lastScreenName); if (count_UnknownErrors > 5) { throw new TcsRpaException("Maximum limit reached for Unknown errors Exception"); } } //} if (!EntityGlobal.isTransactionComplete) { SystemLog.LogExceptionMessage("Transaction Not Completed", EntityGlobal.transactionId, EntityGlobal.lastScreenName); } SystemLog.LogAuditMessage(MethodBase.GetCurrentMethod().Name, DiagnosticLevel.level1, EntityGlobal.TRANSACTION_END, EntityGlobal.transactionId); }
public Mensaje createEventoParticipante([FromBody]UtilsJson.AEventoParticipante eventoParticipante) { Mensaje mensaje = null; try { if (eventoParticipante != null) { if (!string.IsNullOrWhiteSpace(eventoParticipante.token_string)) { if (AutenticacionToken.validateToken(eventoParticipante.token_string) == 1) { long id_inst = eventoParticipante.id_institucion; long id_pub = eventoParticipante.id_evento; Institucion institucion = _repositorio.Get<Institucion>(id_inst); Publicacion publicacion = _repositorio.Get<Publicacion>(id_pub); Expression<Func<EventoParticipante, bool>> query = (u => u.institucion.id == id_inst && u.evento.id==id_pub && u.estado == true); List<EventoParticipante> result = _repositorio.Filter<EventoParticipante>(query); if (institucion != null && publicacion !=null && result.Count ==0) { if (AutenticacionToken.validateUserToken(eventoParticipante.token_string, institucion.logueo.correo_electronico)) { //datos institucion y publicacion EventoParticipante newRegistro = new EventoParticipante { institucion=institucion, evento=publicacion, fecha_ult_modificacion=DateTime.Now, estado=eventoParticipante.estado }; //Almaceno o actualizo la salaMesa _repositorio.SaveOrUpdate<EventoParticipante>(newRegistro); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Institucion registrada al evento exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes para modificar estos campos."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se puede insertar un objeto nulo"); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
/// <summary> /// 保存日志到文件(以后扩展) /// </summary> /// <param name="log"></param> /// <returns></returns> private bool SaveLog(SystemLog log) { return(false); }
public void Record(SystemLog log) { _repository.AddVoid(log); }
private void btnSave_Click(object sender, System.EventArgs e) { if (MessageBox.Show("是否确定保存静脉采血相关费用?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } IsSave = true; string sSql = ""; string strSql = ""; DataTable myTempTb = new DataTable(); bool IsErr = false; DataTable myTb = (DataTable)myDataGrid1.DataSource; //取静脉采血费 sSql = @"Select a.order_id,a.order_name,a.order_unit,a.order_type " + "from jc_hoitemdiction a,jc_CONFIG b " + "where a.order_id=convert(bigint,b.config) and b.id=7015 "; DataTable myJTb = InstanceForm.BDatabase.GetDataTable(sSql); //取静脉采血管费 sSql = @"Select a.order_id,a.order_name,a.order_unit,a.order_type " + "from jc_hoitemdiction a,jc_CONFIG b " + "where a.order_id=convert(bigint,b.config) and b.id=7016"; DataTable myGTb = InstanceForm.BDatabase.GetDataTable(sSql); //如果没有设置静脉采血费代码,将不插入煎药费 if (myJTb.Rows.Count == 0 || myJTb == null) { MessageBox.Show("没有设置静脉采血费代码,请手工输入静脉采血费!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); IsErr = true; } else if (myGTb.Rows.Count == 0 || myGTb == null) { MessageBox.Show("没有设置静脉采血管代码,请手工输入静脉采血管费!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); IsErr = true; } else { decimal v_hoitem_id = Convert.ToDecimal(myJTb.Rows[0]["order_id"].ToString()); string v_order_context = myJTb.Rows[0]["order_name"].ToString().Trim(); string v_unit = myJTb.Rows[0]["order_unit"].ToString().Trim(); int v_order_type = Convert.ToInt32(myJTb.Rows[0]["order_type"].ToString().Trim()); decimal v_hoitem_id1 = Convert.ToDecimal(myGTb.Rows[0]["order_id"].ToString()); string v_order_context1 = myGTb.Rows[0]["order_name"].ToString().Trim(); string v_unit1 = myGTb.Rows[0]["order_unit"].ToString().Trim(); int v_order_type1 = Convert.ToInt32(myGTb.Rows[0]["order_type"].ToString().Trim()); int i = 0; int iYZH = 0; // //生成数据访问对象 // RelationalDatabase database=RelationalDatabase.GetDatabase(DatabaseType.IbmDb2ZY); // database.Initialize(""); // database.Open(); // //开始一个事物 // database.BeginTransaction(); InstanceForm.BDatabase.BeginTransaction(); try { for (i = 0; i < myTb.Rows.Count; i++) { if (myTb.Rows[i]["采血费次数"].ToString().Trim() != "0" && myTb.Rows[i]["采血费次数"].ToString().Trim() != "") { //取组号 sSql = @"select max(Group_Id) as YZH " + " from Zy_OrderRecord " + " where inpatient_id='" + myTb.Rows[i]["inpatient_id"].ToString().Trim() + "'" + " and baby_id=" + myTb.Rows[i]["baby_id"].ToString().Trim(); //+ // " and mngtype=3"; myTempTb.Clear(); myTempTb = InstanceForm.BDatabase.GetDataTable(sSql); if (myTempTb.Rows[0]["YZH"].ToString().Trim() == "") { iYZH = 0; } else { iYZH = Convert.ToInt32(myTempTb.Rows[0]["YZH"]) + 1; } //插入医嘱记录表 strSql = @"INSERT INTO ZY_ORDERRECORD( " + "order_id,jgbm,xmly,INPATIENT_ID,Baby_ID,WARD_ID,DEPT_BR,DEPT_ID, " + "MNGTYPE,ORDER_BDATE,GROUP_ID,NTYPE, " + "HOITEM_ID,ORDER_CONTEXT,NUM,DOSAGE,UNIT,ORDER_USAGE,FREQUENCY, " + "EXEC_DEPT,FIRST_TIMES,STATUS_FLAG, " + "AUDITING_USER,AUDITING_DATE,OPERATOR,BOOK_DATE,SERIAL_NO ) " + "VALUES('" + PubStaticFun.NewGuid() + "'," + FrmMdiMain.Jgbm + ",2, '" + myTb.Rows[i]["inpatient_id"].ToString().Trim() + "'," + Convert.ToDecimal(myTb.Rows[i]["baby_id"].ToString().Trim()) + ",'" + InstanceForm.BCurrentDept.WardId + "'," + Convert.ToDecimal(myTb.Rows[i]["dept_br"].ToString().Trim()) + "," + Convert.ToDecimal(myTb.Rows[i]["dept_id"].ToString().Trim()) + ",3,getdate()," + iYZH.ToString() + "," + v_order_type + "," + v_hoitem_id + ",'" + v_order_context + "'," + myTb.Rows[i]["采血费次数"] + ",1,'" + v_unit + "','',''," + Convert.ToDecimal(myTb.Rows[i]["dept_br"].ToString().Trim()) + ", 1,2," + InstanceForm.BCurrentUser.EmployeeId + ",getdate() ," + InstanceForm.BCurrentUser.EmployeeId + ",getdate(),0)"; InstanceForm.BDatabase.DoCommand(strSql); } //Add By Tany 2004-11-13 if (myTb.Rows[i]["采血管次数"].ToString().Trim() != "0" && myTb.Rows[i]["采血管次数"].ToString().Trim() != "") { //取组号 sSql = @"select max(Group_Id) as YZH " + " from Zy_OrderRecord " + " where inpatient_id='" + myTb.Rows[i]["inpatient_id"].ToString().Trim() + "'" + " and baby_id=" + myTb.Rows[i]["baby_id"].ToString().Trim(); //+ // " and mngtype=3"; myTempTb.Clear(); myTempTb = InstanceForm.BDatabase.GetDataTable(sSql); if (myTempTb.Rows[0]["YZH"].ToString().Trim() == "") { iYZH = 0; } else { iYZH = Convert.ToInt32(myTempTb.Rows[0]["YZH"]) + 1; } //插入医嘱记录表 strSql = @"INSERT INTO ZY_ORDERRECORD( " + "order_id,jgbm,xmly,INPATIENT_ID,Baby_ID,WARD_ID,DEPT_BR,DEPT_ID, " + "MNGTYPE,ORDER_BDATE,GROUP_ID,NTYPE, " + "HOITEM_ID,ORDER_CONTEXT,NUM,DOSAGE,UNIT,ORDER_USAGE,FREQUENCY, " + "EXEC_DEPT,FIRST_TIMES,STATUS_FLAG, " + "AUDITING_USER,AUDITING_DATE,OPERATOR,BOOK_DATE,SERIAL_NO ) " + "VALUES( '" + PubStaticFun.NewGuid() + "'," + FrmMdiMain.Jgbm + ",2,'" + myTb.Rows[i]["inpatient_id"].ToString().Trim() + "'," + myTb.Rows[i]["baby_id"].ToString().Trim() + ",'" + InstanceForm.BCurrentDept.WardId + "'," + Convert.ToDecimal(myTb.Rows[i]["dept_br"].ToString().Trim()) + "," + Convert.ToDecimal(myTb.Rows[i]["dept_id"].ToString().Trim()) + ",3,getdate()," + iYZH.ToString() + "," + v_order_type1 + "," + v_hoitem_id1 + ",'" + v_order_context1 + "'," + myTb.Rows[i]["采血管次数"] + ",1,'" + v_unit1 + "','',''," + Convert.ToDecimal(myTb.Rows[i]["dept_br"].ToString().Trim()) + ", 1,2," + InstanceForm.BCurrentUser.EmployeeId + ",getdate() ," + InstanceForm.BCurrentUser.EmployeeId + ",getdate(),0)"; InstanceForm.BDatabase.DoCommand(strSql); } } InstanceForm.BDatabase.CommitTransaction(); } catch (Exception err) { InstanceForm.BDatabase.RollbackTransaction(); //写错误日志 Add By Tany 2005-01-12 SystemLog _systemErrLog = new SystemLog(-1, InstanceForm.BCurrentDept.DeptId, InstanceForm.BCurrentUser.EmployeeId, "程序错误", "保存静脉采血费用错误:" + err.Message + " Source:" + err.Source, DateManager.ServerDateTimeByDBType(InstanceForm.BDatabase), 1, "主机名:" + System.Environment.MachineName, 39); _systemErrLog.Save(); _systemErrLog = null; MessageBox.Show("错误:将静脉采血相关费用插入临时账单错误,请手工生成静脉采血相关费用!\n系统:" + err.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Stop); IsErr = true; } // database.Close(); } if (IsErr == false) { MessageBox.Show("已经成功生成静脉采血相关费用临时账单!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } this.Close(); }
public EntityCommandBuilder(EntityModel model) { _model = model; _log = _model.App.SystemLog; }
public static bool AddSL(SystemLog sl) { return(DALLoginsertion.AddSL(sl)); }
/// <summary> /// Name: Save /// Description: Method to save a systemLog register /// </summary> /// <param name="systemLog">SystemLog</param> public void Save(SystemLog systemLog) { this.DAO.Save(systemLog); }
public override DbModelLoader CreateDbModelLoader(DbSettings settings, SystemLog log) { return(new SqlCeDbModelLoader(settings, log)); }
public IQueryable<UtilsJson.AInstitucionMapa> getFilterInstitutionMapa([FromBody]UtilsJson.AParamsFilterMapa filter) { IQueryable<UtilsJson.AInstitucionMapa> listado = null; try { if (filter != null) { string opcion = filter.opcion; string sub_opcion = filter.sub_opcion; SqlParameter[] param = new SqlParameter[2]; if (opcion == null) { param[0] = new SqlParameter("opcion", DBNull.Value); } else { param[0] = new SqlParameter("opcion", opcion); } if (sub_opcion == null) { param[1] = new SqlParameter("sub_opcion", DBNull.Value); } else { param[1] = new SqlParameter("sub_opcion", sub_opcion); } listado = _repositorio.executeStored<UtilsJson.AInstitucionMapa>("getListingFilterInstitucionMapa", param).Cast<UtilsJson.AInstitucionMapa>().AsQueryable<UtilsJson.AInstitucionMapa>(); } } catch (Exception ex) { SystemLog log = new SystemLog(); log.ErrorLog(ex.Message); } return listado; }
public void ResolveSystem(object send, BasicDeliverEventArgs ea) { try { var body = ea.Body; var message = System.Text.Encoding.UTF8.GetString(body); var routingKey = ea.RoutingKey; Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(message); DateTime begin = DateTime.ParseExact(dic["begin"], "yyyy-MM-dd HH:mm:ss:fff", System.Globalization.CultureInfo.CurrentCulture); DateTime end = DateTime.ParseExact(dic["end"], "yyyy-MM-dd HH:mm:ss:fff", System.Globalization.CultureInfo.CurrentCulture); TimeSpan ts = (TimeSpan)(end - begin); double ms = ts.TotalMilliseconds; Enum cl = null; if (ms <= 7000) { cl = CostLevel.Normal; } else if (ms > 7000 && ms <= 12000) { cl = CostLevel.Warn; } else { cl = CostLevel.Block; } string pageName = ""; string p1 = dic["url"].Split('?')[0]; string[] p1s = p1.Split('/'); pageName = p1s[p1s.Length - 1]; List <string> argument = null; if (!string.IsNullOrEmpty(dic["post"])) { string post = HttpUtility.HtmlDecode(dic["post"]); argument = post.Split('&').ToList(); } List <string> cookies = null; if (!string.IsNullOrEmpty(dic["cookies"])) { string c = HttpUtility.HtmlDecode(dic["cookies"]); cookies = c.Split(new string[] { "@@" }, StringSplitOptions.RemoveEmptyEntries).ToList(); } string key = "wms_system_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); SystemLog slog = new SystemLog { LogId = key, ProjectKey = dic["key"], SubKey = dic["subkey"], Type = dic["type"], Status = dic["status"], CreateTime = DateTime.ParseExact(dic["ct"], "yyyy-MM-dd HH:mm:ss:fff", System.Globalization.CultureInfo.CurrentCulture), Url = dic["url"], Interval = ts.TotalMilliseconds.ToString(), BeginTime = begin, EndTime = end, QueryString = dic["query"], PostArgument = argument, RequestIP = dic["ip"], Cookies = cookies, StatusCode = dic["code"], Method = dic["method"], ServerIP = dic["sip"], Tag = cl.ToString() + "," + dic["code"] + "," + pageName }; //TrackLogBL logBL = new TrackLogBL(); //logBL.UpsertSystemLog(slog); UpsertSystemLog(slog); if (Notice != null) { Dictionary <string, string> args = new Dictionary <string, string>(); args["ip"] = dic["ip"]; args["tag"] = slog.Tag; args["url"] = dic["url"]; args["ConsumerTag"] = ea.ConsumerTag; args["type"] = "2"; args["projectKey"] = dic["key"]; args["logType"] = LogType.SystemLog.ToString(); args["ct"] = dic["ct"]; Notice(args); } } catch (Exception ex) { } }
public override void Create(SystemLog obj) { base.Create(obj); this.Logger.Info(obj.LogDescrption); }
public BaseResultDto <string> HandExec(RQHandExecDto Exec) { SystemRequestRecord model = Exec.RequestRecord; BaseResultDto <string> result = new BaseResultDto <string>(); YeePay yeepay = new YeePay(); YeePayOper yeePayOper = new YeePayOper(); string strResult = "未处理"; try { if (helper.IsExists <SystemRequestRecord>(string.Format(" Id={0} and RequestOperStatus=1", model.Id))) { switch (model.RequestType) { case 1: //注册 { } break; case 2: //充值 { MoneyCarCar.Models.YeePay.RequestModel.Query query = new MoneyCarCar.Models.YeePay.RequestModel.Query(); query.mode = EnumMode.RECHARGE_RECORD.ToEnumDesc(); // 转款记录 query.platformUserNo = model.UserId.ToString(); query.requestNo = model.Id.ToString(); BaseResultDto <MoneyCarCar.Models.YeePay.Response.QUERY.response> baseResultDtoResponse = new BaseResultDto <MoneyCarCar.Models.YeePay.Response.QUERY.response>(); baseResultDtoResponse = yeepay.QUERY <MoneyCarCar.Models.YeePay.Response.QUERY.response>(query); string str = baseResultDtoResponse.ErrorMsg; //XML 数据 // 反序列化 MoneyCarCar.Models.YeePay.Response.QUERY.RECHARGE_RECORD.response _response = baseResultDtoResponse.ErrorMsg.XmlDeserialize <MoneyCarCar.Models.YeePay.Response.QUERY.RECHARGE_RECORD.response>(); if (_response.status == EnumNotifyStatus.SUCCESS.ToEnumDesc()) { bool b_reuslt = yeePayOper.ToRecharge(model.UserId.ToString(), model.Id.ToString()); if (b_reuslt) { strResult = "充值成功"; } else { strResult = "未充值成功"; } } else { // 未充值成功 strResult = "未充值成功"; } } break; case 3: // 投资 { } break; case 4: //提现 { } break; case 5: //查询 { } break; case 6: //绑卡 { } break; case 7: //解绑 { } break; case 8: //结息 { MoneyCarCar.Models.YeePay.RequestModel.Query query = new MoneyCarCar.Models.YeePay.RequestModel.Query(); query.mode = EnumMode.CP_TRANSACTION.ToEnumDesc(); // 转款记录 query.platformUserNo = model.UserId.ToString(); query.requestNo = model.Id.ToString(); BaseResultDto <MoneyCarCar.Models.YeePay.Response.QUERY.response> baseResultDtoResponse = new BaseResultDto <MoneyCarCar.Models.YeePay.Response.QUERY.response>(); baseResultDtoResponse = yeepay.QUERY <MoneyCarCar.Models.YeePay.Response.QUERY.response>(query); string str = baseResultDtoResponse.ErrorMsg; //XML 数据 // 反序列化 MoneyCarCar.Models.YeePay.Response.QUERY.CP_TRANSACTION.response _response = baseResultDtoResponse.ErrorMsg.XmlDeserialize <MoneyCarCar.Models.YeePay.Response.QUERY.CP_TRANSACTION.response>(); if (_response.status == EnumNotifyStatus.DIRECT.ToEnumDesc()) { bool b_reuslt = yeePayOper.Direct_Transaction(model.Id.ToString()); if (b_reuslt) { strResult = "结息成功"; } else { strResult = "结息未成功"; } } else { //结息未成功 strResult = "结息未成功"; } } break; default: break; } result.IsSeccess = true; result.ErrorCode = 1; result.ErrorMsg = strResult; } else { result.IsSeccess = true; result.ErrorCode = 1; result.ErrorMsg = "状态已处理"; } SystemLog log = new SystemLog(); log.OperatorUserId = Exec.OperatorUserId; log.OperatorUserName = Exec.OperatorUserName; log.OperatorType = 4; log.BusinessType = "手动同步数据"; log.OperatorTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); log.OperatorContent = Exec.OperatorContent + " " + strResult; log.OperatorIP = Exec.IP; //添加日志 helper.Add <SystemLog>(log); } catch (Exception ex) { result.ErrorMsg = ex.Message; result.ErrorCode = -1; } return(result); }
public Mensaje editConferencista([FromBody]UtilsJson.APersona conferencista) { Mensaje mensaje = null; try { if (conferencista != null) { if (!string.IsNullOrWhiteSpace(conferencista.token)) { if (AutenticacionToken.validateToken(conferencista.token) == 1) { long id_institucion_c = (!string.IsNullOrWhiteSpace(conferencista.Ainstitucion)) ? long.Parse(conferencista.Ainstitucion) : 0; Institucion institucion = _repositorio.Get<Institucion>(id_institucion_c); Conferencista conferencistaDB = _repositorio.Get<Conferencista>(conferencista.id); if (institucion != null && conferencistaDB != null) { if (AutenticacionToken.validateUserToken(conferencista.token, institucion.logueo.correo_electronico)) { //datos personales string tipo_identificacion = validarTipoIdentificacion(conferencista.tipo_identificacion); string identificacion = conferencista.identificacion; string nombre_persona = conferencista.nombre; string apellido_persona = conferencista.apellido; string correo_persona = conferencista.correo_electronico; string urlCvlac = conferencista.urlCvlac; string perfil = conferencista.perfil_profesional; string foto = conferencista.foto; if (tipo_identificacion != null) { Imagen newImagen = null; if (!string.IsNullOrWhiteSpace(foto)) { if (conferencistaDB.persona.foto != null) { conferencistaDB.persona.foto.imagenBase64 = foto; } else { newImagen = new Imagen { imagenBase64 = foto }; conferencistaDB.persona.foto = newImagen; } } conferencistaDB.persona.tipo_identificacion = tipo_identificacion; conferencistaDB.persona.identificacion = identificacion; conferencistaDB.persona.nombre = nombre_persona; conferencistaDB.persona.apellido = apellido_persona; conferencistaDB.persona.correo_electronico = correo_persona; conferencistaDB.persona.urlCvlac = urlCvlac; conferencistaDB.persona.perfil_profesional = perfil; conferencistaDB.fecha_ult_modificacion = DateTime.Now; //Almaceno o actualizo la salaMesa _repositorio.SaveOrUpdate<Conferencista>(conferencistaDB); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Conferencista editado exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "El tipo de identificacion no existe. verifique que el valor sea valido"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se encontro la sala solicitada o esta asociada a otra institucion."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se puede insertar un objeto nulo"); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
void SystemLog_OnAppend(object sender, SystemLog.OnAppend_EventArgs e) { m_parent.m_Strings.Add(e.Data); m_parent.lineIndex++; }
static string getCWStyle(string strContent, SystemLog.SystemLog.LogType logType) { strContent = "* " + strContent + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); _LocalLogger.WriteLog(strContent, string.Empty, logType); return strContent; }
/** Metodo que obtiene la direccion ip publica del host desde donde se modifica la contraseña */ private object[] getExternalIp() { string externalIP = string.Empty; object[] infoIpAddress = null; try { externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/"); externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) .Matches(externalIP)[0].ToString(); /*-----------------------------------------------------------------------------------------*/ WebRequest rssReq = WebRequest.Create("http://freegeoip.net/xml/" + externalIP); WebProxy px = new WebProxy("http://freegeoip.net/xml/" + externalIP, true); rssReq.Proxy = px; rssReq.Timeout = 5000; WebResponse rep = rssReq.GetResponse(); XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream()); DataSet ds = new DataSet(); ds.ReadXml(xtr); infoIpAddress = ds.Tables[0].Rows[0].ItemArray; } catch (Exception ex) { SystemLog log = new SystemLog(); log.ErrorLog(ex.Message); } return infoIpAddress; }
public Mensaje deleteCronograma([FromBody]UtilsJson.ACronograma cronograma) { Mensaje mensaje = null; try { if (cronograma != null) { if (!string.IsNullOrWhiteSpace(cronograma.token_string)) { if (AutenticacionToken.validateToken(cronograma.token_string) == 1) { Institucion institucion = _repositorio.Get<Institucion>(cronograma.institucionId); Cronograma cronogramaDB = _repositorio.Get<Cronograma>(cronograma.id); if (institucion != null && cronogramaDB != null) { if (AutenticacionToken.validateUserToken(cronograma.token_string, institucion.logueo.correo_electronico)) { _repositorio.Delete<Conferencista>(cronogramaDB.id); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Cronograma fue eliminada exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se encontro el evento solicitada o esta asociada a otra institucion."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se puede eliminar un objeto nulo"); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
public Mensaje createInstitution([FromBody]UtilsJson.AInstitucion institution) { Mensaje mensaje = null; try { if (institution != null) { //datos logueo string correo_electronico_l = institution.logueo.correo_electronico; string password1 = institution.logueo.contrasena1; string password2 = institution.logueo.contrasena2; //datos representante string nombre_r = institution.representante.nombre; string apellido_r = institution.representante.apellido; string tipo_identificacion = institution.representante.tipo_identificacion; string identificacion = institution.representante.identificacion; string urlCvlac = institution.representante.urlCvlac; string correo_electronico_r = institution.representante.correo_electronico; //datos institucion string codigo = institution.codigo_registro; string nombre = institution.nombre; string descripcion = institution.descripcion; string correo_electronico = institution.correo_electronico; string direccion_postal = institution.direccion_postal; string facebook = institution.facebook; string fax = institution.fax; string impacto = institution.impacto; string linkedin = institution.linkedin; string naturaleza = institution.naturaleza; string pagina_web = institution.pagina_web; int tamano = institution.tamano; string telefono = institution.telefono; string tipo_institucion = institution.tipo_institucion; string twitter = institution.twitter; string constitucion = institution.constitucion; string fecha_creacion = institution.fecha_creacion; string latitud = institution.latitud; string longitud = institution.longitud; string imagen_base64 = institution.imagen_base64; string tipo_empresa = (!String.IsNullOrWhiteSpace(institution.tipo_empresa)) ? institution.tipo_empresa : EnumTipoEmpresa.Compañia; UtilsJson.AMunicipio municipio = institution.municipio; UtilsJson.ASector[] sectores = institution.sectores; UtilsJson.ATipoBiotecnologia[] Tipos_Biotecnologia = institution.Tipos_Biotecnologia; if (codigo != null) { //verificacion de existencia y estado del codigo Expression<Func<SolicitudRegistro, bool>> query = u => u.codigo == codigo && u.estado == true; SolicitudRegistro solicitud = _repositorio.Get<SolicitudRegistro>(query); //Si la solicitud existe y no se ha usado subo a session el codigo if (solicitud != null) { Municipio municipioDb = null; List<Sector> lstSectores = new List<Sector>(); List<TipoBiotecnologia> lstTipoBiotecnologia = new List<TipoBiotecnologia>(); if (municipio.id > 0) { municipioDb = _repositorio.Get<Municipio>(municipio.id); } if (sectores != null) { lstSectores = convertToSector(sectores); } if (Tipos_Biotecnologia != null) { lstTipoBiotecnologia = convertToTipoBiotecnologia(Tipos_Biotecnologia); } Institucion institucion_api = new Institucion(); if (password1.Equals(password2)) { institucion_api.logueo = new LogueoInstitucion { correo_electronico = correo_electronico_l, contrasena = CifradoDatos.cifrarPassword(password2), fecha_ult_modificacion = DateTime.Now, rol = EnumTipoRol.usuario }; institucion_api.descripcion = descripcion; institucion_api.impacto = impacto; institucion_api.correo_electronico = correo_electronico; institucion_api.latitud = latitud; institucion_api.linkedin = linkedin; institucion_api.longitud = longitud; institucion_api.municipio = municipioDb; institucion_api.naturaleza = naturaleza; institucion_api.constitucion = constitucion; institucion_api.nombre = nombre; institucion_api.pagina_web = pagina_web; institucion_api.tamano = tamano; institucion_api.telefono = telefono; institucion_api.fax = fax; institucion_api.direccion_postal = direccion_postal; institucion_api.facebook = facebook; institucion_api.tipo_institucion = tipo_institucion; institucion_api.twitter = twitter; institucion_api.fecha_creacion = (!string.IsNullOrWhiteSpace(fecha_creacion)) ? Convert.ToDateTime(fecha_creacion) : (DateTime?)null; if (institucion_api.banner == null) { if (!string.IsNullOrWhiteSpace(imagen_base64)) { institucion_api.banner = new Imagen { imagenBase64 = imagen_base64, fecha_ult_modificacion = DateTime.Now }; //Redimension de la imagen y creacion de icono string extension = imagen_base64.Split(',')[0]; imagen_base64 = imagen_base64.Split(',')[1]; byte[] bytes = Convert.FromBase64String(imagen_base64); if (bytes.Length > 0) { byte[] filebytesIcon =UtilsHost.Redimensionar(Image.FromStream(new MemoryStream(bytes)), 100, 100, 32); string encodedDataIcon = extension + "," + Convert.ToBase64String(filebytesIcon, Base64FormattingOptions.None); institucion_api.icono = new Imagen { imagenBase64 = encodedDataIcon, fecha_ult_modificacion = DateTime.Now }; } } } else { if (!string.IsNullOrWhiteSpace(imagen_base64)) { institucion_api.banner.imagenBase64 = imagen_base64; institucion_api.banner.fecha_ult_modificacion = DateTime.Now; //Redimension de la imagen y creacion de icono string extension = imagen_base64.Split(',')[0]; imagen_base64 = imagen_base64.Split(',')[1]; byte[] bytes = Convert.FromBase64String(imagen_base64); if (bytes.Length > 0) { byte[] filebytesIcon = UtilsHost.Redimensionar(Image.FromStream(new MemoryStream(bytes)), 100, 100, 32); string encodedDataIcon = extension + "," + Convert.ToBase64String(filebytesIcon, Base64FormattingOptions.None); institucion_api.icono.imagenBase64 = encodedDataIcon; institucion_api.icono.fecha_ult_modificacion = DateTime.Now; } } } //creo un nuevo representante para la institucion Persona persona = new Persona { nombre = nombre_r, apellido = apellido_r, tipo_identificacion = tipo_identificacion, identificacion = identificacion, urlCvlac = urlCvlac, correo_electronico = correo_electronico_r, tipoPersona = EnumTipoPersona.director, fecha_ult_modificacion = DateTime.Now, estado=true }; //Genero el correo para confirmacion para habilitar el perfil StringBuilder bodyMail = new StringBuilder(); //Creo un token de autenticacion para habilitar el perfil string codigoEnabled = CifradoDatos.cifrarRSA(institucion_api.logueo.correo_electronico); bodyMail.AppendLine("Para habilitar el perfil de la institucion " + institucion_api.nombre + " dirijase al siguiente enlace."); string informacionHost = UtilsHost.serverInfoCurrent(); bodyMail.AppendLine("<a href=\"" + informacionHost + "/Institucion/HabilitarCuenta?tokenEnabled=" + codigoEnabled + "\">Activar perfil.</a>" + "</br>"); string subject = "Confirmación y habilitacion de perfil."; Mail mail = new Mail(institucion_api.logueo.correo_electronico, subject, bodyMail); //Verifico si la institucion existe en el sistema List<Mensaje> lstVerificaExiste = existeInstitucion(persona); List<Mensaje> lstVerificaExisteEmail = mail.existeEmail(); if (lstVerificaExiste.Count == 0 && lstVerificaExisteEmail.Count == 0) { //Envio el correo de confirmacion if (mail.sendMail()) { persona.institucion = institucion_api; _repositorio.SaveOrUpdate<Persona>(persona); //Elimino las relaciones de la entidad institucion con sectores y tipoBiotecnologia Expression<Func<InstitucionSector, bool>> query3 = u => u.institucion.id == institucion_api.id; _repositorio.DeleteFilter<InstitucionSector>(query3); Expression<Func<InstitucionTipoBiotec, bool>> query4 = u => u.institucion.id == institucion_api.id; _repositorio.DeleteFilter<InstitucionTipoBiotec>(query4); //almaceno las relaciones de la entidad institucion con sectores y tipoBiotecnologia foreach (Sector sector in lstSectores) { _repositorio.SaveOrUpdate(new InstitucionSector { institucion = institucion_api, sector = sector, fecha_ult_modificacion = DateTime.Now }); } foreach (TipoBiotecnologia tipo in lstTipoBiotecnologia) { _repositorio.SaveOrUpdate(new InstitucionTipoBiotec { institucion = institucion_api, tipoBiotecnologia = tipo, fecha_ult_modificacion = DateTime.Now }); } // Desabilito el codigoPreRegistro en el poll de codigo para que no se pueda volver a usar solicitud.estado = false; solicitud.fecha_ult_modificacion = DateTime.Now; _repositorio.SaveOrUpdate<SolicitudRegistro>(solicitud); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Verifique el correo de logueo para activar el perfil."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "Se produjo un error mientras se enviaba el correo. Correo invalido"); } } } else { mensaje = new Mensaje(); mensaje.titulo = "Error en validacion de password diferente"; mensaje.tipo = "Error"; mensaje.cuerpo = "Error en validacion de password diferente"; } } else { mensaje = new Mensaje(); mensaje.titulo = "Error en validacion de codigo"; mensaje.tipo = "Error"; mensaje.cuerpo = "Error el codigo no existe o ya fue utilizado"; } } else { mensaje = new Mensaje(); mensaje.titulo = "Error en validacion de codigo"; mensaje.tipo = "Error"; mensaje.cuerpo = "Error el codigo es requerido"; } } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
private string getCWStyle(string strContent, SystemLog.SystemLog.LogType? logType) { strContent = "* " + strContent + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); if (logType != null) { this._LocalLogger.WriteLog(strContent, string.Empty, logType.Value); } return strContent; }
public override void PaymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue queue) { // Restore succeeded SystemLog.Info(" ** RESTORE PaymentQueueRestoreCompletedTransactionsFinished "); }
/// <summary> /// Create a new SystemLog object. /// </summary> /// <param name="logID">Initial value of LogID.</param> public static SystemLog CreateSystemLog(int logID) { SystemLog systemLog = new SystemLog(); systemLog.LogID = logID; return systemLog; }
public override void RestoreCompletedTransactionsFailedWithError(SKPaymentQueue queue, NSError error) { // Restore failed somewhere... SystemLog.Info(" ** RESTORE RestoreCompletedTransactionsFailedWithError " + error.LocalizedDescription); }
protected void rbSel_CheckedChanged(object sender, EventArgs e) { string id = lbID.Value; LogInfo lInfo = new SystemLog().GetLogInfoByID(id); // 使用全角替换 tbDetail.Text = lInfo.Message.Replace("<", "<").Replace(">", ">"); }
public abstract DbModelLoader CreateDbModelLoader(DbSettings settings, SystemLog log);
public SemiFinishedGoods GetStockGoodsONSFT(string dept, string product) { SemiFinishedGoods semiFinished = new SemiFinishedGoods(); try { GetStockinINVMC getStockinINVMC = new GetStockinINVMC(); var StockInWarehouse = getStockinINVMC.GetItemsInINVMCs(dept, product); if (StockInWarehouse != null) { semiFinished.QtyInWarehouse = StockInWarehouse.Select(d => d.Quantity).Sum(); semiFinished.QtyWarehouse = StockInWarehouse.Select(d => d.Quantity).Sum(); } semiFinished.Item = product; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(@"select isnull(sum(LOTSIZE),'0') from LOT a left join MODETAIL b on CMOID = ID where ERP_OPSEQ = '0010' and a.STATUS = '0' and b.STATUS !='99' and b.STATUS !='100' "); stringBuilder.Append(" and a.ITEMID = '" + product + "'"); sqlSFT sqlERPCON = new sqlSFT(); var Temp = sqlERPCON.sqlExecuteScalarString(stringBuilder.ToString()); if (Temp != null && Temp != "") { semiFinished.QtyInMQC = double.Parse(Temp); } stringBuilder = new StringBuilder(); stringBuilder.Append(@"select isnull(sum(LOTSIZE),'0') from LOT a left join MODETAIL b on CMOID = ID where ERP_OPSEQ = '0010' and a.STATUS = '50' and b.STATUS !='99' and b.STATUS !='100' "); stringBuilder.Append(" and a.ITEMID = '" + product + "'"); // sqlERPCON sqlERPCON = new sqlERPCON(); Temp = sqlERPCON.sqlExecuteScalarString(stringBuilder.ToString()); if (Temp != null && Temp != "") { semiFinished.QtyOutMQC = double.Parse(Temp.ToString()); } stringBuilder = new StringBuilder(); stringBuilder.Append(@"select isnull(sum(LOTSIZE),'0') from LOT a left join MODETAIL b on CMOID = ID where ERP_OPSEQ = '0020' and a.STATUS = '0' and b.STATUS !='99' and b.STATUS !='100' "); stringBuilder.Append(" and a.ITEMID = '" + product + "'"); // sqlERPCON sqlERPCON = new sqlERPCON(); Temp = sqlERPCON.sqlExecuteScalarString(stringBuilder.ToString()); if (Temp != null && Temp != "") { semiFinished.QtyInPQC = double.Parse(Temp.ToString()); } stringBuilder = new StringBuilder(); stringBuilder.Append(@"select isnull(sum(LOTSIZE),'0') from LOT a left join MODETAIL b on CMOID = ID where ERP_OPSEQ = '0020' and a.STATUS = '50' and b.STATUS !='99' and b.STATUS !='100' "); stringBuilder.Append(" and a.ITEMID = '" + product + "'"); // sqlERPCON sqlERPCON = new sqlERPCON(); Temp = sqlERPCON.sqlExecuteScalarString(stringBuilder.ToString()); if (Temp != null && Temp != "") { semiFinished.QtyOutPQC = double.Parse(Temp.ToString()); } stringBuilder = new StringBuilder(); stringBuilder.Append(@"select isnull(sum(LOTSIZE),'0') from LOT a left join MODETAIL b on CMOID = ID where ERP_OPSEQ = '0020' and a.STATUS = '130' and b.STATUS !='99' and b.STATUS !='100' "); stringBuilder.Append(" and a.ITEMID = '" + product + "'"); // sqlERPCON sqlERPCON = new sqlERPCON(); Temp = sqlERPCON.sqlExecuteScalarString(stringBuilder.ToString()); if (Temp != null && Temp != "") { semiFinished.QtyPendingWarehouse = double.Parse(Temp.ToString()); } semiFinished.QTyAtMQC = semiFinished.QtyOutMQC; semiFinished.QTyAtPQC = semiFinished.QtyInPQC + semiFinished.QtyOutPQC; semiFinished.QtyWip = semiFinished.QTyAtMQC + semiFinished.QTyAtPQC + semiFinished.QtyPendingWarehouse; GetAccessory getAccessory = new GetAccessory(); semiFinished.accessories = getAccessory.GetAccessories(dept, product); } catch (Exception ex) { SystemLog.Output(SystemLog.MSG_TYPE.Err, "GetStockGoodsONSFT(string product) : " + product, ex.Message); } return(semiFinished); }
public Mensaje editAEventoParticipante([FromBody]UtilsJson.AEventoParticipante eventoParticipante) { Mensaje mensaje = null; try { if (eventoParticipante != null) { if (!string.IsNullOrWhiteSpace(eventoParticipante.token_string)) { if (AutenticacionToken.validateToken(eventoParticipante.token_string) == 1) { long id_institucion_c = eventoParticipante.id_institucion; long id_publicacion = eventoParticipante.id_evento; Institucion institucion = _repositorio.Get<Institucion>(id_institucion_c); Publicacion publicacion = _repositorio.Get<Publicacion>(id_publicacion); EventoParticipante registro = _repositorio.Get<EventoParticipante>(eventoParticipante.id_evento_institucion); if (institucion != null && publicacion != null && registro != null) { if (AutenticacionToken.validateUserToken(eventoParticipante.token_string, institucion.logueo.correo_electronico)) { registro.institucion=institucion; registro.evento=publicacion; registro.fecha_ult_modificacion=DateTime.Now; registro.estado = eventoParticipante.estado; //Almaceno o actualizo el registro _repositorio.SaveOrUpdate<EventoParticipante>(registro); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Participante a evento editado exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se encontro el registro solicitada o esta asociada a otra institucion."); } } else { mensaje = new Mensaje(EnumTipoMensaje.Expiracion, "Error", "La sesion actual ha expirado. Inicie sesion"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No cuenta con los privilegios suficientes"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "No se puede insertar un objeto nulo"); } } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }
// called when the transaction status is updated public override void UpdatedTransactions(SKPaymentQueue queue, SKPaymentTransaction[] transactions) { SystemLog.Debug("UpdatedTransactions - {0}", transactions.Length); foreach (var transaction in transactions) { // ISSUE: The transaction (and any dangling ones) are marked as finished straight away. Apple recommends we finish after app has done // what it needs to. What happens if user's phone turns off right after finish? The app may not // have registered purchase and the user will have to re-buy again! // // Solution is to to return a scope in the "PurchaseMethod" that // finishes the transaction on dispose // // using(inAppPurchaseManager.Purchase("productid")) { // UpgradeApp(); // } <-- dispose will finish transaction // if (transaction.TransactionState != SKPaymentTransactionState.Purchasing) { SKPaymentQueue.DefaultQueue.FinishTransaction(transaction); } } if (transactions.Any(p => p.TransactionState.IsIn(SKPaymentTransactionState.Purchased, SKPaymentTransactionState.Restored))) { var paymentTransaction = transactions.First(t => t.TransactionState.IsIn(SKPaymentTransactionState.Purchased, SKPaymentTransactionState.Restored)); switch (paymentTransaction.TransactionState) { case SKPaymentTransactionState.Purchased: SystemLog.Info("PURCHASED"); _result = new PurchaseResult { AppStoreProductID = paymentTransaction.Payment.ProductIdentifier, Result = TransactionResult.Purchased, PurchaseDate = paymentTransaction.TransactionDate.ToNullableDateTime() }; break; case SKPaymentTransactionState.Restored: SystemLog.Info("RESTORED"); _result = new PurchaseResult { AppStoreProductID = paymentTransaction.Payment.ProductIdentifier, Result = TransactionResult.Restored, PurchaseDate = paymentTransaction.OriginalTransaction.TransactionDate.ToNullableDateTime() }; break; } _waiter.Set(); } else if (transactions.All(t => t.TransactionState == SKPaymentTransactionState.Failed)) { SystemLog.Info("FAILED"); var paymentTransaction = transactions.First(t => t.TransactionState == SKPaymentTransactionState.Failed); SystemLog.Info("WITH ERROR {0}", paymentTransaction.Error); _result = new PurchaseResult { AppStoreProductID = paymentTransaction.Payment.ProductIdentifier, Result = TransactionResult.Failed, Error = paymentTransaction.Error, PurchaseDate = null }; _waiter.Set(); } else { // still waiting for response (this was just dangling response from prior requests) } }
public Mensaje createAutor([FromBody]UtilsJson.APersona autor) { Mensaje mensaje = null; try { /* //datos logueo string correo_logueo = autor.correo_logueo; string contrasena = autor.contrasena; //datos publicacion string tipo_identificacion = autor.tipo_identificacion; double identificacion = autor.identificacion; string nombre_persona = autor.nombre; string apellido_persona = autor.apellido; string correo_persona = autor.correo_electronico; string urlCvlac = autor.urlCvlac; if (!String.IsNullOrWhiteSpace(correo_logueo) && !String.IsNullOrWhiteSpace(contrasena)) { //Cifrado de la contrasena contrasena = CifradoDatos.cifrarPassword(contrasena); //Busco la institucion asociada al usuario y a la contrasena Expression<Func<Representante, bool>> query = (u => u.institucion.logueo.correo_electronico == correo_logueo && u.institucion.logueo.contrasena == contrasena && u.institucion.estado == true); List<Representante> institucion = _repositorio.Filter<Representante>(query); if (institucion != null) { if (institucion.Count > 0) { Persona persona = new Persona(nombre_persona, apellido_persona, tipo_identificacion, identificacion, urlCvlac, correo_persona); Autor autorB = new Autor(institucion[0].institucion, persona); _repositorio.SaveOrUpdate<Autor>(autorB); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Autor registrada exitosamente."); } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "Correo logueo y contraseña son requeridos"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "Correo logueo y contraseña son requeridos"); } } else { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "Correo logueo y contraseña son requeridos"); }*/ } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var sb = new System.Text.StringBuilder(); foreach (var failure in ex.EntityValidationErrors) { sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType()); foreach (var error in failure.ValidationErrors) { sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage); sb.AppendLine(); } } mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", sb.ToString()); SystemLog log = new SystemLog(); log.ErrorLog(sb.ToString()); throw new Exception(sb.ToString()); } return mensaje; }