Esempio n. 1
0
        private void SaveAttachments(int newsId, NewsEntity newsEnity, IEnumerable <AttachmentEntity> attachments)
        {
            foreach (AttachmentEntity attachment in attachments)
            {
                TB_T_NEWS_ATTACHMENT dbAttach = null;
                var isIDNull = attachment.AttachmentId == null || attachment.AttachmentId == 0 ? true : false;

                if (isIDNull)
                {
                    dbAttach                 = new TB_T_NEWS_ATTACHMENT();
                    dbAttach.NEWS_ID         = newsId;
                    dbAttach.ATTACHMENT_NAME = attachment.Name;
                    dbAttach.ATTACHMENT_DESC = attachment.Description;
                    dbAttach.CREATE_DATE     = DateTime.Now;
                    dbAttach.EXPIRY_DATE     = attachment.ExpiryDate;

                    // New file
                    var tempFile = attachment.TempPath;
                    _commonDataAccess = new CommonDataAccess(_context);
                    int    nextSeq     = _commonDataAccess.GetNextAttachmentSeq();
                    string fileNameUrl = ApplicationHelpers.GenerateFileName(newsEnity.DocumentFolder, attachment.FileExtension, nextSeq);

                    var targetFile = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", newsEnity.DocumentFolder, fileNameUrl);

                    if (StreamDataHelpers.TryToCopy(tempFile, targetFile))
                    {
                        // Save new file
                        dbAttach.FILE_NAME    = attachment.Filename;
                        dbAttach.URL          = fileNameUrl;
                        dbAttach.CONTENT_TYPE = attachment.ContentType;
                        dbAttach.FILE_SIZE    = attachment.FileSize;

                        _context.TB_T_NEWS_ATTACHMENT.Add(dbAttach);
                    }
                }

                if (!isIDNull && attachment.IsDelete == true)
                {
                    // Delete AttachmentType
                    var listType = _context.TB_T_ATTACHMENT_TYPE.Where(x => x.NEWS_ATTACHMENT_ID == attachment.AttachmentId);
                    _context.TB_T_ATTACHMENT_TYPE.RemoveRange(listType);

                    // Delete News Attachment
                    dbAttach = _context.TB_T_NEWS_ATTACHMENT.FirstOrDefault(x => x.NEWS_ATTACHMENT_ID == attachment.AttachmentId);
                    var prevFile = dbAttach.URL; // for delete file
                    _context.TB_T_NEWS_ATTACHMENT.Remove(dbAttach);

                    StreamDataHelpers.TryToDelete(string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", newsEnity.DocumentFolder, prevFile));
                }

                if (!isIDNull && attachment.IsDelete == false)
                {
                    // Get previous path file
                    dbAttach = _context.TB_T_NEWS_ATTACHMENT.FirstOrDefault(x => x.NEWS_ATTACHMENT_ID == attachment.AttachmentId);
                    dbAttach.ATTACHMENT_NAME = attachment.Name;
                    dbAttach.ATTACHMENT_DESC = attachment.Description;
                    //dbAttach.CREATE_DATE = DateTime.Now;
                    dbAttach.EXPIRY_DATE = attachment.ExpiryDate;

                    if (!string.IsNullOrWhiteSpace(attachment.TempPath))
                    {
                        var prevFile = dbAttach.URL;

                        // New file
                        var tempFile = attachment.TempPath;
                        _commonDataAccess = new CommonDataAccess(_context);
                        int    nextSeq     = _commonDataAccess.GetNextAttachmentSeq();
                        string fileNameUrl = ApplicationHelpers.GenerateFileName(newsEnity.DocumentFolder, attachment.FileExtension, nextSeq);

                        var targetFile = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", newsEnity.DocumentFolder, fileNameUrl);

                        if (StreamDataHelpers.TryToCopy(tempFile, targetFile))
                        {
                            if (StreamDataHelpers.TryToDelete(string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", newsEnity.DocumentFolder, prevFile)))
                            {
                                // Save new file
                                dbAttach.FILE_NAME    = attachment.Filename;
                                dbAttach.URL          = fileNameUrl;
                                dbAttach.CONTENT_TYPE = attachment.ContentType;
                                dbAttach.FILE_SIZE    = attachment.FileSize;
                            }
                        }
                    }

                    SetEntryStateModified(dbAttach);
                }

                this.Save();

                if (attachment.IsDelete == false && attachment.AttachTypeList != null && attachment.AttachTypeList.Count > 0)
                {
                    this.SaveAttachTypes(dbAttach.NEWS_ATTACHMENT_ID, attachment.AttachTypeList);
                }
            }
        }
Esempio n. 2
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"));
            }
        }