コード例 #1
0
        public void DeleteDocument_Document_ShouldRemoveDocument()
        {
            IDocumentRepository repo = new DocumentRepository(new BadgerDataModel());

            // Create a new Document
            Document doc = new Document
            {
                Description  = "New Resource",
                DateCreated  = System.DateTime.Now,
                Creator      = "Richard",
                PartID       = 1,
                DocumentPath = ".png",
                DocumentView = "Front"
            };


            repo.Add(doc);
            var returnedDoc = repo.Find(doc.DocId);
            int key         = returnedDoc.DocId;

            repo.Delete(returnedDoc);
            var test = repo.Find(key);

            Assert.IsTrue(test == null);
        }
コード例 #2
0
        public ActionResult Create(Document d)
        {
            if (!ModelState.IsValid)
            {
                ViewData["errors"] = ModelState.Values.SelectMany(v => v.Errors);
                return(PartialView(d));
            }

            foreach (string f in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[f];
                if (file.ContentLength > 0)
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("/Content/Uploads")
                                                   , Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);
                    d.FilePath = "/Pdf/" + Path.GetFileNameWithoutExtension(file.FileName);
                }
            }

            _db.Add(d);
            _db.Commit();

            return(PartialView("ListAll", _db.GetAll()));
        }
コード例 #3
0
ファイル: DocumentController.cs プロジェクト: ka1n/moeDeloTst
 public IActionResult Create(Document?doc)
 {
     if (ModelState.IsValid)
     {
         documentRepository.Add(doc);
         return(RedirectToAction("Index"));
     }
     return(View(doc));
 }
コード例 #4
0
        public DocumentResponse InsertDocument(DocumentRequest request)
        {
            DocumentResponse       response           = new DocumentResponse();
            DocumentDto            documentDto        = request.DocumentDto;
            DocumentRepository     documentRepository = dmsUnitOfWork.DocumentRepository;
            EntityEntry <Document> document           = documentRepository.Add(documentDto.ToEntity <DocumentDto, Document>());

            response.Document = document.Entity.ToDto <Document, DocumentDto>();
            return(response);
        }
コード例 #5
0
        private void Crawl(Action <string> reportProgress)
        {
            base.watch.Start();
            base.reportProgress("Crawler for www.rs-sandanski.com started.");
            string baseUrl = @"http://rs-sandanski.com/";

            using (WebClient client = new WebClient())
            {
                string initialUrl   = baseUrl + "verdicts.php";
                string page         = client.DownloadString(initialUrl);
                string regexPattern = "<td><a href=\"([^\"]*?)\"[\\w\\W]*?</td>\\s*<td>([^<]*?)</td>\\s*<td>([^<]*?)</td>\\s*<td>([^/]*?)/([^<]*?)</td>";

                foreach (Match match in Regex.Matches(page, regexPattern, RegexOptions.IgnoreCase))
                {
                    var    href = match.Groups[1].Value;
                    string url  = baseUrl + href.Substring(2);

                    string fileName      = Path.GetFileNameWithoutExtension(href);
                    string fileExtension = Path.GetExtension(href);
                    fileName = $"{fileName}{fileExtension}";
                    byte[] dataContent = client.DownloadData(url);
                    int?   format      = (int?)this.GetDataFormat(fileName);

                    Document doc = new Document
                    {
                        Name        = fileName,
                        Url         = url,
                        Format      = format,
                        DataContent = dataContent,
                        Encoding    = (int?)EncodingType.Windows1251,
                        Md5         = MD5.Create().ComputeHash(dataContent)
                    };

                    using (IRepository <Document> repository = new DocumentRepository())
                    {
                        repository.Add(doc);
                        repository.Save();
                    }

                    base.documentsDownloaded++;

                    reportProgress($"Downloaded {base.documentsDownloaded}" +
                                   $" documents in {base.watch.Elapsed}");
                }

                base.watch.Stop();
                reportProgress($"Downloading finished in {base.watch.Elapsed}.");
                reportProgress($"Total documents downloaded: {base.documentsDownloaded}");
            }
        }
コード例 #6
0
        private void AddToRepository(string sourceDocumentDirectory, DocumentRepositoryInfo documentRepositoryInfo, DocumentGenerator.AwsConfigInfo awsConfigInfo)
        {
            var generateFromTemplate = new DocumentGenerator.GenerateFromTemplate();

            var documentRepositoryInfoList = generateFromTemplate.GenerateDocument(sourceDocumentDirectory, documentRepositoryInfo, awsConfigInfo);

            foreach (var item in documentRepositoryInfoList)
            {
                if (string.IsNullOrWhiteSpace(item.SaveError))
                {
                    var workingSetDocument = new WorkingSetDocument();
                    workingSetDocument.DocumentTitle = item.DocumentTitle;
                    workingSetDocument.DocumentUri   = $"{documentRepositoryInfo.FilePath}/{item.DocumentTitle}";
                    workingSetDocument.WorkingSetId  = documentRepositoryInfo.WorkingSetId;

                    documentRepository.Add(workingSetDocument);
                }
            }
        }
コード例 #7
0
        public void AddDocument_Document()
        {
            DocumentRepository docRepo = new DocumentRepository(new BadgerDataModel());

            // Create a new Document
            Document doc = new Document
            {
                Description  = "New Resource",
                DateCreated  = System.DateTime.Now,
                Creator      = "Richard",
                PartID       = 1,
                DocumentPath = ".png",
                DocumentView = "Front"
            };

            docRepo.Add(doc);
            int key  = doc.DocId;
            var test = docRepo.Find(key);

            Assert.IsTrue(doc.DocId == key);
        }
コード例 #8
0
        public Document Add(string userEmail, Document document)
        {
            if (UserRepository.Exists(userEmail))
            {
                document.Id               = Guid.NewGuid();
                document.CreationDate     = DateTime.Now;
                document.LastModification = document.CreationDate;
                document.Creator          = UserRepository.GetByEmail(userEmail);
                if (document.StyleClass != null && !StyleClassRepository.Exists(document.StyleClass.Name))
                {
                    document.StyleClass = null;
                }

                DocumentRepository.Add(document);

                return(document);
            }
            else
            {
                throw new MissingUserException("The user is not on the database.");
            }
        }
コード例 #9
0
        public void CrawlPage(string url)
        {
            using (WebClient client = new WebClient())
            {
                // Character set for the link list pages - UTF8
                client.Encoding = Encoding.UTF8;
                string       pageHtml = client.DownloadString(url);
                HtmlDocument htmlDoc  = new HtmlDocument();
                htmlDoc.LoadHtml(pageHtml);

                IEnumerable <HtmlNode> contentRows = htmlDoc
                                                     .DocumentNode
                                                     .SelectNodes("//div[@id = 'body-content']/table[1]/tr")
                                                     .Skip(1);

                if (contentRows.Count() > 249)
                {
                    // For debugging purposes.
                }

                foreach (HtmlNode contentRow in contentRows)
                {
                    Document actDocument = this.GetActDocument(contentRow);

                    using (IRepository <Document> repository = new DocumentRepository())
                    {
                        repository.Add(actDocument);
                        repository.Save();


                        base.documentsDownloaded++;

                        base.reportProgress($"Downloaded {base.documentsDownloaded} " +
                                            $"documents in {base.watch.Elapsed}");
                    }
                }
            }
        }
コード例 #10
0
ファイル: Smolian.cs プロジェクト: hwfbcisod/SiteCrawler
        private void DownloadDocuments(List <string> documentUrls)
        {
            foreach (var documentUrl in documentUrls)
            {
                using (WebClient client = new WebClient())
                {
                    string   normalizedUrl = $"http://213.91.128.55{documentUrl}";
                    string[] urlArgs       = documentUrl.Split('/');
                    string   docName       = urlArgs[5].Replace("?OpenDocument", "");
                    byte[]   dataContent   = client.DownloadData(normalizedUrl);
                    //string docName = new string(docUrl.Split('/').Skip(5).First().TakeWhile(x => x != '?').ToArray());

                    Document actDocument = new Document()
                    {
                        Name        = docName + "_act.html",
                        Url         = normalizedUrl,
                        Format      = (int?)this.GetDataFormat(".html"),
                        Encoding    = (int?)EncodingType.Utf8,
                        DataContent = dataContent,
                        Md5         = MD5.Create().ComputeHash(dataContent)
                    };

                    using (IRepository <Document> repository = new DocumentRepository())
                    {
                        repository.Add(actDocument);
                        repository.Save();
                    }


                    base.documentsDownloaded++;

                    base.reportProgress($"Downloaded {base.documentsDownloaded}" +
                                        $" documents in {base.watch.Elapsed}");
                }
            }
        }
コード例 #11
0
 public Document Post([FromBody] Document document)
 {
     document.ProjectId = SessionUser.ActiveProject;
     return(_documentRepository.Add(document));
 }
コード例 #12
0
        /// <summary>
        /// Opens document in write mode.
        /// </summary>
        void writeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Document selectedDocument = documentRepository.GetDocumentByVersion(
                listView1.SelectedItems[0].Text, int.Parse(listView1.SelectedItems[0].SubItems[1].Text));

            if (listView1.SelectedItems[0].SubItems[3].Text.CompareTo("Write") != 0)
            {
                MessageBox.Show("You don't have permission to open this document in write mode.");
            }
            else
            {
                if (selectedDocument.IsActive)
                {
                    if (selectedDocument.IsWriting || (selectedDocument.IsReading != 0))
                    {
                        MessageBox.Show("Document is already open," +
                                        "\nyou can not access document at the moment.\nPlease try again later.");
                    }
                    else
                    {
                        if (selectedDocument.IsReading == 0)
                        {
                            selectedDocument.IsWriting = true;

                            documentRepository.Update(selectedDocument);

                            string filepath = MainForm.DocumentPath + "\\" + selectedDocument.Title +
                                              "_" + selectedDocument.Version + "_" + loggedEmployee.Username + "." + selectedDocument.Type;

                            if (File.Exists(filepath))
                            {
                                File.Delete(filepath);
                            }

                            File.WriteAllBytes(filepath, selectedDocument.Content.Data);

                            Process writeDocumentProcess = new Process();

                            if (selectedDocument.Type.Contains("doc") || selectedDocument.Type.Contains("docx"))
                            {
                                writeDocumentProcess.StartInfo.FileName  = "WINWORD.EXE";
                                writeDocumentProcess.StartInfo.Arguments = filepath;
                            }
                            else
                            {
                                writeDocumentProcess.StartInfo.FileName = filepath;
                            }
                            writeDocumentProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;

                            writeDocumentProcess.Start();
                            writeDocumentProcess.WaitForExit();

                            if (MessageBox.Show("Do you want to upload new version to server",
                                                "Confirmation dialog", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                DocumentContent newVersionContent = new DocumentContent();

                                FileStream   fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                                BinaryReader br = new BinaryReader(fs);
                                newVersionContent.Data = br.ReadBytes((Int32)fs.Length);
                                br.Close();
                                fs.Close();

                                documentContentRepository.Add(newVersionContent);

                                Document newVersion = new Document(selectedDocument);

                                if (selectedDocument.Owner == null)
                                {
                                    newVersion.Writers.Remove(loggedEmployee);
                                }
                                else
                                {
                                    if (selectedDocument.Owner.Username.CompareTo(loggedEmployee.Username) != 0)
                                    {
                                        newVersion.Writers.Remove(loggedEmployee);
                                    }
                                }

                                newVersion.Created = DateTime.Now;

                                IList <Document> existingVersions = documentRepository.GetDocumentsByTitle(selectedDocument.Title);
                                newVersion.Version = (existingVersions == null) ? 0 : existingVersions.Count;

                                newVersion.Owner = new Employee(loggedEmployee);

                                newVersion.Content = newVersionContent;

                                documentRepository.Add(newVersion);

                                populateLists();
                                updateListView(ownDocuments, readableDocuments, writableDocuments);
                            }

                            selectedDocument.IsWriting = false;

                            documentRepository.Update(selectedDocument);
                        }
                        else
                        {
                            MessageBox.Show("Document is already open in read mode," +
                                            "\nyou can not open it for write.\nPlease try again later.");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Document is archived. You can not change it.");
                }
            }
        }
コード例 #13
0
        public async Task <JsonResult> Add(IFormFileCollection files)
        {
            await CheckPermission();

            var cr          = new DocumentRepository(_logger);
            var fileService = new FileService();
            var docs        = new List <Document>();

            var thumbs = new Dictionary <string, string>();

            foreach (var uploadedFile in files)
            {
                var documentTypeInt = fileService.Save(uploadedFile, uploadedFile.FileName);

                //var name = uploadedFile.FileName;
                //var newName = Guid.NewGuid() + Path.GetExtension(name);
                //var path = "/docs/" + newName;
                //using (var fileStream = new FileStream(AppSettings.WebRootPath + path, FileMode.Create))
                //{
                //    await uploadedFile.CopyToAsync(fileStream);
                //}
                //image
                thumbs.Add(uploadedFile.FileName, uploadedFile.FileName);
                if ((DocumentType)documentTypeInt == DocumentType.Image)
                {
                    //thumbs.Add(AppSettings.ImagePathUi(uploadedFile.FileName),AppSettings.ImageThumbsPathUi(uploadedFile.FileName));

                    docs.Add(new Document
                    {
                        TrainTaskCommentId = null,
                        Name = uploadedFile.FileName,
                        //Name = AppSettings.ImagePathUi(uploadedFile.FileName),
                        Description  = uploadedFile.FileName,
                        DocumentType = (DocumentType)documentTypeInt
                    });
                }
                //sound
                if ((DocumentType)documentTypeInt == DocumentType.Sound)
                {
                    docs.Add(new Document
                    {
                        TrainTaskCommentId = null,
                        //Name = AppSettings.SoundPathUi(uploadedFile.FileName),
                        Name         = uploadedFile.FileName,
                        Description  = uploadedFile.FileName,
                        DocumentType = (DocumentType)documentTypeInt
                    });
                }
                //other
                if ((DocumentType)documentTypeInt == DocumentType.Other)
                {
                    docs.Add(new Document
                    {
                        TrainTaskCommentId = null,
                        //Name = AppSettings.DocumentPathUi(uploadedFile.FileName),
                        Name         = uploadedFile.FileName,
                        Description  = uploadedFile.FileName,
                        DocumentType = (DocumentType)documentTypeInt
                    });
                }
            }

            //Document[] docs1;
            //try
            //{
            var docs1 = await cr.Add(docs.ToArray());

            //}
            //catch (Exception e)
            //{
            //    //delete all uploaded files in case of db error (rollback)
            //    foreach (var doc in docs)
            //    {
            //        if (System.IO.File.Exists(AppSettings.WebRootPath + doc.Name))
            //        {
            //            System.IO.File.Delete(AppSettings.WebRootPath + doc.Name);
            //        }
            //    }
            //    throw e;
            //}

            var ret    = new DocumentsUI();
            var docsUi = new List <DocumentUI>();

            foreach (var doc in docs1)
            {
                docsUi.Add(ConvertDocToDocUi(doc, thumbs[doc.Name]));
            }
            ret.Files = docsUi.ToArray();

            cr.Dispose();

            return(Json(ret));
        }
コード例 #14
0
 public Task Add(Dummy document = null)
 {
     document = document ?? Document;
     return(DocumentRepository.Add(document, RequestOptions));
 }