public void GetRelativeTwoSameRoots()
        {
            var path1 = @"c:\";

            var result = PathExtensions.GetRelativePath(path1, path1);

            result.Should().Be(string.Empty);
        }
        public void BuildPath_WithAllNull()
        {
            //Act
            var actual = PathExtensions.BuildPath(null, null, null, null);

            //Assert
            actual.Should().BeEmpty();
        }
        public void GetRelativePathTestPathsSame()
        {
            var path1        = @"R:\temp\git-test3\trees\g1";
            var path2        = @"R:\temp\git-test3\trees\g1";
            var relativePath = PathExtensions.GetRelativePath(path1, path2);

            relativePath.Should().Be(string.Empty);
        }
        public void CompactPath_PathIsNull()
        {
            //Act
            var actual = PathExtensions.CompactPath(null, 100);

            //Assert
            actual.Should().BeEmpty();
        }
        public void TexturePackerJsonImporter_Import_Test()
        {
            var filePath = PathExtensions.GetApplicationFullPath(@"TestData/test-tileset.json");
            var importer = new TexturePackerJsonImporter();
            var data     = importer.Import(filePath, Substitute.For <ContentImporterContext>());

            Assert.NotNull(data);
        }
        public void GetCommonPath_Path1IsNull()
        {
            //Act
            var actual = PathExtensions.GetCommonPath(null, @"C:\Windows\System32");

            //Assert
            actual.Should().BeEmpty();
        }
        public void GetRelativePathNotRelative()
        {
            var path3        = @"c:\temp\goat\elephant\zebra";
            var path4        = @"c:\temp\goat\elephant\sheep\monkey";
            var relativePath = PathExtensions.GetRelativePath(path3, path4);

            relativePath.Should().Be(path4);
        }
        public void GetCommonPath_DifferentParents()
        {
            //Act
            var actual = PathExtensions.GetCommonPath(@"C:\Temp", @"D:\Temp");

            //Assert
            actual.Should().BeEmpty();
        }
Exemple #9
0
        /// <summary>
        /// Deletes the items from the database.
        /// </summary>
        /// <param name="serviceProvider">The application service provider.</param>
        /// <param name="token">The cancellation token for the task.</param>
        public async Task DeleteAsync(IServiceProvider serviceProvider, CancellationToken token)
        {
            // Check if there weren't any valid items found.
            if (Items == null)
            {
                // Throw an exception.
                throw new TaskException("No valid items could be found with the provided data.");
            }
            // Get the total number of batches.
            var count = Math.Ceiling((double)Items.Count() / ApplicationDbContext.BatchSize);

            // Go over each batch.
            for (var index = 0; index < count; index++)
            {
                // Check if the cancellation was requested.
                if (token.IsCancellationRequested)
                {
                    // Break.
                    break;
                }
                // Get the items in the current batch.
                var batchItems = Items
                                 .Skip(index * ApplicationDbContext.BatchSize)
                                 .Take(ApplicationDbContext.BatchSize);
                // Get the IDs of the items in the current batch.
                var batchIds = batchItems.Select(item => item.Id);
                // Define the list of items to get.
                var paths = new List <Path>();
                // Use a new scope.
                using (var scope = serviceProvider.CreateScope())
                {
                    // Use a new context instance.
                    using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                    // Get the items with the provided IDs.
                    var items = context.Paths
                                .Where(item => batchIds.Contains(item.Id));
                    // Check if there were no items found.
                    if (items == null || !items.Any())
                    {
                        // Continue.
                        continue;
                    }
                    // Get the items found.
                    paths = items
                            .ToList();
                }
                // Get the IDs of the items.
                var pathIds = paths
                              .Select(item => item.Id);
                // Delete the related entities.
                await PathExtensions.DeleteRelatedEntitiesAsync <PathNode>(pathIds, serviceProvider, token);

                await PathExtensions.DeleteRelatedEntitiesAsync <PathEdge>(pathIds, serviceProvider, token);

                // Delete the items.
                await IEnumerableExtensions.DeleteAsync(paths, serviceProvider, token);
            }
        }
        public void GetRelativeEmpty()
        {
            var path1 = string.Empty;
            var path2 = string.Empty;

            Action act = () => PathExtensions.GetRelativePath(path1, path2);

            act.Should().ThrowExactly <ArgumentException>();
        }
        public void Split_PathContainsInvalidChars_ThrowsException(string path)
        {
            var result = Should.Throw <ArgumentException>(() =>
            {
                PathExtensions.Split(path);
            });

            result.ParamName.ShouldBe(nameof(path));
        }
        public void GetRelativePathTestNoCommonRoot()
        {
            var path1 = @"d:\temp";
            var path2 = @"c:\temp\dog\cat\hamster";

            var relativePath = PathExtensions.GetRelativePath(path1, path2);

            relativePath.Should().Be(path2);
        }
        public void GetRelativePathTestStandardTest2()
        {
            var path1        = @"R:\temp\git-test3\trees\g1";
            var path2        = @"R:\temp\git-test3\trees\g1\fred\jim";
            var relativePath = PathExtensions.GetRelativePath(path1, path2);
            var expected     = MakeExpectedPath("fred", "jim");

            relativePath.Should().Be(expected);
        }
Exemple #14
0
 public FileSystemKVStore(string rootPath, string extension = ".json")
 {
     this.rootPath = PathExtensions.Parse(rootPath);
     if (!Directory.Exists(rootPath))
     {
         Directory.CreateDirectory(rootPath);
     }
     this.extension = extension;
 }
        public bool Exists(string indexName)
        {
            if (String.IsNullOrWhiteSpace(indexName))
            {
                return(false);
            }

            return(Directory.Exists(PathExtensions.Combine(_rootPath, indexName)));
        }
Exemple #16
0
        public virtual Matcher AddIncludes(params string[] patterns)
        {
            foreach (string pattern in patterns)
            {
                _includePatterns.Add(PathExtensions.RemoveRelativeSegments(pattern));
            }

            return(this);
        }
        public INode Create(FileSystemInfoBase root, FileSystemInfoBase location, ParsingReport report)
        {
            string relativePathFromRoot = root == null ? @".\" : PathExtensions.MakeRelativePath(root, location, this.fileSystem);

            var directory = location as DirectoryInfoBase;

            if (directory != null)
            {
                return(new FolderNode(directory, relativePathFromRoot));
            }

            var file = location as FileInfoBase;

            if (file != null)
            {
                if (this.relevantFileDetector.IsFeatureFile(file))
                {
                    try
                    {
                        Feature feature = this.featureParser.Parse(file.FullName);
                        return(feature != null ? new FeatureNode(file, relativePathFromRoot, feature) : null);
                    }
                    catch (FeatureParseException exception)
                    {
                        report.Add(exception.Message);
                        Log.Error(exception.Message);
                        return(null);
                    }
                }
                else if (this.relevantFileDetector.IsMarkdownFile(file))
                {
                    try
                    {
                        XElement markdownContent =
                            this.htmlMarkdownFormatter.Format(this.fileSystem.File.ReadAllText(file.FullName));
                        return(new MarkdownNode(file, relativePathFromRoot, markdownContent));
                    }
                    catch (Exception exception)
                    {
                        string description = "Error parsing the Markdown file located at " + file.FullName + ". Error: " + exception.Message;
                        report.Add(description);
                        Log.Error(description);
                        return(null);
                    }
                }
                else if (this.relevantFileDetector.IsImageFile(file))
                {
                    return(new ImageNode(file, relativePathFromRoot));
                }
            }

            var message = "Cannot create an IItemNode-derived object for " + location.FullName;

            report.Add(message);
            Log.Error(message);
            return(null);
        }
Exemple #18
0
 public void ResolvePaths()
 {
     OutputFolder                 = PathExtensions.Parse(OutputFolder);
     StorageFolderRoot            = PathExtensions.Parse(StorageFolderRoot);
     StorageFolderDownloadedFiles = PathExtensions.Parse(StorageFolderDownloadedFiles);
     PathToTesseract              = PathExtensions.Parse(PathToTesseract);
     StorageFolderSbcHtml         = PathExtensions.Parse(StorageFolderSbcHtml);
     StorageFolderSIE             = PathExtensions.Parse(StorageFolderSIE);
 }
        private ProjectTool GetProjectTool(string projectRelativePath)
        {
            var currentFolder      = System.IO.Path.GetDirectoryName(new Uri(this.GetType().Assembly.CodeBase).LocalPath);
            var csProjAbsolutePath = PathExtensions.GetAbsolutePath(currentFolder, projectRelativePath);

            var projectTool = new ProjectTool(csProjAbsolutePath, new DebugLogger(true));

            return(projectTool);
        }
Exemple #20
0
        public async Task Unsubscribe(string path, string pattern = null)
        {
            string filter;
            var    normalizedFolder = PathExtensions.NormalizePath(path);

            using (new UpgradeableReadLockCookie(_subscriptionLock))
            {
                if (!_watchers.TryGetValue(normalizedFolder, out var watcher))
                {
                    Debug.WriteLine($"No subscribed watchers for \"{path}\". Thread = {Thread.CurrentThread.ManagedThreadId}");
                    return;
                }

                filter = string.IsNullOrWhiteSpace(pattern)
                    ? DefaultFilePattern
                    : watcher.Filters.FirstOrDefault(x => x.Equals(pattern, StringComparison.InvariantCultureIgnoreCase));

                using (new WriteLockCookie(_subscriptionLock))
                {
                    if (filter != null)
                    {
                        watcher.Filters.Remove(filter);
                    }

                    if (string.IsNullOrWhiteSpace(pattern) || !watcher.Filters.Any())
                    {
                        _watchers.Remove(normalizedFolder);
                        UnsubscribeWatcher(watcher);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(filter))
            {
                var tasks = new List <Task>();
                using (new WriteLockCookie(_queueLock))
                {
                    tasks.AddRange(DirectoryExtensions
                                   .GetFilesSafe(normalizedFolder, filter)
                                   .Select(x =>
                    {
                        var normalizedFile = PathExtensions.NormalizePath(x);
                        _backgroundTaskQueue.CancelTasks(normalizedFile);
                        return(_backgroundTaskQueue.QueueTask(normalizedFolder, () =>
                        {
                            Debug.WriteLine($"Removing index for \"{x}\". Thread = {Thread.CurrentThread.ManagedThreadId}");
                            Indexer.Remove(normalizedFile);
                        }));
                    }));
                }

                await Task.WhenAll(tasks).IgnoreExceptions();

                await Task.Yield();
            }
        }
Exemple #21
0
        public void Pull(string pkgname, bool withdeps)
        {
            IPackage localpkg = this.LocalRep.GetPackage(pkgname);

            if (localpkg != null)
            {
                PrintInfo("Package " + pkgname + " is already in local repository. No action done.");
                return;
            }

            List <string> allpkgnames;

            try
            {
                allpkgnames = this.GetDependencies(pkgname, withdeps);
            }
            catch (PackageNotFoundException ex)
            {
                PrintError(ex);
                return;
            }
            foreach (string pname in allpkgnames)
            {
                IPackage remotepkg = this.RemoteRep.GetPackage(pname);
                if (remotepkg == null)
                {
                    PrintError("Package " + pname + " not found in remote repository.");
                    return;
                }
                string tmppkgpath;
                if (!PathExtensions.GetTempPath(out tmppkgpath))
                {
                    PrintError("Could not get a temporary directory.");
                    return;
                }
                try
                {
                    this.RemoteRep.CopyPackageFiles(pname, tmppkgpath);
                }
                catch (PackageIoException ex)
                {
                    PrintError(ex);
                    return;
                }
                if (this.LocalRep.GetPackage(pname) == null)
                {
                    this.LocalRep.AddPackage(remotepkg, tmppkgpath);
                    PrintInfo("Added package " + pname + " to local repository.");
                }
                else
                {
                    PrintInfo("Package " + pkgname + " is already in local repository.");
                }
            }
            Console.Write("{0}", Environment.NewLine);
        }
Exemple #22
0
        public override void ConfigureServices(IServiceCollection services)
        {
            // services.AddSession();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // transformalize services
            services.AddScoped(sp => new MemoryLogger(LogLevel.Info));
            services.AddScoped(typeof(CombinedLogger <>));
            services.AddScoped <ILinkService, LinkService>();
            services.AddScoped <ISortService, SortService>();
            services.AddScoped <IArrangementService, ArrangementService>();
            services.AddScoped <IArrangementLoadService, ArrangementLoadService>();
            services.AddScoped <IArrangementRunService, ArrangementRunService>();
            services.AddScoped <IArrangementSchemaService, ArrangementSchemaService>();
            services.AddScoped <IParameterService, ParameterService>();
            services.AddScoped <ICommonService, CommonService>();
            services.AddScoped <IReportService, ReportService>();
            services.AddScoped <ITaskService, TaskService>();
            services.AddScoped <IFormService, FormService>();
            services.AddScoped <ISchemaService, SchemaService>();
            services.AddScoped <ISettingsService, SettingsService>();
            services.AddScoped <ITransformalizeParametersModifier, TransformalizeParametersModifier>();
            services.AddScoped <ILoadFormModifier, LoadFormModifier>();
            services.AddScoped <IFileService, FileService>();

            services.AddTransient <IConfigurationContainer, OrchardConfigurationContainer>();
            services.AddTransient <IContainer, OrchardContainer>();

            // orchard cms services
            services.AddScoped <IDataMigration, Migrations>();
            services.AddScoped <IPermissionProvider, Permissions>();
            services.AddScoped <IResourceManifestProvider, ResourceManifest>();
            services.AddScoped <IContentHandler, TransformalizeHandler>();

            // parts
            services.AddContentPart <TransformalizeReportPart>().UseDisplayDriver <TransformalizeReportPartDisplayDriver>();
            services.AddContentPart <TransformalizeTaskPart>().UseDisplayDriver <TransformalizeTaskPartDisplayDriver>();
            services.AddContentPart <TransformalizeFormPart>().UseDisplayDriver <TransformalizeFormPartDisplayDriver>();
            services.AddContentPart <TransformalizeFilePart>().UseDisplayDriver <TransformalizeFilePartDisplayDriver>();

            // settings
            services.AddScoped <IDisplayDriver <ISite>, TransformalizeSettingsDisplayDriver>();
            services.AddScoped <INavigationProvider, TransformalizeSettingsAdminMenu>();

            // activities
            services.AddActivity <TransformalizeActivity, TransformalizeActivityDisplayDriver>();

            // file system, see https://github.com/Lombiq/Orchard-Training-Demo-Module/blob/dev/Startup.cs
            services.AddSingleton <ICustomFileStore>(serviceProvider => {
                var options  = serviceProvider.GetRequiredService <IOptions <ShellOptions> >().Value;
                var settings = serviceProvider.GetRequiredService <ShellSettings>();
                var sitePath = PathExtensions.Combine(options.ShellsApplicationDataPath, options.ShellsContainerName, settings.Name);
                var path     = PathExtensions.Combine(sitePath, "Transformalize", "Files");
                return(new CustomFileStore(path));
            });
        }
        public void ProjectsWhichShareOneContentProjectAreAllowedIfTheyShareSameNamespace()
        {
            service.ChangeProject("DeltaEngine.Tutorials");
            string basicsTutorialSolutionFilePath =
                Path.Combine(PathExtensions.GetFallbackEngineSourceCodeDirectory(), "Tutorials",
                             "DeltaEngine.Tutorials.Basics.sln");

            viewModel.UserSolutionPath = basicsTutorialSolutionFilePath;
            Assert.IsTrue(viewModel.IsBuildActionExecutable);
        }
Exemple #24
0
        public void TexturePackerJsonImporter_Processor_Test()
        {
            var filePath  = PathExtensions.GetApplicationFullPath(@"TestData\test-tileset.json");
            var importer  = new TexturePackerJsonImporter();
            var input     = importer.Import(filePath, Substitute.For <ContentImporterContext>());
            var processor = new TexturePackerProcessor();
            var output    = processor.Process(input, Substitute.For <ContentProcessorContext>());

            Assert.IsNotNull(output);
        }
Exemple #25
0
        private void SaveStage()
        {
            string texoDataFolder = PathExtensions.GetAndCreateDataDirectoryPath(FileManagerConstants.STORAGE_DIRECTORY_NAME);
            string filePath       = texoDataFolder.CombinePathWith(FileManagerConstants.STORAGE_STAGE_FILE_NAME);

            using (FileStream file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                serialisation.SerializeToStream(BuildStash(), file);
            }
        }
Exemple #26
0
        public void BuildPath_WithNullPath1()
        {
            var expected = @"System32\Drivers";

            //Act
            var actual = PathExtensions.BuildPath(null, @"System32", "Drivers");

            //Assert
            actual.Should().Be(expected);
        }
Exemple #27
0
        public void BuildPath_WithNullPath2()
        {
            var expected = @"C:\Windows\System32";

            //Act
            var actual = PathExtensions.BuildPath(@"C:\Windows", null, "System32");

            //Assert
            actual.Should().Be(expected);
        }
Exemple #28
0
        public void Get_A_Relative_Path_When_Location_Is_Deeper_Than_Root_Even_When_Root_Contains_End_Slash()
        {
            MockFileSystem fileSystem = FileSystem;

            fileSystem.AddFile(@"c:\test\deep\blah.feature", "Feature:"); // adding a file automatically adds all parent directories

            string actual = PathExtensions.MakeRelativePath(@"c:\test\", @"c:\test\deep\blah.feature", fileSystem);

            Check.That(actual).IsEqualTo(@"deep\blah.feature");
        }
 public SampleCreator()
 {
     Samples = new List <Sample>();
     sourceCodeRootDirectory = GetEngineSourceCodeDirectory(Directory.GetCurrentDirectory()) ??
                               GetFallbackEngineSourceCodeDirectory();
     sourceCodeSamplesPath   = Path.Combine(sourceCodeRootDirectory, "Samples");
     sourceCodeTutorialsPath = Path.Combine(sourceCodeRootDirectory, "Tutorials");
     installPath             = PathExtensions.GetDeltaEngineInstalledDirectory() ??
                               GetParentOfWorkingDirectory();
 }
Exemple #30
0
        public static void StartLogging()
        {
            string fileName = string.Format("Log {0}.txt", DateTime.Now.ToString("MM-dd-yyyy"));

            FilePath = Path.Combine(PathExtensions.GetProgramPath(), "Logs", fileName);
            Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
            sw      = File.AppendText(FilePath);
            Started = true;
            Message("STARTED SESSION");
        }