예제 #1
0
        public IHttpActionResult AddDocument(AddDocumentViewModel model)
        {
            if (model.Document == null)
            {
                return(BadRequest("Object is null"));
            }
            if (model.DocFile == null)
            {
                return(BadRequest("Provided Doc File is null"));
            }

            var employee = _employeeService.GetById(model.EmployeeId);

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

            // save the document file to the server /Content/docs directory
            string filePath = Utility.Utility.SaveToDisk(HttpContext.Current, model.DocFile, "~/Content/docs");

            // saving only the image name
            model.Document.DocumentPath = filePath;

            _documentService.Add(model.Document, model.DocTypeId, model.EmployeeId);
            return(Ok());
        }
예제 #2
0
        public ActionResult Upload(List <HttpPostedFileBase> fileData)
        {
            string fileDestination = Server.MapPath("~/Uploads/");

            foreach (HttpPostedFileBase postedFile in fileData)
            {
                if (postedFile != null)
                {
                    string fileName = Path.GetFileName(postedFile.FileName);
                    string path     = fileDestination + fileName;
                    postedFile.SaveAs(path);

                    object pathObject = path;
                    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                    object miss     = System.Reflection.Missing.Value;
                    object readOnly = true;
                    Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref pathObject, ref miss, ref readOnly, ref miss, ref miss,
                                                                                      ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                    string totaltext = "";
                    for (int i = 0; i < docs.Paragraphs.Count; i++)
                    {
                        totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
                    }
                    documentService.Add(fileName, totaltext, User.Identity.Name);

                    docs.Close();
                    word.Quit();
                }
            }

            return(Content("Success"));
        }
        public ActionResult Create(DocumentVM DocVM, HttpPostedFileBase Image)
        {
            Documents t1 = new Documents();

            t1.Name      = DocVM.Name + "  " + DateTime.Now.ToString();
            t1.DateDoc   = DateTime.Now;
            t1.Size      = DocVM.Size;
            t1.FileType  = (FileType)DocVM.TypeVm;
            t1.ImageUrl  = Image.FileName;
            t1.ProjectId = DocVM.ProjectId;
            t1.FileType  = (FileType)DocVM.TypeVm;

            MyDocService.Add(t1);
            MyDocService.Commit();
            var path = Path.Combine(Server.MapPath("~/Content/Upload/"), Image.FileName);

            //ajout de l'image dans un dossier Upload
            Image.SaveAs(path);
            // MailMessage mail = new MailMessage("*****@*****.**", "*****@*****.**");
            //  mail.Subject = "documet cree";
            //  mail.Body = "test document envoiyer";

            //  mail.IsBodyHtml = true;
            // SmtpClient smtpClient = new SmtpClient("Smtp.gmail.com", 587);
            // smtpClient.EnableSsl = true;

            //  smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "123456aze");
            //  smtpClient.Send(mail);
            /// https://www.google.com/settings/security/lesssecureapps go to link and alllow
            return(RedirectToAction("Index"));
        }
예제 #4
0
        public async Task <IHttpActionResult> PostDocument(Document document)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            docService.Add(document);
            docService.CommitAsync();

            return(CreatedAtRoute("DefaultApi", new { id = document.DocumentId }, document));
        }
예제 #5
0
        public async Task <IActionResult> Create(DocumentCreateModel model)
        {
            //todo: создать отдельный класс валидации свойства
            // Если документ с таким номером уже есть в базе
            if (_documents.IsDocumentExist(model.DocumentNumber))
            {
                ModelState.AddModelError("", "Документ с таким номером уже есть в базе.");
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(User);

                model.CreatedBy = user.FullName;
                model.CreatedOn = DateTime.Now;

                try
                {
                    // Маппинг сущности
                    var newDocument = _mapper.Map <DocumentDTO>(model);
                    // Загружаем файл на сервер
                    var result = _files.UploadFile(model.DocumentFile, newDocument.DocumentFile.Path);
                    // Добавляем запись в базу
                    await _documents.Add(newDocument);

                    // Уведомляем пользователя об успешном добавлении
                    this.AddAlertSuccess("Свидетельство успешно добавленно в базу!");
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError("", exception.Message);
                }
            }

            CreateSelectLists();

            // Отображаем ошибки операции
            foreach (var state in ModelState.Values)
            {
                foreach (var error in state.Errors)
                {
                    this.AddAlertDanger(error.ErrorMessage);
                }
            }

            return(View(model));
        }
예제 #6
0
        public async Task <IActionResult> Add([FromBody] DocumentModel model)
        {
            try
            {
                var response = await _service.Add(model);

                if (!response.IsSuccessful)
                {
                    return(BadRequest(response));
                }
                return(Ok(response));
            }
            catch
            {
                return(StatusCode(500, "Internal Server Error."));
            }
        }
예제 #7
0
 public ActionResult Add(Document model)
 {
     if (ModelState.IsValid)
     {
         if (!model.documentUrl.Contains("/van-ban/"))
         {
             model.documentUrl = "/van-ban/" + model.documentUrl;
         }
         _Service.Add(model);
         _Service.Save();
         return(RedirectToAction("Index"));
     }
     ViewBag.documentTypeId = _toolAdmin.DocumentTypeSelectList();
     ViewBag.categoryId     = _toolAdmin.DocumentTypeDropdown(model.categoryId);
     ViewBag.languageId     = _toolAdmin.LanguageSelectList();
     ViewBag.Quanlyvanban   = "active";
     return(View(model));
 }
예제 #8
0
        public async Task <ActionResult> Upload(DocumentUploadRequest documentUploadRequest)
        {
            using (var ms = new MemoryStream())
            {
                documentUploadRequest.File.CopyTo(ms);
                var fileBytes = ms.ToArray();

                await documentService.Add(new Document
                {
                    Bytes        = fileBytes,
                    Name         = documentUploadRequest.File.FileName,
                    Category     = documentUploadRequest.Category,
                    LastReviewed = documentUploadRequest.LastReviewed,
                    Key          = Guid.NewGuid()
                });
            }
            return(Redirect("/documents"));
        }
예제 #9
0
        public ActionResult Create(int idProject, HttpPostedFileBase file, DocumentViewModel DVM)
        {
            if (!Request.IsAuthenticated)
            {
                return(RedirectToAction("Login", "Account"));
            }
            //redirect to nowhere if not admin
            if (!(User.IsInRole("Team Leader")))
            {
                return(RedirectToAction("Nowhere", "Account"));
            }
            Project  P = PS.GetById(idProject);
            Document D = new Document();

            D.DocumentId   = DVM.DocumentId;
            D.DocumentName = DVM.DocumentName;
            D.categorie    = (Domain.Entities.Categorie)DVM.categorie;
            try
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path     = Path.Combine(Server.MapPath("~/Content/Documents/"), fileName);
                    file.SaveAs(path);
                    DVM.Size        = file.ContentLength / 1024;
                    D.Path          = "~/Content/Documents/" + fileName;
                    D.Size          = DVM.Size;
                    D.DateCreation  = DateTime.Now;
                    D.ProjectFK     = P.ProjectId;
                    ViewBag.Message = "File Uploaded Successfully!!";
                    DS.Add(D);
                    DS.Commit();
                }
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return(View(DVM));
            }


            return(RedirectToAction("Details", "Project", new { id = idProject }));
        }
예제 #10
0
        public ActionResult Create(DocumentViewModel DVM, System.Web.HttpPostedFileBase file)
        {
            Document D = new Document();

            D.DocumentId   = DVM.DocumentId;
            D.DocumentName = DVM.DocumentName;
            D.Size         = DVM.Size;

            D.categorie = (Domain.Entities.Categorie)DVM.categorie;
            try
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path     = Path.Combine(Server.MapPath("~/Content/Documents/"), fileName);

                    file.SaveAs(path);
                    D.Path          = "~/Content/Documents/" + fileName;
                    ViewBag.Message = "File Uploaded Successfully!!";
                }
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return(View());
            }
            D.DateCreation = DateTime.Now;

            DS.Add(D);
            DS.Commit();
            if (DVM.categorie == Web.Models.Categorie.Image)
            {
                return(View("Index"));
            }

            else
            {
                return(View("IndexDocument"));
            }
        }
예제 #11
0
 public ActionResult Add([Bind(Include = "Code,Description,UnitsOfMeasure,QtyOnHand")] DocumentDetailVM documentVM)
 {
     if (ModelState.IsValid)
     {
         try
         {
             _documentService.Add(documentVM);
             return(Json(new { success = true, model = documentVM }));
         }
         catch (Exception ex)
         {
             if (ex.Message.Contains("IX_Code"))
             {
                 ModelState.AddModelError("Code", "This Document Number already exists. Duplicate Document Numbers are not allowed.");
             }
             else
             {
                 ModelState.AddModelError(string.Empty, "The save failed.");
             }
         }
     }
     return(JsonErrorResult());
 }
예제 #12
0
        public ActionResult Add([FromBody] DocumentRequest entity)
        {
            var response = new Response <object>();

            try
            {
                if (_documentService.Add(entity))
                {
                    response.Result  = 1;
                    response.Message = "Documento registrado correctamente.";
                }
                else
                {
                    response.Message = "No se pudo registrado el documento.";
                }

                return(Ok(response));
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                return(Ok(response));
            }
        }
예제 #13
0
        public IHttpActionResult Post(int id)
        {
            if (id == 0)
            {
                return(BadRequest("Invalid Id provided for the complaint"));
            }

            var resultList  = new List <ViewDataUploadFilesResult>();
            var httpRequest = HttpContext.Current.Request;

            filesHelper.UploadAndShowResults(httpRequest, resultList, id);
            documentService.Add(id, filesHelper.currentFileName);
            JsonFiles files   = new JsonFiles(resultList);
            bool      isEmpty = !resultList.Any();

            if (isEmpty)
            {
                return(Json("Error "));
            }
            else
            {
                return(Json(files));
            }
        }
예제 #14
0
 public ActionResult Create(FormCollection collection)
 {
     try
     {
         // TODO: Add insert logic here
         if (ModelState.IsValid)
         {
             Document document = new Document( );
             TryUpdateModel(document, collection);
             document.Creator    = "Admin";
             document.CreateDate = DateTime.Now;
             service.Add(document);
             return(RedirectToAction("Index"));
         }
         else
         {
             return(View( ));
         }
     }
     catch (Exception ex)
     {
         return(View());
     }
 }
예제 #15
0
        public IActionResult Upload(List <IFormFile> files)
        {
            Dictionary <string, string> FileResults = new Dictionary <string, string>();

            if (files.Count == 0)
            {
                return(Json(new Result()
                {
                    reason = "No files were sent",
                    result = "Failure",
                    status_code = 400
                }));
            }
            foreach (var file in files)
            {
                //Verify the file type
                if (Path.GetExtension(file.FileName) == ".pdf")
                {
                    Document pdfDoc = new Document()
                    {
                        CategoryId   = Guid.Parse("23E78816-B264-4403-8763-C5DE3300202B"),
                        Name         = Path.GetFileNameWithoutExtension(file.FileName),
                        TemplateName = file.FileName
                    };
                    pdfDoc = _DocumentService.Add(pdfDoc, User);
                    ///TODO
                    //Read the entire document and warn of any unsuppored fields


                    string path = Path.Combine(_HostingEnv.WebRootPath, "dist", "documents");

                    int FileExistCount = 2;
                    if (System.IO.File.Exists(Path.Combine(path, file.FileName)))
                    {
                        while (System.IO.File.Exists(Path.Combine(path, FileExistCount + "_" + file.FileName)))
                        {
                            FileExistCount++;
                        }
                        path = Path.Combine(path, FileExistCount + "_" + file.FileName);
                    }
                    else
                    {
                        path = Path.Combine(path, file.FileName);
                    }
                    using (FileStream fs = new FileStream(path, FileMode.CreateNew))
                    {
                        file.CopyTo(fs);
                    }
                    FileResults.Add(file.FileName, "Success");
                }
                else
                {
                    FileResults.Add(file.FileName, "Failure; Filetype not supported");
                }
            }
            return(Json(new
            {
                reason = "Result Received",
                result = "Success",
                status_code = 200,
                result_data = FileResults
            }));
        }
        public async Task <IActionResult> Post([BindRequired, FromBody] Document document)
        {
            var id = await _service.Add(document);

            return(CreatedAtAction(nameof(Get), new { id }, id));
        }