Ejemplo n.º 1
0
        public async Task <IActionResult> CreateFileAsync([FromBody] CreateFileCommand command)
        {
            command.UserId = UserId;
            await CommandDispatcher.DispatchAsync(command);

            return(StatusCode(201));
        }
Ejemplo n.º 2
0
        private void filePathValidate(string value)
        {
            IsFilePathCorrect = true;
            if (string.IsNullOrEmpty(value))
            {
                IsFilePathCorrect         = false;
                FilePathValidatedWrongTip = "位置不能为空";
            }
            else
            {
                if (!Directory.Exists(value))
                {
                    IsFilePathCorrect         = false;
                    FilePathValidatedWrongTip = "指定的位置不存在";
                }
            }

            //判断是否是在项目目录中的子目录里
            if (!value.IsSubPathOf(ProjectPath))
            {
                IsFilePathCorrect         = false;
                FilePathValidatedWrongTip = "指定的位置必须是项目所在目录或其子目录中";
            }

            CreateFileCommand.RaiseCanExecuteChanged();
        }
        public async Task Handle_Invalid_Throws()
        {
            // arrange
            var request = new CreateFileCommand()
            {
                Name           = "Test",
                ParentFolderId = new Guid("97b7e004-be8e-424d-90c9-fa070996beb1")
            };

            var repositoryMock = new Mock <IRepository <File> >();

            repositoryMock.Setup(x => x.Insert(It.IsAny <File>(), CancellationToken.None)).ThrowsAsync(new Exception());


            var _mediatorMock = new Mock <IMediator>();

            _mediatorMock.Setup(x => x.Send(It.IsAny <GetFolderQuery>(), CancellationToken.None)).ReturnsAsync(new FolderDto()
            {
                HierarchyId = "/Test/"
            });


            var handler = new CreateFileCommandHandler(repositoryMock.Object, AutomapperFactory.Get(), _mediatorMock.Object);

            // act
            await Assert.ThrowsAsync <CreateException>(() => handler.Handle(request, CancellationToken.None));

            // assert
            repositoryMock.Verify(x => x.Insert(It.IsAny <File>(), CancellationToken.None), Times.Once);
            repositoryMock.VerifyNoOtherCalls();
        }
Ejemplo n.º 4
0
        private void filePathValidate(string value)
        {
            IsFilePathCorrect = true;
            if (string.IsNullOrEmpty(value))
            {
                IsFilePathCorrect = false;
                // 位置不能为空
                FilePathValidatedWrongTip = ResxIF.GetString("PathCannotBeEmpty");
            }
            else
            {
                if (!Directory.Exists(value))
                {
                    IsFilePathCorrect = false;
                    // 指定的位置不存在
                    FilePathValidatedWrongTip = ResxIF.GetString("ThePathDoesNotExist");
                }
            }

            //判断是否是在项目目录中的子目录里
            if (!value.IsSubPathOf(ProjectPath))
            {
                IsFilePathCorrect = false;
                // 指定的位置必须是项目所在目录或其子目录中
                FilePathValidatedWrongTip = ResxIF.GetString("NotInSubDirectory");
            }

            CreateFileCommand.RaiseCanExecuteChanged();
        }
Ejemplo n.º 5
0
        public static async Task <Guid?> CreateCasterWorkspaceAsync(CasterApiClient casterApiClient, EventEntity eventEntity, Guid directoryId, string varsFileContent, bool useDynamicHost, CancellationToken ct)
        {
            try
            {
                // remove special characters from the user name, use lower case and replace spaces with underscores
                var userName = Regex.Replace(eventEntity.Username.ToLower().Replace(" ", "_"), "[@&'(\\s)<>#]", "", RegexOptions.None);
                // create the new workspace
                var workspaceCommand = new CreateWorkspaceCommand()
                {
                    Name        = $"{userName}-{eventEntity.UserId.ToString()}",
                    DirectoryId = directoryId,
                    DynamicHost = useDynamicHost
                };
                var workspaceId = (await casterApiClient.CreateWorkspaceAsync(workspaceCommand, ct)).Id;
                // create the workspace variable file
                var createFileCommand = new CreateFileCommand()
                {
                    Name        = $"{workspaceCommand.Name}.auto.tfvars",
                    DirectoryId = directoryId,
                    WorkspaceId = workspaceId,
                    Content     = varsFileContent
                };
                await casterApiClient.CreateFileAsync(createFileCommand, ct);

                return(workspaceId);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 6
0
        public static async Task <BoxFile> CreateSmallFile(string parentId = "0", CommandScope commandScope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.User)
        {
            var createFileCommand = new CreateFileCommand(GetUniqueName("file"), GetSmallFilePath(), parentId, commandScope, accessLevel);

            await ExecuteCommand(createFileCommand);

            return(createFileCommand.File);
        }
Ejemplo n.º 7
0
        public void Validate_NameIsNullString_Invalid()
        {
            var validator = new CreateFileCommandValidator();

            var query  = new CreateFileCommand(null, null);
            var result = validator.Validate(query);

            Assert.False(result.IsValid);
        }
Ejemplo n.º 8
0
        public void Validate_ValidRequest()
        {
            var validator = new CreateFileCommandValidator();

            var query1  = new CreateFileCommand("Test", null);
            var result1 = validator.Validate(query1);

            Assert.True(result1.IsValid);
        }
Ejemplo n.º 9
0
        private void fileNameValidate(string value)
        {
            IsFileNameCorrect = true;

            if (string.IsNullOrEmpty(value))
            {
                IsFileNameCorrect = false;
                // 名称不能为空
                FileNameValidatedWrongTip = ResxIF.GetString("NameIsRequired");
            }
            else
            {
                if (value.Contains(@"\") || value.Contains(@"/"))
                {
                    IsFileNameCorrect = false;
                    // 名称不能有非法字符
                    FileNameValidatedWrongTip = ResxIF.GetString("NameHasIlligalCharacter");
                }
                else
                {
                    System.IO.FileInfo fi = null;
                    try
                    {
                        fi = new System.IO.FileInfo(value);
                    }
                    catch (ArgumentException) { }
                    catch (System.IO.PathTooLongException) { }
                    catch (NotSupportedException) { }
                    if (ReferenceEquals(fi, null))
                    {
                        // file name is not valid
                        IsFileNameCorrect         = false;
                        FileNameValidatedWrongTip = ResxIF.GetString("NameHasIlligalCharacter");
                    }
                    else
                    {
                        // file name is valid... May check for existence by calling fi.Exists.
                    }
                }
            }

            if (File.Exists(FilePath + @"\" + FileName + @".xaml"))
            {
                IsFileNameCorrect = false;
                // 指定的文件已存在
                FileNameValidatedWrongTip = ResxIF.GetString("TheFileAlreadyExists");
            }

            CreateFileCommand.RaiseCanExecuteChanged();
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> ImportExcelFile(IFormFile file)
        {
            if (file != null && file.Length >= 0)
            {
                using (var fileStreamMemory = new MemoryStream())
                {
                    await file.CopyToAsync(fileStreamMemory);

                    var id = Guid.NewGuid();

                    // get list word from excel file
                    var listWord = await this._officeFileService.GetListWordAsync(fileStreamMemory);

                    // save file to disk
                    PathRequest pathRequest = new PathRequest
                    {
                        ServerPath = this._env.ContentRootPath,
                        FielType   = FileTypeExtension.OfficeExtension.TypeName,
                        FileName   = id + System.IO.Path.GetExtension(file.FileName)
                    };
                    var path = this._fileUploadService.GetPath(pathRequest);
                    await this._fileUploadService.SaveFileOnDisk(fileStreamMemory, path);

                    // save file to db
                    CreateFileCommand createFileCommand = new CreateFileCommand
                    {
                        FileName = file.FileName,
                        FileType = (int)FileType.Office,
                        Id       = id,
                        Path     = path
                    };

                    await this._fileUploadService.SaveFileToDb(createFileCommand);

                    var reponse = new
                    {
                        id
                    };

                    return(Ok(reponse));
                }
            }

            return(BadRequest());
        }
Ejemplo n.º 11
0
        public static async Task <Tuple <BoxFile, string> > CreateSmallFileWithMetadata
            (string parentId          = "0", Dictionary <string, object> metadata = null,
            CommandScope commandScope = CommandScope.Test, CommandAccessLevel accessLevel = CommandAccessLevel.Admin)
        {
            var createFileCommand = new CreateFileCommand(GetUniqueName("file"), GetSmallFilePath(), parentId, commandScope, accessLevel);

            await ExecuteCommand(createFileCommand);

            var createMetadataTemplateCommand = new CreateMetadataTemplateCommand(GetUniqueName("template_key", false), ToStringMetadataFields(metadata), commandScope, accessLevel);

            await ExecuteCommand(createMetadataTemplateCommand);

            var applyMetadataCommand = new ApplyMetadataCommand(createMetadataTemplateCommand.TemplateKey, createFileCommand.FileId, metadata, commandScope, accessLevel);

            await ExecuteCommand(applyMetadataCommand);

            return(Tuple.Create(createFileCommand.File, createMetadataTemplateCommand.TemplateKey));
        }
Ejemplo n.º 12
0
        public void Visit(CreateFileCommand command)
        {
            if (!TryGetPrefixedPathTo(command.DirectoryId, out var pathToDirectory))
            {
                return;
            }

            var path = Path.Combine(pathToDirectory, command.Name);

            Directory.CreateDirectory(pathToDirectory);

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

            using var file = File.Create(path);
        }
Ejemplo n.º 13
0
        public static void Command()
        {
            IFileOperator fileOperator = new FileSystemOperator(Path.GetTempPath());
            //IFileOperator fileOperator = new FtpFileOperator(new Uri("ftp://tepuri.org"));

            var      invoker = new FileOperationInvoker();
            ICommand command;

            command = new CreateFileCommand(fileOperator, "HelloWorld.txt");
            invoker.Enqueue(command);

            command = new RenameFileCommand(fileOperator, "HelloWorld.txt", "GoodbyeWorld.txt");
            invoker.Enqueue(command);

            command = new DeleteFileCommand(fileOperator, "GoodbyeWorld.txt");
            invoker.Enqueue(command);

            invoker.InvokeAll();
        }
Ejemplo n.º 14
0
        public void should_add_note_not_throw_exception()
        {
            var newNote = new CreateFileCommand
            {
                Name = $"Test file {DateTime.Now.Ticks}",
                Author = "ApiTester",
                Content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            };

            bool exceptionThrown = false;
            try
            {
                service.Add(newNote);
            }
            catch
            {
                exceptionThrown = true;
            }

            Assert.IsFalse(exceptionThrown);
        }
Ejemplo n.º 15
0
        public CreateFileCommand imgUpload(IFormCollection form)
        {
            CreateFileCommand listaForm = new CreateFileCommand();

            foreach (var item in form)
            {
                if (item.Key == "NroDocReferencia")
                {
                    listaForm.NroDocReferencia = item.Value;
                }
                if (item.Key == "NroSubDocReferencia")
                {
                    listaForm.NroSubDocReferencia = item.Value;
                }
                if (item.Key == "CodTablaRef" || string.IsNullOrEmpty(item.Key))
                {
                    listaForm.CodTablaRef = item.Value;
                }
            }
            return(listaForm);
        }
        public async Task Handle_Valid_Inserts()
        {
            // arrange
            var request = new CreateFileCommand()
            {
                Name           = "Test",
                ParentFolderId = new Guid("97b7e004-be8e-424d-90c9-fa070996beb1")
            };

            var  mockRes      = new Guid("a87887ec-df44-4607-9e6f-28f361670f9b");
            File fileToAssert = null;

            var repositoryMock = new Mock <IRepository <File> >();
            var insertSetup    = repositoryMock.Setup(x => x.Insert(It.IsAny <File>(), CancellationToken.None));

            insertSetup.ReturnsAsync(mockRes);
            insertSetup.Callback((File file, CancellationToken _) => fileToAssert = file);

            var _mediatorMock = new Mock <IMediator>();

            _mediatorMock.Setup(x => x.Send(It.IsAny <GetFolderQuery>(), CancellationToken.None)).ReturnsAsync(new FolderDto()
            {
                HierarchyId = "/Test/"
            });


            var handler = new CreateFileCommandHandler(repositoryMock.Object, AutomapperFactory.Get(), _mediatorMock.Object);

            // act
            var result = await handler.Handle(request, CancellationToken.None);

            // assert
            repositoryMock.Verify(x => x.Insert(It.IsAny <File>(), CancellationToken.None), Times.Once);
            repositoryMock.VerifyNoOtherCalls();
            Assert.Equal(mockRes, result);
            Assert.Equal(fileToAssert.Name, request.Name);
            Assert.Equal(fileToAssert.ParentFolderId, request.ParentFolderId);
        }
Ejemplo n.º 17
0
        public void Visit(CreateFileCommand command)
        {
            Visit((ICommand)command);

            if (Root.TryFindNode(command.DirectoryId, out var node) &&
                node is Directory directory)
            {
                var existingFile = directory.Children.FirstOrDefault(c => c.Name == command.Name);
                if (existingFile == null)
                {
                    var file = _factory.CreateFile(command.Name, 0);
                    directory.Children.Add(file);
                    Message = $"ID={file.Id}";
                }
                else
                {
                    OnNodeAlreadyExists(command.Name, command.DirectoryId);
                }
            }
            else
            {
                OnDirectoryDoesNotExist(command.DirectoryId);
            }
        }
Ejemplo n.º 18
0
 public async Task <IActionResult> Create([FromBody] CreateFileCommand command, CancellationToken cancellationToken = default)
 {
     return(Ok(await Mediator.Send(command, cancellationToken)));
 }
Ejemplo n.º 19
0
        public async Task <HttpResponseMessage> Create(CreateFileCommand request)
        {
            var content = Utilities.GetRequestContent(request);

            return(await _client.PostAsync($"api/File/", content));
        }
Ejemplo n.º 20
0
 public void Add(CreateFileCommand command)
 {
     gateway.ExecuteAPICommand("files/create",
                               Method.POST, command, HttpStatusCode.Created, logonInfo.authToken);
 }
Ejemplo n.º 21
0
        public async Task <IActionResult> Create(CreateFileCommand command)
        {
            var result = await _mediator.Send(command);

            return(Ok(result));
        }
 public async Task SaveFileToDb(CreateFileCommand createFileCommand)
 {
     await this._mediator.Send(createFileCommand);
 }
Ejemplo n.º 23
0
 public async Task <ActionResult <int> > Create(CreateFileCommand command)
 {
     return(await Mediator.Send(command));
 }