Inheritance: ApiController
Exemplo n.º 1
0
 public void SetUp()
 {
     _mockPostUseCase = new Mock <IUploadFile>();
     _mockGetUseCase  = new Mock <IGetFileUsecase>();
     _mockLogger      = new Mock <ILogger <FilesController> >();
     _filesController = new FilesController(_mockPostUseCase.Object, _mockGetUseCase.Object, _mockLogger.Object);
 }
        public ActionResult Add(Music.Model.EF.Singer singer, HttpPostedFileBase IMG, string del)
        {
            singer.singer_bin        = false;
            singer.singer_dateupdate = DateTime.Now;

            if (singer.singer_active != true && singer.singer_active != false)
            {
                singer.singer_active = false;
            }

            //Chèn ảnh
            if (IMG != null)
            {
                var code = Guid.NewGuid().ToString();
                var img  = new FilesController();
                img.AddImages(IMG, Common.Link.IMG_SINGER, code);
                singer.singer_img = code + IMG.FileName;
            }
            else
            {
                singer.singer_img = "notImg.png";
            }

            if (singersDAO.Add(singer))
            {
                return(Redirect("/Admin/SingersAdmin"));
            }
            else
            {
                return(Redirect(Common.Link.NOT_404));
            }
        }
Exemplo n.º 3
0
        private void OpenFileButton_Click(object sender, EventArgs e)
        {
            var             selectedProjectFiles = new List <ProjectFile>();
            FilesController filesController      = GetFilesController();

            if (!filesController.AreAllSelectedTaskFilesAssignedToCurrentUser)
            {
                DialogResult dialogResult = MessageBox.Show("Warning", "Not all selected files are assigned to the current user. Would you like to continue?", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.No)
                {
                    return;
                }
            }

            for (int i = 0; i < FilesListView.SelectedItems.Count; i++)
            {
                selectedProjectFiles.Add((ProjectFile)FilesListView.SelectedItems[i].Tag);
            }

            if (selectedProjectFiles.Count == 0)
            {
                return;
            }

            try
            {
                SdlTradosStudio.Application.GetController <EditorController>()
                .Open(selectedProjectFiles, EditingMode.Translation);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Cannot open the project file: \n{0}", ex.Message));
            }
        }
        public FilesControllerTest()
        {
            _filesService.SetupFilesService(MockData.FilesList);
            _productsService.SetupProductsService(MockData.ProductsList);

            _filesController = new FilesController(_logger.Object, _filesService.Object, _productsService.Object, _inventoryService.Object);
        }
        public ActionResult Add(Music.Model.EF.User user, HttpPostedFileBase IMG)
        {
            user.user_bin = false;

            if (user.user_active != true && user.user_active != false)
            {
                user.user_active = false;
            }

            //Chèn ảnh
            if (IMG != null)
            {
                var code = Guid.NewGuid().ToString();
                var img  = new FilesController();
                img.AddImages(IMG, Common.Link.IMG_USER, code);
                user.user_img = code + IMG.FileName;
            }
            else
            {
                user.user_img = "notImg.png";
            }

            if (usersDAO.Add(user))
            {
                return(Redirect("/Admin/UsersAdmin"));
            }
            else
            {
                return(Redirect(Common.Link.NOT_404));
            }
        }
Exemplo n.º 6
0
        public void should_get_page_content()
        {
            // given
            var contextService        = new Mock <IContextService>();
            var documentRender        = new Mock <IDocumentRender>();
            var fileStorage           = new Mock <IFilesStorage>();
            var fileSaver             = new Mock <IFileSaver>();
            var filesOperationService = new Mock <IFilesOperationService>();
            var controller            = new FilesController(
                contextService.Object,
                documentRender.Object,
                fileStorage.Object,
                fileSaver.Object,
                filesOperationService.Object);

            // when
            var fileId = Guid.NewGuid();
            var page   = new byte[] { 1, 2, 3, 4, 5, 6, 7 };

            fileStorage.Setup(fs => fs.GetImageFile(fileId, 1)).Returns(page);
            var result = controller.GetDocumentPageContent(fileId.ToString(), 1) as FileContentResult;

            // then
            Assert.AreEqual(page, result.FileContents);
        }
Exemplo n.º 7
0
        public void should_get_pages_count_from_storage()
        {
            // given
            var contextService        = new Mock <IContextService>();
            var documentRender        = new Mock <IDocumentRender>();
            var fileStorage           = new Mock <IFilesStorage>();
            var fileSaver             = new Mock <IFileSaver>();
            var filesOperationService = new Mock <IFilesOperationService>();
            var controller            = new FilesController(
                contextService.Object,
                documentRender.Object,
                fileStorage.Object,
                fileSaver.Object,
                filesOperationService.Object);
            // when
            var fileId = Guid.NewGuid();
            var page   = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

            fileStorage.Setup(fs => fs.GetPages(fileId)).Returns(new List <byte[]> {
                page
            });
            var result = controller.GetDocumentPagesCount(fileId.ToString(), 500, 1);

            // then
            Assert.AreEqual(1, result);
        }
Exemplo n.º 8
0
        public void should_get_thumbnail_from_render()
        {
            // given
            var contextService        = new Mock <IContextService>();
            var documentRender        = new Mock <IDocumentRender>();
            var fileStorage           = new Mock <IFilesStorage>();
            var fileSaver             = new Mock <IFileSaver>();
            var filesOperationService = new Mock <IFilesOperationService>();
            var controller            = new FilesController(
                contextService.Object,
                documentRender.Object,
                fileStorage.Object,
                fileSaver.Object,
                filesOperationService.Object);

            // when
            var fileId        = Guid.NewGuid();
            var fileSize      = 10;
            var thumbnailFile = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var thumbnail     = new byte[] { 1, 2, 3, 4, 5 };

            fileStorage.Setup(fs => fs.GetThumbnail(fileId)).Returns((byte[])null);
            contextService.Setup(hs => hs.GetTokenActor(It.IsAny <HttpContext>())).Returns("sedov");
            var fileLoader = new Mock <IFileLoader>();

            fileLoader.Setup(fl => fl.Download(fileId, fileSize)).Returns(thumbnailFile);
            contextService.Setup(cs => cs.GetFileLoader("sedov")).Returns(fileLoader.Object);
            documentRender.Setup(dr => dr.RenderPage(thumbnailFile, 1, 0.2)).Returns(thumbnail);

            var result = controller.GetThumbnail(fileId.ToString(), fileSize) as FileContentResult;

            // then
            Assert.AreEqual(thumbnail, result.FileContents);
            fileSaver.Verify(fs => fs.PutThumbnailAsync(fileId, thumbnail));
        }
Exemplo n.º 9
0
        public void should_get_thumbnail_from_storage()
        {
            // given
            var contextService        = new Mock <IContextService>();
            var documentRender        = new Mock <IDocumentRender>();
            var fileStorage           = new Mock <IFilesStorage>();
            var fileSaver             = new Mock <IFileSaver>();
            var filesOperationService = new Mock <IFilesOperationService>();
            var controller            = new FilesController(
                contextService.Object,
                documentRender.Object,
                fileStorage.Object,
                fileSaver.Object,
                filesOperationService.Object);

            // when
            var fileId    = Guid.NewGuid();
            var fileSize  = 10;
            var thumbnail = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            fileStorage.Setup(fs => fs.GetThumbnail(fileId)).Returns(thumbnail);
            var result = controller.GetThumbnail(fileId.ToString(), fileSize) as FileContentResult;

            // then
            Assert.AreEqual(thumbnail, result.FileContents);
        }
Exemplo n.º 10
0
        public void DownloadFile()
        {
            var fileName    = "Test.pdf";
            var contentType = "application/pdf";

            byte[]            bytes       = Encoding.ASCII.GetBytes("Test Content String");
            FileContentResult fileContent = new FileContentResult(bytes, contentType);

            fileContent.FileDownloadName = fileName;

            File _file = new File()
            {
                FileName    = fileName,
                ContentType = contentType,
                Content     = fileContent.FileContents
            };

            this._mockBlobService.Setup(x => x.CheckFileExists(It.IsAny <string>())).Returns(true);
            this._mockBlobService.Setup(x => x.GetFile(It.IsAny <string>())).Returns(() => _file);
            this._fileController = new FilesController(this._mockBlobService.Object, this._mockLogger.Object, this._mockConfiguration.Object);
            var actual   = this._fileController.GetFile(fileName) as FileContentResult;
            var expected = fileContent;

            Assert.Equal(expected.FileContents, actual.FileContents);
        }
        public ActionResult Add(Music.Model.EF.Author author, HttpPostedFileBase IMG, string del)
        {
            author.author_bin = false;

            if (author.author_active != true && author.author_active != false)
            {
                author.author_active = false;
            }

            //Chèn ảnh
            if (IMG != null)
            {
                var code = Guid.NewGuid().ToString();
                var img  = new FilesController();
                img.AddImages(IMG, Common.Link.IMG_AUTHOR, code);
                author.author_img = code + IMG.FileName;
            }
            else
            {
                author.author_img = "notImg.png";
            }

            if (authorsDAO.Add(author))
            {
                return(Redirect("/Admin/AuthorsAdmin"));
            }
            else
            {
                return(Redirect(Common.Link.NOT_404));
            }
        }
Exemplo n.º 12
0
        public void PostTestWrongExtensionReturnsErrorMessage()
        {
            //Arrange
            var             txtFileName    = "Data.txt";
            TestFileHelper  tstHelper      = new TestFileHelper(txtFileName, "");
            FilesController fileController = new FilesController(tstHelper.config.Object,
                                                                 new CsvFileHandler(new ValidationService(),
                                                                                    new FileService(tstHelper.config.Object),
                                                                                    new ParsingService()));

            // Expected result
            var expectedResult = new NotFoundObjectResult(new
            {
                message =
                    $"Selected file, {txtFileName}, does not have supported format CSV"
            });

            //Act
            var actualResult = fileController.Post(new List <IFormFile>()
            {
                tstHelper.fileMock.Object
            }, true);

            //Assert
            Assert.IsNotNull(actualResult);
            Assert.IsNotNull(actualResult.Result);
            Assert.AreEqual(expectedResult.StatusCode,
                            ((NotFoundObjectResult)actualResult.Result).StatusCode);
            Assert.AreEqual(expectedResult.Value.ToString(),
                            ((NotFoundObjectResult)actualResult.Result).Value.ToString());
        }
Exemplo n.º 13
0
        public async void Returns_FileOut_when_FileExistAndBelongsToUser()
        {
            FileOut file = new FileOut
            {
                ID   = Guid.NewGuid(),
                Name = Guid.NewGuid().ToString()
            };

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.GetByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <FileOut>(StatusCodes.Status200OK, file)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Get(Guid.NewGuid());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);
            Assert.IsType <FileOut>(okObjectResult.Value);
        }
Exemplo n.º 14
0
        public async void Returns_PatchedFileOut_when_Success()
        {
            FileOut file = new FileOut
            {
                ID = Guid.NewGuid()
            };

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.PatchByIdAndFilePatchAndUser(It.IsAny <Guid>(), It.IsAny <JsonPatchDocument <FilePatch> >(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <FileOut>(StatusCodes.Status200OK, file)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Patch(Guid.NewGuid(), new JsonPatchDocument <FilePatch>());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);
            Assert.IsType <FileOut>(okObjectResult.Value);
        }
Exemplo n.º 15
0
        public async void Returns_ListFileUploadResult()
        {
            List <FileUploadResult> fileUploadResults = new List <FileUploadResult>();
            Mock <IFileService>     fileService       = new Mock <IFileService>();

            fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <List <FileUploadResult> >(StatusCodes.Status200OK, fileUploadResults)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            FilePost filePost = new FilePost
            {
                ParentDirectoryID = null,
                Files             = new FormFileCollection
                {
                    new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("Some content")), 0, 12, "file", "file.txt")
                }
            };

            IActionResult result = await filesController.Post(filePost);

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);

            Assert.IsType <List <FileUploadResult> >(okObjectResult.Value);
        }
Exemplo n.º 16
0
        public IHttpActionResult SaveDoiTuongKhenThuong([FromBody] tblDoituongKhenthuong ndkt)
        {
            if (ndkt.Id == null || ndkt.Id == 0)
            {
                db.tblDoituongKhenthuongs.Add(ndkt);
                db.SaveChanges();
            }
            else
            {
                if (ndkt.Trangthai == 3)
                {
                    FilesController fl = new FilesController();
                    fl.RemoveFileXetDuyetKhenThuong(ndkt.Duongdan, ndkt.Id);

                    ndkt.SoQD                 = null;
                    ndkt.TieuchiDat           = null;
                    ndkt.Duongdan             = null;
                    ndkt.IdHinhthucKhenthuong = null;
                }

                db.Entry(ndkt).State = EntityState.Modified;
                db.SaveChanges();
            }
            return(Ok(ndkt));
        }
Exemplo n.º 17
0
        public async void Returns_ParentDirectoryOfDeletingFile_when_FileExistAndBelongsToUser()
        {
            Guid parentId = Guid.NewGuid();
            StatusCode <DirectoryOut> status = new StatusCode <DirectoryOut>(StatusCodes.Status200OK, new DirectoryOut
            {
                ID = parentId
            });

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.DeleteByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Delete(Guid.NewGuid());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);

            DirectoryOut parentDirectoryOut = okObjectResult.Value as DirectoryOut;

            Assert.NotNull(parentDirectoryOut);
            Assert.Equal(parentId, parentDirectoryOut.ID);
        }
        public FilesControllerTests()
        {
            //TODO NInject or some other resolvers.
            var fileServices          = new EnvironmentBuilder("FileServicesClient:Username", "FileServicesClient:Password", "FileServicesClient:Url");
            var lookupServices        = new EnvironmentBuilder("LookupServicesClient:Username", "LookupServicesClient:Password", "LookupServicesClient:Url");
            var locationServices      = new EnvironmentBuilder("LocationServicesClient:Username", "LocationServicesClient:Password", "LocationServicesClient:Url");
            var lookupServiceClient   = new LookupCodeServicesClient(lookupServices.HttpClient);
            var locationServiceClient = new LocationServicesClient(locationServices.HttpClient);
            var fileServicesClient    = new FileServicesClient(fileServices.HttpClient);

            _fileServicesClient = fileServicesClient;
            var lookupService   = new LookupService(lookupServices.Configuration, lookupServiceClient, new CachingService());
            var locationService = new LocationService(locationServices.Configuration, locationServiceClient, new CachingService());

            _agencyIdentifierId = fileServices.Configuration.GetNonEmptyValue("Request:AgencyIdentifierId");
            _partId             = fileServices.Configuration.GetNonEmptyValue("Request:PartId");
            var claims = new[] {
                new Claim(CustomClaimTypes.JcParticipantId, _partId),
                new Claim(CustomClaimTypes.JcAgencyCode, _agencyIdentifierId),
            };
            var identity  = new ClaimsIdentity(claims, "Cookies");
            var principal = new ClaimsPrincipal(identity);

            var filesService = new FilesService(fileServices.Configuration, fileServicesClient, new Mapper(), lookupService, locationService, new CachingService(), principal);

            //TODO fake this.
            var vcCivilFileAccessHandler = new VcCivilFileAccessHandler(new ScvDbContext());

            _controller = new FilesController(fileServices.Configuration, fileServices.LogFactory.CreateLogger <FilesController>(), filesService, vcCivilFileAccessHandler);
            _controller.ControllerContext = HttpResponseTest.SetupMockControllerContext(fileServices.Configuration);
        }
Exemplo n.º 19
0
        public ActionResult Add(Music.Model.EF.Category category, HttpPostedFileBase IMG, string del)
        {
            category.category_bin = false;

            if (category.category_active != true && category.category_active != false)
            {
                category.category_active = false;
            }

            //Chèn ảnh
            if (IMG != null)
            {
                var code = Guid.NewGuid().ToString();
                var img  = new FilesController();
                img.AddImages(IMG, Common.Link.IMG_CATEGORY, code);
                category.category_img = code + IMG.FileName;
            }
            else
            {
                category.category_img = "notImg.png";
            }

            if (categoriesDAO.ADD(category))
            {
                return(Redirect("/Admin/CategoryAdmin"));
            }
            else
            {
                return(Redirect(Common.Link.NOT_404));
            }
        }
Exemplo n.º 20
0
        public void should_get_file_content()
        {
            // given
            var contextService        = new Mock <IContextService>();
            var documentRender        = new Mock <IDocumentRender>();
            var fileStorage           = new Mock <IFilesStorage>();
            var fileSaver             = new Mock <IFileSaver>();
            var filesOperationService = new Mock <IFilesOperationService>();
            var controller            = new FilesController(
                contextService.Object,
                documentRender.Object,
                fileStorage.Object,
                fileSaver.Object,
                filesOperationService.Object);

            // when
            var fileId   = Guid.NewGuid();
            var fileSize = 10;
            var file     = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            contextService.Setup(hs => hs.GetTokenActor(It.IsAny <HttpContext>())).Returns("sedov");
            var fileLoader = new Mock <IFileLoader>();

            fileLoader.Setup(fl => fl.Download(fileId, fileSize)).Returns(file);
            contextService.Setup(cs => cs.GetFileLoader("sedov")).Returns(fileLoader.Object);

            var result = controller.GetFile(fileId.ToString(), fileSize) as FileContentResult;

            // then
            Assert.AreEqual(file, result.FileContents);
        }
        public ActionResult Add(Music.Model.EF.Album album, HttpPostedFileBase IMG, string del)
        {
            album.album_bin      = false;
            album.album_dateedit = DateTime.Now;

            if (album.album_active != true && album.album_active != false)
            {
                album.album_active = false;
            }

            //Chèn ảnh
            if (IMG != null)
            {
                var code = Guid.NewGuid().ToString();
                var img  = new FilesController();
                img.AddImages(IMG, Common.Link.IMG_ALBUM, code);
                album.album_img = code + IMG.FileName;
            }
            else
            {
                album.album_img = "notImg.png";
            }

            if (albumsDAO.Add(album))
            {
                return(Redirect("/Admin/AlbumsAdmin"));
            }
            else
            {
                return(Redirect(Common.Link.NOT_404));
            }
        }
Exemplo n.º 22
0
 public FilesControllerTest()
 {
     fileRepository = new Mock <IRepository <File> >();
     testSubject    = new FilesController(fileRepository.Object);
     testSubject.ControllerContext = new ControllerContext(new ActionContext(new DefaultHttpContext(),
                                                                             new RouteData(), new ControllerActionDescriptor()));
 }
Exemplo n.º 23
0
 public ActionResult SentFormData(Form1Data model, HttpPostedFileBase files)
 {
     if (ModelState.IsValid)
     {
         try
         {
             if (files != null)
             {
                 if (files.ContentLength > 0)
                 {
                     model.File_Info = FilesController.GetFilesInfo(files);
                     if (model.File_Info != string.Empty)
                     {
                         FilesController.ToSaveFile(files);
                     }
                 }
             }
             bool result = Form1Data.ToInsForm1Data(model);
             if (result)
             {
                 return(RedirectToAction("ViewShowData"));
             }
             else
             {
                 return(View());
             }
         }
         catch (Exception err)
         {
             ModelState.AddModelError("Error", err.Message);
             return(View(err.Message));
         }
     }
     return(View(model));
 }
Exemplo n.º 24
0
        /// <summary>
        /// 刪除資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool ToDelForm1Data(int?id)
        {
            bool result = false;

            using (var conn = new SqlConnection(MainController.connStr))
            {
                conn.Open();
                SqlTransaction sqlTrans = conn.BeginTransaction();
                try
                {
                    string sqlStr = "";
                    sqlStr = @"SELECT * FROM dt_formdata WHERE ID = @dc_ID ";
                    var que = conn.Query <Form1Data>(sqlStr, new { dc_ID = id }, sqlTrans).FirstOrDefault();

                    if (que.File_Info != string.Empty)
                    {
                        FilesController.ToDelFile(que.File_Info);
                    }

                    sqlStr = @"DELETE FROM dt_formdata WHERE ID = @dc_ID";
                    conn.Execute(sqlStr, new[] {
                        new { dc_ID = id }
                    }, sqlTrans);

                    sqlTrans.Commit();
                }
                catch (Exception err)
                {
                    sqlTrans.Rollback();
                    throw (err);
                }
            }
            return(result);
        }
Exemplo n.º 25
0
        public async void Returns_NotFoundObjectResult_when_ParentDirectoryNotExistsOrNotBelongsToUser()
        {
            StatusCode <List <FileUploadResult> > status = new StatusCode <List <FileUploadResult> >(StatusCodes.Status404NotFound);
            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>()))
            .Returns(Task.FromResult(status));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            FilePost filePost = new FilePost
            {
                ParentDirectoryID = Guid.NewGuid(),
                Files             = new FormFileCollection
                {
                    new FormFile(null, 0, 0, "", "")
                }
            };
            IActionResult result = await filesController.Post(filePost);

            Assert.IsType <NotFoundObjectResult>(result);
        }
Exemplo n.º 26
0
        public async void Returns_DownloadingFile_when_FileExistAndBelongsToUser()
        {
            byte[] content  = Encoding.UTF8.GetBytes("File content ...");
            string fileName = "file.txt";

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.DownloadByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <DownloadFileInfo>(StatusCodes.Status200OK, new DownloadFileInfo(fileName, content))));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Download(Guid.NewGuid());

            FileContentResult fileContentResult = result as FileContentResult;

            Assert.NotNull(fileContentResult);

            Assert.NotNull(fileContentResult.FileDownloadName);
            Assert.NotNull(fileContentResult.FileContents);
            Assert.NotNull(fileContentResult.ContentType);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Publish a <see cref="List{T}"/> of <paramref name="diffResults"/>s to the <see cref="IDatabaseContext"/> and GitHub
        /// </summary>
        /// <param name="pullRequest">The <see cref="PullRequest"/> the <paramref name="diffResults"/> are for</param>
        /// <param name="diffResults">The map of <see cref="MapDiff"/>s to <see cref="MapRegion"/>s</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
        /// <returns>A <see cref="Task"/> representing the running operation</returns>
        async Task HandleResults(PullRequest pullRequest, Dictionary <MapDiff, MapRegion> diffResults, CancellationToken cancellationToken)
        {
            int formatterCount = 0;

            var databaseContext = serviceProvider.GetRequiredService <IDatabaseContext>();

            var deleteTask = databaseContext.MapDiffs.Where(x => x.InstallationRepositoryId == pullRequest.Base.Repository.Id && x.PullRequestNumber == pullRequest.Number).DeleteAsync(cancellationToken);

            var commentBuilder = new StringBuilder();
            var prefix         = generalConfiguration.ApplicationPrefix;

            logger.LogTrace("Generating comment and preparing database query...");
            foreach (var kv in diffResults)
            {
                var I         = kv.Key;
                var beforeUrl = String.Concat(prefix, FilesController.RouteTo(pullRequest, formatterCount, "before"));
                var afterUrl  = String.Concat(prefix, FilesController.RouteTo(pullRequest, formatterCount, "after"));
                var logsUrl   = String.Concat(prefix, FilesController.RouteTo(pullRequest, formatterCount, "logs"));

                commentBuilder.Append(String.Format(CultureInfo.InvariantCulture,
                                                    "<details><summary>{0}</summary>{11}{11}{1} | {2}{11}--- | ---{11}![]({3}) | ![]({4}){11}{11}{5} | {6} | {7} | {12}{11}--- | --- | --- | ---{11}{8} | {9} | [{7}]({10}) | [{1}]({3}) \\| [{2}]({4}){11}{11}</details>{11}{11}",
                                                    I.MapPath,
                                                    stringLocalizer["Old"],
                                                    stringLocalizer["New"],
                                                    beforeUrl,
                                                    afterUrl,
                                                    stringLocalizer["Status"],
                                                    stringLocalizer["Region"],
                                                    stringLocalizer["Logs"],
                                                    I.BeforeImage != null ? (I.AfterImage != null ? stringLocalizer["Modified"] : stringLocalizer["Deleted"]) : stringLocalizer["Created"],
                                                    kv.Value?.ToString() ?? stringLocalizer["ALL"],
                                                    logsUrl,
                                                    Environment.NewLine,
                                                    stringLocalizer["Raw"]
                                                    ));
                logger.LogTrace("Adding MapDiff for {0}...", I.MapPath);
                databaseContext.MapDiffs.Add(I);
                ++formatterCount;
            }

            var comment = String.Format(CultureInfo.CurrentCulture,
                                        "{4}<br>{0}{3}{3}{3}{3}<br>{1}{3}{3}{3}{3}{2}{3}{3}{3}{3}{5}",
                                        commentBuilder,
                                        stringLocalizer["Last updated from merging commit {0} into {1}", pullRequest.Head.Sha, pullRequest.Base.Sha],
                                        stringLocalizer["Full job logs available [here]({0})", String.Concat(prefix, FilesController.RouteToBrowse(pullRequest))],
                                        Environment.NewLine,
                                        stringLocalizer["Maps with diff:"],
                                        stringLocalizer["Please report any issues [here]({0}).", issueReportUrl]
                                        );

            logger.LogTrace("Waiting for old MapDiffs to delete...");
            await deleteTask.ConfigureAwait(false);

            logger.LogTrace("Committing new MapDiffs to the database...");
            await databaseContext.Save(cancellationToken).ConfigureAwait(false);

            logger.LogTrace("Creating MapDiffBot comment...");
            await serviceProvider.GetRequiredService <IGitHubManager>().CreateSingletonComment(pullRequest, comment, cancellationToken).ConfigureAwait(false);
        }
Exemplo n.º 28
0
        public HttpResponseMessage DownloadTsvMetadataById(int id)
        {
            var predictor = Database.Query <PredictorEntity>().SingleEx(p => p.Id == id);

            byte[] content = predictor.GetTsvMetadata();

            return(FilesController.GetHttpReponseMessage(new MemoryStream(content), $"{predictor.Name}.metadata.tsv"));
        }
Exemplo n.º 29
0
        public FileStreamResult GenerateExcelReport([Required, FromBody] ExcelReportRequest request)
        {
            byte[] file = ExcelLogic.ExecuteExcelReport(request.excelReport, request.queryRequest.ToQueryRequest());

            var fileName = request.excelReport.ToString() + "-" + TimeZoneManager.Now.ToString("yyyyMMdd-HHmmss") + ".xlsx";

            return(FilesController.GetFileStreamResult(new MemoryStream(file), fileName));
        }
Exemplo n.º 30
0
 public void LoadImages(FilesController workingDirectory)
 {
     workingDirectory.CreateDirectory(@"Images\CGs\" + Name);
     BGImage1 = BGImage1 ?? PartialPalettedImage.FromFile(workingDirectory, @"CGs\" + Name + @"\BG1");
     BGImage2 = BGImage2 ?? PartialPalettedImage.FromFile(workingDirectory, @"CGs\" + Name + @"\BG2");
     FGImage1 = FGImage1 ?? PartialPalettedImage.FromFile(workingDirectory, @"CGs\" + Name + @"\FG1");
     FGImage2 = FGImage2 ?? PartialPalettedImage.FromFile(workingDirectory, @"CGs\" + Name + @"\FG2");
 }