예제 #1
0
        public ActionResult Add()
        {
            _logger.Info("DocumentController 添加文档");

            try
            {
                var fileCollection = _requestProvider.FileCollection;

                var userId    = _contextService.UserId;
                var userName  = _contextService.NickName;
                var depId     = _contextService.DepId;
                var timeStamp = _requestProvider["TimeStamp"];
                var spaceId   = _requestProvider["SpaceId"];

                var space = string.IsNullOrWhiteSpace(spaceId) ? _spaceService.GetDefaultSpace() : _spaceService.GetSpace(spaceId);

                _logger.Info(string.Format("Add Document, spaceId:[{0}];spaceSeqNo:[{1}], spaceName:[{2}], userId:[{3}];userName:[{4}]。",
                                           space.Id, space.SpaceSeqNo, space.SpaceName, userId, userName));



                var documents = new List <DocumentObject>();

                for (int i = 0; i < fileCollection.Count; ++i)
                {
                    var document = DocumentBuilder.Build(fileCollection[i], space.Id.ToString(), space.SpaceSeqNo, space.SpaceName, userId, userName, depId, Visible.Public);
                    documents.Add(document);
                    var mimeType = MimeMapping.GetMimeMapping(document.FileName);
                    _storePolicy.AddStream(fileCollection[i].FileStream, mimeType, document.StorePath);
                }


                var contracts = _documentService.Add(documents);
                if (!string.IsNullOrWhiteSpace(timeStamp))
                {
                    MemoryContainer.Push(timeStamp, documents);
                }

                return(Json(new UploadViewModel(ErrorMessages.Success,
                                                ErrorMessages.GetErrorMessages(ErrorMessages.Success),
                                                contracts)));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.StackTrace);
                _logger.Error(ex.Message);
            }

            _logger.Error(ErrorMessages.GetErrorMessages(ErrorMessages.UploadFailed));
            return(Json(new UploadViewModel(ErrorMessages.UploadFailed,
                                            ErrorMessages.GetErrorMessages(ErrorMessages.UploadFailed))));
        }
예제 #2
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!fuUploader.BinaryFileId.HasValue)
            {
                return;
            }

            using (var rockContext = new RockContext())
            {
                var documentService = new DocumentService(rockContext);
                var document        = new Document();

                if (hfDocumentId.Value.IsNotNullOrWhiteSpace())
                {
                    document = documentService.Get(hfDocumentId.ValueAsInt());
                }
                else
                {
                    documentService.Add(document);
                }

                document.DocumentTypeId = ddlAddEditDocumentType.SelectedValueAsInt().Value;
                document.EntityId       = this.ContextEntity().Id;
                document.Name           = tbDocumentName.Text;
                document.Description    = tbDescription.Text;
                document.SetBinaryFile(fuUploader.BinaryFileId.Value, rockContext);

                rockContext.SaveChanges();
            }

            pnlAddEdit.Visible = false;
            BindGrid();
            pnlList.Visible = true;
            ClearForm();
        }
        public ActionResult Create(DocumentViewModel Dvm)
        {
            Document d = new Document();

            d.DocumentID = Dvm.DocumentID;

            d.Titre     = Dvm.Titre;
            d.Categorie = Dvm.Categorie;

            d.Etat = (Domain.Entities.Etat)Dvm.Etat;

            d.Biblio = new Bibliotheque {
                BibliothequeCode = Dvm.BibliothequeFK
            };

            DS.Add(d);
            DS.Commit();
            return(RedirectToAction("Index"));

            //   }

//        try
//        {
//            // TODO: Add insert logic here

//            return RedirectToAction("Index");
//    }
//        catch
//        {
//            return View();
//}
        }
예제 #4
0
 private void btnAddDocs_Click(object sender, EventArgs e)
 {
     if (_Dossier == null)
     {
         MessageBox.Show("لطفا اطلاعات پرونده را وارد کنید.");
     }
     else
     {
         if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             foreach (string file in openFileDialog1.FileNames)
             {
                 imageListView1.Items.Add(file);
                 try
                 {
                     string path = SaveFile(file);
                     _DocumentService.Add(new Document {
                         PN = _Dossier.PN, ParentDocumentID = null, FileName = path, AttachedToDossier = false
                     });
                 }
                 catch
                 {
                     imageListView1.Items.Clear();
                 }
             }
             showImage();
         }
     }
 }
예제 #5
0
        private void VsTwain_ImageAcquired(object sender, EventArgs e)
        {
            lblStatus.Text = "درحال ذخیره تصویر...";
            string fileName     = PersianCalendar.GetDate(DateTime.Now, "-") + " " + PersianCalendar.GetTime(DateTime.Now, "-", true, true);
            string documentPath = Path.Combine(tempDirectory, fileName + ".tiff").ToString();
            int    i            = 0;

            while (System.IO.File.Exists(documentPath))
            {
                documentPath = Path.Combine(tempDirectory, fileName + "(" + (++i).ToString() + ")" + ".tiff").ToString();
            }
            try
            {
                VsTwain.FileFormat = Vintasoft.Twain.FileFormat.TiffMulti;
                VsTwain.SaveImage(0, documentPath);
                VsTwain.DeleteImage(0);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "خطا در ذخیره فایل اسکن شده" + "\r\n\r\n" + ex.Message);
                return;
            }

            imageListView1.Items.Add(documentPath);
            string path = SaveFile(documentPath);

            _DocumentService.Add(new Document {
                PN = this.p, ParentDocumentID = null, FileName = path, AttachedToDossier = false
            });
        }
예제 #6
0
        public void GivenIhaveaPDFtoupload()
        {
            //Given I have a PDF to upload
            var attachment = new AttachmentRequest()
            {
                Data = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, 0xA1 }, FileName = "Chambers.pdf", Type = "application/pdf"
            };

            //PS: in real world we don't need the user or shouldn't trust the user to provide the mime type

            //    When I send the PDF to the API
            _docService.Add(attachment);

            //    Then it is uploaded successfully
            //no errors. Response from Add will be void.
            Assert.AreEqual(1, 1);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.Validate("AddEdit");
            if (this.IsValid)
            {
                int documentTypeID = Convert.ToInt32(ddlDocumentType.SelectedValue);
                try
                {
                    if (DocumentService.CanChangeStatus(txtCustomerCode.Text))
                    {
                        switch (RowID)
                        {
                        case 0:
                            DocumentService.Add(
                                Convert.ToInt32(ddlFindBranch.SelectedValue),
                                DateTime.Today,
                                calStartDate.SelectedDate.GetValueOrDefault(),
                                chkEndDate.Checked ? calEndDate.SelectedDate : (DateTime?)null,
                                txtCustomerCode.Text,
                                documentTypeID,
                                txtNotes.Text);
                            break;

                        default:
                            DocumentService.Update(
                                RowID,
                                DateTime.Today,
                                calStartDate.SelectedDate.GetValueOrDefault(),
                                chkEndDate.Checked ? calEndDate.SelectedDate : (DateTime?)null,
                                txtCustomerCode.Text,
                                documentTypeID,
                                txtNotes.Text);
                            break;
                        }

                        mvwForm.ActiveViewIndex = 0;
                        gvwMaster.DataBind();
                    }
                    else
                    {
                        WebFormHelper.SetLabelTextWithCssClass(
                            lblStatus,
                            "Cannot change customer status for any unpaid contract",
                            LabelStyleNames.ErrorMessage);
                    }
                }
                catch (Exception ex)
                {
                    WebFormHelper.SetLabelTextWithCssClass(
                        lblStatus,
                        ex.Message,
                        LabelStyleNames.ErrorMessage);

                    LogService.ErrorException(GetType().FullName, ex);
                }
            }
        }
예제 #8
0
        public ActionResult Upload(HttpPostedFileBase file)
        {
            var type     = Request.Form["fileType"];
            var training = Request.Form["trainings"];

            var    description = Request.Form["description"];
            string newName     = Request.Form["newFileName"];

            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);

                    if (newName != null && newName.Trim() != "")
                    {
                        String[] nameAndType = fileName.Split('.');
                        fileName = newName + "." + nameAndType.Last();
                    }

                    var      path     = Path.Combine(Server.MapPath("~/App_Data/File"), fileName);
                    FileInfo fileInfo = new FileInfo(path);
                    if (!fileInfo.Exists)
                    {
                        file.SaveAs(path);
                    }
                    else
                    {
                        TempData["message"] = "There is a file named: '" + fileName + "' has existed. Please change the file name and try to upload again!";
                        return(RedirectToAction("AddDocument"));
                    }
                    newName = fileName;

                    document.Size         = file.ContentLength;
                    document.DocumentName = newName;
                    document.Type         = type;
                    if (training == null || training.Trim() == "")
                    {
                        document.TrainingId = 0;
                    }
                    else
                    {
                        document.TrainingId = Convert.ToInt32(training);
                    }
                    document.Description = description;
                    documentService.Add(document);
                }
                ViewBag.Message = "Upload successful";
                return(RedirectToAction("Index"));
            }
            catch
            {
                ViewBag.Message = "Upload failed";
                return(RedirectToAction("Index"));
            }
        }
예제 #9
0
        public Document Add(AddDocumentViewModel addData)
        {
            var document = new Document {
                Alias   = addData.Alias,
                Title   = addData.Title,
                Content = "# " + addData.Title
            };

            return(_documentService.Add(document, addData.ParentId));
        }
예제 #10
0
        public Result Add(Document Document)
        {
            var result = new Result();

            try
            {
                DocumentService DocumentService = new DocumentService();
                DocumentService.Add(Document);
                result.IsSuccess = true;
            }
            catch (Exception exception)
            {
                result.IsSuccess     = false;
                result.ExceptionInfo = exception;
            }
            return(result);
        }
        public ActionResult Create(CommitteeResolutionViewModel model)
        {
            try
            {
                var file = model.attachment;
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var guid = Guid.NewGuid();
                    var path = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + guid.ToString() + Path.GetExtension(file.FileName);
                    file.SaveAs(path);

                    using (var unitOfWork = new UnitOfWork(new BankModuleFactory()))
                    {
                        var DocumentService = new DocumentService(unitOfWork);
                        var document = new Document()
                        {
                            DocumentType = BusinessEntities.DocumentTypes.Other,
                            Link = "Uploads/" + guid.ToString() + Path.GetExtension(file.FileName),
                        };
                        model.ProtocolDocument = DocumentService.Add(document);
                        unitOfWork.Commit();
                        model.ProtocolDocumentId = model.ProtocolDocument.Id;
                    }
                }

                if (!ModelState.IsValid)
                {
                    return View(model);
                }

                var result = _controleHelper.CreateEntity<CommitteeResolution, CommitteeResolutionViewModel>(model);
                if (result.Error.Any())
                {
                    ModelState.AddModelError(string.Empty, result.Error.First().ErrorMessage);
                    return View(model);
                }
                return RedirectToAction("Details", new { id = result.Entity.LoanApplicationId });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return View(model);
            }
        }
예제 #12
0
        public ActionResult Create(DocumentModels dm)
        {
            try
            {
                document d = new document();
                d.name = dm.Name;
                d.numberDownloading = dm.numberDownloading;
                d.path = dm.path;

                service.Add(d);
                service.Commit();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
예제 #13
0
        public ActionResult Create(DocumentViewModel DVM)
        {
            Document d = new Document()
            {
                Etat = (BibDomain.Entities.Etat)DVM.Etat
            };

            d.DocumentCode = DVM.DocumentCode;

            d.Titre     = DVM.Titre;
            d.Categorie = DVM.Categorie;
            //d.BibliothequeFK = DVM.BibliothequeFK;
            d.Bibliotheque = new Bibliotheque {
                BibliothequeCode = DVM.BibliothequeFK
            };

            DS.Add(d);
            DS.Commit();
            return(RedirectToAction("Index"));
        }
예제 #14
0
        public void should_pass_add_document_without_downloadPath()
        {
            int count = _documentService.GetAllDocuments().Count;

            var document = MakeSimpleDocument();

            Assert.IsNotNull(_documentService.Add(document));
            var result = _documentService.GetDocument(document.Id.ToString());


            Assert.AreEqual(result.FileName, "Test.doc");

            _documentService.Delete(document.Id.ToString());
            result = _documentService.GetDocument(document.Id.ToString());
            Assert.IsNull(result);

            int count2 = _documentService.GetAllDocuments().Count;

            Assert.AreEqual(count, count2);
        }
예제 #15
0
        static void Main(string[] args)
        {
            //Ajout Biblotheque
            Bibliotheque b = new Bibliotheque()
            {
                NbrDoc = 100
            };
            IBibliothequeService bibliothequeser = new BibliothequeService();

            bibliothequeser.Add(b);
            bibliothequeser.Commit();
            //Ajout 3 Livres
            Document D = new Livre()
            {
                Categorie = "informatique", Titre = "C# pour les debutants", nbrdepage = 157, Etat = Etat.Disponible, BibliothequeFK = 1
            };
            Document D1 = new Livre()
            {
                Categorie = "informatique", Titre = "Developper en .NET", nbrdepage = 209, Etat = Etat.Emprunte, BibliothequeFK = 1
            };
            Document D2 = new Livre()
            {
                Categorie = "informatique", Titre = "UML 2.0", nbrdepage = 358, Etat = Etat.Disponible, BibliothequeFK = 1
            };
            IDocumetService LS = new DocumentService();

            LS.Add(D);
            LS.Add(D1);
            LS.Add(D2);

            //Ajout 3 CD
            Document cd1 = new CD()
            {
                Categorie = "scientifique", Titre = "science de la vie et de la terre", NbreDePlage = 5, Duree = new TimeSpan(10, 10, 10), Etat = Etat.Disponible, BibliothequeFK = 1
            };
            Document cd2 = new CD()
            {
                Categorie = "education", Titre = "parler en francais", NbreDePlage = 12, Duree = new TimeSpan(08, 10, 50), Etat = Etat.Emprunte, BibliothequeFK = 1
            };
            Document cd3 = new CD()
            {
                Categorie = "litterature", Titre = "le Rouge et le noir", NbreDePlage = 8, Duree = new TimeSpan(12, 10, 10), Etat = Etat.Disponible, BibliothequeFK = 1
            };

            LS.Add(cd1);
            LS.Add(cd2);
            LS.Add(cd3);

            LS.Commit();
            Console.WriteLine("----------------------------Affichages des livres--------------------------------------");
            foreach (var item in LS.GetAll().OfType <Livre>())
            {
                Console.WriteLine("les Livres:" + item.Titre + "  " + item.Categorie + "  " + item.nbrdepage + " " + item.Etat);
            }
            Console.WriteLine("-----------------------------Affichage des CDs-----------------------------------------");
            foreach (var item in LS.GetAll().OfType <CD>())
            {
                Console.WriteLine("LES CD :" + item.Categorie + " " + item.Titre + " " + item.NbreDePlage + " " + item.Etat);
            }
            //Ajout des professeurs
            Professeur professeur = new Professeur()
            {
                nomComplet = new NomComplet()
                {
                    Nom = "Ahmed", Prenom = "ben salem"
                }, Departement = "TIC", Salaire = 1200, Image = "ff", Email = "*****@*****.**", nbAvertissement = 3, MotDePasse = "123456", ConfirmMotDePasse = "123456", DateDePriseDeFonction = new DateTime(2018, 01, 22)
            };
            Professeur professeur1 = new Professeur()
            {
                nomComplet = new NomComplet()
                {
                    Nom = "cyrine", Prenom = "slimen"
                },
                Departement           = "TIC",
                Salaire               = 1400f,
                Image                 = "ff",
                Email                 = "*****@*****.**",
                nbAvertissement       = 3,
                MotDePasse            = "123456",
                ConfirmMotDePasse     = "123456",
                DateDePriseDeFonction = new DateTime(2018, 08, 22)
            };
            Professeur professeur2 = new Professeur()
            {
                nomComplet = new NomComplet()
                {
                    Nom = "Amine", Prenom = "ben said"
                },
                Departement           = "TIC",
                Salaire               = 1000f,
                Image                 = "ff",
                Email                 = "*****@*****.**",
                nbAvertissement       = 3,
                MotDePasse            = "123456",
                ConfirmMotDePasse     = "123456",
                DateDePriseDeFonction = new DateTime(2017, 08, 22)
            };
            IProfesseurService ps = new ProfesseurService();

            ps.Add(professeur);
            ps.Add(professeur1);
            ps.Add(professeur2);
            ps.Commit();
            Console.WriteLine("-------------------------------------------Affichage des profs-------------------------");
            foreach (var item in ps.GetAll())
            {
                Console.WriteLine("les Profs : " + item.nomComplet.Nom + "  " + item.Salaire + " " + item.nbAvertissement);
            }
            //Ajout des etudiants
            Etudiant Etud = new Etudiant()
            {
                nomComplet = new NomComplet()
                {
                    Nom = "sami", Prenom = "ben salem"
                },
                Filiere           = "BI",
                Image             = "ff",
                Email             = "*****@*****.**",
                nbAvertissement   = 3,
                MotDePasse        = "123456",
                ConfirmMotDePasse = "123456"
            };
            Etudiant Etud1 = new Etudiant()
            {
                nomComplet = new NomComplet()
                {
                    Nom = "Ramzi", Prenom = "Louati"
                },
                Filiere           = "GL",
                Image             = "ff",
                Email             = "*****@*****.**",
                nbAvertissement   = 3,
                MotDePasse        = "123456",
                ConfirmMotDePasse = "123456"
            };
            IEtudiantService ES = new EtudiantService();

            ES.Add(Etud);
            ES.Add(Etud1);
            ES.Commit();
            Console.WriteLine("---------------------------Affichage des Etudiants-------------------------------------");
            foreach (var item in ES.GetAll())
            {
                Console.WriteLine("les etudiants:" + item.nomComplet.Nom + " " + item.nomComplet.Prenom + " " + item.Filiere);
            }
            Console.WriteLine("---------------------------Affichage de la liste trié de prof  selon leur Code---------");
            ps.ListProfTrie();
            Console.WriteLine("---------------------------Affichage des deux premiers Profs---------------------------");
            ps.deuxPremiersProf();
            Console.WriteLine("---------------------------Nombre Total des etudiants--------------------------------- ");
            Console.WriteLine(ES.nbrtotdesetudiants());
            Console.WriteLine("---------------------------Liste des livres disponibles---------------------------------");
            LS.LISTElivreDispo();
            Console.WriteLine("--------------------------Autorisation Emprunt-----------------------------------------");
            Emprunt E = new Emprunt()
            {
                DocumentCode = 1, AdherantCode = 1, Date = new DateTime(2018, 12, 12)
            };
            Emprunt E1 = new Emprunt()
            {
                AdherantCode = 1, DocumentCode = 3, Date = new DateTime(2018, 01, 01)
            };
            Emprunt E2 = new Emprunt()
            {
                AdherantCode = 1, DocumentCode = 4, Date = new DateTime(2018, 02, 12)
            };
            Emprunt E3 = new Emprunt()
            {
                AdherantCode = 1, DocumentCode = 6, Date = new DateTime(2018, 04, 14)
            };
            EmpruntService Em = new EmpruntService();


            //Em.AutorisationEmprunt(E);
            //Em.AutorisationEmprunt(E1);
            // Em.AutorisationEmprunt(E2);
            Em.AutorisationEmprunt(E3);



            Console.WriteLine("----------------------nouveaux Enseignants---------------------------------------------");
            ps.NouvEnseignants();
            Console.ReadKey();
        }
예제 #16
0
        public DocumentContract Add()
        {
            _logger.Info("DocumentController 添加文档.");

            var userId   = _requestProvider["UserId"];
            var spaceId  = _requestProvider["SpaceId"];
            var userName = _requestProvider["UserName"];
            var depId    = _requestProvider["DepId"];
            var visible  = _requestProvider["Visible"];
            var path     = _requestProvider["Path"];

            var timeStamp = _requestProvider["TimeStamp"];

            if (string.IsNullOrWhiteSpace(userId))
            {
                _logger.Error("文档参数错误, 缺少 UserId 参数.");
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            _logger.InfoFormat("文档参数userId:{0}", userId);

            if (string.IsNullOrWhiteSpace(userName))
            {
                _logger.Error("文档参数错误, 缺少 userName 参数.");
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            _logger.InfoFormat("文档参数userName:{0}", userName);

            if (string.IsNullOrWhiteSpace(depId))
            {
                _logger.Error("文档参数缺少 depId 参数,默认设置为空");
                depId = string.Empty;
            }
            _logger.InfoFormat("文档参数depId:{0}", depId);

            var visiblity = Visible.Public;

            if (!string.IsNullOrWhiteSpace(visible))
            {
                visiblity = (Visible)Enum.Parse(typeof(Visible), visible);
                _logger.InfoFormat("文档参数为:{0}", visiblity);
            }
            else
            {
                _logger.Info("文档参数缺少 visible 参数,默认设置为Public");
            }

            SpaceObject space;

            if (string.IsNullOrWhiteSpace(path))
            {
                _logger.Info("文档参数缺少 path 参数,采用spaceId参数");
                space = string.IsNullOrWhiteSpace(spaceId) ? _spaceService.GetDefaultSpace() : _spaceService.GetSpace(spaceId);
            }
            else
            {
                _logger.InfoFormat("文档参数path:{0}", path);
                space = _spaceService.MakeSpace(string.Empty, path, userId, userName, depId, visiblity);
            }

            var fileData = _requestProvider.FileCollection[0];

            if (fileData == null)
            {
                _logger.Error("文档参数错误, fileData ContentLength为0.");
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            _logger.Info(string.Format("Add Document, spaceId:[{0}];userId:[{1}];userName:[{2}]。", spaceId, userId, userName));

            try
            {
                var document = DocumentBuilder.Build(fileData,
                                                     space.Id.ToString(),
                                                     space.SpaceSeqNo,
                                                     space.SpaceName,
                                                     userId,
                                                     userName,
                                                     depId,
                                                     visiblity);
                var mimeType = MimeMapping.GetMimeMapping(document.FileName);
                _storePolicy.AddStream(fileData.FileStream, mimeType, document.StorePath);

                var documentObj = _documentService.Add(document);
                if (documentObj.DocumentCategory != DocumentCategory.Image)
                {
                    documentObj.DisplayPath = documentObj.PreviewUrl;
                }

                var contract = documentObj.ToObject <DocumentContract>();

                if (!string.IsNullOrWhiteSpace(timeStamp))
                {
                    MemoryContainer.Push(timeStamp, contract);
                }

                return(contract);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }
예제 #17
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get the entity type
            EntityTypeCache entityType     = null;
            var             entityTypeGuid = GetAttributeValue(action, AttributeKey.EntityType).AsGuidOrNull();

            if (entityTypeGuid.HasValue)
            {
                entityType = EntityTypeCache.Get(entityTypeGuid.Value);
            }

            if (entityType == null)
            {
                var message = $"Entity Type could not be found for selected value ('{entityTypeGuid.ToString()}')!";
                errorMessages.Add(message);
                action.AddLogEntry(message, true);
                return(false);
            }

            var mergeFields  = GetMergeFields(action);
            var _rockContext = new RockContext();

            // Get the entity
            var     entityTypeService  = new EntityTypeService(_rockContext);
            IEntity entityObject       = null;
            var     entityIdGuidString = GetAttributeValue(action, AttributeKey.EntityIdOrGuid, true).ResolveMergeFields(mergeFields).Trim();
            var     entityId           = entityIdGuidString.AsIntegerOrNull();

            if (entityId.HasValue)
            {
                entityObject = entityTypeService.GetEntity(entityType.Id, entityId.Value);
            }
            else
            {
                var entityGuid = entityIdGuidString.AsGuidOrNull();
                if (entityGuid.HasValue)
                {
                    entityObject = entityTypeService.GetEntity(entityType.Id, entityGuid.Value);
                }
            }

            if (entityObject == null)
            {
                var value = GetActionAttributeValue(action, AttributeKey.EntityIdOrGuid);
                entityObject = action.GetEntityFromAttributeValue(value, rockContext);
            }

            if (entityObject == null)
            {
                var message = $"Entity could not be found for selected value ('{entityIdGuidString}')!";
                errorMessages.Add(message);
                action.AddLogEntry(message, true);
                return(false);
            }

            var attributeFilteredDocumentType = GetAttributeValue(action, AttributeKey.DocumentType).Split(',').Select(int.Parse).FirstOrDefault();
            var documentType = DocumentTypeCache.Get(attributeFilteredDocumentType);

            if (documentType == null)
            {
                var message = $"Document Type could not be found for selected value ('{attributeFilteredDocumentType}')!";
                errorMessages.Add(message);
                action.AddLogEntry(message, true);
                return(false);
            }

            var documentypesForContextEntityType = DocumentTypeCache.GetByEntity(entityType.Id, true);

            if (!documentypesForContextEntityType.Any(d => attributeFilteredDocumentType == d.Id))
            {
                var message = "The Document Type does not match the selected entity type.";
                errorMessages.Add(message);
                action.AddLogEntry(message, true);
                return(false);
            }

            var isDocumentTypeValid = IsDocumentTypeValidForEntity(entityObject, documentType);

            if (!isDocumentTypeValid)
            {
                var message = "The Document Type selected is not valid for the entity.";
                errorMessages.Add(message);
                action.AddLogEntry(message, true);
                return(false);
            }

            var binaryFile = new BinaryFileService(rockContext).Get(GetAttributeValue(action, AttributeKey.DocumentAttribute, true).AsGuid());

            if (binaryFile == null)
            {
                action.AddLogEntry("The document to add to the entity was not found.", true);

                // returning true here to allow the action to run 'successfully' without a document.
                // This allows the action to be easily used when the document is optional without a bunch of action filter tests.
                return(true);
            }

            var documentName = GetAttributeValue(action, AttributeKey.DocumentName).ResolveMergeFields(mergeFields);

            if (documentName.IsNullOrWhiteSpace())
            {
                documentName = Path.GetFileNameWithoutExtension(binaryFile.FileName);
            }

            var document = new Document();

            document.Name           = documentName;
            document.Description    = GetAttributeValue(action, AttributeKey.DocumentDescription).ResolveMergeFields(mergeFields);
            document.EntityId       = entityObject.Id;
            document.DocumentTypeId = documentType.Id;
            document.SetBinaryFile(binaryFile.Id, rockContext);

            if (!document.IsValidDocument(rockContext, out string errorMessage))
            {
                errorMessages.Add(errorMessage);
                action.AddLogEntry(errorMessage, true);
                return(false);
            }

            var documentService = new DocumentService(rockContext);

            documentService.Add(document);
            rockContext.SaveChanges();

            action.AddLogEntry("Added document to the Entity.");
            return(true);
        }
        public FinancialStatementGeneratorUploadGivingStatementResult UploadGivingStatementDocument([FromBody] FinancialStatementGeneratorUploadGivingStatementData uploadGivingStatementData)
        {
            var rockContext = new RockContext();

            var saveOptions = uploadGivingStatementData?.FinancialStatementIndividualSaveOptions;

            if (saveOptions == null)
            {
                throw new FinancialGivingStatementArgumentException("FinancialStatementIndividualSaveOptions must be specified");
            }

            if (!saveOptions.SaveStatementsForIndividuals)
            {
                throw new FinancialGivingStatementArgumentException("FinancialStatementIndividualSaveOptions.SaveStatementsForIndividuals is not enabled.");
            }

            var documentTypeId = saveOptions.DocumentTypeId;

            if (!documentTypeId.HasValue)
            {
                throw new FinancialGivingStatementArgumentException("Document Type must be specified");
            }

            var documentType = new DocumentTypeService(rockContext)
                               .Queryable()
                               .AsNoTracking()
                               .Where(dt => dt.Id == documentTypeId.Value)
                               .Select(a => new
            {
                BinaryFileTypeId = ( int? )a.BinaryFileTypeId
            })
                               .FirstOrDefault();

            if (documentType == null)
            {
                throw new FinancialGivingStatementArgumentException("DocumentType must be specified");
            }

            if (documentType.BinaryFileTypeId == null)
            {
                throw new FinancialGivingStatementArgumentException("DocumentType.BinaryFileType must be specified");
            }

            var pdfData = uploadGivingStatementData.PDFData;

            string fileName = saveOptions.DocumentName + ".pdf";

            var financialStatementGeneratorRecipient = uploadGivingStatementData.FinancialStatementGeneratorRecipient;

            if (financialStatementGeneratorRecipient == null)
            {
                throw new FinancialGivingStatementArgumentException("FinancialStatementGeneratorRecipient must be specified");
            }

            var documentName = saveOptions.DocumentName;

            List <int> documentPersonIds;

            if (financialStatementGeneratorRecipient.PersonId.HasValue)
            {
                // If we are saving for a person that gives an individual, just give document to that person (ignore the FinancialStatementIndividualSaveOptionsSaveFor option)
                // only upload the document to the individual person
                documentPersonIds = new List <int>();
                documentPersonIds.Add(financialStatementGeneratorRecipient.PersonId.Value);
            }
            else
            {
                var groupId = financialStatementGeneratorRecipient.GroupId;
                var givingFamilyMembersQuery = new GroupMemberService(rockContext).GetByGroupId(groupId, false);

                // limit to family members within the same giving group
                givingFamilyMembersQuery = givingFamilyMembersQuery.Where(a => a.Person.GivingGroupId.HasValue && a.Person.GivingGroupId == groupId);

                if (saveOptions.DocumentSaveFor == FinancialStatementGeneratorOptions.FinancialStatementIndividualSaveOptions.FinancialStatementIndividualSaveOptionsSaveFor.AllActiveAdultsInGivingGroup)
                {
                    documentPersonIds = givingFamilyMembersQuery
                                        .Where(a => a.Person.AgeClassification == AgeClassification.Adult).Select(a => a.PersonId).ToList();
                }
                else if (saveOptions.DocumentSaveFor == FinancialStatementGeneratorOptions.FinancialStatementIndividualSaveOptions.FinancialStatementIndividualSaveOptionsSaveFor.AllActiveFamilyMembersInGivingGroup)
                {
                    documentPersonIds = givingFamilyMembersQuery
                                        .Select(a => a.PersonId).ToList();
                }
                else if (saveOptions.DocumentSaveFor == FinancialStatementGeneratorOptions.FinancialStatementIndividualSaveOptions.FinancialStatementIndividualSaveOptionsSaveFor.PrimaryGiver)
                {
                    // Set document for PrimaryGiver (aka Head of Household).
                    // Note that HeadOfHouseHold would calculated based on family members within the same giving group
                    var headOfHouseHoldPersonId = givingFamilyMembersQuery.GetHeadOfHousehold(s => ( int? )s.PersonId);
                    documentPersonIds = new List <int>();
                    if (headOfHouseHoldPersonId.HasValue)
                    {
                        documentPersonIds.Add(headOfHouseHoldPersonId.Value);
                    }
                }
                else
                {
                    // shouldn't happen
                    documentPersonIds = new List <int>();
                }
            }

            var today    = RockDateTime.Today;
            var tomorrow = today.AddDays(1);

            foreach (var documentPersonId in documentPersonIds)
            {
                // Create the document, linking the entity and binary file.
                if (saveOptions.OverwriteDocumentsOfThisTypeCreatedOnSameDate == true)
                {
                    using (var deleteDocContext = new RockContext())
                    {
                        var deleteDocumentService = new DocumentService(deleteDocContext);

                        // See if there is an existing one.
                        // Note include BinaryFile in the Get since we'll have to mark it temporary if it exists.
                        var existingDocument = deleteDocumentService.Queryable().Where(
                            a => a.DocumentTypeId == documentTypeId.Value &&
                            a.EntityId == documentPersonId &&
                            a.CreatedDateTime.HasValue &&
                            a.CreatedDateTime >= today && a.CreatedDateTime < tomorrow)
                                               .Include(a => a.BinaryFile).FirstOrDefault();

                        // NOTE: Delete vs update since we normally don't change the contents of documents/binary files once they've been created
                        if (existingDocument != null)
                        {
                            deleteDocumentService.Delete(existingDocument);
                            deleteDocContext.SaveChanges();
                        }
                    }
                }

                // Create the binary file.
                var binaryFile = new BinaryFile
                {
                    BinaryFileTypeId = documentType.BinaryFileTypeId,
                    MimeType         = "application/pdf",
                    FileName         = fileName,
                    FileSize         = pdfData.Length,
                    IsTemporary      = false,
                    ContentStream    = new MemoryStream(pdfData)
                };

                new BinaryFileService(rockContext).Add(binaryFile);
                rockContext.SaveChanges();

                Document document = new Document
                {
                    DocumentTypeId = documentTypeId.Value,
                    EntityId       = documentPersonId,
                    PurposeKey     = saveOptions.DocumentPurposeKey,
                    Name           = saveOptions.DocumentName,
                    Description    = saveOptions.DocumentDescription
                };

                document.SetBinaryFile(binaryFile.Id, rockContext);

                var documentService = new DocumentService(rockContext);

                documentService.Add(document);
            }

            rockContext.SaveChanges();

            return(new FinancialStatementGeneratorUploadGivingStatementResult
            {
                NumberOfIndividuals = documentPersonIds.Count
            });
        }
예제 #19
0
        //
        // GET: /Upload/
        /// <summary>
        /// path数据结构
        /// 001_西山区|4567_虹桥立交|8889_日常巡检 解析为三个文件夹
        /// 西山区(001)
        ///   |
        ///   |---虹桥立交(4567)
        ///         |
        ///         |----日常巡检(8889)
        /// </summary>
        public JsonResult Add(UploadSession uploadSession, string userId, string spaceId, string userName, string depId, string visible, string path)
        {
            //var userId = _requestProvider["UserId"];
            //var spaceId = _requestProvider["SpaceId"];
            //var userName = _requestProvider["UserName"];
            //var depId = _requestProvider["DepId"];
            //var visible = _requestProvider["Visible"];
            //var path = _requestProvider["Path"];
            _logger.Info("DocumentController 添加文档.");

            if (string.IsNullOrWhiteSpace(userId))
            {
                _logger.Error("文档参数错误, 缺少 UserId 参数.");
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            _logger.InfoFormat("文档参数userId:{0}", userId);

            if (string.IsNullOrWhiteSpace(userName))
            {
                _logger.Error("文档参数错误, 缺少 userName 参数.");
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            _logger.InfoFormat("文档参数userName:{0}", userName);

            if (string.IsNullOrWhiteSpace(depId))
            {
                _logger.Error("文档参数缺少 depId 参数,默认设置为空");
                depId = string.Empty;
            }
            _logger.InfoFormat("文档参数depId:{0}", depId);

            var visiblity = Visible.Public;

            if (!string.IsNullOrWhiteSpace(visible))
            {
                visiblity = (Visible)Enum.Parse(typeof(Visible), visible);
                _logger.InfoFormat("文档参数为:{0}", visiblity);
            }
            else
            {
                _logger.Info("文档参数缺少 visible 参数,默认设置为Public");
            }

            SpaceObject space;

            if (string.IsNullOrWhiteSpace(path))
            {
                _logger.Info("文档参数缺少 path 参数,采用spaceId参数");
                space = string.IsNullOrWhiteSpace(spaceId) ?
                        _spaceService.GetDefaultSpace() : _spaceService.GetSpace(spaceId);
            }
            else
            {
                _logger.InfoFormat("文档参数path:{0}", path);
                space = _spaceService.MakeSpace(string.Empty, path, userId, userName, depId, visiblity);
            }

            if (uploadSession.UploadedFiles.Count == 0)
            {
                _logger.Error("文档参数错误, 上传文件失败.");
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            _logger.Info(string.Format("Add Document, spaceId:[{0}];userId:[{1}];userName:[{2}]。", spaceId, userId, userName));

            try
            {
                var file     = uploadSession.UploadedFiles.First();
                var document = DocumentBuilder.Build(file,
                                                     space.Id.ToString(),
                                                     space.SpaceSeqNo,
                                                     space.SpaceName,
                                                     userId,
                                                     userName,
                                                     depId,
                                                     visiblity);
                var documentObj = _documentService.Add(document);
                if (documentObj.DocumentCategory != DocumentCategory.Image)
                {
                    documentObj.DisplayPath = documentObj.PreviewUrl;
                }

                return(Json(documentObj.ToObject <DocumentContract>()));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                _logger.Error(ex.StackTrace);
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }