예제 #1
0
파일: Tests.cs 프로젝트: kmhtoo/Repository
        public void LockingTest()
        {
            Task.Factory.StartNew(() =>
            {
                using (var repo = new FileSystemRepository<TestClass, String, String>("Test", x => Tuple.Create(x.ID, x.StringValue)))
                {
                    var obj = new TestClass("key", "value");
                    repo.Insert(obj);
                    repo.SaveChanges();

                    repo.Remove(obj);
                    repo.SaveChanges();
                }
            });

            Task.Factory.StartNew(() =>
            {
                using (var repo = new FileSystemRepository<TestClass, String, String>("Test", x => Tuple.Create(x.ID, x.StringValue)))
                {
                    var obj = new TestClass("key", "value");
                    repo.Insert(obj);
                    repo.SaveChanges();

                    repo.Remove(obj);
                    repo.SaveChanges();
                }
            });
        }
예제 #2
0
        public ActionResult Index()
        {
            string             userId      = User.Identity.GetUserId();
            ApplicationUser    currentUser = UserRepository.GetUserById(userId);
            HomeIndexViewModel model       = HomeIndexViewModel.CreateNewViewModel(currentUser, DbContext, 5, 5, 5);

            // Display benchmark data
            if (User.IsInRole(UserRolesEnum.Admin.ToString()))
            {
                FileSystemRepository fileSystemRepository = new FileSystemRepository(Server, FileSystemRepository.BenchmarkFolder);

                //string fileName = $"{Server.MachineName}_Benchmark.json";
                string fileName = CONSTANTS.GetDefaultFileNameForBenchmark(Server);

                (List <ActionResultBenchmark> result, bool hasLoaded, string message) = fileSystemRepository
                                                                                        .LoadJsonFile <List <ActionResultBenchmark> >(fileName);

                if (hasLoaded)
                {
                    ViewBag.BenchmarkResults = result.OrderByDescending(p => p.Created).ToList();
                }

                ViewBag.BenchmarkMessage  = message;
                ViewBag.BenchmarkFileName = fileName;
            }

            return(View(model));
        }
 public DataFileHandler(FileSystemRepository inputFileSysRepo, FileSystemRepository appDataSysRepo, FileSystemRepository attackFileSysRepo, FileSystemRepository languageFileSysRepo)
 {
     _appDataSysRepo      = appDataSysRepo;
     _inputFileSysRepo    = inputFileSysRepo;
     _attackFileSysRepo   = attackFileSysRepo;
     _languageFileSysRepo = languageFileSysRepo;
 }
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseMetadataProvider" /> class.
        /// </summary>
        /// <param name="logManager">The log manager.</param>
        /// <param name="configurationManager">The configuration manager.</param>
        /// <param name="mediaEncoder">The media encoder.</param>
        public AudioImageProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder)
            : base(logManager, configurationManager)
        {
            _mediaEncoder = mediaEncoder;

            ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.AudioImagesDataPath);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageManager" /> class.
        /// </summary>
        /// <param name="apiClient">The API client.</param>
        /// <param name="paths">The paths.</param>
        /// <param name="config"></param>
        public ImageManager(Func<IApiClient> apiClient, IApplicationPaths paths, ITheaterConfigurationManager config)
        {
            _apiClient = apiClient;
            _config = config;

            _remoteImageCache = new FileSystemRepository(Path.Combine(paths.CachePath, "remote-images"));
        }
 public void SetUp()
 {
     _pathResolver = MockRepository.GenerateMock <ITemplatePathResolver>();
     _pathResolver.Stub(arg => arg.Absolute("Template")).Return(@"C:\Template.cshtml");
     _fileSystem = MockRepository.GenerateMock <IFileSystem>();
     _fileSystem.Stub(arg => arg.OpenFile(@"C:\Template.cshtml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)).Return(new MemoryStream(Encoding.ASCII.GetBytes("Hello, world.")));
     _compiler = MockRepository.GenerateMock <ITemplateCompiler>();
     _compiler
     .Stub(arg => arg.Compile <ITemplate <string> >(
               Arg <string> .Is.Anything,
               Arg <string> .Is.Anything,
               Arg <ITemplateCodeBuilder> .Is.Anything,
               Arg <CodeDomProvider> .Is.Anything,
               Arg <Action <CodeTypeDeclaration> > .Is.Anything,
               Arg <IEnumerable <string> > .Is.Anything))
     .Return(typeof(ITemplate <string>));
     _classNameBuilder = MockRepository.GenerateMock <ITemplateClassNameBuilder>();
     _classNameBuilder.Stub(arg => arg.BuildFromRandomGuid()).Return("ClassName");
     _codeBuilder            = MockRepository.GenerateMock <ITemplateCodeBuilder>();
     _codeDomProvider        = MockRepository.GenerateMock <CodeDomProvider>();
     _codeDomProviderFactory = MockRepository.GenerateMock <ICodeDomProviderFactory>();
     _codeDomProviderFactory.Stub(arg => arg.CreateFromFileExtension(Arg <string> .Is.Anything)).Return(_codeDomProvider);
     _template = MockRepository.GenerateMock <ITemplate <string> >();
     _compiledTemplateFactory = MockRepository.GenerateMock <ICompiledTemplateFactory>();
     _compiledTemplateFactory.Stub(arg => arg.CreateFromType <string>(Arg <Type> .Is.Anything)).Return(_template);
     _fileSystemRepositoryConfiguration = MockRepository.GenerateMock <IFileSystemRepositoryConfiguration>();
     _repository = new FileSystemRepository(_pathResolver, _fileSystem, _compiler, _classNameBuilder, _codeBuilder, _codeDomProviderFactory, _compiledTemplateFactory, _fileSystemRepositoryConfiguration);
     _repository.Get <ITemplate <string>, string>("Template", "Model", _namespaces);
 }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        /// <param name="zipClient">The zip client.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <param name="protobufSerializer">The protobuf serializer.</param>
        /// <param name="logger">The logger.</param>
        /// <exception cref="System.ArgumentNullException">zipClient</exception>
        public FFMpegManager(Kernel kernel, IZipClient zipClient, IJsonSerializer jsonSerializer, IProtobufSerializer protobufSerializer, ILogManager logManager, IServerApplicationPaths appPaths)
        {
            if (kernel == null)
            {
                throw new ArgumentNullException("kernel");
            }
            if (zipClient == null)
            {
                throw new ArgumentNullException("zipClient");
            }
            if (jsonSerializer == null)
            {
                throw new ArgumentNullException("jsonSerializer");
            }
            if (protobufSerializer == null)
            {
                throw new ArgumentNullException("protobufSerializer");
            }

            _kernel             = kernel;
            _zipClient          = zipClient;
            _jsonSerializer     = jsonSerializer;
            _protobufSerializer = protobufSerializer;
            _appPaths           = appPaths;
            _logger             = logManager.GetLogger("FFMpegManager");

            // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
            SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);

            VideoImageCache = new FileSystemRepository(VideoImagesDataPath);
            AudioImageCache = new FileSystemRepository(AudioImagesDataPath);
            SubtitleCache   = new FileSystemRepository(SubtitleCachePath);

            Task.Run(() => VersionedDirectoryPath = GetVersionedDirectoryPath());
        }
        protected override void ProcessRecord()
        {
            //create repository
            var request = new CreateRepositoryRequest(this.Name)
            {
#if ESV1
                Repository = new FileSystemRepository
                {
                    Settings = this.GetSettings()
                }
#else
                Repository = new FileSystemRepository(this.GetSettings())
#endif
            };

            var response = this.Client.CreateRepository(request);

            CheckResponse(response);

            //get repository
            var response1 = this.Client.GetRepository(new GetRepositoryRequest(this.Name));

            CheckResponse(response1);

            foreach (var repo in response1.Repositories.Keys)
            {
                WriteObject(response1.GetRepository(repo));
            }
        }
    }
예제 #9
0
 public void Standard()
 {
     var implicitKeyRepo = new FileSystemRepository<TestClass>(x => x.ID, new FileSystemOptions<TestClass> { FolderPath = "Tests/ImplicitKeyRepositories" });
     var typedRepo = new FileSystemRepository<TestClass, String>(x => x.ID, new FileSystemOptions<TestClass> { FolderPath = "Tests/TypedKeyRepositories" });
     var explicitKeyRepo = new ExplicitKeyFileSystemRepository<TestClass>(new FileSystemOptions<TestClass> { FolderPath = "Tests/ExplicitKeyRepositories" });
     StandardTests.All(implicitKeyRepo);
 }
예제 #10
0
        public async Task RetrieveFile()
        {
            // Arrange
            var fileSystemRepository = new FileSystemRepository(WebHostEnvironment.Object, FolderOptions);

            // Create test folder and test file
            Directory.CreateDirectory(FolderPath);
            using (var stream = File.CreateText(FilePathWithExtension))
            {
                stream.Write(FileData);
                stream.Flush();
            }

            // Act
            byte[] result = await fileSystemRepository.RetrieveFile(RandomFileName, RandomFileExtension);

            // Cleanup test folder and test file
            File.Delete(FilePathWithExtension);
            Directory.Delete(FolderPath);
            Directory.Delete(ContentRootFolderName);

            // Assert
            Assert.IsTrue(result.Length > 0);
            string returnedData = Encoding.UTF8.GetString(result);

            Assert.AreEqual(FileData, returnedData);
        }
예제 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageSaver"/> class.
 /// </summary>
 /// <param name="config">The config.</param>
 /// <param name="directoryWatchers">The directory watchers.</param>
 public ImageSaver(IServerConfigurationManager config, IDirectoryWatchers directoryWatchers, IFileSystem fileSystem)
 {
     _config            = config;
     _directoryWatchers = directoryWatchers;
     _fileSystem        = fileSystem;
     _remoteImageCache  = new FileSystemRepository(config.ApplicationPaths.DownloadedImagesDataPath);
 }
예제 #12
0
        public void TestMethod1()
        {
            var data = new EmployeeData
            {
                Id    = 1,
                Name  = "First Employee",
                Email = "*****@*****.**",
            };

            var           ms          = new MemoryStream();
            var           repository  = new FileSystemRepository("sample.xml");
            PrivateObject privateRepo = new PrivateObject(repository);

            privateRepo.Invoke("SaveToStream", new Type[] { typeof(Stream), typeof(EmployeeData) },
                               new object[] { ms, data });

            string result = ms.ToString();

            ms.Position = 0;
            EmployeeData loaded = (EmployeeData)privateRepo.Invoke("LoadFromStream", new Type[] { typeof(Stream) },
                                                                   new object[] { ms });


            Assert.AreEqual(data.Id, loaded.Id);
            Assert.AreEqual(data.Name, loaded.Name);
            Assert.AreEqual(data.Email, loaded.Email);
        }
예제 #13
0
        public async Task DeleteFile()
        {
            // Arrange
            var fileSystemRepository = new FileSystemRepository(WebHostEnvironment.Object, FolderOptions);

            // Create test folder and test file
            Directory.CreateDirectory(FolderPath);
            using (var stream = File.CreateText(FilePathWithExtension))
            {
                stream.Write(FileData);
                stream.Flush();
            }

            // Act
            fileSystemRepository.DeleteFile(RandomFileName, RandomFileExtension);

            // Assert
            try
            {
                await fileSystemRepository.RetrieveFile(RandomFileName, RandomFileExtension);
            }
            catch (FileNotFoundException ex)
            {
                // Expecting exception
                // Cleanup
                Directory.Delete(FolderPath);
                Directory.Delete(ContentRootFolderName);
                return;
            }

            Assert.Fail("Expected to throw Exception: FileNotFoundException");
        }
예제 #14
0
파일: Tests.cs 프로젝트: kmhtoo/Repository
        public void Standard()
        {
            var implicitKeyRepo = new FileSystemRepository<TestClass>("Test", x => x.ID, new FileSystemOptions<TestClass> { FolderPath = "Tests/ImplicitKeyRepositories" });
            var gzipRepo = new FileSystemRepository<TestClass>("Test", x => x.ID, new FileSystemOptions<TestClass> { FolderPath = "Tests/ImplicitKeyRepositories", StreamGenerator = new GZipStreamGenerator(), FileExtension = ".txt.gz" });
            var explicitKeyRepo = new ExplicitKeyFileSystemRepository<TestClass>("Test", new FileSystemOptions<TestClass> { FolderPath = "Tests/ExplicitKeyRepositories" });

            StandardTests.All(implicitKeyRepo, null, explicitKeyRepo);
            StandardTests.All(gzipRepo);
        }
예제 #15
0
        public Benchmark([Optional] string benchmarkName)
        {
            HttpServerUtilityWrapper = new HttpServerUtilityWrapper(HttpContext.Current.Server);
            FileSystemRepository     = new FileSystemRepository(HttpServerUtilityWrapper, BenchmarkFolder);
            BenchmarkName            = benchmarkName ?? $"{HttpServerUtilityWrapper.MachineName}_Benchmark";

            (List <ActionResultBenchmark> result, bool hasLoaded, _) = FileSystemRepository.LoadJsonFile <List <ActionResultBenchmark> >(BenchmarkName);
            Benchmarks = hasLoaded ? result : new List <ActionResultBenchmark>();
        }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageManager" /> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="appPaths">The app paths.</param>
        /// <param name="itemRepo">The item repo.</param>
        public ImageManager(ILogger logger, IServerApplicationPaths appPaths, IItemRepository itemRepo)
        {
            _logger   = logger;
            _itemRepo = itemRepo;

            ImageSizeCache     = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "image-sizes"));
            ResizedImageCache  = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "resized-images"));
            CroppedImageCache  = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "cropped-images"));
            EnhancedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "enhanced-images"));
        }
예제 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
        /// </summary>
        /// <param name="appPaths">The app paths.</param>
        /// <param name="encoder">The encoder.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="itemRepo">The item repo.</param>
        /// <exception cref="System.ArgumentNullException">zipClient</exception>
        public FFMpegManager(IServerApplicationPaths appPaths, IMediaEncoder encoder, ILogger logger, IItemRepository itemRepo)
        {
            _appPaths = appPaths;
            _encoder  = encoder;
            _logger   = logger;
            _itemRepo = itemRepo;

            VideoImageCache = new FileSystemRepository(VideoImagesDataPath);
            SubtitleCache   = new FileSystemRepository(SubtitleCachePath);
        }
예제 #18
0
        public async Task DeleteFileSystemItem(Guid itemKey)
        {
            var deleted = await FileSystemRepository.DeleteFileSystemItem(itemKey);

            if (Selected == deleted.Key)
            {
                await SetSelected(InputStreamItem.Key);
            }
            SelectedChanged?.Invoke();
        }
예제 #19
0
        public void DeleteFile_folder_not_exist()
        {
            // Arrange
            var fileSystemRepository = new FileSystemRepository(WebHostEnvironment.Object, FolderOptions);

            // Act
            fileSystemRepository.DeleteFile(RandomFileName, RandomFileExtension);

            // Assert
        }
예제 #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProviderManager" /> class.
        /// </summary>
        /// <param name="httpClient">The HTTP client.</param>
        /// <param name="configurationManager">The configuration manager.</param>
        /// <param name="directoryWatchers">The directory watchers.</param>
        /// <param name="logManager">The log manager.</param>
        public ProviderManager(IHttpClient httpClient, IServerConfigurationManager configurationManager, IDirectoryWatchers directoryWatchers, ILogManager logManager)
        {
            _logger              = logManager.GetLogger("ProviderManager");
            _httpClient          = httpClient;
            ConfigurationManager = configurationManager;
            _directoryWatchers   = directoryWatchers;
            _remoteImageCache    = new FileSystemRepository(configurationManager.ApplicationPaths.DownloadedImagesDataPath);

            configurationManager.ConfigurationUpdated += configurationManager_ConfigurationUpdated;
        }
예제 #21
0
        private static async Task <List <string> > LangUpToDateAudit(bool persist = false)
        {
            const string  translationExportUrl = "https://api.assistantapps.com/TranslationExport/{0}/{1}";
            const string  appGuid       = "dfe0dbc7-8df4-47fb-a5a5-49af1937c4e2";
            List <string> consoleOutput = new List <string>();

            BaseExternalApiRepository apiRepo = new BaseExternalApiRepository();
            ResultWithValue <List <LanguageViewModel> > langResult = await apiRepo.Get <List <LanguageViewModel> >("https://api.assistantapps.com/Language");

            if (langResult.HasFailed)
            {
                consoleOutput.Add("Could not get Server Languages");
                return(consoleOutput);
            }

            FileSystemRepository appLangRepo = new FileSystemRepository(AppLangDirectory);

            foreach (LanguageType langType in AvailableLangs)
            {
                LanguageDetail language = LanguageHelper.GetLanguageDetail(langType);

                string languageFile = $"language.{language.LanguageAppFolder}.json";
                Dictionary <string, dynamic> langJson = appLangRepo.LoadJsonDict <dynamic>(languageFile);
                langJson.TryGetValue("hashCode", out dynamic localHashCode);

                LanguageViewModel langViewModel = langResult.Value.FirstOrDefault(l => l.LanguageCode.Equals(language.LanguageAppFolder));
                if (langViewModel == null)
                {
                    continue;
                }

                ResultWithValue <Dictionary <string, string> > languageContent = await apiRepo.Get <Dictionary <string, string> >(translationExportUrl.Replace("{0}", appGuid).Replace("{1}", langViewModel.Guid.ToString()));

                if (languageContent.HasFailed)
                {
                    continue;
                }
                languageContent.Value.TryGetValue("hashCode", out string serverHashCode);

                bool hashCodeMatches = serverHashCode != null && localHashCode != null && localHashCode.Equals(serverHashCode);
                if (hashCodeMatches)
                {
                    continue;
                }

                if (persist)
                {
                    appLangRepo.WriteBackToJsonFile(languageContent.Value, languageFile);
                }

                consoleOutput.Add($"{languageFile} Language Hashcode Audit has failed");
            }

            return(consoleOutput);
        }
예제 #22
0
        public void DeleteDirectory(string path)
        {
            var dirName       = FileSystemRepository.GetFileName(path);
            var parentDirPath = FileSystemRepository.GetParentDirectory(path);

            directoriesTableEvent
            .Where(d => d.Path == parentDirPath && d.Name == dirName)
            .Delete()
            .SetTimestamp(timestampProvider.UpdateTimestamp())
            .Execute();
        }
예제 #23
0
        public bool IsFileExists(string path)
        {
            var parentDirPath = FileSystemRepository.GetParentDirectory(path);
            var fileName      = FileSystemRepository.GetFileName(path);
            var file          = filesTableEvent
                                .Where(f => f.Path == parentDirPath && f.Name == fileName)
                                .Execute();
            var result = file.Any();

            return(result);
        }
예제 #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageManager" /> class.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        /// <param name="protobufSerializer">The protobuf serializer.</param>
        /// <param name="logger">The logger.</param>
        public ImageManager(Kernel kernel, IProtobufSerializer protobufSerializer, ILogger logger, IServerApplicationPaths appPaths)
        {
            _protobufSerializer = protobufSerializer;
            _logger             = logger;
            _kernel             = kernel;

            ImageSizeCache     = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "image-sizes"));
            ResizedImageCache  = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "resized-images"));
            CroppedImageCache  = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "cropped-images"));
            EnhancedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "enhanced-images"));
        }
        private async Task ExecuteCommand(string command)
        {
            if (command == "#test-color")
            {
                OutputText = GetTestColor();
                return;
            }

            await SaveTextEditorContent();
            await AddCommandToHistory(command);

            var sourceKey = GetSourceKey();
            var config    = await GetEnvironmentalConfig();

            var fileSystem = await FileSystemProviderConnector.GetProvider();  // TODO set current folder, set encoding

            var engine = new ServiceEngine(
                configureContext: context =>
            {
                context.IsAtty   = config.IsAtty;
                context.TimeZone = config.TimeZone;
                context.SetEnvironmentVariables(config.EnvironmentVariables);
            },
                createCustomProvider: mem =>
            {
                mem.Attach(w => new MemoryAnsiTextWriter(w));
                return(new ApplicationServiceProvider(
                           fileSystemProviderFactory: () => fileSystem,
                           virtualConsoleProviderFactory: () => new VirtualConsoleProvider(mem.ConsoleInput, mem.ConsoleOutput, mem.ConsoleError)));
            });

            ServiceSession session;

            if (sourceKey == FileSystemRepository.InputStream.Key)
            {
                session = engine.CreateSession("-f /dev/stdin", await FileSystemRepository.GetFileContent(sourceKey));
            }
            else
            {
                session = engine.CreateSession($"-f {(await FileSystemRepository.GetItem(sourceKey)).Path}");
            }

            var response = session.ExecuteCommand(command);

            OutputText = response.OutputText;
            ErrorText  = response.ErrorText;
            ResultCode = response.Status;

            // TODO - save possible changes in FS
            //if (fileSystem.HasChanges())
            //    await FileSystemProviderConnector.ApplyChanges();
        }
예제 #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AudioImagesTask" /> class.
        /// </summary>
        /// <param name="libraryManager">The library manager.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="mediaEncoder">The media encoder.</param>
        /// <param name="isoManager">The iso manager.</param>
        public VideoImagesTask(ILibraryManager libraryManager, ILogManager logManager, IMediaEncoder mediaEncoder, IIsoManager isoManager, IItemRepository itemRepo)
        {
            _libraryManager = libraryManager;
            _mediaEncoder   = mediaEncoder;
            _isoManager     = isoManager;
            _itemRepo       = itemRepo;
            _logger         = logManager.GetLogger(GetType().Name);

            ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.VideoImagesDataPath);

            libraryManager.ItemAdded   += libraryManager_ItemAdded;
            libraryManager.ItemUpdated += libraryManager_ItemAdded;
        }
 public GameFilesReader(FileSystemRepository outputFileSysRepo,
                        FileSystemRepository shapeSetsFileSysRepo, FileSystemRepository legacyShapeSetsFileSysRepo,
                        FileSystemRepository survivalCraftingFileSysRepo, FileSystemRepository characterFileSysRepo,
                        FileSystemRepository legacyLanguageFileSysRepo, FileSystemRepository survivalLanguageFileSysRepo)
 {
     _outputFileSysRepo           = outputFileSysRepo;
     _legacyShapeSetsFileSysRepo  = legacyShapeSetsFileSysRepo;
     _shapeSetsFileSysRepo        = shapeSetsFileSysRepo;
     _survivalCraftingFileSysRepo = survivalCraftingFileSysRepo;
     _characterFileSysRepo        = characterFileSysRepo;
     _legacyLanguageFileSysRepo   = legacyLanguageFileSysRepo;
     _survivalLanguageFileSysRepo = survivalLanguageFileSysRepo;
 }
예제 #28
0
        public void Get()
        {
            // Arrange
            IRepository<Employee> repository = new FileSystemRepository(new TestFileHelper());
            EmployeeController controller = new EmployeeController(repository);

            // Act
            IEnumerable<Employee> result = controller.GetAllEmployees();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count());
        }
예제 #29
0
        public void GetById()
        {
            // Arrange
            IRepository<Employee> repository = new FileSystemRepository(new TestFileHelper());
            EmployeeController controller = new EmployeeController(repository);

            //// Act
            Employee result = controller.GetEmployeeById(2);

            //// Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.id);
        }
예제 #30
0
        /// <summary>
        /// Fetches the bd info.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="inputPath">The input path.</param>
        /// <param name="bdInfoCache">The bd info cache.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        private void FetchBdInfo(BaseItem item, string inputPath, FileSystemRepository bdInfoCache, CancellationToken cancellationToken)
        {
            var video = (Video)item;

            // Get the path to the cache file
            var cacheName = item.Id + "_" + item.DateModified.Ticks;

            var cacheFile = bdInfoCache.GetResourcePath(cacheName, ".pb");

            BlurayDiscInfo result;

            try
            {
                result = _protobufSerializer.DeserializeFromFile <BlurayDiscInfo>(cacheFile);
            }
            catch (FileNotFoundException)
            {
                result = GetBDInfo(inputPath);

                _protobufSerializer.SerializeToFile(result, cacheFile);
            }

            cancellationToken.ThrowIfCancellationRequested();

            int?currentHeight  = null;
            int?currentWidth   = null;
            int?currentBitRate = null;

            var videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);

            // Grab the values that ffprobe recorded
            if (videoStream != null)
            {
                currentBitRate = videoStream.BitRate;
                currentWidth   = videoStream.Width;
                currentHeight  = videoStream.Height;
            }

            // Fill video properties from the BDInfo result
            Fetch(video, inputPath, result);

            videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);

            // Use the ffprobe values if these are empty
            if (videoStream != null)
            {
                videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
                videoStream.Width   = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
                videoStream.Height  = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
            }
        }
        public void FileSystemRepository_RestoreIntegrationTest()
        {
            AppLoggingFactory.Init(new TestLoggerFactory());

            var localStorageRepository = new TestLocalStorageRepository();

            var fileSystemRepository1 = new FileSystemRepository(localStorageRepository);
            var dataFolder            = fileSystemRepository1.CreateFolder(fileSystemRepository1.RootFolder.Key, "data").Result;

            fileSystemRepository1.CreateFile(dataFolder.Key, "drawr.dat").Wait();

            var fileSystemRepository2 = new FileSystemRepository(localStorageRepository);
            var items = fileSystemRepository2.GetDirectory();
        }
예제 #32
0
        public async Task GetSourcesAsync_SetOneDependencyInRepository_ReturnProperProjectName()
        {
            var reposPath = Settings.Instanse.PathToTestData + Settings.OneDepndencyInRepository;

            var             fileRepos = new FilesStrategy(reposPath);
            IRepositoryData data      = new FileSystemRepository
            {
                Name = reposPath,
                Path = reposPath
            };
            var result = await fileRepos.GetSourcesAsync(data);

            Assert.Equal("ServiceName", result.ProjectName);
        }
예제 #33
0
        public async Task GetSourcesAsync_SetOneDependencyInRepository_ReturnOneDependencyFile()
        {
            var reposPath = Settings.Instanse.PathToTestData + Settings.OneDepndencyInRepository;

            var             fileRepos = new FilesStrategy(reposPath);
            IRepositoryData data      = new FileSystemRepository
            {
                Name = reposPath,
                Path = reposPath
            };
            var result = await fileRepos.GetSourcesAsync(data);

            Assert.Single(result.Files);
        }
예제 #34
0
        public void Backup()
        {
            var implicitKeyRepo = new FileSystemRepository<TestClass>("Test", x => x.ID, new FileSystemOptions<TestClass> { FolderPath = "BackupTests/SingleFile" });
            var multipleFileRepo = new FileSystemRepository<TestClass>("Test", x => x.ID, new FileSystemOptions<TestClass> { FolderPath = "BackupTests/FilePerObject", FileStorageType = FileStorageType.FilePerObject });

            var expectedSingleFilePath = "BackupTests/SingleFile/backup/" + DateTime.Today.ToString("yyyyMMdd");
            var expectedFilePerObjectPath = "BackupTests/FilePerObject/Test/backup/" + DateTime.Today.ToString("yyyyMMdd");

            try
            {

                var obj = new TestClass("key", "value");
                implicitKeyRepo.Insert(obj);
                multipleFileRepo.Insert(obj);

                implicitKeyRepo.SaveChanges();
                multipleFileRepo.SaveChanges();

                implicitKeyRepo.CreateBackup();
                multipleFileRepo.CreateBackup();

                Assert.IsTrue(Directory.Exists(expectedSingleFilePath) && Directory.EnumerateFiles(expectedSingleFilePath).Any());
                Assert.IsTrue(Directory.Exists(expectedFilePerObjectPath) && Directory.EnumerateFiles(expectedFilePerObjectPath).Any());

                // Try again to make sure we don't have any issues with overwriting existing files
                implicitKeyRepo.CreateBackup();
                multipleFileRepo.CreateBackup();

                Assert.IsTrue(Directory.Exists(expectedSingleFilePath) && Directory.EnumerateFiles(expectedSingleFilePath).Any());
                Assert.IsTrue(Directory.Exists(expectedFilePerObjectPath) && Directory.EnumerateFiles(expectedFilePerObjectPath).Any());
            }

            catch (Exception)
            {
                throw;
            }

            finally
            {
                Directory.Delete(expectedSingleFilePath, true);
                Directory.Delete(expectedFilePerObjectPath, true);

                implicitKeyRepo.RemoveAll();
                multipleFileRepo.RemoveAll();

                implicitKeyRepo.SaveChanges();
                multipleFileRepo.SaveChanges();
            }
        }
예제 #35
0
        public DirectoryModel ReadDirectory(string path)
        {
            if (path == "/" || path == "." || path == Path.DirectorySeparatorChar.ToString())
            {
                return(root);
            }

            var parentDirPath = FileSystemRepository.GetParentDirectory(path);
            var dirName       = Path.GetFileName(path);
            var dir           = directoriesTableEvent
                                .FirstOrDefault(d => d.Path == parentDirPath && d.Name == dirName)
                                .Execute();

            return(GetDirectoryModel(dir));
        }
예제 #36
0
        public void Post()
        {
            // Arrange
            IRepository<Employee> repository = new FileSystemRepository(new TestFileHelper());
            EmployeeController controller = new EmployeeController(repository);
            int lengthBefore = controller.GetAllEmployees().Count();

            // Act
            Employee e = new Employee {id = 4, name="test",age=45,sex="female"};
            controller.PostEmployee(e);
            int lengthAfter = controller.GetAllEmployees().Count();

            // Assert
            Assert.AreEqual(lengthBefore + 1, lengthAfter);
        }
예제 #37
0
        public FileModel ReadFile(string path)
        {
            var parentDirPath = FileSystemRepository.GetParentDirectory(path);
            var fileName      = FileSystemRepository.GetFileName(path);
            var file          = filesTableEvent
                                .FirstOrDefault(f => f.Path == parentDirPath && f.Name == fileName)
                                .Execute();
            var fileModel = GetFileModel(file);

            if (file?.ContentGuid != null)
            {
                fileModel.Data = blobStorage.TryRead(file.ContentGuid.Value.ToString());
            }
            return(fileModel);
        }
예제 #38
0
        public void GetByIdMergeTitleTest()
        {
            DependencyManager.CachingService = new InProcCachingService();
            FileSystemRepository repo = new FileSystemRepository();
            ContentItem          item = repo.GetById(new ValidUrl()
            {
                SiteId = 1, Id = Guid.Parse("A1ED7FDF-498D-43EE-BC81-9E23F0294C57"), View = "Layout-Default"
            }, ContentViewType.PUBLISH);

            Assert.IsNotNull(item);
            Assert.AreEqual("I am actual title", item.Head.Title);
            Assert.AreEqual("Explo Travel", item.Head.KeyWords);
            Assert.AreEqual("search cheap flights", item.Head.Description);
            Assert.AreEqual("no tags", item.Head.PageMetaTags);
        }
예제 #39
0
파일: Tests.cs 프로젝트: kmhtoo/Repository
        public void MultipleKeys()
        {
            using (var repo = new FileSystemRepository<TestClass, String, String>("Test", x => Tuple.Create(x.ID, x.StringValue)))
            {
                var obj = new TestClass("key", "value");
                repo.Insert(obj);
                repo.SaveChanges();

                Assert.AreEqual(1, repo.Items.Count());

                repo.Remove(obj);
                repo.SaveChanges();
                Assert.AreEqual(0, repo.Items.Count());
            }
        }