Ejemplo n.º 1
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"));
            }
        }