/// <summary>
 /// Deletes all files except native type in document entity.
 /// </summary>
 /// <param name="document">The document entity</param>
 /// <param name="edrmFile">The edrm file.</param>
 private static void DeleteFilesInDocumentEntity(DocumentEntity document, FileInfo edrmFile)
 {
     // Loop through all file entities in EDRM Document
     foreach (ExternalFileEntity externalFile in document.Files.Where(file => !file.FileType.ToLower().Equals(Constants.EDRMAttributeNativeFileType.ToLower())).SelectMany(file => file.ExternalFile))
     {
         // Delete all non native files
         File.Delete(CreateFilePath(externalFile,edrmFile.DirectoryName));
     }
 }
Example #2
0
    public DocumentEntity GetDocument()
    {
        DocumentEntity obj = new DocumentEntity();
        obj.DocumentName = Filter.GetMaxString(txtName.Text.Trim(), DocumentFields.DocumentName.MaxLength);
        obj.TextId = DocumentManager.CreateInstant().GetUniqueTextIdFromUnicodeText(obj.DocumentName);
        obj.Description = Filter.GetMaxString(txtDescription.Value.Trim(), DocumentFields.Description.MaxLength);
        if (!string.IsNullOrEmpty(txtMark.Text))
        {
            obj.Mark = int.Parse(txtMark.Text.Trim());
        }
        else
            obj.Mark = 0;
        obj.GroupId = int.Parse(ddlGroup.SelectedValue);
        if (rdoUpload.Checked)
        {
            if (UpLoadDocument.HasFile)
            {
                obj.PathName = FileUploadControl.FullPath(UpLoadDocument, EnumsFile.Document, obj.TextId, DocumentFields.PathName.MaxLength);
                obj.FileSize = Math.Round((double)UpLoadDocument.PostedFile.ContentLength / (1024 * 1024), 3);
            }
            else
            {
                //obj.PathName = "";
                CustomValidator1.ErrorMessage = "File rỗng, chọn file khác";
                CustomValidator1.IsValid = false;
                return null;
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(ddlSelectFile.SelectedValue))
            {
                obj.PathName = Config.UploadDoc().TrimEnd('/') + "/" + ddlSelectFile.SelectedValue;
                FileInfo f = new FileInfo(Server.MapPath("~" + obj.PathName));
                obj.FileSize = Math.Round((double)f.Length / (1024 * 1024), 3);
            }
            else
            {
                CustomValidator1.ErrorMessage = "File rỗng, chọn file khác";
                CustomValidator1.IsValid = false;
                return null;
            }
        }

        obj.DisplayImage = FileUploadControl.FullPath(UpLoadImage, EnumsFile.Images, obj.TextId, DocumentFields.DisplayImage.MaxLength);

        obj.VideoTrailer = FileUploadControl.FullPath(UploadVideo, EnumsFile.Videos, obj.TextId, DocumentFields.VideoTrailer.MaxLength);
        obj.ShowVideo = check.Checked;
        //obj.Description = Filter.GetMaxString(txtGuide.Value.Trim(), DocumentFields.Guide.MaxLength);
        obj.CountDown = 0;
        obj.CreatedBy = Util.CurrentUserName;
        obj.CreatedDate = DateTime.Now;
        obj.IsVisible = true;
        obj.IsDeleted = false;
        return obj;
    }
        public DocumentEntity ParseEdrmDocumentXml(string sDocumentEntity)
        {
            DocumentEntity documentEntity = new DocumentEntity();
            XmlReader xmlReader = XmlReader.Create(new StringReader(sDocumentEntity));

            while (xmlReader.Read())
            {
                // set these values only if they were not already set.
                if (string.IsNullOrEmpty(documentEntity.MIMEType)) documentEntity.MIMEType = xmlReader.SafeGetAttribute("MimeType");
                if (string.IsNullOrEmpty(documentEntity.DocumentID)) documentEntity.DocumentID = xmlReader.SafeGetAttribute("DocID");

                if (xmlReader.Name.Equals("tag", StringComparison.InvariantCultureIgnoreCase))
                {
                    #region Parse all Tag elements
                    documentEntity.Tags.Add(new TagEntity()
                    {
                        TagName = xmlReader.SafeGetAttribute("TagName"),
                        TagDataType = xmlReader.SafeGetAttribute("TagDataType"),
                        TagValue = xmlReader.SafeGetAttribute("TagValue")
                    });
                    #endregion Parse all Tag elements
                }
                else if (xmlReader.Name.Equals("file", StringComparison.InvariantCultureIgnoreCase))
                {
                    #region Parse File elements

                    FileEntity fileEntity = new FileEntity { FileType = xmlReader.SafeGetAttribute("FileType") };

                    XmlReader xmlReaderForExternalFile = XmlReader.Create(new StringReader(xmlReader.ReadOuterXml()));

                    while (xmlReaderForExternalFile.Read())
                    {
                        #region Parse external file elements
                        if (xmlReaderForExternalFile.Name.Equals("ExternalFile", StringComparison.InvariantCultureIgnoreCase))
                        {
                            fileEntity.ExternalFile.Add(new ExternalFileEntity()
                            {
                                FileName = xmlReaderForExternalFile.SafeGetAttribute("FileName"),
                                FilePath = xmlReaderForExternalFile.SafeGetAttribute("FilePath"),
                                FileSize = xmlReaderForExternalFile.SafeGetAttribute("FileSize"),
                                Hash = xmlReaderForExternalFile.SafeGetAttribute("Hash")
                            });
                        }
                        #endregion Parse external file elements
                    }
                    documentEntity.Files.Add(fileEntity);
                    #endregion Parse File elements
                }
            }

            return documentEntity;
        }
Example #4
0
 public bool Delete(Guid Id)
 {
     bool toReturn = false;
     using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
     {
         DocumentEntity _DocumentEntity = new DocumentEntity(Id);
         if (adapter.FetchEntity(_DocumentEntity))
         {
             adapter.DeleteEntity(_DocumentEntity);
             toReturn = true;
         }
     }
     return toReturn;
 }
        public async Task <HttpStatusCode> UpdateAsync <T>(T entity, bool undelete = false) where T : Reference
        {
            string             documentType = GetDocumentType <T>();
            DocumentEntity <T> doc          = new DocumentEntity <T>(entity);

            if (doc.DocumentType != null && doc.DocumentType != documentType)
            {
                throw new ArgumentException($"Cannot change {entity.Id} from {doc.DocumentType} to {typeof(T).Name}");
            }
            doc.DocumentType = documentType; // in case not specified
            doc.UpdatedAt    = DateTimeOffset.Now;

            if (undelete)
            {
                // need to reset deleted flag
                doc.Deleted = false;
            }

            ResourceResponse <Document> response = await _documentClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_databaseName, _collectionName, entity.Id), doc);

            return(response.StatusCode);
        }
Example #6
0
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            DocumentEntity documentEntity = await _context.Documents.Include(d => d.Gender)
                                            .Include(d => d.DocumentLanguage)
                                            .Include(d => d.TypeOfDocument)
                                            .Include(d => d.Author)
                                            .Where(d => d.Id == id)
                                            .FirstOrDefaultAsync();

            if (documentEntity == null)
            {
                return(NotFound());
            }
            DocumentViewModel documentViewModel = _converterHelper.ToDocumentViewModel(documentEntity);

            return(View(documentViewModel));
        }
Example #7
0
        // GET: Documents/Details/5
        public ActionResult Details(DocumentEntity entity)
        {
            Document document = db.Documents.Find(entity.Id);

            var viewModel = new DocumentViewModel()
            {
                Id = document.Id,
                DocumentContent  = document.DocumentContent,
                DocumentName     = document.DocumentName,
                UploadDate       = document.UploadDate,
                DueDate          = document.DueDate,
                DocumentTypeId   = document.DocumentTypeId,
                DocumentTypeName = document.DocumentTypes.DocumentTypeName,
                assignedEntity   = entity
            };

            string owner = User.Identity.GetUserId();

            if (entity.EntityType == "Course")
            {
                owner = db.CourseDocuments.Where(r => r.DocumentId == document.Id).FirstOrDefault().OwnerId;
            }
            else if (entity.EntityType == "Module")
            {
                owner = db.ModuleDocuments.Where(r => r.DocumentId == document.Id).FirstOrDefault().OwnerId;
            }
            else
            {
                owner = db.ActivityDocuments.Where(r => r.DocumentId == document.Id).FirstOrDefault().OwnerId;
            }

            var user = db.Users.Find(owner);
            var role = UserViewModel.userToRole(user.Id)?.Name ?? "Not Assigned";

            viewModel.ownerName = role + " " + user.Fullname;

            return(View(viewModel));
        }
Example #8
0
        public ActionResult Edit(DocumentViewModel document, HttpPostedFileBase upload)
        {
            var tempEntity = new DocumentEntity()
            {
                Id               = document.assignedEntity.Id,
                returnTarget     = document.assignedEntity.returnTarget,
                EntityName       = document.assignedEntity.EntityName,
                returnId         = document.assignedEntity.returnId,
                EntityType       = document.assignedEntity.EntityType,
                DocumentTypeName = document.assignedEntity.DocumentTypeName
            };

            document.assignedEntity = tempEntity;

            Document documentToEdit = db.Documents.Find(document.Id);

            documentToEdit.DocumentContent = document.DocumentContent;
            documentToEdit.DueDate         = document.DueDate;

            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    documentToEdit.DocumentName = System.IO.Path.GetFileName(upload.FileName);
                    documentToEdit.FileType     = upload.ContentType;
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        documentToEdit.Content = reader.ReadBytes(upload.ContentLength);
                    }
                }

                db.Entry(documentToEdit).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Details", "Courses", new { id = document.assignedEntity.returnId, redirect = document.assignedEntity.returnTarget }));
            }
            ViewBag.DocumentTypeId = new SelectList(db.DocumentTypes, "Id", "DocumentTypeName", document.DocumentTypeId);
            return(View(document));
        }
        private async Task<ItemResponse<DocumentEntity<T>>> SoftDeleteAsync<T>(T entity,
            PartitionKey partitionKey,
            string etag = null) where T : IIdentifiable
        {
            DocumentEntity<T> item = new DocumentEntity<T>(entity)
            {
                Deleted = true,
                UpdatedAt = DateTime.UtcNow,
                DocumentType = GetDocumentType<T>()
            };

            if (string.IsNullOrEmpty(etag))
            {
                return await RepositoryContainer.ReplaceItemAsync(item: item, id: entity.Id, partitionKey);
            }
            else
            {
                return await RepositoryContainer.ReplaceItemAsync(item: item, id: entity.Id, partitionKey, new ItemRequestOptions
                {
                    IfMatchEtag = etag
                });
            }
        }
Example #10
0
 ///// <summary>
 ///// To set audit fields for document
 ///// </summary>
 ///// <param name="documentEntity"></param>
 ///// <param name="isEditMode"></param>
 ///// <param name="drpLinkFromCookie"> </param>
 //public void SetAuditFields(DocumentEntity documentEntity, bool isEditMode,DropBoxLink drpLinkFromCookie)
 //{
 //    if (!documentEntity.IsActive)
 //    {
 //        documentEntity.DeletedBy = GetLoginUserId(drpLinkFromCookie);
 //        documentEntity.DeletedTimeStamp = DateTime.Now;
 //    }
 //    else
 //    {
 //        if (isEditMode)
 //        {
 //            documentEntity.ModifiedBy = GetLoginUserId(drpLinkFromCookie);
 //            documentEntity.ModifiedTimeStamp = DateTime.Now;
 //        }
 //        else
 //        {
 //            documentEntity.CreatedBy = GetLoginUserId(drpLinkFromCookie);
 //            documentEntity.CreatedTimeStamp = DateTime.Now;
 //        }
 //    }
 //}
 /// <summary>
 /// To set audit fields for document
 /// </summary>
 /// <param name="documentEntity"></param>
 /// <param name="isEditMode"></param>
 /// <param name="drpLinkFromCookie"></param>
 public void SetAuditFields(DocumentEntity documentEntity, bool isEditMode, DropBoxLink drpLinkFromCookie)
 {
     string loginUserId = GetLoginUserId(drpLinkFromCookie);
     DateTime currentServerTime = DateTime.Now;
     if (!documentEntity.IsActive)
     {
         documentEntity.DeletedBy = loginUserId;
         documentEntity.DeletedTimeStamp = currentServerTime;
     }
     else
     {
         if (isEditMode)
         {
             documentEntity.ModifiedBy = loginUserId;
             documentEntity.ModifiedTimeStamp = currentServerTime;
         }
         else
         {
             documentEntity.CreatedBy = loginUserId;
             documentEntity.CreatedTimeStamp = currentServerTime;
         }
     }
 }
Example #11
0
        public DocumentEntity UploadDocument(string filename, string extension, Stream filestream)
        {
            // Try to retrieve existing file
            DocumentEntity document = documentDb.GetDocumentRecord(User.UserName, filename);

            // If Exists
            if (document != null)
            {
                var status = documentUploadUtility.UploadDocumentToS3(filestream, filename, User.UserName);

                if (status.IsSuccess)
                {
                    document.LastUpdateDate = DateTime.Now;
                    documentDb.UpdateDocumentRecord(document);
                }
            }
            else
            {
                document = UploadNewDocument(filename, extension, filestream);
            }

            return(document);
        }
        public async Task <HttpStatusCode> BulkUpdateAsync <T>(IEnumerable <T> entities, string storedProcedureName) where T : IIdentifiable
        {
            string documentType = GetDocumentType <T>();

            IList <DocumentEntity <T> > documents = new List <DocumentEntity <T> >();

            foreach (T entity in entities)
            {
                DocumentEntity <T> doc = new DocumentEntity <T>(entity);
                if (doc.DocumentType != null && doc.DocumentType != documentType)
                {
                    throw new ArgumentException($"Cannot change {entity.Id} from {doc.DocumentType} to {typeof(T).Name}");
                }

                doc.DocumentType = documentType;
                doc.UpdatedAt    = DateTimeOffset.Now;
                documents.Add(doc);
            }

            try
            {
                string documentsAsJson = JsonConvert.SerializeObject(documents);

                dynamic[] args = new dynamic[] { JsonConvert.DeserializeObject <dynamic>(documentsAsJson) };

                Uri link = UriFactory.CreateStoredProcedureUri(_databaseName, _collectionName, storedProcedureName);

                StoredProcedureResponse <string> result = await _documentClient.ExecuteStoredProcedureAsync <string>
                                                              (link, args);

                return(result.StatusCode);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async Task<HttpStatusCode> UpdateAsync<T>(T entity,
            bool undelete = false,
            string etag = null) where T : Reference
        {
            Guard.ArgumentNotNull(entity, nameof(entity));

            string documentType = GetDocumentType<T>();
            DocumentEntity<T> doc = new DocumentEntity<T>(entity);
            if (doc.DocumentType != null && doc.DocumentType != documentType)
            {
                throw new ArgumentException($"Cannot change {entity.Id} from {doc.DocumentType} to {typeof(T).Name}");
            }

            doc.DocumentType = documentType; // in case not specified
            doc.UpdatedAt = DateTimeOffset.Now;

            if (undelete)
            {
                // need to reset deleted flag
                doc.Deleted = false;
            }

            if (string.IsNullOrWhiteSpace(etag))
            {
                ItemResponse<DocumentEntity<T>> response = await RepositoryContainer.ReplaceItemAsync(item: doc, id: entity.Id, requestOptions: _disableContentResponseOnWriteRequestOptions);
                return response.StatusCode;
            }
            else
            {
                ItemResponse<DocumentEntity<T>> response = await RepositoryContainer.ReplaceItemAsync(item: doc, id: entity.Id, requestOptions: new ItemRequestOptions
                {
                    EnableContentResponseOnWrite = false,
                    IfMatchEtag = etag
                });
                return response.StatusCode;   
            }
        }
Example #14
0
        public async Task <IActionResult> Edit(int id, DocumentViewModel documentViewModel)
        {
            if (id != documentViewModel.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    string path = documentViewModel.DocumentPath;

                    if (documentViewModel.DocumentFile != null)
                    {
                        path = await _documentHelper.UploadDocumentAsync(documentViewModel.DocumentFile, "document");
                    }
                    DocumentEntity document = await _converterHelper.ToDocumentEntity(documentViewModel, path, false);

                    _context.Update(document);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DocumentEntityExists(documentViewModel.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(documentViewModel));
        }
        /// <summary>
        /// 检查实体
        /// </summary>
        /// <param name="folderEntity">实体校验</param>
        private void CheckEntity(DocumentEntity documentEntity)
        {
            if (string.IsNullOrEmpty(documentEntity.Name))
            {
                throw new BusinessException("文件名称不允许为空");
            }
            else if (documentEntity.Name.Length > 255)
            {
                throw new BusinessException("文件名称最大长度255");
            }
            else if (string.IsNullOrEmpty(documentEntity.Type))
            {
                throw new BusinessException("文件类型不允许为空");
            }
            else if (documentEntity.Type.Length > 100)
            {
                throw new BusinessException("文件类型最大长度100");
            }
            else if (string.IsNullOrEmpty(documentEntity.Url))
            {
                throw new BusinessException("文件Url不允许为空");
            }
            else if (documentEntity.Url.Length > 3000)
            {
                throw new BusinessException("url最大长度3000");
            }
            else if (!string.IsNullOrEmpty(documentEntity.Words) && documentEntity.Words.Length > 1000)
            {
                throw new BusinessException("关键词最大长度1000");
            }
            int n = DocumentDA.ValidUserTagAndName(documentEntity);

            if (n > 0)
            {
                throw new BusinessException("在同一种用户类型中,文件名称不可与其他文件重复");
            }
        }
Example #16
0
        public async Task CreateDocument(Document document)
        {
            try
            {
                StatusEntity statusEntity = _statusRepository
                                            .GetAll()
                                            .AsNoTracking()
                                            .FirstOrDefault(s => s.Name == "Approved");

                document.Status = Mapper.Map <StatusEntity, Status>(statusEntity);

                DocumentEntity documentEntity = Mapper.Map <Document, DocumentEntity>(document);

                documentEntity.UsersWithApprove = documentEntity.Reviewers;

                _documentRepository.Add(documentEntity);

                await _documentRepository.CommitAsync();
            }
            catch (Exception e)
            {
                throw new DocManagerException("Error during document creation.", e.Message, e);
            }
        }
        public async Task <Dictionary <string, Dictionary <string, ProviderSourceDataset> > > GetProviderSourceDatasetsByProviderIdsAndRelationshipIds(
            string specificationId,
            IEnumerable <string> providerIds,
            IEnumerable <string> dataRelationshipIds)
        {
            if (providerIds.IsNullOrEmpty() || dataRelationshipIds.IsNullOrEmpty())
            {
                return(new Dictionary <string, Dictionary <string, ProviderSourceDataset> >());
            }

            Dictionary <string, Dictionary <string, ProviderSourceDataset> > results = new Dictionary <string, Dictionary <string, ProviderSourceDataset> >(providerIds.Count());

            List <Task <DocumentEntity <ProviderSourceDataset> > > requests = new List <Task <DocumentEntity <ProviderSourceDataset> > >(providerIds.Count() * dataRelationshipIds.Count());

            // Iterate through providers first, to give a higher possibility to batch requests based on partition ID in cosmos
            foreach (string providerId in providerIds)
            {
                EnsureResultsDictionaryContainsProvider(results, providerId);
                GenerateLookupRequestForDatasetForAProvider(specificationId, dataRelationshipIds, requests, providerId);
            }

            // No throttling required for tasks, as it's assumed the cosmos client's AllowBatch will handle the parallism
            await TaskHelper.WhenAllAndThrow(requests.ToArray());

            foreach (Task <DocumentEntity <ProviderSourceDataset> > request in requests)
            {
                DocumentEntity <ProviderSourceDataset> providerSourceDatasetDocument = request.Result;

                if (IsReturnedDocumentNotNullAndNotDeleted(providerSourceDatasetDocument))
                {
                    AddProviderSourceDatasetToResults(results, providerSourceDatasetDocument);
                }
            }

            return(results);
        }
Example #18
0
        public BaseObject InsertDocument(DocumentEntity param)
        {
            var obj = new BaseObject();

            if (_db.Documents.Any(m => m.Title == param.Title))
            {
                obj.Tag     = -1;
                obj.Message = "该页面标题已存在!";

                return(obj);
            }
            var article = new Document()
            {
                Content         = param.Content,
                MetaDescription = param.MetaDescription,
                MetaKeywords    = param.MetaKeywords,
                Overview        = param.Overview,
                PageTitle       = param.PageTitle,
                PageVisits      = 0,
                Slug            = param.Slug,
                DateCreated     = DateTime.Now,
                UpdateUser      = param.UpdateUser,
                Title           = param.Title
            };

            _db.Documents.Add(article);
            _db.SaveChanges();
            article.Slug = article.ID.ToString();
            _db.SaveChanges();

            obj.Tag     = 1;
            obj.Message = "保存成功!";


            return(obj);
        }
Example #19
0
 public override DocumentEntity ConvertToHtml(DocumentEntity _docEntity)
 {
     if (!_docEntity.isConvert && String.IsNullOrEmpty(_docEntity.ConvertError))
     {
         var imagePath             = Path.Combine(_docEntity.ResourcesPath, _docEntity.ImageFolder);
         Aspose.Words.Document doc = new Aspose.Words.Document(_docEntity.FilePath);
         //记录解析前的页面数
         _docEntity.HtmlData.PageNumber = doc.PageCount;
         HtmlSaveOptions saveOptions = new HtmlSaveOptions();
         if (!Directory.Exists(imagePath))
         {
             Directory.CreateDirectory(imagePath);
         }
         saveOptions.ImagesFolder         = imagePath;
         saveOptions.ImageSavingCallback  = new HandleImageSaving();
         saveOptions.TableWidthOutputMode = HtmlElementSizeOutputMode.RelativeOnly;
         saveOptions.CssStyleSheetType    = CssStyleSheetType.Inline;
         using (MemoryStream htmlStream = new MemoryStream())
         {
             try
             {
                 doc.Save(htmlStream, saveOptions);
                 //记录解析实体
                 //HTMLContent 表示原始的HTML内容,此处设置为数组主要为了配合表格多Sheet页的情况,待重构
                 _docEntity.HtmlData.HtmlContent.Add(Encoding.UTF8.GetString(htmlStream.ToArray()));
                 _docEntity.isConvert = true;
             }
             catch (Exception e)
             {
                 _docEntity.isConvert    = false;
                 _docEntity.ConvertError = e.Message;
             }
         }
     }
     return(_docEntity);
 }
Example #20
0
        /// <summary>
        /// Update document entity
        /// </summary>
        /// <param name="keyId"></param>
        /// <param name="modelEntity"></param>
        /// <returns></returns>
        public bool UpdateDocument(int keyId, DocumentEntity modelEntity)
        {
            var success = false;

            if (modelEntity != null)
            {
                using (var scope = new TransactionScope())
                {
                    var document = _unitOfWork.DocumentRepository.GetByID(keyId);
                    if (document != null)
                    {
                        document.ID2            = modelEntity.ID2;
                        document.DocTypeID      = modelEntity.DocTypeID;
                        document.DocumentFolder = modelEntity.DocumentFolder;
                        document.Description    = modelEntity.Description;
                        _unitOfWork.DocumentRepository.Update(document);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return(success);
        }
Example #21
0
        /// <summary>
        /// Create document entity
        /// </summary>
        /// <param name="modelEntity"></param>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public int CreateDocuments(DocumentEntity modelEntity, string filePath, string fileName)
        {
            using (var scope = new TransactionScope())
            {
                modelEntity.DocPath = SaveFileName(filePath, fileName, modelEntity.ID1.ToString());
                int result;
                try
                {
                    result = _unitOfWork.CPDocumentsInsert(modelEntity.ID1, modelEntity.ID2, modelEntity.DocType, modelEntity.DocPath, modelEntity.Description, modelEntity.DiscRefNo,
                                                           modelEntity.ClientViewable, modelEntity.DocSource, modelEntity.EnteredBy, DateTime.Now.Date, modelEntity.EventId, modelEntity.VendorViewable,
                                                           modelEntity.BorrowerViewable, modelEntity.DocTypeID, modelEntity.DocumentFolder,
                                                           modelEntity.uidHUDLine.HasValue ? modelEntity.uidHUDLine.Value.ToString() : null,
                                                           modelEntity.uidDisbursement.HasValue ? modelEntity.uidDisbursement.Value.ToString() : null,
                                                           modelEntity.IsLocked, modelEntity.S3KeyName, modelEntity.TCD_RowId, modelEntity.DisbursementID, modelEntity.UploadfromWeb, modelEntity.UploadBy);
                }
                catch (Exception)
                {
                    throw new Exception("Save failed in DB");
                }

                scope.Complete();
                return(result);
            }
        }
 /// <summary>
 /// If the document is a e-mail in PST file generate and return document id using Conversation Index and Threading Constraint value. Otherwise return document id as is
 /// It uses delegate - if null, uses original document id.
 /// </summary>
 /// <param name="document"> EDRM Document Entity </param>
 /// <returns> conversation index or original document id </returns>
 protected override string GetDocumentId(DocumentEntity document)
 {
     TagEntity tag = document.Tags.FirstOrDefault<TagEntity>(p => p.TagName.Equals(OutlookEdrmManagerConstants.TagNameConversationIndex));
    
     if (tag != null && GetDocumentIdFromConversationIndex != null) return  GetDocumentIdFromConversationIndex(tag.TagValue);
     return base.GetDocumentId(document);
 }
Example #23
0
 private IEnumerable<Tuple<string, Type>> GetDocumentEntityIdentities(DocumentEntity documentEntity)
 {
     return settings
         .GetAllRegistredBaseTypes(documentEntity.EntityType)
         .Select(type => new Tuple<string, Type>(documentEntity.EntityId, type));
 }
Example #24
0
        public async Task <IActionResult> PostReview([FromBody] ReviewRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CultureInfo cultureInfo = new CultureInfo(request.CultureInfo);

            Resource.Culture = cultureInfo;


            UserEntity userEntity = await _context.Users.FindAsync(request.User);

            if (userEntity == null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = Resource.UserDoesntExists
                }));
            }

            DocumentEntity documentEntity = await _context.Documents.FindAsync(request.Document);

            if (documentEntity == null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = Resource.DocumentDoesntexist
                }));
            }

            ReviewEntity reviewEntity = await _context.Reviews
                                        .FirstOrDefaultAsync(p => p.User.Id == request.User && p.Document.Id == request.Document);

            string message = "";

            if (reviewEntity == null)
            {
                reviewEntity = new ReviewEntity
                {
                    Document = documentEntity,
                    Comment  = request.Comment,
                    Rating   = request.Rating,
                    Favorite = request.Favorite,
                    User     = userEntity
                };
                message = Resource.TheReviewWasMadeCorrectly;
                _context.Reviews.Add(reviewEntity);
            }
            else
            {
                reviewEntity.Comment  = request.Comment;
                reviewEntity.Rating   = request.Rating;
                reviewEntity.Favorite = request.Favorite;
                message = Resource.TheReviewWasEditedSuccessfully;
                _context.Reviews.Update(reviewEntity);
            }

            await _context.SaveChangesAsync();

            return(Ok(new Response
            {
                IsSuccess = true,
                Message = message
            }));
        }
        public async Task <TemplateMapping> GetTemplateMapping(string specificationId, string fundingStreamId)
        {
            DocumentEntity <TemplateMapping> result = await _cosmosRepository.ReadDocumentByIdAsync <TemplateMapping>($"templatemapping-{specificationId}-{fundingStreamId}");

            return(result?.Content);
        }
        /// <summary>
        /// Transforms EDRM fields to list of EV Document field Business entities
        /// </summary>
        /// <param name="rvwDocumentBEO"> call by reference - Document object for which fields to be updated. </param>
        /// <param name="edrmDocument"> EDRM document object </param>
        /// <param name="mappedFields"> fields mapped while scheduling import. </param>
        protected virtual void TransformEDRMFieldsToDocumentFields(ref RVWDocumentBEO rvwDocumentBEO, DocumentEntity edrmDocument, List<FieldMapBEO> mappedFields)
        {
            #region Add all mapped fields
            foreach (FieldMapBEO mappedField in mappedFields)
            {
                //Create a Tag Entity for each mapped field
                TagEntity tag = new TagEntity();

                // Get tag/field from EDRM file for give mapped field
                IEnumerable<TagEntity> tagEnumerator = edrmDocument.Tags.Where(p => p.TagName.Equals(mappedField.SourceFieldName, StringComparison.CurrentCultureIgnoreCase));
                if (tagEnumerator.Count<TagEntity>() > 0) { tag = tagEnumerator.First<TagEntity>(); }

                // Adding Field map information only if Tag Value is available.

                // Create a Field business Entity for each mapped field
                RVWDocumentFieldBEO fieldBEO = new RVWDocumentFieldBEO()
                {
                    // set required properties / field data
                    FieldId = mappedField.DatasetFieldID,
                    FieldName = mappedField.DatasetFieldName,
                    FieldValue = tag.TagValue ?? string.Empty,
                    FieldType = new FieldDataTypeBusinessEntity() { DataTypeId = mappedField.DatasetFieldTypeID }
                };

                // Add tag to the document
                rvwDocumentBEO.FieldList.Add(fieldBEO);

            } // End of loop through fields in a document.           
            #endregion
        }
        /// <summary>
        /// Transform "EDRM document entity" to EV's Document BEO
        /// This function doesn't set field data
        /// Field data is set separately as there are two variances of this operation. </summary>
        /// 1) set all fields available in the EDRM file<param name="rvwDocumentBEO"></param>
        /// 2) set mapped fields only.
        /// </summary>
        /// <param name="rvwDocumentBEO"> Document Business Entity, by reference so that the transformed data is updated in this object. </param>
        /// <param name="edrmDocument"> EDRM document entity which is going tobe transformed to EV Document Business Entity. </param>
        protected virtual void TransformEDRMDocumentEntityToDocumentBusinessEntity(ref RVWDocumentBEO rvwDocumentBEO, DocumentEntity edrmDocument)
        {
            // Initialize if the object is not created
            if (rvwDocumentBEO == null)
                rvwDocumentBEO = new RVWDocumentBEO();

            // Document ID is MD5 hash of EDRM file + EDRM Document ID.
            // This makes document unique in the system and identifies if same EDRM file attempted to be imported twice.
            // Special character to 
            rvwDocumentBEO.DocumentId = GetDocumentId(edrmDocument);

            // Set MIME type
            rvwDocumentBEO.MimeType = edrmDocument.MIMEType;

            #region Add associate file details/names from EDRM file

            // NOTES: 
            // Binary and text is set later by the consuming module. This is to reduce weight of objects
            // Binary and text could increase memory by great extent.

            foreach (FileEntity fileEntity in edrmDocument.Files)
            {
                // Check if type is native
                if (fileEntity.FileType.ToLower().Equals(Constants.EDRMAttributeNativeFileType.ToLower()))
                {
                    // Set file path for native file types.
                    // Condition - check if native file entity has external file entities in it or not.
                    if (fileEntity.ExternalFile != null)
                    {
                        // Checks in below statement 1) null check on "file path" and 2) are there any external files
                        rvwDocumentBEO.FileName = (fileEntity.ExternalFile.Count > 0) ? fileEntity.ExternalFile[0].FileName : string.Empty;
                        rvwDocumentBEO.NativeFilePath = (fileEntity.ExternalFile.Count > 0) ? CreateFileURI(fileEntity.ExternalFile[0].FilePath, fileEntity.ExternalFile[0].FileName) : string.Empty;
                        rvwDocumentBEO.FileExtension = (fileEntity.ExternalFile.Count > 0) ? fileEntity.ExternalFile[0].FileName.Substring(fileEntity.ExternalFile[0].FileName.LastIndexOf(".")) : string.Empty;

                        if (!string.IsNullOrEmpty(rvwDocumentBEO.NativeFilePath) && File.Exists(rvwDocumentBEO.NativeFilePath))
                        {
                            //Calculating size of file in KB
                            FileInfo fileInfo = new FileInfo(rvwDocumentBEO.NativeFilePath);
                            rvwDocumentBEO.FileSize = (int)Math.Ceiling(fileInfo.Length / Constants.KBConversionConstant);
                        }
                    }
                }

                // Check if the type is Text.
                if (fileEntity.FileType.ToLower().Equals(Constants.EDRMAttributeTextFileType.ToLower()))
                {
                    if (fileEntity.ExternalFile != null)
                    {
                        // For text set file details in TextContent property. Set the real text just before import.
                        // This is to help reduce weight of the object.

                        // Checks in below statement 1) null check on "file path" and 2) are there any external files
                        if (rvwDocumentBEO.DocumentBinary == null) { rvwDocumentBEO.DocumentBinary = new RVWDocumentBinaryBEO(); }

                        RVWExternalFileBEO textFile = new RVWExternalFileBEO
                        {
                            Type = Constants.EDRMAttributeTextFileType,
                            Path = (fileEntity.ExternalFile.Count > 0) ? CreateFileURI(fileEntity.ExternalFile[0].FilePath, fileEntity.ExternalFile[0].FileName) : string.Empty
                        };

                        rvwDocumentBEO.DocumentBinary.FileList.Add(textFile);
                    }
                }
            }

            #endregion
        }
Example #28
0
 public WordDocument(DocumentEntity docentity)
     : base(docentity)
 {
 }
Example #29
0
        public ActionResult Create(DocumentViewModel document, HttpPostedFileBase upload)
        {
            var tempEntity = new DocumentEntity()
            {
                Id               = document.assignedEntity.Id,
                returnTarget     = document.assignedEntity.returnTarget,
                EntityName       = document.assignedEntity.EntityName,
                returnId         = document.assignedEntity.returnId,
                EntityType       = document.assignedEntity.EntityType,
                DocumentTypeName = document.assignedEntity.DocumentTypeName
            };

            document.assignedEntity = tempEntity;

            var addDocument = new Document()
            {
                //Id = document.Id,
                DocumentTypeId  = document.DocumentTypeId,
                DocumentContent = document.DocumentContent,
                DocumentName    = document.DocumentName,
                DueDate         = document.DueDate,
                UploadDate      = DateTime.Now
            };

            if (upload != null && upload.ContentLength > 0)
            {
                try
                {
                    if (ModelState.IsValid)

                    {
                        if (upload != null && upload.ContentLength > 0)
                        {
                            addDocument.DocumentName = System.IO.Path.GetFileName(upload.FileName);
                            addDocument.FileType     = upload.ContentType;
                            using (var reader = new System.IO.BinaryReader(upload.InputStream))
                            {
                                addDocument.Content = reader.ReadBytes(upload.ContentLength);
                            }
                        }

                        db.Documents.Add(addDocument);
                        db.SaveChanges();



                        var user = User.Identity.GetUserId();

                        if (document.assignedEntity.EntityType == "Course")
                        {
                            var courseDocument = new CourseDocument()
                            {
                                DocumentId = addDocument.Id,
                                AssignDate = DateTime.Now,
                                OwnerId    = User.Identity.GetUserId(),
                                CourseId   = document.assignedEntity.Id
                            };

                            db.CourseDocuments.Add(courseDocument);
                            db.SaveChanges();
                        }
                        else if (document.assignedEntity.EntityType == "Module")
                        {
                            var moduleDocument = new ModuleDocument()
                            {
                                DocumentId = addDocument.Id,
                                AssignDate = DateTime.Now,
                                OwnerId    = User.Identity.GetUserId(),
                                ModuleId   = document.assignedEntity.Id
                            };

                            db.ModuleDocuments.Add(moduleDocument);
                            db.SaveChanges();
                        }
                        else if (document.assignedEntity.EntityType == "Activity")
                        {
                            var activityDocument = new ActivityDocument()
                            {
                                DocumentId = addDocument.Id,
                                AssignDate = DateTime.Now,
                                OwnerId    = User.Identity.GetUserId(),
                                ActivityId = document.assignedEntity.Id
                            };

                            db.ActivityDocuments.Add(activityDocument);
                            db.SaveChanges();
                        }



                        return(RedirectToAction("Details", "Courses", new { id = document.assignedEntity.returnId, redirect = document.assignedEntity.returnTarget }));
                    }
                }
                catch
                {
                    //Log the error (uncomment dex variable name and add a line here to write a log.
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                }
            }

            ViewBag.DocumentTypeId = new SelectList(db.DocumentTypes, "Id", "DocumentTypeName", document.DocumentTypeId);
            return(View(document));
        }
 /// <summary>
 /// If the document is a lotus notes e-mail generate and return document id using EDRM Document Id and Threading Constraint value. Otherwise return document id as is
 /// It uses delegate - if null, uses original document id.
 /// </summary>
 /// <param name="document"> EDRM Document Entity </param>
 /// <returns> conversation index or original document id </returns>
 protected override string GetDocumentId(DocumentEntity document)
 {
     // Create Document Id from Doc Id value of Lotus Notes e-mail message
     if (document != null && (!string.IsNullOrEmpty(document.DocumentID)) && CreateDocumentId != null) return CreateDocumentId(document.DocumentID);
     else return base.GetDocumentId(document);
 }
Example #31
0
 public ActionResult DeleteAjax(DocumentEntity entity)
 {
     return(View(entity));
 }
Example #32
0
        internal static DocumentEntity ConvertToDocumentEntity(IContentItem fileInfo, IPolicyResponseObject uro)
        {
            if (fileInfo == null)
                return null;

            DocumentEntity documentEntity = new DocumentEntity();
            List<PolicySetEventEntity> policyEvents = new List<PolicySetEventEntity>();

            // Can't actually do much populating if this is null
            documentEntity.ContentType = fileInfo.Type;
            documentEntity.Name = fileInfo.Name;

            InitialiseFileEntityMetadata(documentEntity, fileInfo);

            if (fileInfo.PolicySetCollection != null)
            {
                foreach (IPolicySetResponse policySetInfo in fileInfo.PolicySetCollection)
                {
                    PolicySetEventEntity PolicySet = new PolicySetEventEntity();
                    PolicySet.EventDate = policySetInfo.Date;
                    PolicySet.PolicySetName = policySetInfo.Name;
                    List<PolicyEntity> PolicyEntities = new List<PolicyEntity>();

                    if (policySetInfo.PolicyReportCollection != null)
                    {
                        foreach (IPolicyResponse policyInfo in policySetInfo.PolicyReportCollection)
                        {
                            if (!ProEntityConverter.ShouldAudit(policyInfo))
                                continue;

                            PolicyEntity PolicyEntity = new PolicyEntity();

                            PolicyEntity.PolicyName = policyInfo.Name;
                            PolicyEntity.Triggered = policyInfo.Triggered;

                            List<ExpressionEntity> expressionList = new List<ExpressionEntity>();
                            if (policyInfo.ExpressionCollection != null)
                            {
                                foreach (IExpressionResponse expressionInfo in policyInfo.ExpressionCollection)
                                {
                                    if (!expressionInfo.Triggered)
                                        continue;

                                    ExpressionEntity expression = new ExpressionEntity();
                                    expression.ExpressionName = expressionInfo.Name;
                                    expression.ExpressionRating = expressionInfo.Rating;
                                    expression.ExpressionType = "CONDITION";
                                    expression.ExpressionTriggered = expressionInfo.Triggered;

                                    // IMPORTANT!! these not put to the audit trail as is storing personal info. bad.
                                    List<ExpressionPropertyEntity> expressionProperty = new List<ExpressionPropertyEntity>();
                                    expression.ExpressionProperties = expressionProperty.ToArray();

                                    expressionList.Add(expression);
                                }
                            }

                            if (policyInfo.Routing != null)
                            {
                                ExpressionEntity routing = new ExpressionEntity();
                                routing.ExpressionName = policyInfo.Routing.Name;
                                routing.ExpressionRating = policyInfo.Routing.Rating;
                                routing.ExpressionType = "ROUTING";
                                routing.ExpressionTriggered = true;

                                // IMPORTANT!! these not put to the audit trail as is storing personal info. bad.
                                List<ExpressionPropertyEntity> expressionProperty = new List<ExpressionPropertyEntity>();
                                routing.ExpressionProperties = expressionProperty.ToArray();

                                expressionList.Add(routing);
                            }
                            PolicyEntity.Expressions = expressionList.ToArray();

                            List<PolicyPropertyEntity> policyPropList = new List<PolicyPropertyEntity>();
                            if (policyInfo.Properties != null)
                            {
                                foreach (KeyValuePair<string, string> de in policyInfo.Properties)
                                {
                                    PolicyPropertyEntity prop = new PolicyPropertyEntity();
                                    prop.Name = de.Key;
                                    prop.PropertyValue = de.Value;
                                    policyPropList.Add(prop);
                                }
                            }
                            PolicyEntity.PolicyProperties = policyPropList.ToArray();

                            List<ActionEntity> acList = new List<ActionEntity>();
                            if (policyInfo.ActionCollection != null)
                            {
                                foreach (IPolicyResponseAction actionInfo in policyInfo.ActionCollection)
                                {
                                    ActionEntity ae = ConvertActionEntity(actionInfo);

                                    if (ae != null)
                                        acList.Add(ae);
                                }
                            }
                            PolicyEntity.Actions = acList.ToArray();
                            PolicyEntities.Add(PolicyEntity);
                        }
                    }
                    PolicySet.Policies = PolicyEntities.ToArray();
                    policyEvents.Add(PolicySet);
                }
            }
            documentEntity.DocumentEvents = policyEvents.ToArray();
            return documentEntity;
        }
 public void Update(DocumentEntity entity)
 {
     this.CheckEntity(entity);
     DocumentDA.Update(entity);
 }
Example #34
0
      internal static void InitialiseFileEntityMetadata(DocumentEntity documentEntity, IContentItem fileInfo)
        {
            if (fileInfo == null)
                return;

            List<DocumentMetadataEntity> metadata = new List<DocumentMetadataEntity>();
            if (documentEntity.ContentType != "Email")
            {
                DocumentMetadataEntity mdSize = new DocumentMetadataEntity();
                mdSize.Name = "Size";
                mdSize.Data = fileInfo.Size.ToString();

                if (fileInfo.Properties.ContainsKey("Encrypted"))
                {
                    DocumentMetadataEntity mdEncrypted = new DocumentMetadataEntity();
                    mdEncrypted.Name = "Encrypted";
                    mdEncrypted.Data = fileInfo.Properties["Encrypted"];
                    metadata.Add(mdEncrypted);
                }

                DocumentMetadataEntity mdFileName = new DocumentMetadataEntity();
                mdFileName.Name = "File Name";
                mdFileName.Data = fileInfo.Name;

                DocumentMetadataEntity mdDisplayName = new DocumentMetadataEntity();
                mdDisplayName.Name = "Display Name";
                mdDisplayName.Data = fileInfo.Name;

                metadata.Add(mdSize);
                metadata.Add(mdFileName);
                metadata.Add(mdDisplayName);
            }
            documentEntity.DocumentMetadata = metadata.ToArray();
        }
        /// <summary>
        /// Create an EmailDocumentEntity object based on DocumentEntity object
        /// </summary>
        /// <param name="documentEntity"> Document Entity object to be converted</param>
        /// <returns> Converted EmailDocumentEntity </returns>
        private static EmailDocumentEntity ConvertDocumentEntityToEmailDocumentEntity(DocumentEntity documentEntity)
        {
            EmailDocumentEntity emailDocumentEntity = new EmailDocumentEntity
            {
                DocumentID = documentEntity.DocumentID,
                MIMEType= documentEntity.MIMEType,                
            };

            emailDocumentEntity.Files.AddRange(documentEntity.Files);
            emailDocumentEntity.Tags.AddRange(documentEntity.Tags);

            return emailDocumentEntity;
        }
Example #36
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.Page.Validate();
            if (!this.Page.IsValid)
            {
                return;
            }

            if (ObjectId != PrimaryKeyId.Empty)
            {
                _bindObject = BusinessManager.Load(ClassName, ObjectId);
            }
            else
            {
                _bindObject = BusinessManager.InitializeEntity(ClassName);
            }

            if (_bindObject != null)
            {
                ProcessCollection(this.Page.Controls, (EntityObject)_bindObject);

                PrimaryKeyId objectId = ObjectId;

                if (ObjectId != PrimaryKeyId.Empty)
                {
                    BusinessManager.Update((EntityObject)_bindObject);
                }
                else
                {
                    CreateRequest request = new CreateRequest((EntityObject)_bindObject);
                    if (PrimaryKeyId.Parse(ddTemplate.SelectedValue) != PrimaryKeyId.Empty)
                    {
                        request.Parameters.Add(DocumentRequestParameters.Create_DocumentTemplatedId, PrimaryKeyId.Parse(ddTemplate.SelectedValue));
                    }
                    CreateResponse response = (CreateResponse)BusinessManager.Execute(request);
                    objectId = response.PrimaryKeyId;
                }

                Response.Redirect(String.Format(CultureInfo.InvariantCulture, "~/Apps/MetaUIEntity/Pages/EntityView.aspx?ClassName={0}&ObjectId={1}", DocumentEntity.GetAssignedMetaClassName(), objectId), true);
            }
        }
Example #37
0
 public DocumentEntity SelectOne(Guid Id)
 {
     DocumentEntity toReturn = null;
     using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
     {
         DocumentEntity _DocumentEntity = new DocumentEntity(Id);
         if (adapter.FetchEntity(_DocumentEntity))
         {
             toReturn = _DocumentEntity;
         }
     }
     return toReturn;
 }
        /// <summary>
        /// Transform "EDRM document entity" to EV's Document BEO
        /// This function doesn't set field data
        /// Field data is set separately as there are two variances of this operation. </summary>
        /// 1) set all fields available in the EDRM file
        /// 2) set mapped fields only.
        /// 
        /// In relationship objects for the EDRM Manager document IDs are updated in a format compatible with Vault/EV system.
        /// </summary>
        /// <param name="rvwDocumentBEO"> Document Business Entity, by reference so that the transformed data is updated in this object. </param>
        /// <param name="edrmDocument"> EDRM document entity which is going tobe transformed to EV Document Business Entity. </param>
        protected virtual void TransformDocumentsAndRelationships(ref RVWDocumentBEO rvwDocumentBEO, DocumentEntity edrmDocument)
        {
            // Transform "EDRM document entity" to EV's Document BEO
            TransformEDRMDocumentEntityToDocumentBusinessEntity(ref rvwDocumentBEO, edrmDocument);

            // Update relationship's IDs 
            foreach (RelationshipEntity relationship in relationships)
            {
                if (edrmDocument.DocumentID.Equals(relationship.ParentDocID))
                {
                    relationship.ParentDocID = rvwDocumentBEO.DocumentId;
                }

                if (edrmDocument.DocumentID.Equals(relationship.ChildDocID))
                {
                    relationship.ChildDocID = rvwDocumentBEO.DocumentId;
                }
            }
        }
Example #39
0
        public bool Update(DocumentEntity _DocumentEntity)
        {
            bool toReturn = false;
            using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
            {
                RelationPredicateBucket filter = new RelationPredicateBucket();
                IPredicateExpression _PredicateExpression = new PredicateExpression();
                _PredicateExpression.Add(DocumentFields.Id == _DocumentEntity.Id);

                filter.PredicateExpression.Add(_PredicateExpression);

                adapter.UpdateEntitiesDirectly(_DocumentEntity, filter);
                toReturn = true;
            }
            return toReturn;
        }
        protected virtual string GetDocumentId(DocumentEntity edrmDocument)
        {
            return Guid.NewGuid().ToString().Replace("-", "").ToUpper();

        }
Example #41
0
 public bool Update(DocumentEntity _DocumentEntity, RelationPredicateBucket filter)
 {
     bool toReturn = false;
     using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
     {
         adapter.UpdateEntitiesDirectly(_DocumentEntity, filter);
         toReturn = true;
     }
     return toReturn;
 }
        public async Task <Calculation> GetCalculationById(string calculationId)
        {
            DocumentEntity <Calculation> calculation = await _cosmosRepository.ReadDocumentByIdAsync <Calculation>(calculationId);

            return(calculation?.Content);
        }
Example #43
0
 public DocumentEntity Insert(DocumentEntity _DocumentEntity)
 {
     using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
     {
         adapter.SaveEntity(_DocumentEntity, true);
     }
     return _DocumentEntity;
 }
 public async Task UpdateDocumentAsync(DocumentEntity document)
 {
     _context.Documents.Update(document);
     await _context.SaveChangesAsync();
 }
Example #45
0
        private void RemoveDocumentEntity(DocumentEntity documentEntity)
        {
            entityMap.Remove(documentEntity.Entity);

            foreach (var identity in GetDocumentEntityIdentities(documentEntity))
                entityIdAndTypeMap.Remove(identity);

            documentIdMap.Remove(documentEntity.DocumentId);
        }
        private async Task<ItemResponse<DocumentEntity<T>>> CreateDocumentInternalAsync<T>(T entity, ItemRequestOptions requestOptions = null) where T : IIdentifiable
        {
            DocumentEntity<T> doc = CreateDocumentEntity(entity);

            return await RepositoryContainer.CreateItemAsync(doc, requestOptions: requestOptions);
        }
Example #47
0
        public DocumentEntity Insert(string DocumentName, string DocumentCode, string TextId, long GroupId, string Description, int Mark, int CountDown, int ReMark, string PathName, string DisplayImage, string VideoTrailer, bool ShowVideo, double FileSize, bool IsVisible, DateTime CreatedDate, string CreatedBy, DateTime UpdatedDate, string UpdatedBy, bool IsDeleted)
        {
            DocumentEntity _DocumentEntity = new DocumentEntity();
            using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
            {

                _DocumentEntity.DocumentName = DocumentName;
                _DocumentEntity.DocumentCode = DocumentCode;
                _DocumentEntity.TextId = TextId;
                _DocumentEntity.GroupId = GroupId;
                _DocumentEntity.Description = Description;
                _DocumentEntity.Mark = Mark;
                _DocumentEntity.CountDown = CountDown;
                _DocumentEntity.ReMark = ReMark;
                _DocumentEntity.PathName = PathName;
                _DocumentEntity.DisplayImage = DisplayImage;
                _DocumentEntity.VideoTrailer = VideoTrailer;
                _DocumentEntity.ShowVideo = ShowVideo;
                _DocumentEntity.FileSize = FileSize;
                _DocumentEntity.IsVisible = IsVisible;
                _DocumentEntity.CreatedDate = CreatedDate;
                _DocumentEntity.CreatedBy = CreatedBy;
                _DocumentEntity.UpdatedDate = UpdatedDate;
                _DocumentEntity.UpdatedBy = UpdatedBy;
                _DocumentEntity.IsDeleted = IsDeleted;
                adapter.SaveEntity(_DocumentEntity, true);
            }
            return _DocumentEntity;
        }
        /// <summary>
        /// Adds a document to the queue.
        /// </summary>
        /// <param name="queueDocumentData">Queue document data.</param>
        /// <returns>Created document entity.</returns>
        public async Task <DocumentEntity> AddDocumentToQueue(QueueDocumentData queueDocumentData)
        {
            // Validate the document
            await _queueDocumentDataValidator.ValidateAndThrowAsync(queueDocumentData);

            if (Log.IsEnabled(LogEventLevel.Verbose))
            {
                Log.Information("Queue document data {@queueDocumentData}", JsonConvert.SerializeObject(queueDocumentData));
            }

            // Get the metadata from the package
            CdaPackageData cdaPackageData = _cdaPackageService.ExtractPackageData(queueDocumentData.CdaPackage);

            // Check if the document already exists with the same ID
            DocumentEntity documentEntity = await _dataStore.GetDocument(cdaPackageData.DocumentId);

            if (documentEntity != null)
            {
                throw new ArgumentException($"Document with ID '{cdaPackageData.DocumentId}' already exists in the queue with the '{documentEntity.Status.ToString()}' state");
            }

            // Validate the replace
            if (!string.IsNullOrEmpty(queueDocumentData.DocumentIdToReplace))
            {
                // Check if the document to replace exists
                var documentToReplace = await _dataStore.GetDocument(queueDocumentData.DocumentIdToReplace);

                if (documentToReplace == null)
                {
                    throw new ArgumentException($"Document to replace with ID '{queueDocumentData.DocumentIdToReplace}' does not exist in the queue");
                }

                // Check the replace document status
                if (documentToReplace.Status == DocumentStatus.RetryLimitReached || documentToReplace.Status == DocumentStatus.Removed)
                {
                    throw new ArgumentException($"Document to replace cannot have a status of '{DocumentStatus.RetryLimitReached.ToString()}' or '{DocumentStatus.Removed.ToString()}' and is '{documentToReplace.Status.ToString()}'");
                }
            }

            DateTime addedDateTime = DateTime.Now;

            // Create the document
            DocumentEntity documentToQueue = new DocumentEntity
            {
                QueueDate           = addedDateTime,
                Status              = DocumentStatus.Pending,
                DocumentId          = cdaPackageData.DocumentId,
                DocumentIdToReplace = queueDocumentData.DocumentIdToReplace,
                FormatCodeName      = queueDocumentData.FormatCodeName,
                FormatCode          = queueDocumentData.FormatCode,
                DocumentData        = queueDocumentData.CdaPackage,
                Ihi = cdaPackageData.Ihi
            };

            // Add the create event
            documentToQueue.AddEvent(new EventEntity
            {
                Type      = EventType.Created,
                EventDate = addedDateTime
            });

            await _dataStore.AddDocument(documentToQueue);

            return(documentToQueue);
        }
Example #49
0
        private DocumentEntity RegisterDocumentEntity(DocumentEntity documentEntity)
        {
            entityMap[documentEntity.Entity] = documentEntity;

            foreach (var identity in GetDocumentEntityIdentities(documentEntity))
                entityIdAndTypeMap[identity] = documentEntity;

            documentIdMap[documentEntity.DocumentId] = documentEntity;

            return documentEntity;
        }
Example #50
0
 public WordDocument(DocumentEntity docentity, ConvertComponentType componenttype)
     : base(docentity, componenttype)
 {
 }
Example #51
0
        public bool Update(Guid Id, long IntId, string DocumentName, string DocumentCode, string TextId, long GroupId, string Description, int Mark, int CountDown, int ReMark, string PathName, string DisplayImage, string VideoTrailer, string VideoUploadType, bool ShowVideo, long FileSize, bool IsVisible, string UploadType, DateTime CreatedDate, string CreatedBy, DateTime UpdatedDate, string UpdatedBy, bool IsDeleted)
        {
            bool toReturn = false;
            using(DataAccessAdapterBase adapter = (new DataAccessAdapterFactory()).CreateAdapter())
            {
                DocumentEntity _DocumentEntity = new DocumentEntity(Id);
                if (adapter.FetchEntity(_DocumentEntity))
                {

                    _DocumentEntity.DocumentName = DocumentName;
                    _DocumentEntity.DocumentCode = DocumentCode;
                    _DocumentEntity.TextId = TextId;
                    _DocumentEntity.GroupId = GroupId;
                    _DocumentEntity.Description = Description;
                    _DocumentEntity.Mark = Mark;
                    _DocumentEntity.CountDown = CountDown;
                    _DocumentEntity.ReMark = ReMark;
                    _DocumentEntity.PathName = PathName;
                    _DocumentEntity.DisplayImage = DisplayImage;
                    _DocumentEntity.VideoTrailer = VideoTrailer;
                    _DocumentEntity.VideoUploadType = VideoUploadType;
                    _DocumentEntity.ShowVideo = ShowVideo;
                    _DocumentEntity.FileSize = FileSize;
                    _DocumentEntity.IsVisible = IsVisible;
                    _DocumentEntity.UploadType = UploadType;
                    _DocumentEntity.CreatedDate = CreatedDate;
                    _DocumentEntity.CreatedBy = CreatedBy;
                    _DocumentEntity.UpdatedDate = UpdatedDate;
                    _DocumentEntity.UpdatedBy = UpdatedBy;
                    _DocumentEntity.IsDeleted = IsDeleted;
                    adapter.SaveEntity(_DocumentEntity, true);
                    toReturn = true;
                }
            }
            return toReturn;
        }
Example #52
0
        public Task <DocumentEntity <Dataset> > GetDatasetDocumentByDatasetId(string datasetId)
        {
            DocumentEntity <Dataset> dataset = _cosmosRepository.QueryDocuments <Dataset>(1).Where(c => c.Id == datasetId && !c.Deleted).AsEnumerable().FirstOrDefault();

            return(Task.FromResult(dataset));
        }
Example #53
0
 public SelectedFileChangedEvent(DocumentEntity doc)
 {
     Selection = doc;
 }