Beispiel #1
0
        public static string CreateFirstProfileUser()
        {
            string strPath = "";

            try
            {
                strPath = HttpContext.Current.Request.PhysicalApplicationPath + string.Format(ResourcePathUrl.FolderUser, EncDec.Encrypt(HttpContext.Current.Session["loginid"].ToString()));
                if (!Directory.Exists(strPath))
                {
                    //tao cau truc thu muc profile
                    Directory.CreateDirectory(strPath);
                    //tao file index.html trong
                    FunctionsFile.WriteFile(strPath + "index.html", "");
                    //tao thu muc config
                    Directory.CreateDirectory(strPath + "Config/");
                    //tao file index.html trong
                    FunctionsFile.WriteFile(strPath + "Config/index.html", "");
                    //tao thu muc uploads
                    Directory.CreateDirectory(strPath + "Uploads/");
                    //tao file index.html trong
                    FunctionsFile.WriteFile(strPath + "Uploads/index.html", "");
                    //tao thu muc uploads
                    Directory.CreateDirectory(strPath + "Temps/");
                    //tao file index.html trong
                    FunctionsFile.WriteFile(strPath + "Temps/index.html", "");
                }
                _logger.Info(strPath);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return(strPath);
        }
Beispiel #2
0
        /// <summary>
        /// Tinh phan tram cong viec theo ngay
        /// </summary>
        /// <param name="ngayBatDau">ngay bat dau</param>
        /// <param name="ngayKetThuc">ngay ket thuc</param>
        /// <returns>ket qua</returns>
        public static int TinhPhanTramCongViec(DateTime ngayBatDau, DateTime ngayKetThuc)
        {
            int kq = 0;

            try
            {
                DateTime now = DateTime.Now;

                // lay TimeSpan cua hai ngay khac nhau
                TimeSpan elapsed    = ngayKetThuc.Subtract(ngayBatDau);
                TimeSpan elapsedNow = now.Subtract(ngayBatDau);

                // lay so ngay da qua (kieu int)
                double daysAgo    = elapsed.TotalDays == 0.0 ? 1 : elapsed.TotalDays;
                double daysNowAgo = elapsedNow.TotalDays + 1;

                //tinh phan tram
                kq = ((int)daysNowAgo * 100 * 60) / (60);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                kq = 0;
            }
            return(kq);
        }
        /// <summary>
        /// Resize hinh anh
        /// </summary>
        /// <param name="PathFileImage"></param>
        /// <param name="iWidth"></param>
        /// <param name="iHeight"></param>
        /// <returns></returns>
        public static Image ScaleByPercent(string PathFileImage, int iWidth, int iHeight)
        {
            Bitmap image = Image.FromFile(PathFileImage) as Bitmap;

            try
            {
                //tính kích thước cho ảnh mới theo tỷ lệ đưa vào
                int resizedW = (int)(iWidth);
                int resizedH = (int)(iHeight);
                //tạo 1 ảnh Bitmap mới theo kích thước trên
                Bitmap bmp = new Bitmap(resizedW, resizedH);
                //tạo 1 graphic mới từ
                Graphics graphic = Graphics.FromImage((Image)bmp);
                //vẽ lại ảnh ban đầu lên bmp theo kích thước mới
                graphic.DrawImage(image, 0, 0, resizedW, resizedH);
                //giải phóng tài nguyên mà graphic đang giữ
                graphic.Dispose();
                image.Dispose();
                image = null;
                //return the image
                return((Image)bmp);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(image = Image.FromFile(PathFileImage) as Bitmap);
            }
        }
Beispiel #4
0
 /// <summary>
 /// Lay dinh dang format string
 /// vi du: string.Format("{0}", ab);
 /// </summary>
 /// <param name="column"></param>
 /// <returns></returns>
 public static string ReturnStringFormatID(string column)
 {
     try
     {
         FunctionXML fnc       = new FunctionXML(Functions.MapPath("/Xml/Config/StringFormat.xml"));
         string      strFormat = fnc.GetStringFormatIDForDataBase(column);
         return(strFormat);
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
     }
     return(string.Empty);
 }
Beispiel #5
0
        protected void Session_End(object sender, EventArgs e)
        {
            try
            {
                if (Functions.CheckSession(Session["loginid"], "string"))
                {
                    LoginServices service = new LoginServices();
                    service.LogoutHistory(Session["loginid"].ToString(), Session["sessionid"].ToString());

                    //set thuoc tinh de xoa thu muc trong sessiong end
                    PropertyInfo p       = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                    object       o       = p.GetValue(null, null);
                    FieldInfo    f       = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
                    object       monitor = f.GetValue(o);
                    MethodInfo   m       = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
                    m.Invoke(monitor, new object[] { });
                    //delete folder
                    DirectoryInfo dirRemove = new DirectoryInfo(string.Format("{0}/Profiles/{1}/Temps/{2}_{3}", Application["dirCache"], EncDec.Encrypt(Session["loginid"].ToString()), Session["userid"].ToString(), Session.SessionID));
                    if (dirRemove.Exists)
                    {
                        dirRemove.Delete(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log4Net logger = new Log4Net("Global");
                logger.Error(ex);
            }
        }
Beispiel #6
0
        public ResponsResult Post([FromBody] FileUploadModel model)
        {
            ResponsResult result = new ResponsResult();

            try
            {
                var ext = System.IO.Path.GetExtension(model.FileName);
                if (string.IsNullOrEmpty(ext))
                {
                    ext = ".jpg";
                }
                string _fileName  = $"{model.Type}_{DateTime.Now.ToString("yyyyMMddHHmmssfffffff")}{ext}";
                var    _virtual   = PathServerUtility.Combine(System.Enum.GetName(typeof(FileType), model.Type), model.Id.ToString(), _fileName);
                var    webApiPath = ConfigLocator.Instance[TbConstant.WebSiteKey] + "/api/UploadBase64File";
                var    sign       = Security.Sign(Domain.Config.TbConstant.UploadKey, _virtual);
                model.Picture = Convert.ToBase64String(ImageHandler.ShrinkImage(ImageHandler.Base64ToBytes(model.Picture)));
                string response;
                if (!string.IsNullOrEmpty(model.WaterMarks))
                {
                    response = HttpUtility.PostString(webApiPath, new { sign = sign, base64 = model.Picture, fileName = _virtual, watermarks = model.WaterMarks }.GetJson(), "application/json");
                }
                else
                {
                    response = HttpUtility.PostString(webApiPath, new { sign = sign, base64 = model.Picture, fileName = _virtual }.GetJson(), "application/json");
                }
                var uploadModel = (response.GetModel <ResponsResult>().Data as Newtonsoft.Json.Linq.JObject).ToObject <UploadModel>();
                result.Data = uploadModel;
                return(result);
            }
            catch (Exception ex)
            {
                Log4Net.Error($"[上传图片异常]_:{ex}");
                return(result.SetError("上传图片异常"));
            }
        }
Beispiel #7
0
        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                var currentUrl = "";

                var context = HttpContext.Current;
                if (context == null)
                {
                    currentUrl = context.Request.RawUrl;
                }

                var lastException = GetException();
                if (lastException == null)
                {
                    return; //nothing to log
                }
                string data = "";
                foreach (DictionaryEntry pair in lastException.Data)
                {
                    data += string.Format("{0}: {1}{2}", pair.Key, pair.Value, Environment.NewLine);
                }

                Log4Net.Error(string.Format("{0} occured executing '{1}'{5}{2}{5}{3}{5}Exception.Data:{5}{4}",
                                            lastException.GetType().FullName, currentUrl, lastException.Message,
                                            lastException.StackTrace, data, Environment.NewLine));
            }
            catch (Exception ex)
            {
                Log4Net.Error(string.Format("Exception occured in OnError: [{0}]", ex.Message));
            }
        }
Beispiel #8
0
        public async Task <ITKConfirmationViewModel> ItkResponseBuilder(OutcomeViewModel model)
        {
            var itkRequestData = CreateItkDispatchRequest(model);

            _auditLogger.LogItkRequest(model, itkRequestData);
            var response = await SendItkMessage(itkRequestData);

            _auditLogger.LogItkResponse(model, response);
            var itkResponseModel = _mappingEngine.Mapper.Map <OutcomeViewModel, ITKConfirmationViewModel>(model);

            itkResponseModel.ItkDuplicate   = IsDuplicateResponse(response);
            itkResponseModel.ItkSendSuccess = response.IsSuccessful;
            if (response.IsSuccessful || IsDuplicateResponse(response))
            {
                itkResponseModel.PatientReference = itkRequestData.CaseDetails.ExternalReference;
            }

            else
            {
                itkResponseModel.ItkSendSuccess = false;
                Log4Net.Error("Error sending ITK message : Status Code -" + response.StatusCode +
                              " Content -" + itkRequestData.CaseDetails.ExternalReference);
            }
            return(itkResponseModel);
        }
Beispiel #9
0
        /// <summary>
        /// 处理api请求我们以json形式返回mvc我们返回view
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                context.ExceptionHandled = true;
                Log4Net.Error(context.Exception);
                if (context.HttpContext.IsAjaxRequest())
                {
#if DEBUG
                    context.Result = Json(new Result(context.Exception, true));
#else
                    context.Result = Json(new Result(context.Exception));
#endif
                }
                else
                {
#if DEBUG
                    context.Result = View("Error", new Result(context.Exception, true));
#else
                    context.Result = View("Error", new Result(context.Exception));
#endif
                }
                return;
            }
            base.OnActionExecuted(context);
        }
Beispiel #10
0
        /// <summary>
        /// 暂停指定任务计划
        /// </summary>
        /// <returns></returns>
        public async Task <ResponsResult> StopScheduleJobAsync(string jobGroup, string jobName)
        {
            ResponsResult result = new ResponsResult();

            try
            {
                scheduler = await GetSchedulerAsync();

                //使任务暂停
                await scheduler.PauseJob(new JobKey(jobName, jobGroup));

                var status = new StatusViewModel()
                {
                    Status = 0,
                    Msg    = "暂停任务计划成功",
                };
                result.Data = status.GetJson();
                return(result);
            }
            catch (Exception ex)
            {
                Log4Net.Error($"[JobCenter_StopScheduleJobAsync]_{ex}");
                var status = new StatusViewModel()
                {
                    Status = -1,
                    Msg    = "暂停任务计划失败",
                };
                result.Data = status.GetJson();
                return(result);
            }
        }
        public static byte[] DownBytes(string url)
        {
            HttpMessageHandler handler = new HttpClientHandler();

            using (HttpClient client = new HttpClient(handler))
            {
                try
                {
                    using (var stream = client.GetStreamAsync(url).GetAwaiter().GetResult())
                    {
                        var ms = new MemoryStream();
                        stream.CopyTo(ms);
                        byte[] bytes = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(bytes, 0, bytes.Length);
                        return(bytes);
                    }
                }
                catch (Exception ex)
                {
                    Log4Net.Error($"[DownBytes]_:{ex}");
                }
            }
            return(default(byte[]));
        }
Beispiel #12
0
        //
        // GET: /SystemInfo/
        public ActionResult SystemInfo()
        {
            if (!IsLogged())
            {
                return(BackToLogin());
            }
            var model = new SystemInfoModel();

            try
            {
                model.OperatingSystem = Environment.OSVersion.VersionString;
            }
            catch (Exception ex) {
                _logger.Error(ex);
            }
            try
            {
                model.AspNetInfo = RuntimeEnvironment.GetSystemVersion();
            }
            catch (Exception ex) {
                _logger.Error(ex);
            }
            try
            {
                model.IsFullTrust = AppDomain.CurrentDomain.IsFullyTrusted.ToString();
            }
            catch (Exception ex) {
                _logger.Error(ex);
            }
            model.ServerTimeZone  = TimeZone.CurrentTimeZone.StandardName;
            model.ServerLocalTime = DateTime.Now.ToString("F");
            model.UtcTime         = DateTime.UtcNow.ToString("F");
            model.HttpHost        = this.Request.ServerVariables["HTTP_HOST"];
            ////Environment.GetEnvironmentVariable("USERNAME");
            //foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            //{
            //    model.LoadedAssemblies.Add(new SystemInfoModel.LoadedAssembly
            //    {
            //        FullName = assembly.FullName,
            //        //we cannot use Location property in medium trust
            //        //Location = assembly.Location
            //    });
            //}
            return(View(model));
        }
Beispiel #13
0
 // GET: Home
 public ActionResult Index()
 {
     Log4Net.Info(this, "信息");
     Log4Net.Debug(this, "调试");
     Log4Net.Error(this, "错误");
     Log4Net.Fatal(this, "失败");
     Log4Net.Warn(this, "警告");
     return(View());
 }
Beispiel #14
0
 private void TestLog4Net()
 {
     Log4Net.Debug("debug log");
     Log4Net.Info("info log");
     Log4Net.Warn("Warn log");
     Log4Net.Error("Error log");
     Log4Net.Fatal("Fatal log");
     Log4Net.DebugInfo("Debug log{0}", 2);
 }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next.Invoke(context);

                if (!SuccessCode.Contains(context.Response.StatusCode))
                {
                    int    statusCode2  = context.Response.StatusCode;
                    string reasonPhrase = ReasonPhrases.GetReasonPhrase(statusCode2);
                    string msg          = string.Format("Status Code: {0}, {1}; {2}{3}", new object[4]
                    {
                        statusCode2,
                        reasonPhrase,
                        context.Request.Path,
                        context.Request.QueryString
                    });
                    if (context.IsAjaxRequest())
                    {
                        context.Response.ContentType = "application/json;charset=utf-8";
                        ResponsResult response2 = new ResponsResult(statusCode2, msg, (Exception)null);
                        await context.Response.WriteAsync(response2.GetJson());
                    }
                }
            }
            catch (Exception exception)
            {
                int statusCode = SuccessCode.Contains(context.Response.StatusCode) ? 500 : context.Response.StatusCode;
                if (exception.TargetSite.DeclaringType != (Type)null)
                {
                    string name = exception.TargetSite.DeclaringType.Name;
                    if (name.Contains("ChallengeAsync"))
                    {
                        statusCode = 401;
                    }
                    else if (name.Contains("ForbidAsync"))
                    {
                        statusCode = 403;
                    }
                }
                Log4Net.Error($"[ErrorHandler中间件:]{exception}");
                Exception     ex      = exception;
                StringBuilder message = new StringBuilder();
                while (ex != null)
                {
                    message.AppendLine(ex.Message);
                    ex = ex.InnerException;
                }
                if (context.IsAjaxRequest() && !context.Response.HasStarted)
                {
                    context.Response.ContentType = "application/json;charset=utf-8";
                    ResponsResult response = new ResponsResult(statusCode, message.ToString(), (Exception)null);
                    await context.Response.WriteAsync(response.GetJson());
                }
            }
        }
Beispiel #16
0
        public override void OnException(HttpActionExecutedContext context)
        {
            var requestUri = string.Empty;

            if (context.Request.RequestUri != null)
            {
                requestUri = string.Join("/", context.Request.RequestUri.AbsolutePath);
            }

            Log4Net.Error(string.Format("ERROR on {0}:  {1} - {2} - {3}", requestUri, context.Exception.Message, context.Exception.StackTrace, context.Exception.Data));
        }
Beispiel #17
0
        public override void OnException(ExceptionContext filterContext)
        {
            var controllerAction = string.Empty;

            if (filterContext.RouteData != null && filterContext.RouteData != null & filterContext.RouteData.Values != null)
            {
                controllerAction = string.Join("/", filterContext.RouteData.Values.Values);
            }

            Log4Net.Error(string.Format("ERROR on {0}:  {1} - {2} - {3}", controllerAction, filterContext.Exception.Message, filterContext.Exception.StackTrace, filterContext.Exception.Data));
        }
Beispiel #18
0
 /// <summary>
 /// Chuyen file thanh mang byte
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static byte[] ReadFileToByte(string path)
 {
     byte[] byteResult = null;
     try
     {
         //using (FileStream MyFileStream = new FileStream(path, FileMode.Open))
         //{
         //    // Total bytes to read:
         //    long size;
         //    size = MyFileStream.Length;
         //    byteResult = new byte[size];
         //    MyFileStream.Read(byteResult, 0, int.Parse(MyFileStream.Length.ToString()));
         //}
         byteResult = File.ReadAllBytes(path);
     }
     catch (Exception ex)
     {
         logger.Error(ex);
     }
     return(byteResult);
 }
Beispiel #19
0
        public async Task Append(string topic, string[] messages)
        {
            try
            {
                var messagesList = messages.Select(message => new Message(message)).ToList();
                var client       = _producer;
                await client.SendMessageAsync(topic, messagesList);
            }

            catch (Exception ex)
            {
                Log4Net.Error(string.Format("ERROR on KafkaClient:  {0} - {1} - {2}", ex.Message, ex.StackTrace, ex.Data));
            }
        }
Beispiel #20
0
        protected override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;

            int HataKey = 0;

            try
            {
                using (DBUtil2 oData = new DBUtil2(DataBaseTipi.Yetki))
                {
                    HataKey = oData.VeriKaydetHataYaz(ArgemSession.OpKullaniciKey, "BaseController", filterContext.Exception.Message, "", "", "", filterContext.Exception.StackTrace, "");
                }
            }
            catch (Exception ex)
            {
                Log4Net.Error("Hata VT: " + filterContext.RouteData.Values["controller"] + " " + filterContext.RouteData.Values["action"], ex);
            }

            bool isAjax = AjaxRequestExtensions.IsAjaxRequest(filterContext.HttpContext.Request);

            isAjax = (filterContext.HttpContext.Request["X-Requested-With"] == "XMLHttpRequest") || ((filterContext.HttpContext.Request.Headers != null) && (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
            isAjax = filterContext.HttpContext.Request.ContentType == "application/json;charset=utf-8";

            // if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
            if (isAjax)
            {
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        Durum    = "E",
                        Aciklama = "Hata Kodu :" + HataKey + " (" + filterContext.Exception.Message + ")",
                    }
                };
            }
            else
            {
                filterContext.Controller.TempData["HataKey"] = HataKey;

                //Redirect or return a view, but not both.
                // filterContext.Result = RedirectToAction("HataKontrol", "Login", new { area = "Yetki" });
                filterContext.Result = new ViewResult
                {
                    ViewName = "~/Yetki/Login/HataKontrol.cshtml"
                };
            }
        }
Beispiel #21
0
        /// <summary>
        /// 恢复指定的任务计划**恢复的是暂停后的任务计划,如果是程序奔溃后 或者是进程杀死后的恢复,此方法无效
        /// </summary>
        /// <returns></returns>
        public async Task <ResponsResult> RunScheduleJobAsync(TaskScheduleModel sm)
        {
            ResponsResult result = new ResponsResult();

            try
            {
                #region 开任务
                //scheduler = await GetSchedulerAsync();
                //DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(sm.StarRunTime, 1);
                //DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(sm.EndRunTime, 1);
                //IJobDetail job = JobBuilder.Create<HttpJob>()
                //  .WithIdentity(sm.JobName, sm.JobGroup)
                //  .Build();
                //ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                //                             .StartAt(starRunTime)
                //                             .EndAt(endRunTime)
                //                             .WithIdentity(sm.JobName, sm.JobGroup)
                //                             .WithCronSchedule(sm.CronExpress)
                //                             .Build();
                //await scheduler.ScheduleJob(job, trigger);
                //await scheduler.Start();
                #endregion
                scheduler = await GetSchedulerAsync();

                //resumejob 恢复
                await scheduler.ResumeJob(new JobKey(sm.JobName, sm.JobGroup));

                var status = new StatusViewModel()
                {
                    Status = 0,
                    Msg    = "恢复任务计划成功",
                };
                result.Data = status.GetJson();
                return(result);
            }
            catch (Exception ex)
            {
                Log4Net.Error($"[JobCenter_RunScheduleJobAsync]_{ex}");
                var status = new StatusViewModel()
                {
                    Status = -1,
                    Msg    = "恢复任务计划失败",
                };
                result.Data = status.GetJson();
                return(result);
            }
        }
Beispiel #22
0
 protected PhongBanDonViModels GetPhongBanDonVi()
 {
     try
     {
         List <PhongBanDonViModels> lst = (List <PhongBanDonViModels>)Session["phongBanDonVi"];
         if (lst.Count > 0)
         {
             PhongBanDonViModels phongBanDonvi = lst[0];
             return(phongBanDonvi);
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
     }
     return(null);
 }
Beispiel #23
0
        /// <summary>
        /// chuyen doi chuoi ngaythang sang kieu datetime
        /// input: 20/02/2013 14:30 - format: dd/MM/yyyy HH:mm
        /// output: datetime
        /// </summary>
        /// <param name="date"></param>
        /// <param name="strFomat"></param>
        /// <returns></returns>
        public static DateTime ConvertDateWithFormat(string date, string strFormat)
        {
            DateTime dateResult = DateTime.Now;

            try
            {
                System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
                DateTime.TryParseExact(date, strFormat, culture,
                                       System.Globalization.DateTimeStyles.None, out dateResult);
            }
            catch (Exception ex)
            {
                dateResult = DateTime.Now;
                logger.Error(ex);
            }
            return(dateResult);
        }
        public override void OnException(ExceptionContext filterContext)
        {
            var controllerAction = string.Empty;

            if (filterContext.RouteData != null && filterContext.RouteData != null & filterContext.RouteData.Values != null)
            {
                controllerAction = string.Join("/", filterContext.RouteData.Values.Values);
            }

            string data = "";

            foreach (DictionaryEntry pair in filterContext.Exception.Data)
            {
                data += string.Format("{0}: {1}{2}", pair.Key, pair.Value, Environment.NewLine);
            }

            Log4Net.Error(string.Format("{0} occured executing '{1}'{5}{2}{5}{3}{5}Exception.Data:{5}{4}", filterContext.Exception.GetType().FullName, controllerAction, filterContext.Exception.Message, filterContext.Exception.StackTrace, data, Environment.NewLine));
        }
Beispiel #25
0
        protected override void OnException(ExceptionContext filterContext)
        {
            //Logger.Error("XprepayControllerBase.OnException", filterContext.Exception);
            //只记录系统错误.
            if (filterContext.Exception is Exception)
            {
                Log4Net.Error(filterContext.Exception.Source, filterContext.Exception);
            }
            if (_actionReturnType == null)
            {
                base.OnException(filterContext);
                return;
            }
            string error;

            if (filterContext.Exception is KnownException)
            {
                error = filterContext.Exception.Message;
            }
            else
            {
                error = filterContext.Exception.GetAllMessages();
            }
            if (_actionReturnType == typeof(StandardJsonResult) || (_actionReturnType == typeof(StandardJsonResult <>)))
            {
                var result = new StandardJsonResult();
                result.Fail(error);
                filterContext.Result = result;
            }
            else if (_actionReturnType == typeof(PartialViewResult))
            {
                filterContext.Result = new ContentResult()
                {
                    Content = error
                };
            }
            else
            {
                filterContext.Result = Error(error);
            }
            filterContext.ExceptionHandled = true;
        }
        private StringBuilder PrepareDataJsonForSelectAlerts(ThongBaoModels model, int couter)
        {
            StringBuilder sbResult = new StringBuilder();

            try
            {
                sbResult.Append("{");
                sbResult.Append("\"col_class\":\"rows-box\",");
                sbResult.Append("\"col_id\":\"" + model.mathongbao + "\",");
                sbResult.Append("\"col_value\":[");
                #region Data cell
                //stt
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col1 stt\",");
                sbResult.Append("\"col_value\":\"" + couter.ToString() + "\"");
                sbResult.Append("},");
                //noi dung
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col2\",");
                sbResult.Append("\"title\":\"" + model.noidung + "\",");
                sbResult.Append("\"col_value\":\"" + model.noidung + "\"");
                sbResult.Append("},");
                //ngay nhap
                sbResult.Append("{");
                sbResult.Append("\"colspan\":\"1\",");
                sbResult.Append("\"col_class\":\"ovh col3\",");
                sbResult.Append("\"col_value\":\"" + FunctionsDateTime.GetDateTimeClientCustomFormat(model.ngaytao) + "\"");
                sbResult.Append("}");
                #endregion

                sbResult.Append("]");
                sbResult.Append("},");
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return(sbResult);
        }
Beispiel #27
0
        static WebBase()
        {
            try
            {
                var actions = ServiceCollectionExtension.Get <IPermissionService>();

                if (actions != null)
                {
                    var provider       = ServiceCollectionExtension.Get <IActionDescriptorCollectionProvider>();
                    var descriptorList = provider.ActionDescriptors.Items.Cast <ControllerActionDescriptor>()
                                         .Where(t => t.MethodInfo.GetCustomAttribute <ActionAttribute>() != null).ToList();
                    actions.RegistAction(descriptorList);

                    actions.RegistRole();
                }
            }
            catch (Exception ex)
            {
                Log4Net.Error(ex);
            }
        }
Beispiel #28
0
        /// <summary>
        /// Insert data
        /// </summary>
        /// <param name="dataInsert"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        ///
        public bool InsertData(Object dataInsert, string tableName)
        {
            _logger.Start("InsertData");
            _logger.Param("TableName", tableName);
            bool result = false;

            try
            {
                sqlMap.BeginTransaction();
                Hashtable param = new Hashtable();

                #region Tao du lieu cho values de import
                ArrayList arrValues  = new ArrayList();
                ArrayList arrColumns = new ArrayList();

                this.SetDataToArrayListForInsert(dataInsert, ref arrColumns, ref arrValues);

                #endregion

                //ten table
                param.Add("tablename", tableName);
                //Cac column trong table
                param.Add("columns", arrColumns);
                //gia tri cua cac du lieu can insert
                param.Add("values", arrValues);
                sqlMap.Insert("Common.InsertRow", param);

                //commit du lieu
                sqlMap.CommitTransaction();
                //them moi du lieu thanh cong
                result = true;
            }
            catch (Exception ex)
            {
                sqlMap.RollbackTransaction();
                _logger.Error(ex);
            }

            _logger.End("InsertData");
            return(result);
        }
Beispiel #29
0
        public async Task <OutcomeViewModel> ItkResponseBuilder(OutcomeViewModel model)
        {
            var itkRequestData = CreateItkDispatchRequest(model);
            await _auditLogger.LogItkRequest(model, itkRequestData);

            var response = await SendItkMessage(itkRequestData);

            await _auditLogger.LogItkResponse(model, response);

            model.ItkDuplicate = response.StatusCode == System.Net.HttpStatusCode.Conflict;
            if (response.IsSuccessStatusCode)
            {
                model.ItkSendSuccess = true;
                var journey = JsonConvert.DeserializeObject <Journey>(model.JourneyJson);
            }
            else
            {
                model.ItkSendSuccess = false;
                Log4Net.Error("Error sending ITK message : Status Code -" + response.StatusCode.ToString() +
                              " Content -" + response.Content.ReadAsStringAsync());
            }
            return(model);
        }
Beispiel #30
0
        /// <summary>
        /// 添加任务计划//或者进程终止后的开启
        /// </summary>
        /// <returns></returns>
        public async Task <ResponsResult> AddScheduleJobAsync(TaskScheduleModel m)
        {
            ResponsResult result = new ResponsResult();

            try
            {
                if (m != null)
                {
                    DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(m.StarRunTime, 1);
                    DateTimeOffset endRunTime  = DateBuilder.NextGivenSecondDate(m.EndRunTime, 1);
                    scheduler = await GetSchedulerAsync();

                    IJobDetail job = JobBuilder.Create <HttpJob>()
                                     .WithIdentity(m.JobName, m.JobGroup)
                                     .Build();
                    ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                           .StartAt(starRunTime)
                                           .EndAt(endRunTime)
                                           .WithIdentity(m.JobName, m.JobGroup)
                                           .WithCronSchedule(m.CronExpress)
                                           .Build();
                    await scheduler.ScheduleJob(job, trigger);

                    await scheduler.Start();

                    result.Data = m;
                    return(result);
                }
                return(result.SetError("传入实体为空"));
            }
            catch (Exception ex)
            {
                Log4Net.Error($"[JobCenter_AddScheduleJobAsync]_{ex}");
                return(result.SetError(ex.Message));
            }
        }