Exemplo n.º 1
0
        public ActionResult CloseJob(JobViewModel jobVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Close Job").Add("JobId", jobVM.JobId).ToInputLogString());

            try
            {
                int userId = this.UserInfo.UserId;
                _commPoolFacade = new CommPoolFacade();
                bool success = _commPoolFacade.UpdateJob(jobVM.JobId, userId, jobVM.JobStatus, string.Empty);

                if (success)
                {
                    return(RedirectToAction("Search", "Job"));
                }

                ViewBag.ErrorMessage = Resource.Error_UpdateFailedDuplicate;
                TempData["jobVM"]    = jobVM;
                return(InitEdit());
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Close Job").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 2
0
        public JsonResult NewSR(int jobId)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Save NewSR").Add("JobId", jobId).ToInputLogString());
            try
            {
                int srId   = 0;
                int userId = this.UserInfo.UserId;
                _commPoolFacade = new CommPoolFacade();
                _commPoolFacade.SaveNewSR(jobId, userId, ref srId);

                return(Json(new
                {
                    Valid = true,
                    SrId = srId
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Save NewSR").Add("Error Message", ex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = Resource.Error_System,
                    Errors = string.Empty
                }));
            }
        }
Exemplo n.º 3
0
        public ActionResult Search()
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitSearch Job").ToInputLogString());
            try
            {
                _commonFacade   = new CommonFacade();
                _commPoolFacade = new CommPoolFacade();

                ViewBag.jobstatus = _commPoolFacade.GetJobStatusSelectList(Resource.Ddl_Status_All, Constants.ApplicationStatus.All);
                ViewBag.channel   = _commPoolFacade.GetChannelWithEmailSelectList(Resource.Ddl_Status_All, Constants.ApplicationStatus.All);
                ViewBag.srstatus  = _commPoolFacade.GetSRStatusSelectList(Resource.Ddl_Status_All, Constants.ApplicationStatus.All);

                JobViewModel jobVM = new JobViewModel();
                jobVM.SearchFilter = new CommPoolSearchFilter
                {
                    FirstName = string.Empty,
                    LastName  = string.Empty,
                    JobStatus = null,
                    Channel   = null,
                    Subject   = string.Empty,
                    From      = string.Empty,
                    DateFrom  = string.Empty,
                    DateTo    = string.Empty,
                    ActionBy  = string.Empty,
                    SRId      = string.Empty,
                    SRStatus  = null,
                    CreatorSR = string.Empty,
                    OwnerSR   = string.Empty,
                    User      = null,
                    PageNo    = 1,
                    PageSize  = _commonFacade.GetPageSizeStart(),
                    SortField = "JobId",
                    SortOrder = "DESC"
                };

                var defSearch = _commonFacade.GetShowhidePanelByUserId(this.UserInfo, Constants.Page.CommunicationPage);

                if (defSearch != null)
                {
                    jobVM.IsSelected = defSearch.IsSelectd ? "1" : "0";
                }
                else
                {
                    jobVM.IsSelected = "0";
                }

                ViewBag.PageSize     = jobVM.SearchFilter.PageSize;
                ViewBag.PageSizeList = _commonFacade.GetPageSizeList();
                ViewBag.Message      = string.Empty;

                return(View(jobVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitSearch Job").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 4
0
        public JsonResult SaveRemarkCloseJob(JobViewModel jobVM)
        {
            try
            {
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Save RemarkCloseJob").ToInputLogString());

                // Validate MaxLength
                if (!string.IsNullOrWhiteSpace(jobVM.Remark) && jobVM.Remark.Count() > Constants.MaxLength.RemarkCloseJob)
                {
                    ModelState.AddModelError("Remark", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_StringLength, Resource.Lbl_Remark, Constants.MaxLength.RemarkCloseJob));
                }

                if (ModelState.IsValid)
                {
                    int userId = this.UserInfo.UserId;
                    _commPoolFacade = new CommPoolFacade();
                    bool success = _commPoolFacade.UpdateJob(jobVM.JobId, userId, jobVM.JobStatus, jobVM.Remark);

                    if (success)
                    {
                        return(Json(new
                        {
                            Valid = true
                        }));
                    }

                    return(Json(new
                    {
                        Valid = false,
                        Error = Resource.Error_UpdateFailedDuplicate
                    }));
                }

                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Save RemarkCloseJob").Add("Error Message", ex.Message).ToInputLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = Resource.Error_System,
                    Errors = string.Empty
                }));
            }
        }
Exemplo n.º 5
0
        public ActionResult Search()
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitSearch Product").ToInputLogString());

            try
            {
                _commonFacade   = new CommonFacade();
                _commPoolFacade = new CommPoolFacade();

                var statusList = _commPoolFacade.GetSRStatusSelectList(Resource.Ddl_Status_All, Constants.ApplicationStatus.All);
                ViewBag.srstatus = new SelectList((IEnumerable)statusList, "Key", "Value", string.Empty);

                ProductViewModel productVM = new ProductViewModel();
                productVM.SearchFilter = new ProductSearchFilter
                {
                    ProductGroupId = null,
                    ProductId      = null,
                    CampaignId     = null,
                    TypeId         = null,
                    AreaId         = null,
                    SubAreaId      = null,
                    FromSRStatus   = null,
                    ToSRStatus     = null,
                    PageNo         = 1,
                    PageSize       = _commonFacade.GetPageSizeStart(),
                    SortField      = "ProductGroup",
                    SortOrder      = "DESC"
                };

                ViewBag.PageSize     = productVM.SearchFilter.PageSize;
                ViewBag.PageSizeList = _commonFacade.GetPageSizeList();
                ViewBag.Message      = string.Empty;

                return(View(productVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitSearch Product").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 6
0
        public JsonResult LoadFileAttachment(int attachmentId)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Load FileAttachment").ToInputLogString());

            try
            {
                _commPoolFacade = new CommPoolFacade();
                AttachmentEntity selectedAttach = _commPoolFacade.GetAttachmentsById(attachmentId);
                TempData["FILE_DOWNLOAD"] = selectedAttach;

                _commonFacade = new CommonFacade();
                string documentFolder = _commonFacade.GetJobDocumentFolder();
                string pathFile       = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", documentFolder, selectedAttach.Url);

                if (!System.IO.File.Exists(pathFile))
                {
                    return(Json(new
                    {
                        Valid = false,
                        Error = "ไม่พบไฟล์ที่ต้องการ Download",
                        Errors = string.Empty
                    }));
                }

                return(Json(new
                {
                    Valid = true
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Load FileAttachment").Add("Error Message", ex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = Resource.Error_System,
                    Errors = string.Empty
                }));
            }
        }
Exemplo n.º 7
0
        public ActionResult PoolBranchList(PoolViewModel poolVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get PoolBranch List").Add("PoolName", poolVM.JsonBranch).ToInputLogString());

            try
            {
                _commPoolFacade       = new CommPoolFacade();
                poolVM.PoolBranchList = _commPoolFacade.GetPoolBranchList(poolVM.SelectedBranch)
                                        .Where(x => x.IsDelete == false).ToList();

                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get PoolBranch List").ToSuccessLogString());
                return(PartialView("~/Views/CommPool/_PoolBranchList.cshtml", poolVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get PoolBranch List").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 8
0
        public ActionResult PoolList(PoolSearchFilter searchFilter)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Pool").Add("PoolName", searchFilter.PoolName)
                        .Add("PoolDesc", searchFilter.PoolDesc).Add("Email", searchFilter.Email).ToInputLogString());

            try
            {
                if (ModelState.IsValid)
                {
                    _commonFacade   = new CommonFacade();
                    _commPoolFacade = new CommPoolFacade();
                    PoolViewModel poolVM = new PoolViewModel();
                    poolVM.SearchFilter = searchFilter;

                    poolVM.PoolList      = _commPoolFacade.GetPoolList(poolVM.SearchFilter);
                    ViewBag.PageSize     = poolVM.SearchFilter.PageSize;
                    ViewBag.PageSizeList = _commonFacade.GetPageSizeList();

                    Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Pool").ToSuccessLogString());
                    return(PartialView("~/Views/CommPool/_PoolList.cshtml", poolVM));
                }

                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Search Pool").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 9
0
        public ActionResult Edit(PoolViewModel poolVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Save CommunicationPool").Add("CommPoolId", poolVM.PoolId)
                        .Add("PoolName", poolVM.PoolName).Add("PoolDesc", poolVM.PoolDesc).ToInputLogString());

            try
            {
                bool skipValidate = false;

                if (poolVM.PoolId != null && string.IsNullOrWhiteSpace(poolVM.Password) &&
                    string.IsNullOrWhiteSpace(poolVM.ConfirmPasswd))
                {
                    ModelState.Remove("Password");
                    ModelState.Remove("ConfirmPasswd");
                    skipValidate = true;
                }

                if (!string.IsNullOrWhiteSpace(poolVM.Password) && !string.IsNullOrWhiteSpace(poolVM.ConfirmPasswd) &&
                    !poolVM.ConfirmPasswd.Equals(poolVM.Password))
                {
                    ModelState.AddModelError("ConfirmPasswd", Resource.ValError_InvalidConfirmPasswd);
                }

                if (ModelState.IsValid)
                {
                    List <PoolBranchEntity> selectedBranch = poolVM.SelectedBranch;

                    // Validate select at least one branch
                    if (!poolVM.SelectedBranch.Any(x => x.IsDelete == false))
                    {
                        ViewBag.ErrorMessage = string.Format(CultureInfo.InvariantCulture, Resource.ValErr_AtLeastOneItemWithField, Resource.Lbl_Branch);
                        goto Outer;
                    }

                    // Save CommPool
                    PoolEntity poolEntity = new PoolEntity
                    {
                        PoolId          = poolVM.PoolId,
                        PoolName        = poolVM.PoolName,
                        PoolDesc        = poolVM.PoolDesc,
                        Email           = poolVM.Email,
                        Status          = poolVM.Status,
                        CreateUser      = UserInfo, //When save the program will select to save this parameter
                        UpdateUser      = UserInfo,
                        ReplyMail       = poolVM.ReplyMail,
                        EmailTemplateId = poolVM.PoolEmailTemplateId
                    };

                    if (!skipValidate)
                    {
                        string encryptedstring = StringCipher.Encrypt(poolVM.Password, Constants.PassPhrase);
                        poolEntity.Password = encryptedstring;
                    }

                    _commPoolFacade = new CommPoolFacade();

                    #region "Check Duplicate"
                    // Check Duplicate
                    if (_commPoolFacade.IsDuplicateCommPool(poolEntity) == true)
                    {
                        ViewBag.ErrorMessage = Resource.Error_SaveFailed_CommPoolDuplicate;
                        goto Outer;
                    }
                    #endregion

                    bool success = _commPoolFacade.SaveCommPool(poolEntity, selectedBranch);

                    if (success)
                    {
                        return(RedirectToAction("Search", "CommPool"));
                    }

                    ViewBag.ErrorMessage = Resource.Error_SaveFailed;
                }

Outer:
                TempData["PoolVM"] = poolVM;
                return(InitEdit());
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Save CommunicationPool").ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 10
0
        public ActionResult InitEdit(int?commPoolId = null)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit CommunicationPool").Add("CommPoolId", commPoolId).ToInputLogString());

            try
            {
                PoolViewModel poolVM = null;

                if (TempData["PoolVM"] != null)
                {
                    poolVM = (PoolViewModel)TempData["PoolVM"];
                }
                else
                {
                    poolVM = new PoolViewModel {
                        PoolId = commPoolId
                    };
                }

                _commonFacade   = new CommonFacade();
                _commPoolFacade = new CommPoolFacade();

                var statusList = _commonFacade.GetStatusSelectList();
                poolVM.StatusList = new SelectList((IEnumerable)statusList, "Key", "Value", string.Empty);
                var replyMailList = _commonFacade.GetReplyMailSelectList();
                poolVM.ReplyMailList      = new SelectList((IEnumerable)replyMailList, "Key", "Value", string.Empty);
                poolVM.PoolEmailTemplates = _commPoolFacade.GetPoolEmailTemplates().Select(c => new SelectListItem {
                    Text = c.Name, Value = c.PoolEmailTemplateId + ""
                }).ToList();

                if (poolVM.PoolId != null)
                {
                    PoolEntity poolEntity = _commPoolFacade.GetPoolByID(poolVM.PoolId.Value);
                    poolVM.PoolName            = poolEntity.PoolName;
                    poolVM.PoolDesc            = poolEntity.PoolDesc;
                    poolVM.Email               = poolEntity.Email;
                    poolVM.Status              = poolEntity.Status;
                    poolVM.ReplyMail           = poolEntity.ReplyMail;
                    poolVM.PoolEmailTemplateId = poolEntity.EmailTemplateId;

                    poolVM.CreateUser  = poolEntity.CreateUser != null ? poolEntity.CreateUser.FullName : string.Empty;
                    poolVM.UpdateUser  = poolEntity.UpdateUser != null ? poolEntity.UpdateUser.FullName : string.Empty;
                    poolVM.CreatedDate =
                        poolEntity.CreatedDate.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                    poolVM.UpdateDate =
                        poolEntity.Updatedate.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);

                    var poolBranches = _commPoolFacade.GetPoolBranchList(poolVM.PoolId.Value);
                    poolVM.PoolBranchList = poolBranches;
                    poolVM.JsonBranch     = JsonConvert.SerializeObject(poolBranches);
                }
                else
                {
                    poolVM.PoolBranchList = _commPoolFacade.GetPoolBranchList(poolVM.SelectedBranch)
                                            .Where(x => x.IsDelete == false).ToList();

                    // default UserLogin
                    if (this.UserInfo != null)
                    {
                        var today = DateTime.Now;
                        poolVM.CreateUser  = this.UserInfo.FullName;
                        poolVM.CreatedDate = today.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                        poolVM.UpdateDate  = today.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                        poolVM.UpdateUser  = this.UserInfo.FullName;
                    }
                }

                return(View("~/Views/CommPool/Edit.cshtml", poolVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit CommunicationPool").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 11
0
        public ActionResult InitEdit(string jsonData = "{}")
        {
            ProductViewModel productVM = null;

            _commPoolFacade = new CommPoolFacade();

            var toRTStatuses = new Dictionary <string, string>();
            var fromStatuses = _commPoolFacade.GetSRStatusSelectList();
            var toLFStatuses = new Dictionary <string, string>(fromStatuses);
            ProductSearchFilter searchFilter = JsonConvert.DeserializeObject <ProductSearchFilter>(jsonData);

            if (TempData["productVM"] != null)
            {
                productVM = (ProductViewModel)TempData["productVM"];

                if (productVM.ToSRStatusRightId != null && productVM.ToSRStatusRightId.Count > 0)
                {
                    foreach (var s in productVM.ToSRStatusRightId)
                    {
                        var statusId   = s.ConvertToString();
                        var statusName = toLFStatuses[statusId];
                        toLFStatuses.RemoveByValue(statusId);
                        toRTStatuses.Add(statusId, statusName);
                    }
                }
            }
            else
            {
                productVM = new ProductViewModel(searchFilter);

                if (searchFilter != null)
                {
                    _productFacade = new ProductFacade();
                    ProductSREntity product = _productFacade.GetProduct(searchFilter);

                    if (product != null)
                    {
                        productVM.FromSRStatusId   = product.FromSRStatusId;
                        productVM.ProductGroupId   = product.ProductGroupId;
                        productVM.ProductGroupName = product.ProductGroupName;
                        productVM.ProductId        = product.ProductId;
                        productVM.ProductName      = product.ProductName;
                        productVM.CampaignId       = product.CampaignId;
                        productVM.CampaignName     = product.CampaignName;
                        productVM.TypeId           = product.TypeId;
                        productVM.TypeName         = product.TypeName;
                        productVM.AreaId           = product.AreaId;
                        productVM.AreaName         = product.AreaName;
                        productVM.SubAreaId        = product.SubAreaId;
                        productVM.SubAreaName      = product.SubAreaName;
                        productVM.IsEdit           = product.IsEdit;

                        productVM.CreateUser  = product.CreateUser != null ? product.CreateUser.FullName : "";
                        productVM.CreatedDate = product.CreatedDate.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                        productVM.UpdateDate  = product.Updatedate.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                        productVM.UpdateUser  = product.UpdateUser != null ? product.UpdateUser.FullName : "";

                        toRTStatuses = product.ToSRStatusList.ToDictionary(x => x.SRStatusId.ConvertToString(), x => x.SRStatusName);
                        productVM.ToSRStatusRightList = new MultiSelectList(toRTStatuses, "Key", "Value");

                        foreach (var s in toRTStatuses)
                        {
                            toLFStatuses.RemoveByValue(s.Key);
                        }
                    }
                }
            }

            productVM.FromStatusList      = new SelectList((IEnumerable)fromStatuses, "Key", "Value", string.Empty);
            productVM.ToSRStatusLeftList  = new MultiSelectList(toLFStatuses, "Key", "Value");
            productVM.ToSRStatusRightList = new MultiSelectList(toRTStatuses, "Key", "Value");

            if (productVM.IsEdit == false)
            {
                // default UserLogin
                if (this.UserInfo != null)
                {
                    var today = DateTime.Now;
                    productVM.CreateUser  = this.UserInfo.FullName;
                    productVM.CreatedDate = today.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                    productVM.UpdateDate  = today.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime);
                    productVM.UpdateUser  = this.UserInfo.FullName;
                }
            }


            return(View("~/Views/Product/Edit.cshtml", productVM));
        }
Exemplo n.º 12
0
        public JobTaskResponse GetMailbox(string username, string password)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();
            ThreadContext.Properties["UserID"]        = "CSM_SCHEDTASK";

            _stopwatch = System.Diagnostics.Stopwatch.StartNew();
            _logger.Debug("-- Start Cron Job --:--Get Mailbox--");

            if (!ApplicationHelpers.Authenticate(username, password))
            {
                _logger.DebugFormat("O:--LOGIN--:Error Message/{0}", "Username and/or Password Invalid.");
            }

            _auditLog           = new AuditLogEntity();
            _auditLog.Module    = Constants.Module.Batch;
            _auditLog.Action    = Constants.AuditAction.CreateCommPool;
            _auditLog.IpAddress = ApplicationHelpers.GetClientIP();

            JobTaskResponse taskResponse;
            DateTime        schedDateTime = DateTime.Now;

            try
            {
                _logger.Info("I:--START--:--Get Mailbox--");

                _commPoolFacade = new CommPoolFacade();
                _taskResults    = new List <JobTaskResult>();

                #region "Retrieve Mail Settings"

                string            hostname = WebConfig.GetPOP3EmailServer();
                int               port     = WebConfig.GetPOP3Port();
                bool              useSsl   = WebConfig.GetMailUseSsl();
                List <PoolEntity> poolList = _commPoolFacade.GetActivePoolList();

                #endregion

                if (poolList == null || poolList.Count == 0)
                {
                    const string errorMessage = "Pool list cannot be null or empty";
                    taskResponse = new JobTaskResponse
                    {
                        SchedDateTime  = schedDateTime,
                        StatusResponse = new StatusResponse
                        {
                            Status      = Constants.StatusResponse.Failed,
                            ErrorCode   = string.Empty,
                            Description = errorMessage
                        }
                    };

                    _logger.InfoFormat("O:--FAILED--:Error Message/{0}", errorMessage);
                    _logger.ErrorFormat("Exception occur:\n{0}", errorMessage);
                    AppLog.AuditLog(_auditLog, LogStatus.Fail, errorMessage);
                    return(taskResponse);
                }

                Task.Factory.StartNew(() => Parallel.ForEach(poolList,
                                                             new ParallelOptions {
                    MaxDegreeOfParallelism = WebConfig.GetTotalCountToProcess()
                },
                                                             x =>
                {
                    lock (sync)
                    {
                        var taskResult = _commPoolFacade.AddMailContent(hostname, port, useSsl, x);
                        _taskResults.Add(taskResult);

                        if (taskResult.StatusResponse.Status == Constants.StatusResponse.Success)
                        {
                            AppLog.AuditLog(_auditLog, LogStatus.Success, taskResult.ToString());
                        }
                        else
                        {
                            AppLog.AuditLog(_auditLog, LogStatus.Fail, string.Format(CultureInfo.InvariantCulture, "Username:{0}\n Error:{1}", taskResult.Username, taskResult.StatusResponse.Description));
                        }
                    }
                })).Wait();

                _logger.Info("I:--SUCCESS--:--Get Mailbox--");

                taskResponse = new JobTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    StatusResponse = new StatusResponse
                    {
                        Status = Constants.StatusResponse.Success
                    },
                    JobTaskResults = _taskResults
                };
                return(taskResponse);
            }
            catch (Exception ex)
            {
                taskResponse = new JobTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    StatusResponse = new StatusResponse
                    {
                        Status      = Constants.StatusResponse.Failed,
                        ErrorCode   = string.Empty,
                        Description = ex.Message
                    }
                };
                _logger.InfoFormat("O:--FAILED--:Error Message/{0}", ex.Message);
                _logger.Error("Exception occur:\n", ex);
                AppLog.AuditLog(_auditLog, LogStatus.Fail, ex.Message);
            }
            finally
            {
                _stopwatch.Stop();
                _elapsedTime = _stopwatch.ElapsedMilliseconds;
                _logger.Debug("-- Finish Cron Job --:ElapsedMilliseconds/" + _elapsedTime);
            }

            return(taskResponse);
        }
Exemplo n.º 13
0
        public JobTaskResponse GetMailbox(string username, string password)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();

            if (!string.IsNullOrWhiteSpace(username))
            {
                ThreadContext.Properties["UserID"] = username.ToUpperInvariant();
            }

            _stopwatch = System.Diagnostics.Stopwatch.StartNew();
            _logger.Debug("-- Start Cron Job --:--Get Mailbox--");

            string          errorMessage  = string.Empty;
            JobTaskResponse taskResponse  = null;
            DateTime        schedDateTime = DateTime.Now;

            if (!ApplicationHelpers.Authenticate(username, password))
            {
                errorMessage = "Username and/or Password Invalid.";
                taskResponse = new JobTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    StatusResponse = new StatusResponse
                    {
                        Status      = Constants.StatusResponse.Failed,
                        ErrorCode   = string.Empty,
                        Description = errorMessage
                    }
                };
                _logger.InfoFormat("O:--LOGIN--:Error Message/{0}", errorMessage);
            }

            _auditLog           = new AuditLogEntity();
            _auditLog.Module    = Constants.Module.Batch;
            _auditLog.Action    = Constants.AuditAction.CreateCommPool;
            _auditLog.IpAddress = ApplicationHelpers.GetClientIP();

            try
            {
                #region "BatchProcess Start"

                if (AppLog.BatchProcessStart(Constants.BatchProcessCode.CreateCommPool, schedDateTime) == false)
                {
                    _logger.Info("I:--NOT PROCESS--:--Get Mailbox--");

                    taskResponse = new JobTaskResponse
                    {
                        SchedDateTime  = schedDateTime,
                        StatusResponse = new StatusResponse
                        {
                            Status      = Constants.StatusResponse.NotProcess,
                            ErrorCode   = string.Empty,
                            Description = string.Empty
                        }
                    };

                    return(taskResponse);
                }

                #endregion

                _logger.Info("I:--START--:--Get Mailbox--");

                _commPoolFacade = new CommPoolFacade();
                _taskResults    = new List <JobTaskResult>();

                #region "Retrieve Mail Settings"

                string            hostname = WebConfig.GetPOP3EmailServer();
                int               port     = WebConfig.GetPOP3Port();
                bool              useSsl   = WebConfig.GetMailUseSsl();
                List <PoolEntity> poolList = _commPoolFacade.GetActivePoolList();

                #endregion

                if (poolList == null || poolList.Count == 0)
                {
                    errorMessage = "Pool list cannot be null or empty";
                    taskResponse = new JobTaskResponse
                    {
                        SchedDateTime  = schedDateTime,
                        StatusResponse = new StatusResponse
                        {
                            Status      = Constants.StatusResponse.Failed,
                            ErrorCode   = string.Empty,
                            Description = errorMessage
                        }
                    };

                    _logger.InfoFormat("O:--FAILED--:Error Message/{0}", errorMessage);
                    _logger.ErrorFormat("Exception occur:\n{0}", errorMessage);
                    AppLog.AuditLog(_auditLog, LogStatus.Fail, errorMessage);
                    return(taskResponse);
                }

                Task.Factory.StartNew(() => Parallel.ForEach(poolList,
                                                             new ParallelOptions {
                    MaxDegreeOfParallelism = WebConfig.GetTotalCountToProcess()
                },
                                                             x =>
                {
                    lock (sync)
                    {
                        var stopwatch = new System.Diagnostics.Stopwatch();
                        stopwatch.Start();

                        var taskDateTime         = DateTime.Now;
                        var taskResult           = _commPoolFacade.AddMailContent(hostname, port, useSsl, x);
                        taskResult.SchedDateTime = taskDateTime;

                        if (taskResult.StatusResponse.Status == Constants.StatusResponse.Success)
                        {
                            AppLog.AuditLog(_auditLog, LogStatus.Success, taskResult.ToString());
                        }
                        if (taskResult.StatusResponse.Status == Constants.StatusResponse.Failed)
                        {
                            if (taskResult.NumFailedDelete == 0)
                            {
                                AppLog.AuditLog(_auditLog, LogStatus.Fail, string.Format(CultureInfo.InvariantCulture, "Username:{0}\n Error:{1}", taskResult.Username, taskResult.StatusResponse.Description));
                            }
                            if (taskResult.NumFailedDelete > 0)
                            {
                                AppLog.AuditLog(_auditLog, LogStatus.Fail, taskResult.ToString());
                            }
                        }

                        stopwatch.Stop();
                        taskResult.ElapsedTime = stopwatch.ElapsedMilliseconds;
                        _taskResults.Add(taskResult);
                    }
                })).Wait();

                _logger.Info("O:--SUCCESS--:--Get Mailbox--");

                taskResponse = new JobTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    StatusResponse = new StatusResponse
                    {
                        Status = Constants.StatusResponse.Success
                    },
                    JobTaskResults = _taskResults
                };

                return(taskResponse);
            }
            catch (Exception ex)
            {
                taskResponse = new JobTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    StatusResponse = new StatusResponse
                    {
                        Status      = Constants.StatusResponse.Failed,
                        ErrorCode   = string.Empty,
                        Description = ex.Message
                    }
                };

                _logger.InfoFormat("O:--FAILED--:Error Message/{0}", ex.Message);
                _logger.Error("Exception occur:\n", ex);
                AppLog.AuditLog(_auditLog, LogStatus.Fail, ex.Message);
                return(taskResponse);
            }
            finally
            {
                _stopwatch.Stop();
                _elapsedTime = _stopwatch.ElapsedMilliseconds;
                _logger.Debug("-- Finish Cron Job --:ElapsedMilliseconds/" + _elapsedTime);

                #region "BatchProcess End"

                if (taskResponse != null && taskResponse.StatusResponse != null &&
                    taskResponse.StatusResponse.Status != Constants.StatusResponse.NotProcess)
                {
                    var batchStatus  = Constants.BatchProcessStatus.Fail;
                    var batchDetails = string.Empty;
                    if (taskResponse.StatusResponse.Status == Constants.StatusResponse.Success)
                    {
                        batchStatus =
                            taskResponse.JobTaskResults.Any(
                                x => x.StatusResponse.Status != Constants.StatusResponse.Success)
                                ? Constants.BatchProcessStatus.Fail
                                : Constants.BatchProcessStatus.Success;

                        //batchDetails = StringHelpers.ConvertListToString(taskResponse.JobTaskResults.Select(x => x.ToString()).ToList<object>(), "\n");

                        if (taskResponse.JobTaskResults != null && taskResponse.JobTaskResults.Count > 0)
                        {
                            foreach (var taskResult in taskResponse.JobTaskResults)
                            {
                                if (taskResult.StatusResponse.Status == Constants.StatusResponse.Success)
                                {
                                    batchDetails += taskResult.ToString() + "\n\n";
                                }

                                if (taskResult.StatusResponse.Status == Constants.StatusResponse.Failed)
                                {
                                    if (taskResult.NumFailedDelete == 0)
                                    {
                                        batchDetails += string.Format(CultureInfo.InvariantCulture, "Username:{0}\n Error:{1} \n\n", taskResult.Username, taskResult.StatusResponse.Description);
                                    }
                                    else
                                    {
                                        batchDetails += taskResult.ToString() + "\n\n";
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        batchDetails = taskResponse.StatusResponse.Description;
                    }

                    DateTime endTime     = taskResponse.SchedDateTime.AddMilliseconds(_elapsedTime);
                    TimeSpan processTime = endTime.Subtract(taskResponse.SchedDateTime);

                    AppLog.BatchProcessEnd(Constants.BatchProcessCode.CreateCommPool, batchStatus, endTime, processTime, batchDetails);
                }

                #endregion

                // Send mail to system administrator
                ImportJobSendMail(taskResponse);
            }
        }
Exemplo n.º 14
0
        public ActionResult JobList(CommPoolSearchFilter searchFilter)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitSearch Job")
                        .Add("FirstName", searchFilter.FirstName).Add("LastName", searchFilter.LastName));

            try
            {
                _commonFacade = new CommonFacade();
                int?monthOfReportExport = _commonFacade.GetCacheParamByName(Constants.ParameterName.ReportExportDate).ParamValue.ToNullable <int>();

                #region "Validation"

                if (!string.IsNullOrWhiteSpace(searchFilter.FirstName) &&
                    searchFilter.FirstName.ExtractString().Length < Constants.MinLenght.SearchTerm)
                {
                    ModelState["FirstName"].Errors.Clear();
                    ModelState["FirstName"].Errors.Add(string.Format(CultureInfo.InvariantCulture, Resource.ValErr_MinLength, Constants.MinLenght.SearchTerm));
                }

                if (!string.IsNullOrWhiteSpace(searchFilter.LastName) &&
                    searchFilter.LastName.ExtractString().Length < Constants.MinLenght.SearchTerm)
                {
                    ModelState["LastName"].Errors.Clear();
                    ModelState["LastName"].Errors.Add(string.Format(CultureInfo.InvariantCulture, Resource.ValErr_MinLength, Constants.MinLenght.SearchTerm));
                }

                bool isValid = TryUpdateModel(searchFilter);

                if (!string.IsNullOrEmpty(searchFilter.DateFrom) && !searchFilter.DateFromValue.HasValue)
                {
                    isValid = false;
                    ModelState.AddModelError("txtFromDate", Resource.ValErr_InvalidDate);
                }
                else if (searchFilter.DateFromValue.HasValue)
                {
                    if (searchFilter.DateFromValue.Value > DateTime.Now.Date)
                    {
                        isValid = false;
                        ModelState.AddModelError("txtFromDate", Resource.ValErr_InvalidDate_MustLessThanToday);
                    }
                }

                if (!string.IsNullOrEmpty(searchFilter.DateTo) && !searchFilter.DateToValue.HasValue)
                {
                    isValid = false;
                    ModelState.AddModelError("txtToDate", Resource.ValErr_InvalidDate);
                }
                else if (searchFilter.DateToValue.HasValue)
                {
                    if (searchFilter.DateToValue.Value > DateTime.Now.Date)
                    {
                        isValid = false;
                        ModelState.AddModelError("txtToDate", Resource.ValErr_InvalidDate_MustLessThanToday);
                    }
                }

                if (searchFilter.DateFromValue.HasValue && searchFilter.DateToValue.HasValue &&
                    searchFilter.DateFromValue.Value > searchFilter.DateToValue.Value)
                {
                    isValid = false;
                    ModelState.AddModelError("dvDateRange", Resource.ValErr_InvalidDateRange);
                }

                // ActionDate
                if (!string.IsNullOrEmpty(searchFilter.DateFrom) && string.IsNullOrEmpty(searchFilter.DateTo))
                {
                    isValid = false;
                    ModelState.AddModelError("txtToDate", Resource.ValErr_Required);
                }
                if (string.IsNullOrEmpty(searchFilter.DateFrom) && !string.IsNullOrEmpty(searchFilter.DateTo))
                {
                    isValid = false;
                    ModelState.AddModelError("txtFromDate", Resource.ValErr_Required);
                }

                if (!string.IsNullOrEmpty(searchFilter.DateFrom) && !string.IsNullOrEmpty(searchFilter.DateTo))
                {
                    if (searchFilter.DateToValue.Value > searchFilter.DateFromValue.Value.AddMonths(monthOfReportExport.Value))
                    {
                        isValid = false;
                        ModelState.AddModelError("dvDateRange", string.Format(CultureInfo.InvariantCulture, Resource.ValError_ReportExportDuration, monthOfReportExport.Value));
                    }
                }

                #endregion

                if (isValid)
                {
                    _commPoolFacade = new CommPoolFacade();
                    JobViewModel jobVM = new JobViewModel();
                    jobVM.SearchFilter          = searchFilter;
                    jobVM.SearchFilter.User     = this.UserInfo;
                    jobVM.CommunicationPoolList = _commPoolFacade.SearchJobs(searchFilter);
                    ViewBag.PageSize            = jobVM.SearchFilter.PageSize;
                    ViewBag.PageSizeList        = _commonFacade.GetPageSizeList();

                    return(PartialView("~/Views/Job/_JobList.cshtml", jobVM));
                }

                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitSearch Job").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Exemplo n.º 15
0
        public ActionResult InitEdit(int?jobId = null)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Job").Add("JobId", jobId).ToInputLogString());

            try
            {
                JobViewModel jobVM = null;

                if (TempData["jobVM"] != null)
                {
                    jobVM = (JobViewModel)TempData["jobVM"];
                }
                else
                {
                    jobVM = new JobViewModel {
                        JobId = jobId
                    };
                }

                if (jobVM.JobId != null)
                {
                    _commPoolFacade = new CommPoolFacade();
                    CommunicationPoolEntity commPoolEntity = _commPoolFacade.GetJob(jobVM.JobId.Value);

                    jobVM.Sender        = commPoolEntity.SenderAddress;
                    jobVM.Subject       = commPoolEntity.Subject;
                    jobVM.StatusDisplay = commPoolEntity.StatusDisplay;
                    jobVM.SequenceNo    = commPoolEntity.SequenceNo;
                    jobVM.Content       = commPoolEntity.Content;
                    jobVM.CreatedDate   = commPoolEntity.CreateDateDisplay;
                    jobVM.UpdatedDate   = commPoolEntity.UpdateDateDisplay;
                    jobVM.Remark        = commPoolEntity.Remark;
                    jobVM.JobStatus     = commPoolEntity.Status;

                    if (commPoolEntity.UpdateUser != null)
                    {
                        jobVM.ActionBy = commPoolEntity.UpdateUser.FullName;
                    }

                    if (commPoolEntity.ChannelEntity != null)
                    {
                        jobVM.Channel = commPoolEntity.ChannelEntity.Name;
                    }

                    //SR
                    if (commPoolEntity.ServiceRequest != null)
                    {
                        jobVM.SrNo          = commPoolEntity.ServiceRequest.SrNo;
                        jobVM.SR_Status     = commPoolEntity.ServiceRequest.Status;
                        jobVM.SrSubject     = commPoolEntity.ServiceRequest.Subject;
                        jobVM.SrRemark      = commPoolEntity.ServiceRequest.Remark;
                        jobVM.SrChannel     = commPoolEntity.ServiceRequest.ChannelName;
                        jobVM.SrMediaSource = commPoolEntity.ServiceRequest.MediaSourceName;
                        jobVM.SrCreateDate  = commPoolEntity.ServiceRequest.CreateDateDisplay;

                        if (commPoolEntity.ServiceRequest.CreateUser != null)
                        {
                            jobVM.SrCreateUser = commPoolEntity.ServiceRequest.CreateUser.FullName;
                        }

                        if (commPoolEntity.ServiceRequest.Owner != null)
                        {
                            jobVM.SrOwner = commPoolEntity.ServiceRequest.Owner.FullName;
                        }

                        if (commPoolEntity.ServiceRequest.Delegator != null)
                        {
                            jobVM.SrDelegator = commPoolEntity.ServiceRequest.Delegator.FullName;
                        }

                        if (commPoolEntity.ServiceRequest.UpdateUser != null)
                        {
                            jobVM.SrUpdateUser = commPoolEntity.ServiceRequest.UpdateUser.FullName;
                        }

                        if (commPoolEntity.ServiceRequest.Customer != null)
                        {
                            //Customer
                            jobVM.FirstNameThai    = commPoolEntity.ServiceRequest.Customer.FirstNameThai;
                            jobVM.LastNameThai     = commPoolEntity.ServiceRequest.Customer.LastNameThai;
                            jobVM.FirstNameEnglish = commPoolEntity.ServiceRequest.Customer.FirstNameEnglish;
                            jobVM.LastNameEnglish  = commPoolEntity.ServiceRequest.Customer.LastNameEnglish;
                        }

                        if (commPoolEntity.ServiceRequest.ProductMapping != null)
                        {
                            jobVM.ProductGroup = commPoolEntity.ServiceRequest.ProductMapping.ProductGroupName;
                            jobVM.Product      = commPoolEntity.ServiceRequest.ProductMapping.ProductName;
                            jobVM.Type         = commPoolEntity.ServiceRequest.ProductMapping.TypeName;
                            jobVM.SubArea      = commPoolEntity.ServiceRequest.ProductMapping.SubAreaName;
                        }
                    }

                    // Attachments
                    jobVM.Attachments = commPoolEntity.Attachments;
                }

                return(View("~/Views/Job/Edit.cshtml", jobVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Job").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }