예제 #1
0
        public IEnumerable <ActivityDataItem> GetActivityLogList(AuditLogEntity auditLog, ActivitySearchFilter searchFilter)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Call CARLogService.InquiryActivityLog").ToInputLogString());

            var resActivity = InquiryActivityLog(auditLog, searchFilter);

            if (resActivity == null || resActivity.ActivityDataItems == null)
            {
                return(null);
            }

            // var activities = resActivity.ActivityDataItems.Where(x => x.SubscriptionID == searchFilter.CardNo).ToList();
            var activities = resActivity.ActivityDataItems.ToList();

            int startPageIndex = (searchFilter.PageNo - 1) * searchFilter.PageSize;

            searchFilter.TotalRecords = activities.Count();
            if (startPageIndex >= searchFilter.TotalRecords)
            {
                startPageIndex      = 0;
                searchFilter.PageNo = 1;
            }

            var sortResult = SetActivityListSort(activities, searchFilter);

            return(sortResult.Skip(startPageIndex).Take(searchFilter.PageSize));
        }
예제 #2
0
        private static void Add(AuditLogEntity log, SqlTransaction trans, SqlConnection conn)
        {
            const string insertSql = @"INSERT INTO dbo.t_Logs
                                ( ZoneTableId ,
                                  LogLevel ,
                                  LogTime ,
                                  LogOperator ,
                                  IP ,
                                  Detail ,
                                  Remark
                                )
                        VALUES  ( @zoneTableId ,
                                  @logLevel ,
                                  @logTime ,
                                  @operator ,
                                  @ip , 
                                  @detail ,
                                  N''
                                )";
            var          cmd       = new SqlCommand(insertSql, conn, trans);

            cmd.Parameters.AddWithValue("@zoneTableId", log.ZoneTableID);
            cmd.Parameters.AddWithValue("@logLevel", log.LogType);
            cmd.Parameters.AddWithValue("@operator", log.LogOperator);
            cmd.Parameters.AddWithValue("@logTime", log.LogTime);
            cmd.Parameters.AddWithValue("@ip", log.IP);
            cmd.Parameters.AddWithValue("@detail", log.Detail);

            cmd.ExecuteNonQuery();
        }
예제 #3
0
        public void AddLog(AuditLogEntity auditlog)
        {
            _context.Configuration.AutoDetectChangesEnabled = false;

            try
            {
                TB_L_AUDIT_LOG dbAuditLog = new TB_L_AUDIT_LOG
                {
                    MODULE      = auditlog.Module,
                    ACTION      = auditlog.Action,
                    IP_ADDRESS  = auditlog.IpAddress,
                    STATUS      = (short)auditlog.Status,
                    DETAIL      = auditlog.Detail,
                    CREATE_DATE = DateTime.Now,
                    CREATE_USER = auditlog.CreateUserId
                };

                _context.TB_L_AUDIT_LOG.Add(dbAuditLog);
                Save();
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
            }
            finally
            {
                _context.Configuration.AutoDetectChangesEnabled = true;
            }
        }
예제 #4
0
        public void LogOperation(IEntity entity, LogOperationType operationType, int?userId = null)
        {
            if (entity != null && entity.GetType().GetCustomAttribute <AuditLogAttribute>() == null)
            {
                return;
            }

            var entityJson = operationType is (LogOperationType.Modify or LogOperationType.Create) && entity != null
                ? JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
            {
                ContractResolver      = new CustomJsonContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            })
                : null;

            var logUserId = userId ?? _appContext.UserId;
            var auditLog  = new AuditLogEntity
            {
                User                = logUserId.HasValue ? _session.Load <UserEntity>(logUserId.Value) : null,
                OperationType       = operationType,
                RelatedEntityId     = entity?.Id,
                RelatedEntityJson   = entityJson,
                CreationDateUtc     = DateTime.UtcNow,
                ModificationDateUtc = DateTime.UtcNow
            };

            _session.Save(auditLog);
        }
        public bool OpenRateLimit(string url, int threshold, int period, out AuditLogEntity errorLog)
        {
            var zoneTableId = ZoneBusiness.GetZoneByZoneId(_zoneId).TableID;

            errorLog = null;
            var ratelimit = GetRateLimitRule(url, threshold, period);

            if (null != ratelimit)
            {
                ratelimit.Disabled = false;
                var response = UpdateRateLimit(ratelimit);
                if (!response.success)
                {
                    errorLog = new AuditLogEntity(zoneTableId, LogLevel.Error,
                                                  $"Open rate limiting rule of Cloudflare failure,the reason is:[{(null != response.errors && response.errors.Length > 0 ? response.errors[0].message : "No error message from Cloudflare.")}].<br />");
                }
                return(response.success);
            }
            else
            {
                var response = CreateRateLimit(new CloudflareRateLimitRule(url, threshold, period, $"[Auto Prevention] {url}"));
                if (!response.success)
                {
                    errorLog = new AuditLogEntity(zoneTableId, LogLevel.Error,
                                                  $"Create rate limiting rule of Cloudflare failure,the reason is:[{(response.errors !=null && response.errors .Length > 0 ? response.errors[0].message : "No error message from Cloudflare.")}].<br />");
                }
                return(response.success);
            }
        }
예제 #6
0
        public bool OpenRateLimit(string url, int threshold, int period, out AuditLogEntity errorLog)
        {
            errorLog = null;
            var ratelimit = GetRateLimitRule(url, threshold, period);

            if (null != ratelimit)
            {
                ratelimit.Disabled = false;
                var response = UpdateRateLimit(ratelimit);
                if (!response.success)
                {
                    errorLog = new AuditLogEntity(_zoneId, LogLevel.Error, string.Format("Open rate limiting rule of Cloudflare failure,the reason is:[{0}].<br />", response.errors.Count() > 0 ? response.errors[0].message : "No error message from Cloudflare."));
                }
                return(response.success);
            }
            else
            {
                var response = CreateRateLimit(new CloudflareRateLimitRule(url, threshold, period));
                if (!response.success)
                {
                    errorLog = new AuditLogEntity(_zoneId, LogLevel.Error, string.Format("Create rate limiting rule of Cloudflare failure,the reason is:[{0}].<br />", response.errors.Count() > 0 ? response.errors[0].message : "No error message from Cloudflare."));
                }
                return(response.success);
            }
        }
예제 #7
0
파일: HpFacade.cs 프로젝트: KKPBank/CSM
        public bool SaveServiceRequestActivity()
        {
            _hpDataAccess = new HpDataAccess(_context);
            var lstSrActivity = _hpDataAccess.GetSrWithHpActivity();

            if (lstSrActivity != null && lstSrActivity.Count > 0)
            {
                var auditLog = new AuditLogEntity();
                auditLog.Module    = Constants.Module.Batch;
                auditLog.Action    = Constants.AuditAction.SubmitActivityToCARSystem;
                auditLog.IpAddress = ApplicationHelpers.GetClientIP();

                _srFacade = new ServiceRequestFacade();
                foreach (var sr in lstSrActivity)
                {
                    // TODO :: Add new parameter: AuditLogEntity for Call CAR Web Service
                    _srFacade.CreateServiceRequestActivity(auditLog, sr, true);
                    //if (result.IsSuccess == false)
                    //{
                    //    Logger.Debug(string.Format("CreateServiceRequestActivity SrId:{0} ErrorMessage:{1} WarningMessages:{2} "
                    //        , sr.SrId.Value.ToString(), result.ErrorMessage, result.WarningMessages));
                    //}
                }
            }

            return(true);
        }
예제 #8
0
        public UpdateCampaignFlagsResponse SaveCampaignFlags(AuditLogEntity auditLog, string cardNo, CampaignSearchFilter searchFilter)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Call CmtService.UpdateCustomerFlags").Add("CardNo", cardNo.MaskCardNo())
                        .Add("HasOffered", searchFilter.HasOffered).Add("IsInterested", searchFilter.IsInterested)
                        .Add("UpdatedBy", searchFilter.UpdatedBy).ToInputLogString());

            return(UpdateCampaignFlagsByCustomer(auditLog, cardNo, searchFilter));
        }
예제 #9
0
        public Ticket CreateLead(AuditLogEntity auditLog, CampaignSearchFilter searchFilter)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Call LeadService.InsertLead").Add("CampaignId", searchFilter.CampaignId)
                        .Add("FirstName", searchFilter.FirstName).Add("LastName", searchFilter.LastName).Add("PhoneNo", searchFilter.PhoneNo)
                        .Add("Email", searchFilter.Email).ToInputLogString());

            return(InsertLead(auditLog, searchFilter));
        }
예제 #10
0
        public async Task AddAsync(AuditLog model)
        {
            var entity = AuditLogEntity.Create(model);

            using (var context = _contextFactory.CreateDataContext())
            {
                context.AuditLogs.Add(entity);
                await context.SaveChangesAsync();
            }
        }
예제 #11
0
        private void InsertAuditLog(string action, bool success, string detail = null)
        {
            var auditLog = new AuditLogEntity
            {
                Module    = "DoNotCall",
                Action    = action,
                IpAddress = ApplicationHelpers.GetClientIP(),
                Status    = success ? LogStatus.Success : LogStatus.Fail,
                Detail    = detail,
            };

            AppLog.AuditLog(auditLog);
        }
예제 #12
0
        private AuditLogEntity MapCompanyModelToNewEntity(Guid?organisationId, AuditLog model)
        {
            var entity = new AuditLogEntity(organisationId);

            entity.UserId   = model.UserId.HasValue ? model.UserId.ToString() : "";
            entity.BranchId = model.BranchId.HasValue ? model.BranchId.ToString() : "";
            entity.Action   = model.Action;
            entity.Entity   = model.Entity;
            entity.EntityId = model.EntityId;
            entity.Data     = JsonSerializer.Serialize(model.Data);

            return(entity);
        }
예제 #13
0
        public ComputerController()
        {
            _computerService = new ComputerServices();
            _auditLogService = new AuditLogServices();
            _userId          = Convert.ToInt32(((ClaimsIdentity)User.Identity).Claims.Where(c => c.Type == "user_id")
                                               .Select(c => c.Value).SingleOrDefault());
            _auditLog            = new AuditLogEntity();
            _auditLog.ObjectType = "Computer";
            _auditLog.UserId     = _userId;
            var user = new UserServices().GetUser(_userId);

            if (user != null)
            {
                _auditLog.UserName = user.Name;
            }
        }
예제 #14
0
            public async Task Handle(Notification notification, CancellationToken cancellationToken)
            {
                var entity = AuditLogEntity
                             .New(notification.Identity.TenantId);

                var requestType = notification.Request.GetType();

                entity.Action  = requestType.DeclaringType?.Name ?? requestType.FullName;
                entity.Request = JsonConvert.SerializeObject(notification.Request.AuditRecord);
                if (notification.Result != null)
                {
                    entity.Response = notification.Result.Success == true ? "OK" : notification.Result.Message;
                }

                await _logTable.InsertAsync(entity);
            }
예제 #15
0
        public static void Add(AuditLogEntity item)
        {
            if (item.ZoneTableID == 0)
            {
                item.ZoneTableID = ZoneAccess.GetZoneByZoneId(item.ZoneID).TableID;
            }
            try
            {
                var cons = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

                using (var conn = new SqlConnection(cons))
                {
                    const string query = @"INSERT INTO dbo.t_Logs
                                ( ZoneTableId ,
                                  LogLevel ,
                                  LogTime ,
                                  LogOperator ,
                                  IP ,
                                  Detail ,
                                  Remark
                                )
                        VALUES  ( @zoneTableId , 
                                  @logLevel ,
                                  @logTime ,
                                  @operator , 
                                  @ip ,
                                  @detail , 
                                  N''
                                )";
                    var          cmd   = new SqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@zoneTableId", item.ZoneTableID);
                    cmd.Parameters.AddWithValue("@logLevel", item.LogType);
                    cmd.Parameters.AddWithValue("@operator", item.LogOperator);
                    cmd.Parameters.AddWithValue("@logTime", item.LogTime);
                    cmd.Parameters.AddWithValue("@ip", item.IP);
                    cmd.Parameters.AddWithValue("@detail", item.Detail);
                    conn.Open();

                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error when adding new log, error message:{ex.Message} \n stack trace:{ex.StackTrace}");
            }
        }
예제 #16
0
파일: AFSFacade.cs 프로젝트: KKPBank/CSM
        public void SaveLogExportMarketingError(ExportNCBTaskResponse taskResponse)
        {
            if (taskResponse != null)
            {
                StringBuilder sb = new StringBuilder("");
                sb.AppendFormat("Error Message = {0}\n", taskResponse.StatusResponse.Description);

                _auditLog              = new AuditLogEntity();
                _auditLog.Module       = Constants.Module.Batch;
                _auditLog.Action       = Constants.AuditAction.ExportMarketing;
                _auditLog.IpAddress    = ApplicationHelpers.GetClientIP();
                _auditLog.Status       = LogStatus.Fail;
                _auditLog.Detail       = sb.ToString();
                _auditLog.CreateUserId = null;
                _auditLog.CreatedDate  = taskResponse.SchedDateTime;
                AppLog.AuditLog(_auditLog);
            }
        }
예제 #17
0
파일: AFSFacade.cs 프로젝트: KKPBank/CSM
        public void SaveLogExportMarketingSuccess(ExportNCBTaskResponse taskResponse)
        {
            if (taskResponse != null)
            {
                StringBuilder sb = new StringBuilder("");
                sb.Append("Success to export marketing\n");
                sb.Append(taskResponse.ToString());

                _auditLog              = new AuditLogEntity();
                _auditLog.Module       = Constants.Module.Batch;
                _auditLog.Action       = Constants.AuditAction.ExportMarketing;
                _auditLog.IpAddress    = ApplicationHelpers.GetClientIP();
                _auditLog.Status       = LogStatus.Success;
                _auditLog.Detail       = sb.ToString();
                _auditLog.CreateUserId = null;
                _auditLog.CreatedDate  = taskResponse.SchedDateTime;
                AppLog.AuditLog(_auditLog);
            }
        }
예제 #18
0
파일: HpFacade.cs 프로젝트: KKPBank/CSM
        public void SaveLogSuccessOrFail(ImportHpTaskResponse taskResponse)
        {
            if (taskResponse != null)
            {
                StringBuilder sb = new StringBuilder("");
                sb.AppendFormat("วัน เวลาที่ run task scheduler = {0}\n",
                                taskResponse.SchedDateTime.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime));
                sb.AppendFormat("ElapsedTime = {0} (ms)\n", taskResponse.ElapsedTime);
                sb.Append(taskResponse.ToString());

                _auditLog           = new AuditLogEntity();
                _auditLog.Module    = Constants.Module.Batch;
                _auditLog.Action    = Constants.AuditAction.ImportHP;
                _auditLog.IpAddress = ApplicationHelpers.GetClientIP();
                _auditLog.Status    = (taskResponse.StatusResponse.Status == Constants.StatusResponse.Failed) ? LogStatus.Fail : LogStatus.Success;
                _auditLog.Detail    = sb.ToString();
                AppLog.AuditLog(_auditLog);
            }
        }
예제 #19
0
파일: AFSFacade.cs 프로젝트: KKPBank/CSM
        public void SaveLogError(ImportAFSTaskResponse taskResponse)
        {
            if (taskResponse != null)
            {
                StringBuilder sb = new StringBuilder("");
                sb.AppendFormat("วัน เวลาที่ run task scheduler = {0}\n",
                                taskResponse.SchedDateTime.FormatDateTime(Constants.DateTimeFormat.DefaultFullDateTime));
                sb.AppendFormat("ElapsedTime = {0} (ms)\n", taskResponse.ElapsedTime);
                sb.AppendFormat("Error Message = {0}\n", taskResponse.StatusResponse.Description);

                _auditLog              = new AuditLogEntity();
                _auditLog.Module       = Constants.Module.Batch;
                _auditLog.Action       = Constants.AuditAction.ImportAFS;
                _auditLog.IpAddress    = ApplicationHelpers.GetClientIP();
                _auditLog.Status       = LogStatus.Fail;
                _auditLog.Detail       = sb.ToString();
                _auditLog.CreateUserId = null;
                AppLog.AuditLog(_auditLog);
            }
        }
예제 #20
0
        public List <CampaignDetail> GetCampaignListByCustomer(AuditLogEntity auditLog, string cardNo, string hasOffered,
                                                               string isInterested, string customerFlag, int campaignNum)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Call CmtService.GetCampaignByCustomers").Add("CardNo", cardNo.MaskCardNo())
                        .Add("HasOffered", hasOffered).Add("IsInterested", isInterested).Add("CustomerFlag", customerFlag).ToInputLogString());

            RecommendCampaignResponse resCamp = GetCampaignByCustomer(auditLog, cardNo, hasOffered, isInterested, customerFlag, campaignNum);

            //RecommendCampaignResponse resCamp = new RecommendCampaignResponse()
            //{
            //    RecommendCampaignDetails = new List<CampaignDetail>()
            //    {
            //          new CampaignDetail { CampaignId = "XXXXX"},
            //          new CampaignDetail { CampaignId = "XXXXX"},
            //          new CampaignDetail { CampaignId = "XXXXX"}
            //    }
            //};

            return(resCamp != null ? resCamp.RecommendCampaignDetails : null);
        }
예제 #21
0
        public ActionResult List(int?customerId = null)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("List Recommended Campaign").ToInputLogString());

            _auditLog              = new AuditLogEntity();
            _auditLog.Module       = Constants.Module.Customer;
            _auditLog.Action       = Constants.AuditAction.ExistingLead;
            _auditLog.IpAddress    = ApplicationHelpers.GetClientIP();
            _auditLog.Status       = LogStatus.Success;
            _auditLog.CreateUserId = this.UserInfo.UserId;

            CustomerInfoViewModel custInfoVM = new CustomerInfoViewModel();

            if (TempData["CustomerInfo"] != null)
            {
                custInfoVM = (CustomerInfoViewModel)TempData["CustomerInfo"];
                TempData["CustomerInfo"] = custInfoVM; // keep for change Tab
            }
            else
            {
                return(RedirectToAction("Search", "Customer"));
            }

            try
            {
                ExistingLeadViewModel existingLeadVM = new ExistingLeadViewModel();
                if (custInfoVM.CustomerId != null)
                {
                    existingLeadVM.CustomerInfo = custInfoVM;
                }

                return(View(existingLeadVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("List Recommended Campaign").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
예제 #22
0
파일: AppLog.cs 프로젝트: KKPBank/CSM
        public static void AuditLog(AuditLogEntity auditLog)
        {
            IAuditLogFacade auditLogFacade = null;

            try
            {
                auditLogFacade = new AuditLogFacade();
                auditLogFacade.AddLog(auditLog);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
            }
            finally
            {
                if (auditLogFacade != null)
                {
                    auditLogFacade.Dispose();
                }
            }
        }
        public Task AddLogAsync <T>(string author, T oldValue, T newValue, Func <T, string> getEntityIdFunc, Func <T, string> getEntityNameFunc = null) where T : class
        {
            var empty = new JValue("{}");
            var left  = oldValue == null ? empty : JToken.FromObject(oldValue);
            var right = newValue == null ? empty : JToken.FromObject(newValue);

            var change = _diffPatch.Diff(left, right);

            string entityId   = getEntityIdFunc(oldValue ?? newValue);
            string entityName = getEntityNameFunc?.Invoke(oldValue ?? newValue);

            if (change != null)
            {
                return(Task.WhenAll(
                           _auditLogsRepository.AddLogAsync <T>(author, entityId, entityName, change.ToString()),
                           _auditLogTypesRepository.AddAsync(AuditLogEntity.GenerateTypePk <T>())
                           ));
            }

            return(Task.CompletedTask);
        }
예제 #24
0
        private static void AddAuditLog(IRpcContext context, ILogger writer, IAuditLoggerFormat format, AuditLogType logType, string methodName, object req, object rsp, long elapsedMS)
        {
            if (writer == null || format == null)
            {
                return;
            }

            var entity = new AuditLogEntity {
                MethodFullName = methodName,
                Request        = req,
                Response       = rsp,
                ElapsedMS      = elapsedMS,
                Writer         = writer,
                Context        = context,
                Formatter      = format,
                LogType        = logType
            };

            logDict.Enqueue(entity);

            StartWrite();
        }
예제 #25
0
파일: ReportFacade.cs 프로젝트: KKPBank/CSM
 public void SaveAuditLogSRReport(ExportSRTaskResponse taskResponse)
 {
     if (taskResponse != null)
     {
         var _auditLog = new AuditLogEntity();
         _auditLog.Module    = Constants.Module.Batch;
         _auditLog.Action    = taskResponse.TaskAction;
         _auditLog.IpAddress = ApplicationHelpers.GetClientIP();
         if (taskResponse.StatusResponse.Status == Constants.StatusResponse.Success)
         {
             _auditLog.Status = LogStatus.Success;
         }
         else
         {
             _auditLog.Status = LogStatus.Fail;
         }
         _auditLog.Detail       = taskResponse.ToString();
         _auditLog.CreateUserId = null;
         _auditLog.CreatedDate  = taskResponse.SchedDateTime;
         AppLog.AuditLog(_auditLog);
     }
 }
예제 #26
0
        private static void AddAuditLog(ILogger writer, IAuditLoggerFormat <AmpMessage> format, AuditLogType logType, IRpcContext context, AmpMessage req, AmpMessage rsp, long elapsedMS)
        {
            if (writer == null || format == null)
            {
                return;
            }

            var entity = new AuditLogEntity()
            {
                Context   = context,
                Request   = req,
                Response  = rsp,
                ElapsedMS = elapsedMS,
                Writer    = writer,
                Formater  = format,
                LogType   = logType
            };

            logDict.Enqueue(entity);

            StartWrite();
        }
예제 #27
0
파일: AppLog.cs 프로젝트: KKPBank/CSM
        public static void AuditLog(AuditLogEntity auditLog, LogStatus status, string detail)
        {
            IAuditLogFacade auditLogFacade = null;

            try
            {
                auditLogFacade  = new AuditLogFacade();
                auditLog.Status = status;
                auditLog.Detail = detail;
                auditLogFacade.AddLog(auditLog);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
            }
            finally
            {
                if (auditLogFacade != null)
                {
                    auditLogFacade.Dispose();
                }
            }
        }
예제 #28
0
        public string OnDemandCheckIn(string mac, int objectId, string task, string userId, string computerId)
        {
            var checkIn          = new CheckIn();
            var computerServices = new ComputerServices();

            if (userId != null) //on demand
            {
                //Check permissions
                if (task.Contains("deploy"))
                {
                    if (
                        !new AuthorizationServices(Convert.ToInt32(userId), AuthorizationStrings.ImageDeployTask)
                        .IsAuthorized())
                    {
                        checkIn.Result  = "false";
                        checkIn.Message = "This User Is Not Authorized To Deploy Images";
                        return(JsonConvert.SerializeObject(checkIn));
                    }
                }

                if (task.Contains("upload"))
                {
                    if (
                        !new AuthorizationServices(Convert.ToInt32(userId), AuthorizationStrings.ImageUploadTask)
                        .IsAuthorized())
                    {
                        checkIn.Result  = "false";
                        checkIn.Message = "This User Is Not Authorized To Upload Images";
                        return(JsonConvert.SerializeObject(checkIn));
                    }
                }

                if (task.Contains("multicast"))
                {
                    if (
                        !new AuthorizationServices(Convert.ToInt32(userId), AuthorizationStrings.ImageMulticastTask)
                        .IsAuthorized())
                    {
                        checkIn.Result  = "false";
                        checkIn.Message = "This User Is Not Authorized To Multicast Images";
                        return(JsonConvert.SerializeObject(checkIn));
                    }
                }
            }

            ComputerEntity computer = null;

            if (computerId != "false")
            {
                computer = computerServices.GetComputer(Convert.ToInt32(computerId));
            }

            ImageProfileWithImage imageProfile;

            var arguments = "";

            if (task == "deploy" || task == "upload" || task == "clobber" || task == "ondupload" || task == "onddeploy" ||
                task == "unregupload" || task == "unregdeploy" || task == "modelmatchdeploy")
            {
                imageProfile = new ImageProfileServices().ReadProfile(objectId);
                arguments    = new CreateTaskArguments(computer, imageProfile, task).Execute();
            }
            else //Multicast
            {
                var multicast = new ActiveMulticastSessionServices().GetFromPort(objectId);
                imageProfile = new ImageProfileServices().ReadProfile(multicast.ImageProfileId);
                arguments    = new CreateTaskArguments(computer, imageProfile, task).Execute(objectId.ToString());
            }

            var imageDistributionPoint = new GetImageServer(computer, task).Run();

            if (imageProfile.Image.Protected == 1 && (task == "upload" || task == "ondupload" || task == "unregupload"))
            {
                checkIn.Result  = "false";
                checkIn.Message = "This Image Is Protected";
                return(JsonConvert.SerializeObject(checkIn));
            }

            if (imageProfile.Image.Environment == "")
            {
                imageProfile.Image.Environment = "linux";
            }
            checkIn.ImageEnvironment = imageProfile.Image.Environment;

            if (imageProfile.Image.Environment == "winpe")
            {
                arguments += "dp_id=\"" + imageDistributionPoint + "\"\r\n";
            }
            else
            {
                arguments += " dp_id=\"" + imageDistributionPoint + "\"";
            }

            var activeTask = new ActiveImagingTaskEntity();

            activeTask.Direction = task;
            activeTask.UserId    = Convert.ToInt32(userId);
            activeTask.Type      = task;

            activeTask.DpId   = imageDistributionPoint;
            activeTask.Status = "1";

            if (computer == null)
            {
                //Create Task for an unregistered on demand computer
                var rnd           = new Random(DateTime.Now.Millisecond);
                var newComputerId = rnd.Next(-200000, -100000);

                if (imageProfile.Image.Environment == "winpe")
                {
                    arguments += "computer_id=" + newComputerId + "\r\n";
                }
                else
                {
                    arguments += " computer_id=" + newComputerId;
                }
                activeTask.ComputerId = newComputerId;
                activeTask.Arguments  = mac;
            }
            else
            {
                //Create Task for a registered on demand computer
                activeTask.ComputerId = computer.Id;
                activeTask.Arguments  = arguments;
            }
            new ActiveImagingTaskServices().AddActiveImagingTask(activeTask);

            var auditLog = new AuditLogEntity();

            switch (task)
            {
            case "ondupload":
            case "unregupload":
            case "upload":
                auditLog.AuditType = AuditEntry.Type.OndUpload;
                break;

            default:
                auditLog.AuditType = AuditEntry.Type.OndDeploy;
                break;
            }

            try
            {
                auditLog.ObjectId = activeTask.ComputerId;
                var user = new UserServices().GetUser(activeTask.UserId);
                if (user != null)
                {
                    auditLog.UserName = user.Name;
                }
                auditLog.ObjectName = computer != null ? computer.Name : mac;
                auditLog.Ip         = "";
                auditLog.UserId     = activeTask.UserId;
                auditLog.ObjectType = "Computer";
                auditLog.ObjectJson = JsonConvert.SerializeObject(activeTask);
                new AuditLogServices().AddAuditLog(auditLog);

                auditLog.ObjectId   = imageProfile.ImageId;
                auditLog.ObjectName = imageProfile.Image.Name;
                auditLog.ObjectType = "Image";
                new AuditLogServices().AddAuditLog(auditLog);
            }
            catch
            {
                //Do Nothing
            }


            checkIn.Result        = "true";
            checkIn.TaskArguments = arguments;
            checkIn.TaskId        = activeTask.Id.ToString();
            return(JsonConvert.SerializeObject(checkIn));
        }
예제 #29
0
파일: BranchFacade.cs 프로젝트: KKPBank/CSM
        public CreateBranchResponse InsertOrUpdateBranch(InsertOrUpdateBranchRequest request)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            CreateBranchResponse response = new CreateBranchResponse();

            Logger.Info(_logMsg.Clear().SetPrefixMsg("Call BranchService.InsertOrUpdateBranch").ToInputLogString());
            Logger.Debug("I:--START--:--BranchService.InsertOrUpdateBranch--");

            try
            {
                bool valid = false;
                _commonFacade = new CommonFacade();

                if (request.Header != null)
                {
                    valid           = _commonFacade.VerifyServiceRequest <Header>(request.Header);
                    response.Header = new Header
                    {
                        reference_no     = request.Header.reference_no,
                        service_name     = request.Header.service_name,
                        system_code      = request.Header.system_code,
                        transaction_date = request.Header.transaction_date
                    };
                }

                Logger.DebugFormat("-- XMLRequest --\n{0}", request.SerializeObject());
                var auditLog = new AuditLogEntity();
                auditLog.Module    = Constants.Module.WebService;
                auditLog.Action    = Constants.AuditAction.CreateBranch;
                auditLog.IpAddress = ApplicationHelpers.GetClientIP();

                #region == Validate Require Field ==

                if (!valid)
                {
                    response.StatusResponse = new StatusResponse()
                    {
                        ErrorCode   = Constants.ErrorCode.CSMBranch001,
                        Status      = Constants.StatusResponse.Failed,
                        Description = "Bad Request, the header is not valid"
                    };

                    return(response);
                }
                else
                {
                    if (string.IsNullOrEmpty(request.BranchCode))
                    {
                        return(GetReturnErrorRequireField("BranchCode", response));
                    }

                    if (string.IsNullOrEmpty(request.BranchName))
                    {
                        return(GetReturnErrorRequireField("BranchName", response));
                    }

                    if (string.IsNullOrEmpty(request.ChannelCode))
                    {
                        return(GetReturnErrorRequireField("ChannelCode", response));
                    }

                    if (request.StartTimeHour < 0 || request.StartTimeHour > 23)
                    {
                        return(GetReturnErrorInvalidFormat("StartTimeHour", "ต้องมีค่าระหว่าง 0 ถึง 23", "5", response));
                    }

                    if (request.StartTimeMinute < 0 || request.StartTimeMinute > 59)
                    {
                        return(GetReturnErrorInvalidFormat("StartTimeHour", "ต้องมีค่าระหว่าง 0 ถึง 59", "5", response));
                    }

                    if (request.EndTimeHour < 0 || request.EndTimeHour > 23)
                    {
                        return(GetReturnErrorInvalidFormat("EndTimeHour", "ต้องมีค่าระหว่าง 0 ถึง 23", "5", response));
                    }

                    if (request.EndTimeMinute < 0 || request.EndTimeMinute > 59)
                    {
                        return(GetReturnErrorInvalidFormat("EndTimeHour", "ต้องมีค่าระหว่าง 0 ถึง 59", "5", response));
                    }

                    if (request.Status != 0 && request.Status != 1)
                    {
                        return(GetReturnErrorInvalidFormat("Status", "ต้องมีค่าระหว่าง 0 ถึง 1", "5", response));
                    }
                }

                #endregion

                #region == Validate Code ==

                var channelDataAccess = new ChannelDataAccess(_context);

                int?channelId = channelDataAccess.GetChannelIdByChannelCode(request.ChannelCode);
                if (!channelId.HasValue)
                {
                    response.StatusResponse = new StatusResponse()
                    {
                        ErrorCode   = Constants.ErrorCode.CSMBranch003,
                        Status      = Constants.StatusResponse.Failed,
                        Description = "Fail to save branch:\r\nไม่พบ Channel Code ในฐานข้อมูล CSM"
                    };

                    return(response);
                }

                var branchDataAccess = new BranchDataAccess(_context);

                int?upperBranchId = null;

                if (!string.IsNullOrEmpty(request.UpperBranchCode))
                {
                    upperBranchId = branchDataAccess.GetBranchIdByBranchCode(request.UpperBranchCode);
                    if (!upperBranchId.HasValue)
                    {
                        response.StatusResponse = new StatusResponse()
                        {
                            ErrorCode   = Constants.ErrorCode.CSMBranch003,
                            Status      = Constants.StatusResponse.Failed,
                            Description = "Fail to save branch:\r\nไม่พบ Upper Branch Code ในฐานข้อมูล CSM"
                        };

                        return(response);
                    }
                }

                #endregion

                var result = branchDataAccess.InsertOrUpdateBranch(request, channelId.Value, upperBranchId);
                if (result.IsSuccess)
                {
                    response.StatusResponse = new StatusResponse
                    {
                        ErrorCode   = string.Empty,
                        Status      = Constants.StatusResponse.Success,
                        Description = "Save successful"
                    };
                    AppLog.AuditLog(auditLog, LogStatus.Success, response.StatusResponse.Description);
                }
                else
                {
                    response.StatusResponse = new StatusResponse
                    {
                        ErrorCode   = Constants.ErrorCode.CSMBranch003,
                        Status      = Constants.StatusResponse.Failed,
                        Description = result.ErrorMessage
                    };
                    AppLog.AuditLog(auditLog, LogStatus.Fail, response.StatusResponse.Description);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                response.StatusResponse = new StatusResponse
                {
                    ErrorCode   = Constants.ErrorCode.CSMBranch004,
                    Status      = Constants.StatusResponse.Failed,
                    Description = ex.ToString()
                };
            }
            finally
            {
                Logger.DebugFormat("-- XMLResponse --\n{0}", response.SerializeObject());
                stopwatch.Stop();
                Logger.DebugFormat("O:--Finish--:ElapsedMilliseconds/{0}", stopwatch.ElapsedMilliseconds);
            }

            return(response);
        }
예제 #30
0
파일: BranchFacade.cs 프로젝트: KKPBank/CSM
        public UpdateCalendarResponse UpdateBranchCalendar(UpdateBranchCalendarRequest request)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            UpdateCalendarResponse response = new UpdateCalendarResponse();

            Logger.Info(_logMsg.Clear().SetPrefixMsg("Call BranchService.UpdateBranchCalendar").ToInputLogString());
            Logger.Debug("I:--START--:--BranchService.UpdateBranchCalendar--");

            try
            {
                bool valid = false;
                _commonFacade = new CommonFacade();

                if (request.Header != null)
                {
                    valid           = _commonFacade.VerifyServiceRequest <Header>(request.Header);
                    response.Header = new Header
                    {
                        reference_no     = request.Header.reference_no,
                        service_name     = request.Header.service_name,
                        system_code      = request.Header.system_code,
                        transaction_date = request.Header.transaction_date
                    };
                }

                Logger.DebugFormat("-- XMLRequest --\n{0}", request.SerializeObject());
                var auditLog = new AuditLogEntity();
                auditLog.Module    = Constants.Module.WebService;
                auditLog.Action    = Constants.AuditAction.CreateBranch;
                auditLog.IpAddress = ApplicationHelpers.GetClientIP();

                if (!valid)
                {
                    response.StatusResponse = new StatusResponse()
                    {
                        ErrorCode   = Constants.ErrorCode.CSMCalendar001,
                        Status      = Constants.StatusResponse.Failed,
                        Description = "Bad Request, the header is not valid"
                    };

                    return(response);
                }
                else
                {
                    #region == Validate Require Field ==

                    if (string.IsNullOrEmpty(request.HolidayDesc))
                    {
                        response.StatusResponse = new StatusResponse()
                        {
                            ErrorCode   = Constants.ErrorCode.CSMCalendar002,
                            Status      = Constants.StatusResponse.Failed,
                            Description = "ข้อมูลที่ส่งมาไม่ครบถ้วน ไม่สามารถบันทึกรายการได้ (Field=HolidateDesc)"
                        };

                        return(response);
                    }

                    if (request.UpdateMode != 1 && request.UpdateMode != 2)
                    {
                        response.StatusResponse = new StatusResponse()
                        {
                            ErrorCode   = Constants.ErrorCode.CSMCalendar002,
                            Status      = Constants.StatusResponse.Failed,
                            Description = "ข้อมูลที่ไม่สามารถบันทึกรายการได้ เนื่องจากข้อมูลที่ส่งมาอยู่ในรูปแบบไม่ถูกต้อง (UpdateMode ต้องมีค่า 1 (Delete and Insert) หรือ 2 (Merge) เท่านั้น)"
                        };

                        return(response);
                    }

                    #endregion

                    #region == Validate Code ==

                    var branchDataAccess = new BranchDataAccess(_context);

                    var branchCodes = request.BranchCodeList;
                    var branchIds   = new List <int>();

                    if (request.BranchCodeList != null)
                    {
                        var branchCodeNotFoundList = new List <string>();

                        foreach (var code in branchCodes)
                        {
                            var branchId = branchDataAccess.GetBranchIdByBranchCode(code);

                            if (branchId == null)
                            {
                                branchCodeNotFoundList.Add(code);
                            }
                            else
                            {
                                branchIds.Add(branchId.Value);
                            }
                        }

                        //ถ้าlist ของ branch code ที่ไม่มีเบส CSM มากกว่า 0 ให้ส่ง code list กลับไป
                        if (branchCodeNotFoundList.Count > 0)
                        {
                            response.StatusResponse = new StatusResponse()
                            {
                                ErrorCode = Constants.ErrorCode.CSMCalendar004,
                                Status    = Constants.StatusResponse.Failed,
                                BranchCodeNotFoundList = branchCodeNotFoundList,
                                Description            = string.Format(CultureInfo.InvariantCulture, "ข้อมูลที่ไม่สามารถบันทึกรายการได้ เนื่องจากไม่พบ Branch Code ในฐานข้อมูล")
                            };

                            return(response);
                        }
                    }
                    else
                    {
                        request.BranchCodeList = new List <string>();
                    }

                    #endregion

                    var result = branchDataAccess.UpdateBranchCalendar(request, branchIds);

                    if (result.IsSuccess)
                    {
                        response.StatusResponse = new StatusResponse
                        {
                            ErrorCode   = string.Empty,
                            Status      = Constants.StatusResponse.Success,
                            Description = "Save successful"
                        };
                    }
                    else
                    {
                        response.StatusResponse = new StatusResponse
                        {
                            ErrorCode   = Constants.ErrorCode.CSMCalendar003,
                            Status      = Constants.StatusResponse.Failed,
                            Description = result.ErrorMessage
                        };
                        AppLog.AuditLog(auditLog, LogStatus.Fail, response.StatusResponse.Description);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                response.StatusResponse = new StatusResponse
                {
                    ErrorCode   = Constants.ErrorCode.CSMBranch004,
                    Status      = Constants.StatusResponse.Failed,
                    Description = ex.ToString()
                };
            }
            finally
            {
                Logger.DebugFormat("-- XMLResponse --\n{0}", response.SerializeObject());
                stopwatch.Stop();
                Logger.DebugFormat("O:--Finish--:ElapsedMilliseconds/{0}", stopwatch.ElapsedMilliseconds);
            }

            return(response);
        }