Exemple #1
0
        public ExportFileResponse ExportFile(ExportFileRequest request)
        {
            string   methodName = $"{nameof(DoNotCallBatchProcess)}.{nameof(ExportFile)}";
            var      response   = new ExportFileResponse();
            DateTime startTime  = DateTime.Now;

            response.StartTime = startTime;
            try
            {
                if (request == null || request.Header == null)
                {
                    throw new NullReferenceException($"{methodName}: Request/Header is null!");
                }
                var requestHeader = request.Header;

                response.Header = GetResponseHeader(requestHeader, methodName);
                // Set batch process status
                if (AppLog.BatchProcessStart(Constants.BatchProcessCode.ExportDoNotCallUpdateFile, startTime) == false)
                {
                    return(SetUnprocessResponse(response, methodName));
                }

                // Authenticate user
                if (!ValidateServiceRequest(request.Header))
                {
                    return(SetInvalidLoginResponse(response));
                }

                _logger.DebugFormat("-- XMLRequest --\n{0}", request.SerializeObject());

                // Export
                ExportUpdateData(response);

                return(SetSuccessResponse(response));
            }
            catch (Exception ex)
            {
                DateTime errorTime = DateTime.Now;
                response    = SetErrorResponse(response, ex);
                _mailSender = CSMMailSender.GetCSMMailSender();
                _mailSender.NotifyFailExportDoNotCall(response.StartTime, errorTime, response.ElapsedTime, response.Error, response.ExportDataCount);

                return(response);
            }
            finally
            {
                UpdateBatchProcessStatus(response);
                //Insert Audit Log
                bool   success = response.ResultStatus == Constants.StatusResponse.Success;
                string detail  = !string.IsNullOrWhiteSpace(response.Error) ? response.Error : response.Description;
                InsertAuditLog(methodName, success, detail ?? response.ResultStatus);
            }
        }
Exemple #2
0
        /// <summary>
        /// Batch Process
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public ReSubmitActivityToCBSHPSystemTaskResponse ReSubmitActivityToCBSHPSystem(string username, string password)
        {
            ThreadContext.Properties["EventClass"]    = ApplicationHelpers.GetCurrentMethod(1);
            ThreadContext.Properties["RemoteAddress"] = ApplicationHelpers.GetClientIP();
            //ThreadContext.Properties["UserID"] = "CSM_SCHEDTASK";
            if (!string.IsNullOrWhiteSpace(username))
            {
                ThreadContext.Properties["UserID"] = username.ToUpperInvariant();
            }

            long     elapsedTime   = 0;
            string   errorMessage  = string.Empty;
            DateTime schedDateTime = DateTime.Now;
            ReSubmitActivityToCBSHPSystemTaskResponse taskResponse = null;

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

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

            #region "BatchProcess Start"

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

                stopwatch.Stop();
                elapsedTime = stopwatch.ElapsedMilliseconds;
                _logger.Debug("-- Finish Cron Job --:ElapsedMilliseconds/" + elapsedTime);

                taskResponse = new ReSubmitActivityToCBSHPSystemTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    ElapsedTime    = elapsedTime,
                    StatusResponse = new CSM.Service.Messages.Common.StatusResponse
                    {
                        Status = Constants.StatusResponse.NotProcess
                    }
                };

                return(taskResponse);
            }

            #endregion

            //_logger.Debug("-- Start Cron Job --:--Get ReSubmitActivityToCBSHPSystem--");

            if (!ApplicationHelpers.Authenticate(username, password))
            {
                errorMessage = "Username and/or Password Invalid.";
                taskResponse = new ReSubmitActivityToCBSHPSystemTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    StatusResponse = new CSM.Service.Messages.Common.StatusResponse
                    {
                        Status      = Constants.StatusResponse.Failed,
                        ErrorCode   = string.Empty,
                        Description = errorMessage
                    }
                };

                _logger.InfoFormat("O:--LOGIN--:Error Message/{0}", errorMessage);
                //AppLog.AuditLog(_auditLog, LogStatus.Fail, "Username and/or Password Invalid.");
                return(taskResponse);
            }

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

                #region "Process Batch"

                var countSuccess = 0;
                var countError   = 0;

                _srFacade = new ServiceRequestFacade();
                _srFacade.ReSubmitActivityToCBSHPSystem(ref countSuccess, ref countError);

                #endregion

                _logger.Info("O:--SUCCESS--:--ReSubmitActivityToCBSHPSystem--");

                stopwatch.Stop();
                elapsedTime = stopwatch.ElapsedMilliseconds;
                _logger.Debug("-- Finish Cron Job --:ElapsedMilliseconds/" + elapsedTime);

                StringBuilder taskResult = new StringBuilder("");
                taskResult.Append(string.Format("Username = {0}\n", username));
                taskResult.Append(string.Format("SchedDateTime = {0}\n", schedDateTime));
                taskResult.Append(string.Format("ElapsedTime = {0}\n", elapsedTime));
                taskResult.Append(string.Format("Count Success = {0}\n", countSuccess));
                taskResult.Append(string.Format("Count Error = {0}\n", countError));
                taskResult.Append(string.Format("Total = {0}\n", countSuccess + countError));

                AppLog.AuditLog(_auditLog, ((countError > 0) ? LogStatus.Fail : LogStatus.Success), taskResult.ToString());

                taskResponse = new ReSubmitActivityToCBSHPSystemTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    ElapsedTime    = elapsedTime,
                    StatusResponse = new CSM.Service.Messages.Common.StatusResponse
                    {
                        Status = (countError > 0) ? Constants.StatusResponse.Failed : Constants.StatusResponse.Success
                    },
                    NumOfComplete = countSuccess,
                    NumOfError    = countError,
                    NumOfTotal    = countSuccess + countError
                };

                return(taskResponse);
            }
            catch (Exception ex)
            {
                _logger.InfoFormat("O:--FAILED--:--ReSubmitActivityToCBSHPSystem--:--Error Message/{0}", ex.Message);
                _logger.Error("Exception occur:\n", ex);

                stopwatch.Stop();
                elapsedTime = stopwatch.ElapsedMilliseconds;
                _logger.Debug("-- Finish Cron Job --:ElapsedMilliseconds/" + elapsedTime);

                AppLog.AuditLog(_auditLog, LogStatus.Fail, ex.Message);

                taskResponse = new ReSubmitActivityToCBSHPSystemTaskResponse
                {
                    SchedDateTime  = schedDateTime,
                    ElapsedTime    = elapsedTime,
                    StatusResponse = new CSM.Service.Messages.Common.StatusResponse
                    {
                        Status      = Constants.StatusResponse.Failed,
                        ErrorCode   = string.Empty,
                        Description = "Failed to ReSubmitActivityToCBSHPSystem"
                    }
                };

                return(taskResponse);
            }
            finally
            {
                // Send mail to system administrator
                ReSubmitActivityToCBSHPSendMail(taskResponse);

                #region "BatchProcess End"

                if (taskResponse != null && taskResponse.StatusResponse != null &&
                    taskResponse.StatusResponse.Status != Constants.StatusResponse.NotProcess)
                {
                    int batchStatus = (taskResponse.StatusResponse.Status == Constants.StatusResponse.Success)
                        ? Constants.BatchProcessStatus.Success
                        : Constants.BatchProcessStatus.Fail;

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

                    string processDetail = !string.IsNullOrEmpty(taskResponse.StatusResponse.Description)
                       ? taskResponse.StatusResponse.Description
                       : taskResponse.ToString();

                    AppLog.BatchProcessEnd(Constants.BatchProcessCode.ReSubmitActivityToCBSHPSystem, batchStatus, endTime, processTime, processDetail);
                }

                #endregion
            }
        }
Exemple #3
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);
            }
        }