Exemplo n.º 1
0
        private async Task UploadDriveDocumentAsync(FileDocument document, string filePath, IFolder destination)
        {
            var assembly   = this.GetType().GetTypeInfo().Assembly;
            var @namespace = typeof(SlideShowPlugin).Namespace;

            filePath = filePath.Replace('\\', '/').TrimStart('/');
            filePath = @namespace + "." + filePath;
            filePath = filePath.Replace('/', '.').Replace("SlideShow", "Slideshow");    // HACK/TODO: Why is the manifest name "Slideshow", not "SlideShow"?

            var url = $"{_connectDocumentOptions.DriveAuthority}/upload";

            using (var client = new HttpClient())
            {
                // var stream = assembly.GetManifestResourceStream();
                using (var fileStream = assembly.GetManifestResourceStream(filePath))
                {
                    if (fileStream == null)
                    {
                        throw new InvalidOperationException($"File not found: '{filePath}'.");
                    }

                    document = await _documentService.CreateAsync(document);

                    try
                    {
                        await _folderManager.AddDocumentAsync(document, destination);

                        try
                        {
                            var fileSize = fileStream.Length;
                            await UploadDocumentAsync(document, fileStream);
                            await UpdateFileSizeAsync(document, fileSize);
                        }
                        catch (Exception exc)
                        {
                            await LogErrorAsync(exc);

                            await _folderManager.RemoveDocumentAsync(document, destination);

                            // Cascade so the document is deleted
                            throw;
                        }
                    }
                    catch (Exception exc)
                    {
                        // Log error
                        await LogErrorAsync(exc);

                        // Delete the FileDocument
                        await _documentService.DeleteAsync(document);
                    }
                }
            }
        }
Exemplo n.º 2
0
 public ActionResult Edit([Bind(Include = "Id,Title,Description")] FileDocument fileDocument)
 {
     if (ModelState.IsValid)
     {
         db.Entry(fileDocument).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Details", "Article", new { id = fileDocument.ArticleId }));
     }
     ViewBag.ArticleId = new SelectList(db.Articles, "Id", "Title", fileDocument.ArticleId);
     return(View(fileDocument));
 }
Exemplo n.º 3
0
        private async Task <FileDocument> CreateDocumentAsync(IFormFile file)
        {
            var document = new FileDocument()
            {
                DocumentId = KeyGen.NewGuid(),
                FileName   = System.IO.Path.GetFileName(file.FileName)
            };

            document.FileType = document.GetFileType();

            return(await _documentService.CreateAsync(document));
        }
        public string CheckBeforeSave(FileDocument filedocument, string command = "")
        {
            var AlertMsg = "";

            // Write your logic here

            //Make sure to assign AlertMsg with proper message
            //AlertMsg = "Validation Alert - Before Save !! Information not saved.";
            //ModelState.AddModelError("CustomError", AlertMsg);
            //ViewBag.ApplicationError = AlertMsg;
            return(AlertMsg);
        }
Exemplo n.º 5
0
        private async Task <Stream> DownloadDocumentAsync(FileDocument document, string userId)
        {
            Ensure.NotNull(document, $"{nameof(document)} cannot be null.");

            var physicalLocation = await GetLibraryPhysicalLocation(document.DocumentId);

            var result = await _uploadService.GetFileStreamAsync(document, physicalLocation);

            await _log.LogEventReadAsync(document, userId);

            return(result);
        }
Exemplo n.º 6
0
        private static byte[] CreateSeedBinary(FileDocument doc)
        {
            var length = new Random().Next(20, 100);
            var data   = new byte[length];
            var random = new Random();

            for (var i = 0; i < length; i++)
            {
                data[i] = (byte)random.Next();
            }

            return(data);
        }
Exemplo n.º 7
0
        public async Task <IHttpActionResult> UploadInfo([FromBody] FileDocumentModel request)
        {
            if (ModelState.IsValid)
            {
                var fileDocument = new FileDocument
                {
                    CreatedBy         = request.CreatedBy,
                    CreatedDate       = DateTime.Now,
                    FileName          = request.FileName,
                    FileNameOnStorage = request.FileNameOnStorage,
                    FilePath          = request.FilePath,
                    FileSize          = request.FileSize,
                    FileTag           = request.FileTag,
                    FileType          = request.FileType,
                    User = request.User
                };

                db.FileDocument.Add(fileDocument);

                await db.SaveChangesAsync();

                // Save the contentFile
                ContentFile contentFile = new ContentFile
                {
                    CourseId  = request.CourseId,
                    FileType  = request.ContentFileType,
                    ContentId = request.ContentId,

                    CreatedBy      = fileDocument.CreatedBy,
                    FileName       = fileDocument.FileName,
                    FileDocument   = fileDocument,
                    FileDocumentId = fileDocument.Id,
                };

                db.ContentFiles.Add(contentFile);

                await db.SaveChangesAsync();

                var content = await db.CourseContents.FirstOrDefaultAsync(x => x.Id == request.ContentId);

                content.ContentFileId = contentFile.Id;

                await db.SaveChangesAsync();

                return(Ok(contentFile.Id));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Exemplo n.º 8
0
        public async Task <ResponseViewModel> PaymentAllocation(PaymentAllocationInputModel model)
        {
            var plot = _plotService.GetByPlotId(model.PlotId);

            if (plot == null)
            {
                return(NotFound(ResponseMessageViewModel.INVALID_PLOT, ResponseErrorCodeStatus.INVALID_PLOT));
            }

            var paymentType = _paymentService.GetAllPaymentTypes().FirstOrDefault(x => x.Id == model.PaymentType);

            if (paymentType == null)
            {
                return(NotFound(ResponseMessageViewModel.INVALID_PAYMENT_TYPE, ResponseErrorCodeStatus.INVALID_PAYMENT_TYPE));
            }

            var paymentMethod = _paymentService.GetAllPaymentMethods().FirstOrDefault(x => x.Id == model.PaymentMethodId);

            if (paymentMethod == null)
            {
                return(NotFound(ResponseMessageViewModel.INVALID_PAYMENT_METHOD, ResponseErrorCodeStatus.INVALID_PAYMENT_METHOD));
            }

            FileDocument uploadResult = FileDocument.Create();

            try
            {
                uploadResult = await
                               BaseContentServer
                               .Build(ContentServerTypeEnum.FIREBASE, _settings)
                               .UploadDocumentAsync(FileDocument.Create(model.Receipt, $"{Helper.RandomNumber(10)}", $"{Helper.RandomNumber(10)}", FileDocumentType.GetDocumentType(MIMETYPE.IMAGE)));

                model.Receipt = uploadResult.Path;
            }
            catch (Exception e)
            {
                return(Failed(ResponseMessageViewModel.UNABLE_TO_UPLOAD_RECEIPT, ResponseErrorCodeStatus.UNABLE_TO_UPLOAD_RECEIPT));
            }

            var allocation = _paymentService.Allocate(_mapper.Map <PaymentAllocationInputModel, PaymentAllocation>(model));

            allocation.PaymentStatusId = (int)PaymentStatusEnum.PENDING;

            var user = await _userService.GetCurrentLoggedOnUserAsync();

            allocation.AppUserId = user.Id;

            var created = _paymentService.Allocate(allocation);

            return(Ok(_mapper.Map <PaymentAllocation, PaymentAllocationViewModel>(created)));
        }
Exemplo n.º 9
0
        // GET: FileDocs/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FileDocument fileDocument = db.FileDocuments.Find(id);

            if (fileDocument == null)
            {
                return(HttpNotFound());
            }
            return(View(fileDocument));
        }
        public bool CheckBeforeDelete(FileDocument filedocument)
        {
            var result = true;

            // Write your logic here

            if (!result)
            {
                var AlertMsg = "Validation Alert - Before Delete !! Information not deleted.";
                ModelState.AddModelError("CustomError", AlertMsg);
                ViewBag.ApplicationError = AlertMsg;
            }
            return(result);
        }
Exemplo n.º 11
0
        public ActionResult Delete(int?id, string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FileDocument fileDocument = db.FileDocuments.Find(id);

            if (fileDocument == null)
            {
                return(HttpNotFound());
            }
            return(View(fileDocument));
        }
Exemplo n.º 12
0
        // GET: Document/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FileDocument file = db.Files.Find(id?.Decode());

            if (file == null)
            {
                return(HttpNotFound());
            }
            Session["fileid"] = file.Id;
            return(PartialView("_Delete", (DocumentDeleteViewModel)file));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Submitting local file or free text to plagiarism scan
        /// </summary>
        /// <param name="scanId">A unique scan Id</param>
        /// <param name="documentModel">The file or free text encoded in base64 and scan properties</param>
        /// <returns>A task that represents the asynchronous submit operation.</returns>
        public async Task SubmitFileAsync(string scanId, FileDocument documentModel, string token)
        {
            if (documentModel.Base64 == null)
            {
                throw new ArgumentException("Base64 is mandatory.", nameof(documentModel.Base64));
            }
            else if (documentModel.Filename == null)
            {
                throw new ArgumentException("Filename is mandatory.", nameof(documentModel.Filename));
            }

            string requestUri = $"{this.CopyleaksApiServer}{this.ApiVersion}/scans/submit/file/{scanId}";

            await SubmitAsync(documentModel, requestUri, token).ConfigureAwait(false);
        }
Exemplo n.º 14
0
 public static DocumentViewModel ToDocumentViewModel(this FileDocument document)
 {
     return(new DocumentViewModel()
     {
         ContentLength = document.ContentLength,
         DocumentId = document.DocumentId,
         FileExtension = document.FileExtension,
         FileName = document.FileName,
         FileSize = document.FileSize,
         FileType = document.FileType,
         Title = document.Title,
         Description = document.Description,
         CreatedDate = document.CreatedDateString
     });
 }
Exemplo n.º 15
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FileDocument fileDocument = db.FileDocuments.Find(id);

            if (fileDocument == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ArticleId = new SelectList(db.Articles, "Id", "Title", fileDocument.ArticleId);
            return(View(fileDocument));
        }
Exemplo n.º 16
0
        public async Task <FileDocument> UploadDocumentAsync(FileDocument document)
        {
            try
            {
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

                CancellationToken token = cancellationTokenSource.Token;

                var profilePhotoPath = string.Empty;

                var bytes = Convert.FromBase64String(document.File);

                var uniqueFileName = Utility.GetUniqueFileName(document.FileNameWithExtension);

                var parentFolder = Path.Combine(_setting.UploadDrive, _setting.DriveName);

                if (!Directory.Exists(parentFolder))
                {
                    Directory.CreateDirectory(parentFolder);
                }

                profilePhotoPath = Path.Combine(parentFolder, uniqueFileName);

                using (var imageFile = new FileStream(profilePhotoPath, FileMode.Create))
                {
                    imageFile.Write(bytes, 0, bytes.Length);

                    imageFile.Flush();

                    var stream = new FileStream(profilePhotoPath, FileMode.Open);

                    var task = new FirebaseStorage(_setting.FireBaseBucket)
                               .Child("oidc")
                               .Child(document.Path)
                               .Child(document.FileNameWithExtension)
                               .PutAsync(stream, token, document.DocumentType.MimeType);

                    task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");

                    var result = await task;

                    return(FileDocument.Create(null, document.Name, result, document.DocumentType));
                }
            }
            catch (Exception e) { return(null); }
        }
Exemplo n.º 17
0
        public FileDocument Update(int id, FileDocument payload)
        {
            var res = _context.FileDocument.Find(id);

            if (res != null)
            {
                res.DocumentTypeId = payload.DocumentTypeId;
                res.DelFlag        = payload.DelFlag;
                res.UpdDt          = DateTime.Now;
                res.FUpdUserId     = payload.FUpdUserId;

                _context.FileDocument.Update(res);
                _context.SaveChanges();
            }

            return(res);
        }
Exemplo n.º 18
0
        public void TestIndexTermCanonicalInDoc()
        {
            GlobalIndex globalIndex = new GlobalIndex();
            Document    document    = new FileDocument("myFile");

            globalIndex.IndexCanonicalTermInDoc("string", document);

            IDictionary <string, int> expectedTermIdMap = new Dictionary <string, int>();

            expectedTermIdMap.Add("string", 0);
            Assert.IsTrue(Comparators.DictionariesAreEqual(expectedTermIdMap, globalIndex.GetTermIdMap()));

            Assert.AreEqual(0, globalIndex.RetrieveCanonicalTerm("string"));

            ISet <string> actualTermsCanonical = new HashSet <string>();

            actualTermsCanonical.UnionWith(globalIndex.GetCanonicalTerms());
            ISet <string> expectedTermsCanonical = new HashSet <string>();

            expectedTermsCanonical.Add("string");
            Assert.IsTrue(Comparators.SetsAreEqual(expectedTermsCanonical, actualTermsCanonical));

            ISet <string> expectedVariants = new HashSet <string>();

            Assert.IsTrue(Comparators.SetsAreEqual(expectedVariants, globalIndex.RetrieveVariantsOfCanonicalTerm("string")));

            Assert.AreEqual("string", globalIndex.RetrieveCanonicalTerm(0));

            IDictionary <Document, int> expectedDocMap = new Dictionary <Document, int>();

            expectedDocMap.Add(document, 0);
            Assert.IsTrue(Comparators.DictionariesAreEqual(expectedDocMap, globalIndex.GetDocMap()));

            ISet <Document> expectedDocuments = new HashSet <Document>();

            expectedDocuments.Add(document);
            Assert.IsTrue(Comparators.SetsAreEqual(expectedDocuments, globalIndex.GetDocuments()));

            IDictionary <int, ISet <int> > expectedTermsToDocs = new Dictionary <int, ISet <int> >();
            ISet <int> expectedDocIds = new HashSet <int>();

            expectedDocIds.Add(0);
            expectedTermsToDocs.Add(0, expectedDocIds);
            Assert.IsTrue(Comparators.DictionariesOfSetsAreEqual(expectedTermsToDocs, globalIndex.GetTermToDocs()));
        }
Exemplo n.º 19
0
        public ActionResult <string> createftp(string namefile, string tipodocumento)
        {
            ResultMessage <FileDocument> resultMessage = new ResultMessage <FileDocument>();

            try
            {
                FileDocument   resultado = new FileDocument();
                documento_sftp sftp      = new documento_sftp(_hostingEnvironment, _isetting);
                resultMessage = sftp.LecturaArchivoSfp(namefile, tipodocumento);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                resultMessage.Code    = 1;
                resultMessage.Message = string.Concat(exception.Message, " ", exception.StackTrace);
            }
            return(Ok(resultMessage));
        }
Exemplo n.º 20
0
        private Stream CreateTemporarySeedData(FileDocument doc)
        {
            var result = new MemoryStream();

            if (LoadResourceStream("Angelo.Drive.Assets.images", doc.FileName, result))
            {
                return(result);
            }

            if (LoadResourceStream("Angelo.Drive.Assets.videos", doc.FileName, result))
            {
                return(result);
            }

            //CreateSeedFile(doc, result);

            return(result);
        }
Exemplo n.º 21
0
        public async Task <ResponseViewModel> CreateNewJob(JobInputModel model)
        {
            //var jobStatus = _jobRepository.GetJobStatuses().FirstOrDefault(x => x.Id == model.JobStatusId);

            //if(jobStatus == null)
            //{
            //    return Failed(ResponseMessageViewModel.INVALID_JOB_STATUS, ResponseErrorCodeStatus.INVALID_JOB_STATUS);
            //}

            var jobType = _jobRepository.GetJobTypes().FirstOrDefault(x => x.Id == model.JobTypeId);

            //model.ValidityPeriod = DateTime.Now;

            if (jobType == null)
            {
                return(Failed(ResponseMessageViewModel.INVALID_JOB_TYPE, ResponseErrorCodeStatus.INVALID_JOB_TYPE));
            }

            var mappedResult = _mapper.Map <JobInputModel, Job>(model);

            var user = _userService.GetCurrentLoggedOnUserAsync().Result;

            mappedResult.AppUserId = user.Id;

            FileDocument uploadResult = FileDocument.Create();

            try
            {
                uploadResult = await
                               BaseContentServer
                               .Build(ContentServerTypeEnum.FIREBASE, _settings)
                               .UploadDocumentAsync(FileDocument.Create(model.Document, "Job", $"{user.GUID}", FileDocumentType.GetDocumentType(MIMETYPE.IMAGE)));

                mappedResult.Document = uploadResult.Path;
            }
            catch (Exception e)
            {
                return(Failed(ResponseMessageViewModel.ERROR_UPLOADING_FILE, ResponseErrorCodeStatus.ERROR_UPLOADING_FILE));
            }

            var result = _mapper.Map <Job, JobViewModel>(_jobRepository.CreateJob(mappedResult));

            return(Ok(result));
        }
        public async Task <bool> UploadFileAsync(UploadFileDocumentDto fileDocumetInfo,
                                                 byte[] fileDocumentData,
                                                 string fileName,
                                                 string contentType,
                                                 string userName,
                                                 CancellationToken ct)
        {
            FileDocument fileDocumentEntity = _mapper.Mapper.Map <FileDocument>(fileDocumetInfo);

            fileDocumentEntity.FileName    = fileName;
            fileDocumentEntity.ContentType = contentType;
            fileDocumentEntity.Data        = fileDocumentData;
            fileDocumentEntity.UploadedBy  = userName;
            fileDocumentEntity.UploadedOn  = DateTime.UtcNow;

            _uow.FileDocuments.Add(fileDocumentEntity);

            return(await _uow.SaveChangesAsync(ct) > 0);
        }
Exemplo n.º 23
0
        private async Task UploadDocumentAsync(FileDocument document, Stream file)
        {
            var url = $"{_connectDocumentOptions.DriveAuthority}/upload";

            using (var client = new HttpClient())
            {
                var content = new MultipartFormDataContent();
                ByteArrayContent fileContent;
                using (var br = new BinaryReader(file, System.Text.Encoding.UTF8, true))
                {
                    fileContent = new ByteArrayContent(br.ReadBytes((int)file.Length));
                }

                content.Add(fileContent, "file", document.FileName);
                content.Add(new StringContent(document.DocumentId), "documentId");

                await client.PostAsync(url, content);
            }
        }
Exemplo n.º 24
0
        private async void EnsurePhysicalFile(FileDocument doc, string libraryLocation)
        {
            var stream = await _uploadService.GetFileStreamAsync(doc, libraryLocation);

            if (stream == null)
            {
                using (stream = CreateTemporarySeedData(doc))
                {
                    if (stream.Length > 0)
                    {
                        await _uploadService.SetFileStreamAsync(doc, stream, libraryLocation);
                    }
                }
            }
            else
            {
                stream.Dispose();
            }
        }
Exemplo n.º 25
0
        public ActionResult ActivityUploader(HttpPostedFileBase postedFile, int id)
        {
            Activity activity            = db.Activities.Find(id);
            ActivitySubmitViewModel asvm = activity;
            var currentUser = UserUtils.GetCurrentUser(HttpContext);

            try
            {
                if (postedFile != null)
                {
                    FileDocument file = new FileDocument();
                    file.Email        = currentUser.Email;
                    file.CourseName   = currentUser.Course.Name;
                    file.Name         = postedFile.FileName;
                    file.ActivityId   = id;
                    file.ActivityName = asvm.Name;
                    file.MemberId     = currentUser.Id;
                    file.TimeStamp    = DateTime.Now;

                    string path = Server.MapPath("~/Uploads/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    db.Files.Add(file);
                    db.SaveChanges();
                    file.Id.Encode().ToString();
                    postedFile.SaveAs(path + file.Id.Encode().ToString());
                    TempData["alert"] = "success|Dokumentet är uppladdad!";
                }
                else
                {
                    TempData["alert"] = "danger|Kunde inte lägga till dokument";
                }
            }
            catch (DataException)
            {
                // Log errors here
                TempData["alert"] = "danger|Allvarligt fel!";
            }
            //return PartialView("_ActivityUploader",asvm);
            return(RedirectToAction("ActivityUpload"));
        }
Exemplo n.º 26
0
        public void RenameFileTest()
        {
            Collectors.InitCollectors();
            Collectors.AddProvider(typeof(FSIndexDirectoryProvider), System.Reflection.Assembly.GetAssembly(typeof(FSIndexDirectoryProvider)), "", typeof(IIndexDirectoryProviderV60));
            Host.Instance = new Host();
            Host.Instance.OverridePublicDirectory(testDir);

            ProviderLoader.SetUp <IIndexDirectoryProviderV60>(typeof(FSIndexDirectoryProvider), "");

            string fileName = "file name_1";

            string filePath = Path.Combine(testDir, "test.txt");

            using (StreamWriter writer = File.CreateText(filePath)) {
                writer.Write("This is the content of a file");
            }

            Assert.IsTrue(SearchClass.IndexFile(fileName, filePath, "wiki1"));

            List <SearchResult> results = SearchClass.Search("wiki1", new SearchField[] { SearchField.FileName, SearchField.FileContent }, "file", SearchOptions.AtLeastOneWord);

            Assert.AreEqual(1, results.Count, "Wrong result length");

            Assert.AreEqual(DocumentType.File, results[0].DocumentType, "Wrong document type");

            FileDocument fileDocument = results[0].Document as FileDocument;

            Assert.AreEqual(fileName, fileDocument.FileName, "Wrong file name");
            Assert.AreEqual("This is the content of a <b class=\"searchkeyword\">file</b>", fileDocument.HighlightedFileContent, "Wrong file content");

            Assert.IsTrue(SearchClass.RenameFile("wiki1", fileName, "file name_2"));

            results = SearchClass.Search("wiki1", new SearchField[] { SearchField.FileName, SearchField.FileContent }, "file", SearchOptions.AtLeastOneWord);

            Assert.AreEqual(1, results.Count, "Wrong result length");

            Assert.AreEqual(DocumentType.File, results[0].DocumentType, "Wrong document type");

            fileDocument = results[0].Document as FileDocument;

            Assert.AreEqual("file name_2", fileDocument.FileName, "Wrong file name");
            Assert.AreEqual("This is the content of a <b class=\"searchkeyword\">file</b>", fileDocument.HighlightedFileContent, "Wrong file content");
        }
Exemplo n.º 27
0
 public string Create([Bind(Include = "Id,Title,Description,Data,ContentType,ArticleId")] FileDocument fileDocument, HttpPostedFileBase uploadedFile)
 {
     if (ModelState.IsValid)
     {
         if (uploadedFile != null)
         {
             byte[] imageData = null;
             // считываем переданный файл в массив байтов
             using (var binaryReader = new BinaryReader(uploadedFile.InputStream))
                 imageData = binaryReader.ReadBytes(uploadedFile.ContentLength);
             // установка массива байтов
             fileDocument.Data        = imageData;
             fileDocument.ContentType = uploadedFile.ContentType;
             db.FileDocuments.Add(fileDocument);
             db.SaveChanges();
         }
         return("ok");
     }
     return("fail");
 }
Exemplo n.º 28
0
        // constructors
        public GridFSForwardOnlyDownloadStream(
            GridFSBucket bucket,
            FileDocument fileInfo,
            bool checkMD5)
            : base(bucket, fileInfo)
        {
            _checkMD5 = checkMD5;
            if (_checkMD5)
            {
                _md5 = new IncrementalMD5();
            }

            _lastChunkNumber = (int)((fileInfo.Length - 1) / fileInfo.ChunkSize);
            _lastChunkSize   = (int)(fileInfo.Length % fileInfo.ChunkSize);

            if (_lastChunkSize == 0)
            {
                _lastChunkSize = fileInfo.ChunkSize;
            }
        }
Exemplo n.º 29
0
        public void TestGetNestIdsOf()
        {
            GlobalIndex   globalIndex = new GlobalIndex();
            FileDocument  document    = new FileDocument("myFile");
            ISet <string> terms       = new HashSet <string>();

            terms.Add("machine");
            terms.Add("sewing machine");

            globalIndex.IndexDocWithCanonicalTerms(document, terms);

            FeatureTermNest featureTermNest = new FeatureTermNest(globalIndex);

            featureTermNest.TermNestIn("machine", "sewing machine");

            ISet <int> expectedNestIds = new HashSet <int>();

            expectedNestIds.Add(1);
            Assert.IsTrue(Comparators.SetsAreEqual(expectedNestIds, featureTermNest.GetNestIdsOf("machine")));
        }
Exemplo n.º 30
0
        public ActionResult DeleteConfirmed()
        {
            int?id = (int?)Session["fileid"];

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FileDocument file = db.Files.Find(id);

            if (file != null && DeleteDocs(new FileDocument[] { file }))
            {
                TempData["alert"] = "success|Dokumentet togs bort!|Upload";
            }
            else
            {
                TempData["alert"] = "danger|Det gick inte att ta bort Dokumentet!";
            }
            return(PartialView("_Delete"));
        }
Exemplo n.º 31
0
 protected Downloads.File GetDownloadFileSetUp(string path, DocumentType doctype)
 {
     var file = new FileDocument(path, doctype);
     return file.GetFile();
 }