Exemplo n.º 1
0
        protected override void FileAction(string fileName, string rawLocation)
        {
            string           location = rawLocation + "\\" + fileName;
            StringCollection paths    = Clipboard.GetFileDropList();

            if (paths.Contains(location))
            {
                string s = FileValidator.IsDirectory(fileName) ? "Directory " : "File ";
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! " + s + fileName + " is already cut.");
            }

            try
            {
                paths.Add(location);
                DataObject data = new DataObject();
                data.SetFileDropList(paths);
                data.SetData("Preferred DropEffect", DragDropEffects.Move);
                Clipboard.SetDataObject(data, true);

                RuntimeVariables.GetInstance().Success();
                Logger.GetInstance().LogCommand("Cut " + fileName);
            }
            catch (Exception)
            {
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! Something went wrong during cutting " + fileName + ".");
            }
        }
Exemplo n.º 2
0
        public void GetAllEntries_ProperConditions_ReturnsAllEntries(string filePath, int numOfLines)
        {
            var fileValidator    = new FileValidator(new ValidationData());
            var setService       = new SetService(fileValidator);
            var fileSource       = new EmbeddedSource(filePath, Assembly.GetExecutingAssembly());
            var wordsSetOperator = new WordsSetOperator(setService, fileSource);

            if (!wordsSetOperator.LoadSet())
            {
                throw new Exception("Set is null.");
            }

            int index = 0;

            foreach (Entry?entry in wordsSetOperator.GetEntries(false, true))
            {
                if (entry == null)
                {
                    break;
                }
                index++;
            }

            Assert.Equal(numOfLines, index);
        }
        public void IsValidTest()
        {
            var sut = new FileValidator("docx");

            Assert.IsTrue(sut.IsValid(fullDocxTestFilePath));
            Assert.IsFalse(sut.IsValid(fullJsonTestFilePath));
        }
        private void ClickButtonImportCardJSONMethod()
        {
            OpenFileDialog openfileDialog = new OpenFileDialog();

            if (openfileDialog.ShowDialog() == true)
            {
                string filePath = openfileDialog.FileName;
                if (FileValidator.ValidateCardFileType(filePath))
                {
                    string cardToImport;
                    cardToImport = File.ReadAllText(filePath);

                    Card resultCard = JsonConvert.DeserializeObject <Card>(cardToImport);
                    // test
                    CurrentCardId      = resultCard.Id;
                    NameText           = resultCard.Name;
                    SelectedTypeIdText = TypeList[resultCard.TypeId - 1]; // hack for å få index som begynner på null til å funke med id som starte på 1
                    ImageSourceText    = resultCard.ImageURL;
                    ManaCostText       = resultCard.ManaCost;
                    AttackText         = resultCard.AttackPower;
                    HpText             = resultCard.Hp;
                    PowerLevelText     = resultCard.PowerLevel;

                    RaisePropertyChanged("");
                }
                else
                {
                    MessageBox.Show("Invalid file type, only json and JSON");
                }
            }
        }
Exemplo n.º 5
0
        public MainWindow()
        {
            InitializeComponent();
            _app = (App)Application.Current;

            var fileValidator   = new FileValidator();
            var errorHandler    = new ErrorHandlerView();
            var librarySelector = new LibrarySelector(fileValidator, errorHandler, Dispatcher, _app.EventAggregator);

            _vm         = new MainVm(new LibraryLocationDialog(), librarySelector, errorHandler, fileValidator, _app.AppSettings, _app.EventAggregator);
            DataContext = _vm;
            Instance    = this;


            var positionData = _app.AppSettings.WindowPositions == null
                                   ? null
                                   : _app.AppSettings.WindowPositions
                               .FirstOrDefault(w => w.WindowId == "MainWindow");

            _windowPositionSettings = new WindowPositionSettings(positionData, 0.7);
            _windowPositionSettings.AttachWindow(this);
            if (positionData == null)
            {
                _windowPositionSettings.PositionData.WindowId = "MainWindow";
                if (_app.AppSettings.WindowPositions == null)
                {
                    _app.AppSettings.WindowPositions = new List <WindowPositionData>();
                }
                _app.AppSettings.WindowPositions.Add(_windowPositionSettings.PositionData);
            }

            _app.MainWindow = this;
        }
Exemplo n.º 6
0
        private bool CheckFile(string filePath)
        {
            bool          result    = true;
            FileValidator validator = new FileValidator();

            if (!validator.DoesFileExist(filePath))
            {
                UI.ConsoleOutPut(StringConstants.FILE_NOT_FOUND);
                result = false;
            }

            else if (!validator.CheckFileType(filePath, ".txt"))
            {
                UI.ConsoleOutPut(StringConstants.WRONG_FILE_TYPE);
                result = false;
            }

            else if (validator.IsFileEmpty(filePath))
            {
                UI.ConsoleOutPut(StringConstants.EMPTY_FILE);
                result = false;
            }

            return(result);
        }
Exemplo n.º 7
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            _executor        = new Executor();
            _env             = new ProcEnvironInfo();
            _defaultCmdPaths = new List <string>();
            _defaultCmdPaths.Add(_env.SysDir.System32);
            _defaultCmdPaths.Add(_env.SysDir.WinDir);

            _configFile = Path.Combine(_env.WorkingDir, CmdConfigFile);
            if (FileValidator.IsValid(_configFile))
            {
                _cmdTable = ObjSerializer.Load <DataTable>(Path.Combine(_env.WorkingDir, CmdConfigFile));
            }
            else
            {
                _cmdTable = new DataTable("CommandTable");
                _cmdTable.Columns.Add("Command");
                _cmdTable.Columns.Add("Parameters");

                object[] itemArray = new object[_cmdTable.Columns.Count];
                itemArray[0] = ExplorerCmd;
                itemArray[1] = ExplorerParam;
                DataRow dtRowTmp = _cmdTable.NewRow();
                dtRowTmp.ItemArray = itemArray;
                _cmdTable.Rows.Add(dtRowTmp);
            }

            FillSettingTable();
        }
        public void Validate_CorrectFilePath_ValidateCorrectly()
        {
            var filePath      = "..\\..\\..\\Resources\\data.csv";
            var fileValidator = new FileValidator();

            Assert.IsTrue(fileValidator.Validate(filePath));
        }
        public void WhenRequiredHeaderExistShouldNotThrowApplicationException()
        {
            //Arrange
            var columnList = new List <string> {
                Constants.ColTeamName, "Header2", Constants.ColFor, "Header4", Constants.ColAgainst, "Header6"
            };
            //var configReaderMock = new Mock<IConfigReader>();

            //configReaderMock.Setup(x => x.FileName).Returns(_filePath);
            //configReaderMock.Setup(x => x.Delimiter).Returns(",");
            var validator = new FileValidator();

            //Act
            try
            {
                validator.ValidateHeader(columnList);
            }
            //Assert
            catch (ApplicationException e)
            {
                Assert.Fail(e.Message);
            }

            Assert.IsTrue(true);
        }
Exemplo n.º 10
0
        // TODO Need to figure out how we rollback if cancellation is requested or prevent it?
        public async Task UploadFileMultipartDocument(Guid userId, string slug, Guid folderId, Stream requestBody, string?contentType, CancellationToken cancellationToken)
        {
            var userCanPerformAction = await _permissionsService.UserCanPerformActionAsync(userId, slug, AddFileRole, cancellationToken);

            if (userCanPerformAction is false)
            {
                _logger.LogError($"Error: CreateFileAsync - User:{0} does not have access to group:{1}", userId, slug);
                throw new SecurityException($"Error: User does not have access");
            }

            var file = await this.UploadMultipartContent(requestBody, contentType, cancellationToken);

            file.CreatedBy    = userId;
            file.ParentFolder = folderId;

            var validator        = new FileValidator();
            var validationResult = await validator.ValidateAsync(file, cancellationToken);

            if (validationResult.Errors.Count > 0)
            {
                throw new ValidationException(validationResult);
            }

            try
            {
                await CreateFileAsync(file, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error: CreateFileAsync - Error adding file to database");
                await _blobStorageProvider.DeleteFileAsync(file.BlobName);
            }
        }
Exemplo n.º 11
0
        public void WhenValidDataIsProvidedInCsvFileThenItShouldBeInLeagueResult()
        {
            //Arrange
            var configReaderMock = new Mock <IConfigReader>();

            configReaderMock.Setup(x => x.FileName).Returns(_filePath);
            configReaderMock.Setup(x => x.Delimiter).Returns(",");

            var fileValidator = new FileValidator();

            //Act
            var leagueResultParser = new LeagueResultParser(configReaderMock.Object, fileValidator);

            IList <string> headerColumnList = new List <string> {
                "Team", "P", "W", "L", "D", "F", "-", "A", "Pts"
            };
            IList <string> dataRows = new List <string>
            {
                "1. Arsenal,38,26,9,3,79,-,36,87",
                "2. Liverpool,38,24,8,6,67,-,30,80",
                "3. Manchester_U,38,24,5,9,87,-,45,77",
                "4. Newcastle,38,21,8,9,74,-,52,71"
            };
            var leagueResultList = leagueResultParser.ReadIntoLeagueResults(headerColumnList, dataRows);

            //Assert
            Assert.IsNotNull(leagueResultList);
            Assert.AreEqual(dataRows.Count, leagueResultList.Count);
        }
Exemplo n.º 12
0
        public static bool Hidden(string file)
        {
            if (file.Equals(""))
            {
                return(false);
            }

            string location = RuntimeVariables.GetInstance().GetWholeLocation() + "//" + file;

            if (FileValidator.IsDirectory(file))
            {
                if (!Directory.Exists(location))
                {
                    return(false);
                }

                DirectoryInfo info = new DirectoryInfo(location);
                return((info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden);
            }
            else
            {
                if (!File.Exists(location))
                {
                    return(false);
                }

                return(File.GetAttributes(location).HasFlag(FileAttributes.Hidden));
            }
        }
Exemplo n.º 13
0
        public static decimal GetSize(string file)
        {
            if (file.Equals(""))
            {
                return(0);
            }

            string location = RuntimeVariables.GetInstance().GetWholeLocation() + "//" + file;

            try
            {
                if (FileValidator.IsDirectory(location))
                {
                    return((decimal)(DirSize(new DirectoryInfo(@location))));
                }
                else
                {
                    return((decimal)(new System.IO.FileInfo(location).Length));
                }
            }
            catch (Exception)
            {
                return(0);
            }
        }
Exemplo n.º 14
0
        public static DateTime GetCreation(string file)
        {
            if (file.Equals(""))
            {
                return(DateTime.MinValue);
            }

            string address = RuntimeVariables.GetInstance().GetWholeLocation() + "//" + file;

            try
            {
                if (FileValidator.IsDirectory(file))
                {
                    return(System.IO.Directory.GetCreationTime(@address));
                }
                else
                {
                    return(System.IO.File.GetCreationTime(@address));
                }
            }
            catch (Exception)
            {
                return(DateTime.MinValue);
            }
        }
Exemplo n.º 15
0
        public static bool ReadOnly(string file)
        {
            if (file.Equals(""))
            {
                return(false);
            }

            string location = RuntimeVariables.GetInstance().GetWholeLocation() + "//" + file;

            if (FileValidator.IsDirectory(file))
            {
                if (!Directory.Exists(location))
                {
                    return(false);
                }

                DirectoryInfo info = new DirectoryInfo(location);
                return((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
            }
            else
            {
                if (!File.Exists(location))
                {
                    return(false);
                }

                FileInfo info = new FileInfo(location);
                return(info.IsReadOnly);
            }
        }
Exemplo n.º 16
0
        public FileValidationError ValidateFile()
        {
            FileValidationError error = FileValidator.Validate(this.FileName,
                                                               SupportedWordFileExtension);

            return(error);
        }
Exemplo n.º 17
0
        protected override void FileAction(string fileName, string rawLocation)
        {
            string           location = rawLocation + "\\" + fileName;
            StringCollection paths    = Clipboard.GetFileDropList();

            if (paths.Contains(location))
            {
                string s = FileValidator.IsDirectory(fileName) ? "Directory " : "File ";
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! " + s + fileName + " is already copied.");
            }

            try
            {
                paths.Add(location);
                RuntimeVariables.GetInstance().Success();
                Logger.GetInstance().LogCommand("Copy " + fileName);
            }
            catch (Exception)
            {
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! Something went wrong during copying " + fileName + ".");
            }

            Clipboard.SetFileDropList(paths);
        }
Exemplo n.º 18
0
        public Tuple <DbResult, List <PersonInfo> > ReadData(Stream stream, string fileName, double allowedSizeKB, params string[] fileTypes)
        {
            bool   success = false;
            string message = "";
            var    data    = new List <PersonInfo>();

            var result1 = FileValidator.ValidatFile(stream, fileName, allowedSizeKB, fileTypes);

            if (!result1.IsFileValid)
            {
                message = result1.Message;
            }
            else
            {
                var dt = stream.ToDataTable(true);
                data = ReadTable(dt);

                if (data != null && data.Any())
                {
                    success = true;
                }
                else
                {
                    message = "Could not read data";
                }
            }

            var result = new DbResult
            {
                IsDbSuccess = success,
                DbMessage   = success ? "Data read successfully" : message
            };

            return(new Tuple <DbResult, List <PersonInfo> >(result, data));
        }
Exemplo n.º 19
0
        public UserValidator(IOptions <FileOptions> options)
        {
            _fileOptions = options.Value;

            RuleFor(user => user.Name)
            .NotNull()
            .Length(3, 50);

            RuleFor(user => user.Surnames)
            .NotNull()
            .Length(3, 50);

            RuleFor(user => user.Bithdate)
            .NotNull()
            .LessThan(DateTime.Now)
            .GreaterThan(new DateTime(1900, 1, 1));

            RuleFor(user => user.Img)
            .Must(img => FileValidator.ValidFileType(img, _fileOptions.ValidTypes))
            .WithMessage($"must be {string.Join(", ", _fileOptions.ValidTypes)}");

            RuleFor(user => user.Img)
            .Must(img => FileValidator.LessThan(img, _fileOptions.MaxKb))
            .WithMessage($"max size {_fileOptions.MaxKb}kb");
        }
        public void TestPackageValidatorTest()
        {
            string currentDirectory = Directory.GetCurrentDirectory();
            string fileName         = "testFile";
            string filePath         = currentDirectory + "\\" + fileName;

            IFileValidator fileValidator = new FileValidator();

            try
            {
                fileValidator.ValidateTestPackage(filePath);
                Assert.Fail();
            }
            catch (FileNotFoundException e) { }

            File.Create(filePath).Close();
            try
            {
                fileValidator.ValidateTestPackage(filePath);
                Assert.Fail();
            }
            catch (InvalidFileException e) { }

            File.Delete(filePath);

            fileName = "testFile.zip";
            filePath = currentDirectory + "\\" + fileName;
            File.Create(filePath).Close();
            fileValidator.ValidateTestPackage(filePath);
            File.Delete(filePath);
        }
Exemplo n.º 21
0
        public void Constructor_DoesNotThrow_OnEmptyExtensions()
        {
            var opts = new FileValidationOptions();
            var val  = new FileValidator(Options.Create(opts));

            Assert.NotNull(val.SupportedExtensions);
            Assert.Empty(val.SupportedExtensions);
        }
Exemplo n.º 22
0
        protected override void FileAction(string fileName, string rawLocation)
        {
            string directoryName = destination.ToString();

            if (!FileValidator.IsNameCorrect(directoryName))
            {
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! " + directoryName + " contains not allowed characters.");
            }

            string newFileName = newName.ToString();

            if (!FileValidator.IsNameCorrect(newFileName))
            {
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! " + newFileName + " contains not allowed characters.");
            }
            if (FileValidator.IsDirectory(newFileName))
            {
                string extension = FileInnerVariable.GetExtension(fileName);
                newFileName += "." + extension;
            }

            string oldLocation = rawLocation + "//" + fileName;
            string newLocation = rawLocation + "//" + directoryName + "//" + newFileName;


            if (!Directory.Exists(rawLocation + "//" + directoryName))
            {
                Directory.CreateDirectory(rawLocation + "//" + directoryName);
            }


            try
            {
                if (forced && File.Exists(newLocation))
                {
                    File.Delete(@newLocation);
                }
                File.Move(@oldLocation, @newLocation);

                RuntimeVariables.GetInstance().Success();
                Logger.GetInstance().LogCommand("Move " + fileName + " to " + directoryName + " as " + newFileName);
            }
            catch (Exception ex)
            {
                RuntimeVariables.GetInstance().Failure();

                if (ex is IOException || ex is UnauthorizedAccessException)
                {
                    throw new CommandException("Action ignored! Access denied during moving " + fileName + " to " + directoryName + " as " + newFileName + ".");
                }
                else
                {
                    throw new CommandException("Action ignored! Something went wrong during moving " + fileName + " to " + directoryName + " as " + newFileName + ".");
                }
            }
        }
Exemplo n.º 23
0
        protected override void DirectoryAction(string movingDirectoryName, string rawLocation)
        {
            string directoryName = destination.ToString();

            if (directoryName.Equals(movingDirectoryName))
            {
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! Directory " + directoryName + " cannot be copied to itself.");
            }


            if (!FileValidator.IsNameCorrect(directoryName))
            {
                RuntimeVariables.GetInstance().Failure();
                throw new CommandException("Action ignored! " + directoryName + " contains not allowed characters.");
            }


            string oldLocation = rawLocation + "//" + movingDirectoryName;
            string newLocation = rawLocation + "//" + directoryName + "//" + movingDirectoryName;


            if (!Directory.Exists(rawLocation + "//" + directoryName))
            {
                Directory.CreateDirectory(rawLocation + "//" + directoryName);
            }

            if (!Directory.Exists(rawLocation + "//" + directoryName + "//" + movingDirectoryName))
            {
                Directory.CreateDirectory(rawLocation + "//" + directoryName + "//" + movingDirectoryName);
            }


            try
            {
                if (forced && Directory.Exists(newLocation))
                {
                    Directory.Delete(@newLocation, true);
                }
                DirectoryCopy(@oldLocation, @newLocation);
                RuntimeVariables.GetInstance().Success();
                Logger.GetInstance().LogCommand("Copy " + movingDirectoryName + " to " + directoryName);
            }
            catch (Exception ex)
            {
                RuntimeVariables.GetInstance().Failure();

                if (ex is IOException || ex is UnauthorizedAccessException)
                {
                    throw new CommandException("Action ignored! Access denied during coping " + movingDirectoryName + " to " + directoryName + ".");
                }
                else
                {
                    throw new CommandException("Action ignored! Something went wrong during coping " + movingDirectoryName + " to " + directoryName + ".");
                }
            }
        }
Exemplo n.º 24
0
        public TextEditor(FileInfo file, int linesPerPage)
        {
            LinesCountValidator.Validate(linesPerPage);
            FileValidator.Validate(file);

            _file         = file;
            _linesPerPage = linesPerPage;
            _textBlock    = new TextBlock(linesPerPage);
        }
Exemplo n.º 25
0
        public void ValidateExtensionFileNameIsNullReturnsFalseTest()
        {
            // arrange
            // act
            var actual = new FileValidator().ValidateExtension(null);

            // assert
            Assert.False(actual);
        }
Exemplo n.º 26
0
        public FileValidationError ValidateFile()
        {
            FileValidationError error = FileValidator.Validate(this.FileName,
                                                               new List <string>()
            {
                ".csv"
            });

            return(error);
        }
Exemplo n.º 27
0
        public void IsValidFile_WithValidFile_ShouldReturnTrue()
        {
            var validFileFactory = Substitute.For<IValidFileFactory>();
            validFileFactory.Get(".csproj").Returns(new KeyValuePair<string, bool>(".csproj", true));

            var fileValidator = new FileValidator(validFileFactory);
            var validFile = fileValidator.IsValidFile(".csproj");

            Assert.IsTrue(validFile);
        }
Exemplo n.º 28
0
        public FileValidatorTests()
        {
            var opts = new FileValidationOptions
            {
                Extensions = new[] { "txt", "jpg" },
                MaxSize    = 100
            };

            _validator = new FileValidator(Options.Create(opts));
        }
Exemplo n.º 29
0
        public void IsValidFile_WithInValidFile_ShouldReturnFalse()
        {
            var validFileFactory = Substitute.For<IValidFileFactory>();
            validFileFactory.Get(".exe").Returns(new KeyValuePair<string, bool>(".exe", false));

            var fileValidator = new FileValidator(validFileFactory);
            var validFile = fileValidator.IsValidFile("exe");

            Assert.IsFalse(validFile);
        }
Exemplo n.º 30
0
        public static bool Empty(string file)
        {
            // need to thing about thie method

            if (file.Equals(""))
            {
                return(true);
            }

            string location = RuntimeVariables.GetInstance().GetWholeLocation() + "//" + file;

            if (FileValidator.IsDirectory(file))
            {
                if (Directory.Exists(@location))
                {
                    try
                    {
                        return(Directory.EnumerateFileSystemEntries(location).Any() ? false : true);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                if (File.Exists(@location))
                {
                    try
                    {
                        if (new FileInfo(location).Length == 0)
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(true);
                }
            }
        }
Exemplo n.º 31
0
        public void GetPermittedExtensionsTest()
        {
            // arrange
            var expected = ".jpeg, .jpg, .png";

            // act
            var actual = new FileValidator().GetPermittedExtensions;

            // arrange
            StringAssert.AreEqualIgnoringCase(expected, actual);
        }
Exemplo n.º 32
0
        public void ValidateExtensionJpgReturnsTrueTestTest()
        {
            // arrange
            var fileName = "test.jpg";

            // act
            var actual = new FileValidator().ValidateExtension(fileName);

            // assert
            Assert.True(actual);
        }
	public void SetFilesValidator(FileValidator validateFileFunction)
	{
		this.validateFileFunction = validateFileFunction;
	}