public ActionResult AttachExperts(AttachViewModel model)
        {
            if (!isLoggedIn())
            {
                return(RedirectToAction("Oops"));
            }

            if (!getUser().ActiveStatus)
            {
                return(View("Deactivated"));
            }

            Ticket          ticket = _dbContext.Ticket.Find(model.TicketID);
            ApplicationUser user   = _dbContext.Users.Find(model.UserID);

            AttachedUsers users = new AttachedUsers();

            users.User   = user;
            users.Ticket = ticket;

            _dbContext.AttachedUsers.Add(users);
            _dbContext.SaveChanges();

            return(RedirectToAction("ViewTicket", ticket));
        }
 public ActionResult Create(AttachViewModel attachViewModel)
 {
     if (attachViewModel.AttachFiles.Count() > 0)
     {
         attachService.CreateViewModelToDatabase(attachViewModel);
     }
     return(RedirectToAction("Index"));
 }
Example #3
0
        //將檔案存到路徑下
        public void SaveHttpPostFile(AttachViewModel viewModel, string storedFolder)
        {
            if (viewModel.AttachFiles != null)
            {
                viewModel.AttachDetails = new List <Attachment>();

                //可能多個檔案上傳
                foreach (var httpPost in viewModel.AttachFiles)
                {
                    if (!String.IsNullOrEmpty(httpPost.FileName) && httpPost.ContentLength > 0)
                    {
                        var   fileName = Path.GetFileName(httpPost.FileName);
                        var   path     = Path.Combine(HttpContext.Current.Server.MapPath(storedFolder), fileName);
                        Regex regex    = new Regex("\\.[^.]*$", RegexOptions.IgnoreCase); //找出副檔名
                        Match match    = regex.Match(httpPost.FileName);

                        //如果不存在資料夾就建立一個
                        if (!Directory.Exists(Path.GetDirectoryName(path)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(path));
                        }

                        ////檢查檔名是否重複,若有重複檔名後加上(2),以此類推編號
                        int    fileExtandNum = 0;
                        string fileNameTmp   = fileName;
                        while (System.IO.File.Exists(path))
                        {
                            fileExtandNum++;

                            fileNameTmp = fileName.Replace(match.Value.ToString(), "") + "(" + fileExtandNum + ")" + match.Value;
                            path        = Path.Combine(HttpContext.Current.Server.MapPath(storedFolder), fileNameTmp);
                        }
                        fileName = fileNameTmp;
                        httpPost.SaveAs(path);


                        AttachmentRecord record = new AttachmentRecord();
                        viewModel.AttachDetails.Add(new Attachment()
                        {
                            AttachmentName       = fileName,
                            AttachmentOriginName = httpPost.FileName,
                            AttachmentPath       = storedFolder,
                            AttachmentType       = match.Success ? match.Value : "unknown",
                            AttachmentUse        = viewModel.AttachmentUse,
                            isDeleted            = false,
                            MemberId             = IdentityHelper.UserId,
                            UploadTime           = DateTime.Now
                        });
                    }
                }
            }
        }
Example #4
0
        public async Task <IActionResult> Attach(Guid userId, [FromBody] AttachViewModel model)
        {
            var report   = _mapper.Map <ReportInnerModel>(model);
            var reportId = await _reportRepository.InsertAsync(report);

            var result = new
            {
                id      = reportId,
                message = $"Report with id='{reportId}' was successfully attached. File expected..."
            };

            return(Ok(result));
        }
        public Attachment MapCreate(AttachViewModel attachViewModel)
        {
            FileUploadManager fileUploadManager = new FileUploadManager(attachViewModel.Attachment);
            var        fileByteArray            = fileUploadManager.GetByteArray();
            Attachment attachment = new Attachment()
            {
                FileContent = fileByteArray,
                FileName    = attachViewModel.Attachment.FileName,
                TableName   = attachViewModel.TableName,
                TableId     = Guid.Parse(attachViewModel.Id),
                MimeType    = attachViewModel.Attachment.ContentType
            };

            return(attachment);
        }
 public ActionResult Post([FromForm] AttachViewModel attachViewModel)
 {
     try
     {
         AttachmentMapper attachmentMapper = new AttachmentMapper(_mapper);
         Attachment       attachment       = attachmentMapper.MapCreate(attachViewModel);
         var         overwrite             = attachViewModel.Overwrite != null ? attachViewModel.Overwrite.Value : false;
         ApiResponse serviceResponse       = _attachmentService.Create(attachment, overwrite);
         return(new ObjectCreatedResult("attachment", serviceResponse.Id.Value, serviceResponse.Data));
     }
     catch (Exception ex)
     {
         return(new UnknownErrorResult(ex, base._errorEnabled));
     }
 }
        public ActionResult CreateaAjax(HttpPostedFileBase[] attachFiles, string attachmentUse, string connId)
        {
            //var httpPostedFile = HttpContext.Request.Files["AttachFiles"];
            string rspStr = string.Empty;

            if (attachFiles.Count() > 0)
            {
                AttachViewModel attachViewModel = new AttachViewModel();
                attachViewModel.AttachFiles   = attachFiles;
                attachViewModel.AttachmentUse = attachmentUse;
                attachViewModel.ConnId        = connId;
                rspStr = attachService.CreateViewModelToDatabase(attachViewModel);
            }


            return(Content("connectId: " + connId + "  rps: " + rspStr));
        }
Example #8
0
        //用viewModel為了通用 不同的class
        //此處viewModel 可能包含HttpPostFileBase物件
        public void CreateViewModelToDatabase(AttachViewModel viewModel)
        {
            SaveHttpPostFile(viewModel, "~/UploadFiles");

            if (viewModel.AttachDetails != null)
            {
                foreach (var item in viewModel.AttachDetails)
                {
                    Create(item);

                    if (item.AttachmentUse == "通聯記錄")
                    {
                        using (CommunRecordService srv = new CommunRecordService())
                        {
                            srv.CreateExcelToDatabase(item);
                        }
                    }
                }
            }
        }
Example #9
0
        //用viewModel為了通用 不同的class
        //此處viewModel 可能包含HttpPostFileBase物件
        public void CreateViewModelToDatabase(AttachViewModel viewModel)
        {
            SaveHttpPostFile(viewModel, "~/UploadFiles");

            if (viewModel.AttachDetails != null)
            {
                foreach (var item in viewModel.AttachDetails)
                {
                    Create(item);

                    if (item.AttachmentUse == "通聯記錄")
                    {
                        CommunRecordService srv = new CommunRecordService();
                        srv.Import(item);
                    }
                    if (item.AttachmentUse == "Cellebrite UFED報告檔")
                    {
                        ForensicService srv = new ForensicService();
                        srv.Import(item);
                    }
                }
            }
        }
Example #10
0
        public ActionResult InitView(int attachmentId, string documentLevel)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitView Attachment").Add("AttachmentId", attachmentId).
                        Add("DocumentLevel", documentLevel).ToInputLogString());

            try
            {
                _customerFacade = new CustomerFacade();
                var attachVM = new AttachViewModel();
                AttachmentEntity selectedAttach = _customerFacade.GetAttachmentByID(attachmentId, documentLevel);

                if (selectedAttach != null)
                {
                    attachVM.AttachmentId       = selectedAttach.AttachmentId;
                    attachVM.Filename           = selectedAttach.Filename;
                    attachVM.DocName            = selectedAttach.Name;
                    attachVM.DocDesc            = selectedAttach.Description;
                    attachVM.ExpiryDate         = selectedAttach.ExpiryDateDisplay;
                    attachVM.CustomerId         = selectedAttach.CustomerId;
                    attachVM.Status             = selectedAttach.Status;
                    attachVM.CreateUserFullName = selectedAttach.CreateUserFullName;

                    attachVM.AttachTypeDisplay = StringHelpers.ConvertListToString(selectedAttach.AttachTypeList.Select(x => x.Name).ToList <object>(), ", ");
                }

                TempData["FILE_DOWNLOAD"] = selectedAttach;

                return(PartialView("~/Views/Document/_ViewAttachment.cshtml", attachVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitView Attachment").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
        public ActionResult Import(Guid communityId, [FromForm] AttachViewModel attachViewModel)
        {
            try
            {
                Guid id = Guid.Parse(attachViewModel.Id);
                FileUploadManager fileUploadManager = new FileUploadManager(attachViewModel.Attachment);
                string            fileName          = fileUploadManager.FileName;

                var outputFilePath = FileUploadManager.GetTempFolderPath(Guid.NewGuid().ToString() + ".xlsx");
                var byteArray      = fileUploadManager.GetByteArray();


                ServiceFactory  serviceFactory      = new ServiceFactory(this._faciTechDbContext, this._contactId);
                CommunityImport communityOnboarding = new CommunityImport(serviceFactory, id, outputFilePath);
                var             isValid             = communityOnboarding.Import(byteArray);

                FileManager fileManager = new FileManager(outputFilePath);
                var         outputFile  = new Attachment()
                {
                    FileName    = fileName,
                    FileContent = fileManager.GetByteArray(),
                    TableName   = "Community",
                    TableId     = _communityId,
                    MimeType    = attachViewModel.Attachment.ContentType
                };

                _attachmentService.Create(outputFile, true);
                _communityService.UpdateLastUpload(communityId, fileName);
                fileUploadManager.DeleteFile();
                return(Ok(new ApiResponse(new { IsAllValid = isValid, FileName = fileName }, ApiStatus.Success)));
            }
            catch (Exception ex)
            {
                return(new UnknownErrorResult(ex, base._errorEnabled));
            }
        }
Example #12
0
        public async Task <IActionResult> PostFile(string id, IList <IFormFile> files)
        {
            CallViewModel call = await this._callService.SelectAsync(Guid.Parse(id));

            if (call == null)
            {
                return(NotFound());
            }

            if (call.UserId != Guid.Parse(this.User.Claims.FirstOrDefault(x => x.Type == "Id").Value))
            {
                return(Forbid());
            }

            long size = files.Sum(x => x.Length);

            if (size == 0)
            {
                return(BadRequest(new
                {
                    message = "no file content",
                    size,
                }));
            }

            IList <string> savedFilePaths = new List <string>();

            foreach (IFormFile file in files)
            {
                if (file.Length <= 0)
                {
                    continue;
                }


                string filePath = Path.Combine(this._baseSource, DateTime.Now.Ticks + "-" + file.FileName);

                using (var stream = System.IO.File.Create(filePath))
                {
                    await file.CopyToAsync(stream);
                }

                AttachViewModel attach = new AttachViewModel();
                attach.Size            = file.Length;
                attach.Name            = file.FileName;
                attach.RelativePath    = filePath.Split("wwwroot")[1];
                attach.TableName       = "Calls";
                attach.TableRegisterId = Guid.Parse(id);
                attach.FullPath        = filePath;

                await this._attachService.InsertAsync(attach);

                savedFilePaths.Add(attach.RelativePath);
            }

            return(Ok(new
            {
                size,
                saved_count = files.Count,
                saved_files = savedFilePaths
            }));
        }
Example #13
0
        //將上傳的檔案,存到資料庫
        public string CreateViewModelToDatabase(AttachViewModel viewModel)
        {
            SaveHttpPostFile(viewModel, "~/UploadFiles");
            string errStr = String.Empty;

            try
            {
                if (viewModel.AttachDetails != null)
                {
                    //計算excel檔案大小,用來回傳signalR
                    CalculateFileSize(viewModel.AttachDetails);


                    HttpContext hctx = HttpContext.Current;//使用非同步處理 httpContext.current = null
                    //使用task非同步處理
                    var task = Task.Factory.StartNew(() =>
                    {
                        foreach (var item in viewModel.AttachDetails)
                        {
                            Create(item);   //無相關資料表
                            FileHelper.FileName = item.AttachmentName;
                            if (item.AttachmentUse == "通聯記錄")
                            {
                                CommunRecordService srv = new CommunRecordService();
                                srv.Import(item, hctx);

                                /// test
                                //總筆數及目前處理筆數
                                //FileHelper.Total = 3000;
                                ////使用Task進行非同步處理
                                //Random rnd = new Random();
                                //for (var i = 0; i < 3000; i++)
                                //{
                                //    //假裝將資料寫入資料庫,Delay 0-4ms
                                //    Thread.Sleep(rnd.Next(5));
                                //    FileHelper.Count++;
                                //}
                            }
                            if (item.AttachmentUse == "Cellebrite UFED報告檔")
                            {
                                ForensicService srv = new ForensicService();
                                srv.Import(item, hctx);
                            }
                        }
                    });

                    float  ratio          = 0;
                    Action updateProgress = () =>
                    {
                        if (FileHelper.Total != 0)
                        {
                            ratio = (float)FileHelper.Count / FileHelper.Total;
                            UploaderHub.UpdateProgress(viewModel.ConnId, FileHelper.FileName,
                                                       ratio * 100, string.Format("{0:n0} /{1:n0}", FileHelper.Count, FileHelper.Total));
                        }
                    };

                    while (!task.IsCompleted && !task.IsCanceled && !task.IsFaulted)
                    {
                        updateProgress();
                        Thread.Sleep(200);//0.2秒傳一次
                    }
                    updateProgress();
                    if (task.IsCompleted && !task.IsFaulted)
                    {
                        return("OK");
                    }
                    else
                    {
                        return(string.Join(" | ",
                                           task.Exception.InnerExceptions.Select(o => o.Message).ToArray()));
                    }
                }
            }
            catch (Exception err)
            {
                errStr = err.Message;
            }
            UploaderHub.UpdateProgress(viewModel.ConnId, "-", 0, "-");
            return(errStr);
        }
Example #14
0
        public ActionResult Edit(AttachViewModel attachVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("Edit Attachment").Add("DocName", attachVM.DocName)
                        .Add("DocDesc", attachVM.DocDesc).ToInputLogString());

            try
            {
                if (attachVM.AttachmentId.HasValue && attachVM.AttachmentId != 0)
                {
                    ModelState.Remove("FileAttach");
                }

                if (string.IsNullOrEmpty(attachVM.ExpiryDate))
                {
                    ModelState.AddModelError("ExpiryDate", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_RequiredField, Resource.Lbl_ExpiryDate));
                }
                else
                {
                    if (attachVM.ExpiryDate.ParseDateTime(Constants.DateTimeFormat.DefaultShortDate) < DateTime.Now.Date)
                    {
                        ModelState.AddModelError("ExpiryDate", Resource.ValErr_InvalidDate_MustMoreThanToday);
                    }
                }

                //if (attachVM.Status.HasValue == false)
                //{
                //    ModelState.AddModelError("Status", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_RequiredField, Resource.Lbl_Status_Thai));
                //}

                // Validate MaxLength
                if (attachVM.DocDesc != null && attachVM.DocDesc.Count() > Constants.MaxLength.AttachDesc)
                {
                    ModelState.AddModelError("DocDesc", string.Format(CultureInfo.InvariantCulture, Resource.ValErr_StringLength, Resource.Lbl_Detail, Constants.MaxLength.AttachDesc));
                    goto Outer;
                }

                if (ModelState.IsValid)
                {
                    AttachmentEntity attach = new AttachmentEntity();

                    var file = attachVM.FileAttach;
                    attach.Name         = attachVM.DocName;
                    attach.Description  = attachVM.DocDesc;
                    attach.ExpiryDate   = attachVM.ExpiryDate.ParseDateTime(Constants.DateTimeFormat.DefaultShortDate);
                    attach.CustomerId   = attachVM.CustomerId;
                    attach.AttachmentId = attachVM.AttachmentId.HasValue ? attachVM.AttachmentId.Value : 0;
                    attach.Status       = Constants.ApplicationStatus.Active;

                    #region "AttachType"

                    var selectedAttachType = attachVM.DocTypeCheckBoxes.Where(x => x.Checked == true)
                                             .Select(x => new AttachmentTypeEntity
                    {
                        DocTypeId    = x.Value.ToNullable <int>(),
                        CreateUserId = this.UserInfo.UserId
                    }).ToList();

                    if (attachVM.AttachTypeList != null && attachVM.AttachTypeList.Count > 0)
                    {
                        var prevAttachTypes = (from at in attachVM.AttachTypeList
                                               select new AttachmentTypeEntity
                        {
                            AttachmentId = at.AttachmentId,
                            Code = at.Code,
                            Name = at.Name,
                            DocTypeId = at.DocTypeId,
                            IsDelete = !selectedAttachType.Select(x => x.DocTypeId).Contains(at.DocTypeId),
                            Status = at.Status,
                            CreateUserId = this.UserInfo.UserId
                        }).ToList();

                        var dupeAttachTypes = new List <AttachmentTypeEntity>(selectedAttachType);
                        dupeAttachTypes.AddRange(prevAttachTypes);

                        var duplicates = dupeAttachTypes.GroupBy(x => new { x.DocTypeId })
                                         .Where(g => g.Count() > 1)
                                         .Select(g => (object)g.Key.DocTypeId);

                        if (duplicates.Any())
                        {
                            //Logger.Info(_logMsg.Clear().SetPrefixMsg("Duplicate ID in list")
                            //    .Add("IDs", StringHelpers.ConvertListToString(duplicates.ToList(), ",")).ToInputLogString());
                            prevAttachTypes.RemoveAll(x => duplicates.Contains(x.DocTypeId));
                        }

                        selectedAttachType.AddRange(prevAttachTypes);
                    }

                    attach.AttachTypeList = selectedAttachType;

                    #endregion

                    // Verify that the user selected a file
                    if (file != null && file.ContentLength > 0)
                    {
                        _commonFacade = new CommonFacade();
                        ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);
                        int?            limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();

                        if (file.ContentLength > limitSingleFileSize.Value)
                        {
                            ModelState.AddModelError("FileAttach", string.Format(CultureInfo.InvariantCulture, Resource.ValError_SingleFileSizeExceedMaxLimit, (limitSingleFileSize.Value / 1048576)));
                            goto Outer;
                        }

                        // extract only the filename
                        var fileName = Path.GetFileName(file.FileName);


                        ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
                        Match           match = Regex.Match(fileName, param.ParamValue, RegexOptions.IgnoreCase);

                        if (!match.Success)
                        {
                            ModelState.AddModelError("FileAttach", Resource.ValError_FileExtension);
                            goto Outer;
                        }

                        var docFolder   = _commonFacade.GetCSMDocumentFolder();
                        int seqNo       = _commonFacade.GetNextAttachmentSeq();
                        var fileNameUrl = ApplicationHelpers.GenerateFileName(docFolder, Path.GetExtension(file.FileName), seqNo, Constants.AttachmentPrefix.Customer);

                        var targetFile = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", docFolder, fileNameUrl);
                        file.SaveAs(targetFile);

                        attach.Url         = fileNameUrl;
                        attach.Filename    = fileName;
                        attach.ContentType = file.ContentType;
                    }

                    attach.CreateUserId = this.UserInfo.UserId; // for add CustomerLog

                    _customerFacade = new CustomerFacade();
                    _customerFacade.SaveCustomerAttachment(attach);

                    return(Json(new
                    {
                        Valid = true
                    }, "text/html"));
                }

Outer:
                return(Json(new
                {
                    Valid = false,
                    Error = string.Empty,
                    Errors = GetModelValidationErrors()
                }, "text/html"));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Edit Attachment").Add("Error Message", ex.Message).ToFailLogString());
                return(Json(new
                {
                    Valid = false,
                    Error = Resource.Error_System,
                    Errors = string.Empty
                }, "text/html"));
            }
        }
Example #15
0
        public ActionResult InitEdit(int?attachmentId, int?customerId, string documentLevel)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Attachment").Add("AttachmentId", attachmentId)
                        .Add("CustomerId", customerId).Add("DocumentLevel", documentLevel).ToInputLogString());

            try
            {
                _commonFacade   = new CommonFacade();
                _customerFacade = new CustomerFacade();

                #region "For show in hint"

                ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
                ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);

                int?limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();
                var singleLimitSize     = limitSingleFileSize.HasValue ? (limitSingleFileSize / 1048576) : 0;
                ViewBag.UploadLimitType = string.Format(CultureInfo.InvariantCulture, param.ParamDesc, singleLimitSize);

                #endregion

                var attachVM = new AttachViewModel();
                List <DocumentTypeEntity> docTypeList = null;

                if (attachmentId.HasValue)
                {
                    AttachmentEntity selectedAttach = _customerFacade.GetAttachmentByID(attachmentId.Value, documentLevel);
                    attachVM.Filename   = selectedAttach.Filename;
                    attachVM.DocName    = selectedAttach.Name;
                    attachVM.DocDesc    = selectedAttach.Description;
                    attachVM.ExpiryDate = selectedAttach.ExpiryDateDisplay;
                    attachVM.CustomerId = selectedAttach.CustomerId;
                    attachVM.Status     = selectedAttach.Status;

                    attachVM.AttachmentId = attachmentId.Value;

                    docTypeList = _commonFacade.GetDocumentTypeList(selectedAttach.AttachTypeList, Constants.DocumentCategory.Customer);
                }
                else
                {
                    attachVM.CustomerId = customerId; // case new
                    docTypeList         = _commonFacade.GetActiveDocumentTypes(Constants.DocumentCategory.Customer);
                }

                if (docTypeList != null)
                {
                    attachVM.JsonAttachType    = JsonConvert.SerializeObject(docTypeList);
                    attachVM.DocTypeCheckBoxes = docTypeList.Select(x => new CheckBoxes
                    {
                        Value   = x.DocTypeId.ToString(),
                        Text    = x.Name,
                        Checked = x.IsChecked
                    }).ToList();
                }

                //var statusList = _commonFacade.GetStatusSelectList();
                //attachVM.StatusList = new SelectList((IEnumerable)statusList, "Key", "Value", string.Empty);

                return(PartialView("~/Views/Document/_EditAttachment.cshtml", attachVM));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);
                Logger.Info(_logMsg.Clear().SetPrefixMsg("InitEdit Attachment").Add("Error Message", ex.Message).ToFailLogString());
                return(Error(new HandleErrorInfo(ex, this.ControllerContext.RouteData.Values["controller"].ToString(),
                                                 this.ControllerContext.RouteData.Values["action"].ToString())));
            }
        }
Example #16
0
 public async Task InsertAsync(AttachViewModel viewModel)
 {
     await this._attachRepository.InsertAsync(this._mapper.Map <Attach>(viewModel));
 }
Example #17
0
        public ActionResult Edit(AttachViewModel attachVM)
        {
            Logger.Info(_logMsg.Clear().SetPrefixMsg("List Attachment").Add("DocName", attachVM.DocName)
                        .Add("DocDesc", attachVM.DocDesc).ToInputLogString());

            AttachmentEntity attach = attachVM.ListIndex != null ? attachVM.AttachmentList[attachVM.ListIndex.Value] : new AttachmentEntity();
            int?oldFileSize         = 0; // เพื่อเช็คขนาดไฟล์รวม

            if (attach.AttachmentId != 0)
            {
                oldFileSize = attach.FileSize; // เพื่อเช็คขนาดไฟล์รวม
                ModelState.Remove("FileAttach");
            }

            if (ModelState.IsValid)
            {
                var file = attachVM.FileAttach;
                attach.Name        = attachVM.DocName;
                attach.Description = attachVM.DocDesc;
                attach.ExpiryDate  = attachVM.ExpiryDate.ParseDateTime(Constants.DateTimeFormat.DefaultShortDate);

                var selectedAttachType = attachVM.DocTypeCheckBoxes.Where(x => x.Checked == true)
                                         .Select(x => new AttachmentTypeEntity
                {
                    DocTypeId    = x.Value.ToNullable <int>(),
                    CreateUserId = this.UserInfo.UserId
                }).ToList();

                if (attach.AttachTypeList != null && attach.AttachTypeList.Count > 0)
                {
                    var prevAttachTypes = (from at in attach.AttachTypeList
                                           select new AttachmentTypeEntity
                    {
                        AttachmentId = at.AttachmentId,
                        Code = at.Code,
                        Name = at.Name,
                        DocTypeId = at.DocTypeId,
                        IsDelete = !selectedAttachType.Select(x => x.DocTypeId).Contains(at.DocTypeId),
                        Status = at.Status,
                        CreateUserId = this.UserInfo.UserId
                    }).ToList();

                    var dupeAttachTypes = new List <AttachmentTypeEntity>(selectedAttachType);
                    dupeAttachTypes.AddRange(prevAttachTypes);

                    var duplicates = dupeAttachTypes.GroupBy(x => new { x.DocTypeId })
                                     .Where(g => g.Count() > 1)
                                     .Select(g => (object)g.Key.DocTypeId);

                    if (duplicates.Any())
                    {
                        //Logger.Info(_logMsg.Clear().SetPrefixMsg("Duplicate ID in list")
                        //    .Add("IDs", StringHelpers.ConvertListToString(duplicates.ToList(), ",")).ToInputLogString());
                        prevAttachTypes.RemoveAll(x => duplicates.Contains(x.DocTypeId));
                    }

                    selectedAttachType.AddRange(prevAttachTypes);
                }

                attach.AttachTypeList = selectedAttachType;

                // Verify that the user selected a file
                if (file != null && file.ContentLength > 0)
                {
                    _commonFacade = new CommonFacade();
                    ParameterEntity paramSingleFileSize = _commonFacade.GetCacheParamByName(Constants.ParameterName.SingleFileSize);
                    ParameterEntity paramTotalFileSize  = _commonFacade.GetCacheParamByName(Constants.ParameterName.TotalFileSize);
                    int?            limitSingleFileSize = paramSingleFileSize.ParamValue.ToNullable <int>();
                    int?            limitTotalFileSize  = paramTotalFileSize.ParamValue.ToNullable <int>();

                    if (file.ContentLength > limitSingleFileSize.Value)
                    {
                        ModelState.AddModelError("FileAttach", string.Format(CultureInfo.InvariantCulture, Resource.ValError_SingleFileSizeExceedMaxLimit, (limitSingleFileSize.Value / 1048576)));
                        goto Outer;
                    }

                    int?totalSize = attachVM.AttachmentList.Where(x => x.IsDelete == false).Sum(x => x.FileSize);
                    totalSize -= oldFileSize; // กรณีแก้ไข จะลบขนาดไฟล์เก่าออก
                    totalSize += file.ContentLength;

                    if (totalSize > limitTotalFileSize.Value)
                    {
                        ModelState.AddModelError("FileAttach", string.Format(CultureInfo.InvariantCulture, Resource.ValError_TotalFileSizeExceedMaxLimit, (limitTotalFileSize.Value / 1048576)));
                        goto Outer;
                    }

                    // extract only the filename
                    var fileName = Path.GetFileName(file.FileName);
                    //const string regexPattern = @"^.*\.(jpg|jpeg|doc|docx|xls|xlsx|ppt|txt)$";

                    ParameterEntity param = _commonFacade.GetCacheParamByName(Constants.ParameterName.RegexFileExt);
                    Match           match = Regex.Match(fileName, param.ParamValue, RegexOptions.IgnoreCase);

                    if (!match.Success)
                    {
                        ModelState.AddModelError("FileAttach", Resource.ValError_FileExtension);
                        goto Outer;
                    }

                    string fileExtension = Path.GetExtension(file.FileName);
                    string path;

                    using (var tmp = new TempFile())
                    {
                        path = tmp.Path;
                        Logger.Debug("-- Upload File --:Is File Exists/" + System.IO.File.Exists(path));
                    }

                    // store the file inside ~/App_Data/uploads folder
                    //var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);

                    attach.Filename      = fileName;
                    attach.ContentType   = file.ContentType;
                    attach.TempPath      = path;
                    attach.FileExtension = fileExtension;
                    attach.FileSize      = file.ContentLength;

                    if (attachVM.ListIndex == null)
                    {
                        attachVM.AttachmentList.Add(attach);
                    }
                }

                return(Json(new
                {
                    Valid = true,
                    Data = attachVM.AttachmentList
                }, "text/html"));
            }

Outer:
            return(Json(new
            {
                Valid = false,
                Error = string.Empty,
                Errors = GetModelValidationErrors()
            }, "text/html"));
        }