Пример #1
0
        public void PopulateMatchingFiles()
        {
            const string filePattern = "*.txt";
            var fileSet = new FileSet(TargetDirectory, _imageProviderFactory, filePattern);

            var expected = TargetDirectory.GetFiles(filePattern).Select(f => new FileNode(f, fileSet, BrowserResources.Properties.Resources.Image_File, _imageProviderFactory));
            CollectionAssert.AreEquivalent(expected, fileSet);
        }
Пример #2
0
 public FileNode(FileInfo file, FileSet parent, Image defaultImage, IImageProviderFactory factory)
 {
     _factory = factory;
     Done = false;
     File = file;
     ParentNode = parent;
     Image = defaultImage;
 }
Пример #3
0
        public void ShouldAddMultipleFiles()
        {
            var fileset = new FileSet();
            fileset.Add(new List<File>
            {
                new File(@"M:\Shows\Lost\101.avi"),
                new File(@"M:\Shows\Lost\102.avi"),
            });

            Assert.NotNull(fileset.Files.SingleOrDefault(f => f.Path == @"M:\Shows\Lost\101.avi"));
            Assert.NotNull(fileset.Files.SingleOrDefault(f => f.Path == @"M:\Shows\Lost\102.avi"));
        }
Пример #4
0
        public FileSetTester()
        {
            _testDirectory = new TestDirectory();
            _testDirectory.ChangeDirectory();
            if (Directory.Exists("target"))
            {
                Directory.Delete("target", true);
            }

            Directory.CreateDirectory("target");

            theFileSet = new FileSet();
        }
Пример #5
0
        public void ShouldFindFileWhenProvidingFullPath()
        {
            var fileset = new FileSet();
            fileset.Add(new List<File>
            {
                new File(@"M:\Shows\Lost\101.avi"),
                new File(@"M:\Shows\Lost\102.avi"),
            });

            var matches = fileset.Find(@"M:\Shows\Lost\101.avi");
            Assert.AreEqual(1, matches.Count());
            Assert.NotNull(matches.SingleOrDefault(f => f.Path == @"M:\Shows\Lost\101.avi"));
        }
Пример #6
0
        public void ShouldNotAddIgnoredFiles()
        {
            var fileset = new FileSet();
            fileset.Add(new List<File>
            {
                new File(@"M:\Shows\Lost\lost.nfo"),
                new File(@"M:\Shows\Lost\101.avi"),
                new File(@"M:\Shows\Lost\cast.jpeg"),
            });

            Assert.AreEqual(1, fileset.Files.Count());
            Assert.NotNull(fileset.Files.SingleOrDefault(f => f.Path == @"M:\Shows\Lost\101.avi"));
        }
Пример #7
0
        public void ShouldFindAllFilesThatMatchStars()
        {
            var fileset = new FileSet();
            fileset.Add(new List<File>
            {
                new File(@"M:\Shows\Lost\101.avi"),
                new File(@"M:\Shows\Lost\102.avi"),
                new File(@"M:\Shows\Dexter\121.avi"),
            });

            var matches = fileset.Find(@"1*1");
            Assert.AreEqual(2, matches.Count());
            Assert.NotNull(matches.SingleOrDefault(f => f.Path == @"M:\Shows\Lost\101.avi"));
            Assert.NotNull(matches.SingleOrDefault(f => f.Path == @"M:\Shows\Dexter\121.avi"));
        }
Пример #8
0
        private void Scan(string root, string directory, FileSet fileSet, Action<FileFound> onFound, IEnumerable<string> excludes)
        {
            if (AlreadyScannedOrNonexistent(directory)) { return; }

            scannedDirectories.Add(directory);

            fileSystem.ChildDirectoriesFor(directory)
                .ForEach(dir => Scan(root, dir, fileSet, onFound, excludes));

            var included = fileSet.IncludedFilesFor(directory).ToList();
            var excluded = included.Where(x => excludes.Any(x.Contains));

            var files = included.Except(excluded).ToList();

            files.ForEach(file => onFound(new FileFound(file, root, directory)));
        }
Пример #9
0
        public virtual async void Foreign_key_to_unique_index()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("FkToAltKey" + DbSuffix).AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS User (
    Id INTEGER PRIMARY KEY,
    AltId INTEGER NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS Comment (
    Id INTEGER PRIMARY KEY,
    UserAltId INTEGER NOT NULL,
    Contents TEXT,
    FOREIGN KEY (UserAltId) REFERENCES User (AltId)
);");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    ConnectionString     = testStore.ConnectionString,
                    ContextClassName     = "FkToAltKeyContext",
                    ProjectPath          = TestProjectPath,
                    ProjectRootNamespace = "E2E.Sqlite",
                    UseFluentApiOnly     = UseFluentApiOnly,
                    TableSelectionSet    = TableSelectionSet.All
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "FkToAltKey"))
                {
                    Files =
                    {
                        "FkToAltKeyContext.expected",
                        "Comment.expected",
                        "User.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, TestProjectFullPath)
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Пример #10
0
        public void CleanTarget(string directory)
        {
            var fileSystem = new FileSystem();

            foreach (var child in Directory.GetDirectories(directory))
            {
                if (child.Contains(".git"))
                {
                    continue;
                }

                fileSystem.DeleteDirectory(child);
            }

            fileSystem.FindFiles(directory, FileSet.Shallow("*.htm"))
            .Each(fileSystem.DeleteFile);
        }
Пример #11
0
        public void find_does_not_wig_out_when_the_exclude_pattern_is_an_invalid_directory()
        {
            writeFile("config/a.config");
            writeFile("config/b.config");
            writeFile("config/zeppelin.yaml");
            writeFile("hitchhiker.config");

            new FileSystem().DeleteDirectory("data");

            theFileSet = new FileSet()
            {
                Include = "*.as*x;*.master;Content{0}*.*;*.config".ToFormat(Path.DirectorySeparatorChar),
                Exclude = "data/*"
            };

            includedFiles().ShouldHaveTheSameElementsAs("a.config", "b.config", "hitchhiker.config");
        }
Пример #12
0
        public void SetUp()
        {
            var testDirectory = TestDirectory.Root("Cake.FileSet", "D:/code/git/Cake.FileSet")
                                .Add("src/a/one.csproj")
                                .Add("src/b/ONE.csproj")
                                .Add("src/c/one.csproj")
                                .Add("src/c/two.csproj");

            var includes = new List <string>
            {
                "**/one.csproj"
            };

            var subject = new FileSet(testDirectory, includes, new List <string>(), true);

            _result = subject.GetFiles().ToList();
        }
Пример #13
0
        public void Index_with_filter()
        {
            using (var scratch = SqlServerTestStore.Create("SqlServerE2E"))
            {
                scratch.ExecuteNonQuery(@"
CREATE TABLE FilteredIndex (
    Id int,
    Number int,
    PRIMARY KEY (Id)
);

CREATE INDEX Unicorn_Filtered_Index
    ON FilteredIndex (Number) WHERE Number > 10
");

                var configuration = new ReverseEngineeringConfiguration
                {
                    ConnectionString     = scratch.ConnectionString,
                    ProjectPath          = TestProjectDir + Path.DirectorySeparatorChar,
                    ProjectRootNamespace = TestNamespace,
                    ContextClassName     = "FilteredIndexContext",
                    UseFluentApiOnly     = true
                };
                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "FilteredIndexContext.expected",
                        "FilteredIndex.expected",
                    }
                };

                var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public void E2ETest_AllFluentApi()
        {
            var configuration = new ReverseEngineeringConfiguration
            {
                ConnectionString     = _connectionString,
                ProjectPath          = TestProjectDir,
                ProjectRootNamespace = TestNamespace,
                OutputPath           = null, // not used for this test
                UseFluentApiOnly     = true,
                TableSelectionSet    = Filter,
            };

            var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

            var actualFileSet = new FileSet(InMemoryFiles, TestProjectDir)
            {
                Files = Enumerable.Repeat(filePaths.ContextFile, 1).Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
            };

            var expectedFileSet = new FileSet(new FileSystemFileService(),
                                              Path.Combine("ReverseEngineering", "ExpectedResults", "E2E_AllFluentApi"))
            {
                Files = (new List <string> {
                    "SqlServerReverseEngineerTestE2EContext.expected"
                })
                        .Concat(_expectedEntityTypeFiles).ToList()
            };

            AssertLog(new LoggerMessages
            {
                Warn =
                {
                    @"For column [dbo][AllDataTypes][hierarchyidColumn]. Could not find type mapping for SQL Server type hierarchyid. Skipping column.",
                    @"For column [dbo][AllDataTypes][sql_variantColumn]. Could not find type mapping for SQL Server type sql_variant. Skipping column.",
                    @"For column [dbo][AllDataTypes][xmlColumn]. Could not find type mapping for SQL Server type xml. Skipping column.",
                    @"For column [dbo][AllDataTypes][geographyColumn]. Could not find type mapping for SQL Server type geography. Skipping column.",
                    @"For column [dbo][AllDataTypes][geometryColumn]. Could not find type mapping for SQL Server type geometry. Skipping column.",
                    @"For column [dbo][PropertyConfiguration][PropertyConfigurationID]. This column is set up as an Identity column, but the SQL Server data type is tinyint. This will be mapped to CLR type byte which does not allow the SqlServerValueGenerationStrategy.IdentityColumn setting. Generating a matching Property but ignoring the Identity setting.",
                    @"For column [dbo][TableWithUnmappablePrimaryKeyColumn][TableWithUnmappablePrimaryKeyColumnID]. Could not find type mapping for SQL Server type hierarchyid. Skipping column.",
                    @"Unable to identify any primary key columns in the underlying SQL Server table [dbo].[TableWithUnmappablePrimaryKeyColumn]."
                }
            });
            AssertEqualFileContents(expectedFileSet, actualFileSet);
            AssertCompile(actualFileSet);
        }
Пример #15
0
        private void ScanFiles()
        {
            // If no includes were specified, add all files and subdirectories
            // from the fileset's base directory to the fileset.
            if ((FileSet.Includes.Count == 0) && (FileSet.AsIs.Count == 0))
            {
                FileSet.Includes.Add("**/*.dll");

                // Make sure to rescan the fileset
                FileSet.Scan();
            }

            AgentProjectInfo projectInfo = new AgentProjectInfo();

            if (String.IsNullOrEmpty(ProjectToken))
            {
                projectInfo.Coordinates = new Coordinates(null, Project.ProjectName, null);
            }
            else
            {
                projectInfo.ProjectToken = ProjectToken;
            }

            // scan files and calculate SHA-1 values
            List <DependencyInfo> dependencies = projectInfo.Dependencies;

            foreach (String pathname in FileSet.FileNames)
            {
                FileInfo srcInfo = new FileInfo(pathname);
                if (srcInfo.Exists)
                {
                    String sha1     = ChecksumUtils.GetSha1Hash(pathname);
                    String filename = srcInfo.Name;
                    Log(Level.Debug, "SHA-1 for " + filename + " is: " + sha1);

                    DependencyInfo dependency = new DependencyInfo();
                    dependency.Sha1       = sha1;
                    dependency.ArtifactId = filename;
                    dependency.SystemPath = pathname;
                    dependencies.Add(dependency);
                }
            }
            Log(Level.Info, "Found " + dependencies.Count + " direct dependencies");
            projects.Add(projectInfo);
        }
Пример #16
0
 protected override void DisposeManagedResources()
 {
     base.DisposeManagedResources();
     Dashboard?.Dispose();
     FileSet.Dispose();
     if (Timeline != null)
     {
         foreach (TimelineEvent evt in Timeline)
         {
             evt.Dispose();
         }
     }
     if (EventTypes != null)
     {
         foreach (var eventType in EventTypes)
         {
             eventType.Dispose();
         }
         EventTypes.Clear();
     }
     if (Timers != null)
     {
         foreach (var element in Timers)
         {
             element.Dispose();
         }
         Timers.Clear();
     }
     if (Periods != null)
     {
         foreach (var element in Periods)
         {
             element.Dispose();
         }
         Periods.Clear();
     }
     if (Playlists != null)
     {
         foreach (var element in Playlists)
         {
             element.Dispose();
         }
         Playlists.Clear();
     }
 }
Пример #17
0
        public void PrimaryKeyWithSequence()
        {
            using (var scratch = SqlServerTestStore.CreateScratch())
            {
                scratch.ExecuteNonQuery(@"
CREATE SEQUENCE PrimaryKeyWithSequenceSequence
    AS int
    START WITH 1
    INCREMENT BY 1

CREATE TABLE PrimaryKeyWithSequence (
    PrimaryKeyWithSequenceId int DEFAULT(NEXT VALUE FOR PrimaryKeyWithSequenceSequence),
    PRIMARY KEY (PrimaryKeyWithSequenceId)
);
");

                var configuration = new ReverseEngineeringConfiguration
                {
                    ConnectionString     = scratch.ConnectionString,
                    ProjectPath          = TestProjectDir + Path.DirectorySeparatorChar,
                    ProjectRootNamespace = TestNamespace,
                    ContextClassName     = "PrimaryKeyWithSequenceContext",
                    UseFluentApiOnly     = true
                };
                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string> {
                        "PrimaryKeyWithSequenceContext.expected",
                        "PrimaryKeyWithSequence.expected"
                    }
                };

                var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Пример #18
0
        public void Non_null_boolean_columns_with_default_constraint_become_nullable_properties()
        {
            using (var scratch = SqlCeTestStore.Create("NonNullBooleanWithDefaultConstraint"))
            {
                scratch.ExecuteNonQuery(@"
CREATE TABLE NonNullBoolWithDefault
(
     Id int NOT NULL PRIMARY KEY,
     BoolWithDefaultValueSql bit NOT NULL DEFAULT (CONVERT(""bit"", GETDATE())),
     BoolWithoutDefaultValueSql bit NOT NULL
)");

                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "ExpectedResults"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "NonNullBoolWithDefaultContext.cs",
                        "NonNullBoolWithDefault.cs",
                    }
                };

                var filePaths = Generator.Generate(
                    scratch.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectDir + Path.DirectorySeparatorChar,
                    outputPath: null,     // not used for this test
                    rootNamespace: TestNamespace,
                    contextName: "NonNullBoolWithDefaultContext",
                    useDataAnnotations: false,
                    overwriteFiles: false,
                    useDatabaseNames: false);


                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                //AssertCompile(actualFileSet);
            }
        }
Пример #19
0
        public async void One_to_one()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("OneToOne" + DbSuffix).AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS Principal (
    Id INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE IF NOT EXISTS Dependent (
    Id INT,
    PrincipalId INT NOT NULL UNIQUE,
    PRIMARY KEY (Id),
    FOREIGN KEY (PrincipalId) REFERENCES Principal (Id)
);
");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    ConnectionString     = testStore.Connection.ConnectionString,
                    ProjectPath          = "testout",
                    ProjectRootNamespace = "E2E.Sqlite",
                    UseFluentApiOnly     = UseFluentApiOnly,
                    TableSelectionSet    = TableSelectionSet.All
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), Path.Combine(ExpectedResultsParentDir, "OneToOne"))
                {
                    Files =
                    {
                        "OneToOne" + DbSuffix + "Context.expected",
                        "Dependent.expected",
                        "Principal.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = Enumerable.Repeat(results.ContextFile, 1).Concat(results.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Пример #20
0
        public AssemblyFiles FindAssemblies(string binDirectory, IEnumerable <string> assemblyNames)
        {
            var assemblySet = FileSet.ForAssemblyNames(assemblyNames);
            var debugSet    = FileSet.ForAssemblyDebugFiles(assemblyNames);

            var files = new AssemblyFiles()
            {
                Files    = _fileSystem.FindFiles(binDirectory, assemblySet),
                PdbFiles = _fileSystem.FindFiles(binDirectory, debugSet)
            };

            var assembliesFound = files.Files.Select(Path.GetFileNameWithoutExtension).Select(x => x.ToLowerInvariant());

            files.MissingAssemblies = assemblyNames.Select(x => x.ToLowerInvariant()).Where(name => !assembliesFound.Contains(name));
            files.Success           = !files.MissingAssemblies.Any();

            return(files);
        }
Пример #21
0
        public void LoadAllProjects()
        {
            var folder = ".".ToFullPath().ParentDirectory().ParentDirectory()
                         .AppendPath("CodeTracker");

            var files = new FileSystem().FindFiles(folder, FileSet.Shallow("*.json"));

            AllProjects = new Dictionary <Guid, GithubProject>();
            foreach (var file in files)
            {
                var project = GithubProject.LoadFrom(file);
                AllProjects.Add(project.Id, project);

                Console.WriteLine($"Loaded {project.OrganizationName}{project.ProjectName} from JSON");
            }

            PublishAllProjectEvents(_store);
        }
Пример #22
0
        private static void writeManifestIfNecessary(string directory, FileSystem fileSystem)
        {
            var manifestFile = directory.AppendPath(PackageManifest.FILE);

            if (!File.Exists(manifestFile))
            {
                var manifest = new PackageManifest {
                    ContentFileSet = FileSet.Deep("*.*")
                };
                string assemblyName = Path.GetFileName(directory);
                manifest.Name = assemblyName;
                manifest.AddAssembly(assemblyName);

                manifest.ContentFileSet.Exclude = "Properties/*;bin/*;obj/*;*.csproj*;packages.config;repositories.config;pak-*.zip;*.sln";

                fileSystem.WriteObjectToFile(manifestFile, manifest);
            }
        }
Пример #23
0
        public void SpecifyInvalidBasePathIteratingFolders()
        {
            var sys = new MemoryFileSystemFake();

            sys.AddFiles(x => x
                         .File("FileInRoot.txt")
                         .Folder("a", a => a
                                 .File("FileInFolder.txt")
                                 .File("AnotherFileInFolder.txt")
                                 .Folder("b", b => b
                                         .File("FileInSubFolder.txt")))
                         .Folder("c", c => c
                                 .File("FileInFolder.txt")));
            var fs = new FileSet(sys, "/DoesNotExist");

            fs.Include(@"**\*");
            Assert.That(() => fs.GetFolders().ToList(), Throws.TypeOf <InvalidOperationException>());
        }
Пример #24
0
        /// <summary>
        /// Check output files to see if we need rebuilding.
        /// </summary>
        /// <returns>
        /// <see langword="true" /> if a rebuild is needed; otherwise,
        /// <see langword="false" />.
        /// </returns>
        private bool NeedsCompiling(FileInfo outputFile)
        {
            if (!outputFile.Exists)
            {
                Log(Level.Verbose, "Output file '{0}' does not exist, recompiling.",
                    outputFile.FullName);
                return(true);
            }
            string fileName = FileSet.FindMoreRecentLastWriteTime(Filename.FullName,
                                                                  outputFile.LastWriteTime);

            if (fileName != null)
            {
                Log(Level.Verbose, "'{0}' is out of date, recompiling.", fileName);
                return(true);
            }
            return(false);
        }
Пример #25
0
        private IDictionary <string, EmbeddedSpec> readSpecs()
        {
            var dict = new Dictionary <string, EmbeddedSpec>();

            var fileSystem = new FileSystem();

            fileSystem.FindFiles(_settings.Root, FileSet.Deep("*.specs.json")).Each(file =>
            {
                var json     = fileSystem.ReadStringFromFile(file);
                var response = JsonSerialization.Deserialize <BatchRunResponse>(json);
                var fixtures = new Dictionary <string, FixtureModel>();
                response.fixtures.Each(x => fixtures.Add(x.key, x));

                response.records.Each(rec => dict.Add(rec.specification.path, new EmbeddedSpec(fixtures, rec)));
            });

            return(dict);
        }
Пример #26
0
        public void PatchMatchesText_PreviousWithoutApplying(FileSet set)
        {
            var correction = 0;

            foreach (var(patchIdx, patch) in set.ReviewPatch.AsIndexed())
            {
                var actual   = set.Previous.Substring(patch.Start1 - correction, patch.Length1);
                var expected = DiffMatchPatchModule.Default.DiffText1(patch.Diffs);

                Assert.That(actual, Is.EqualTo(expected), () =>
                {
                    var foundAt = string.Join(", ", set.Previous.FindAllOccurences(expected));
                    return($"Patch index {patchIdx} Expected position: {patch.Start1} Found at: {foundAt} ");
                });

                correction += patch.Length2 - patch.Length1;
            }
        }
Пример #27
0
        public void ApplyingPatchesOneByOneUpdatesPreviousToCurrent(FileSet set)
        {
            var actual = set.Previous;

            foreach (var patch in set.ReviewPatch)
            {
                var update = DiffMatchPatchModule.Default.PatchApply(new List <Patch>()
                {
                    patch
                }, actual);
                actual = (string)update[0];

                var flags = (bool[])update[1];
                Assert.That(flags.All(x => x), Is.True);
            }

            Assert.That(actual, Is.EqualTo(set.Current));
        }
Пример #28
0
        private void ProcessPHash(string path)
        {
            if (_data == null)
            {
                _data = new FileSet();
            }

            listBox1.DataSource = null; // prevent preliminary updates
            _viewList           = null;
            ClearPictureBoxes();

            _cidCount++; // loading (another) PHASH

            _guiContext            = TaskScheduler.FromCurrentSynchronizationContext();
            _oldColor              = statusStrip1.BackColor;
            statusStrip1.BackColor = Color.Red;
            ParsePHash(path);
        }
Пример #29
0
        private IEnumerable <string> allFiles()
        {
            string path = _root.AppendPath(_folder);

            FileSet searchSpecification = FileSet.Everything();

            searchSpecification.Exclude = "logs/*.*;instructions.txt;*-TestResults.xml;fubu.templates.config";

            return
                (FileSystem.FindFiles(path, searchSpecification)
                 .Select(x => x.PathRelativeTo(path).Replace("\\", "/"))
                 .Where(x => !x.StartsWith("src/packages"))
                 .Where(x => !x.Contains("/bin/"))
                 .Where(x => !x.Contains("/obj/"))
                 .Where(x => !x.Contains("fubu.templates.config"))
                 .Where(x => !x.Contains(".bottle-alias"))
                 .Where(x => !x.Contains("TestResults.xml")));
        }
Пример #30
0
        /// <summary>
        /// Read [name].table and [name].function files from the named directory
        /// to serve as templates for extra DDL (GRANT's probably)
        /// </summary>
        /// <param name="directory"></param>
        public void ReadTemplates(string directory)
        {
            var system = new FileSystem();

            system.FindFiles(directory, FileSet.Shallow("*.function")).Each(file =>
            {
                var name = Path.GetFileNameWithoutExtension(file).ToLower();

                Templates[name].FunctionCreation = system.ReadStringFromFile(file);
            });

            system.FindFiles(directory, FileSet.Shallow("*.table")).Each(file =>
            {
                var name = Path.GetFileNameWithoutExtension(file).ToLower();

                Templates[name].TableCreation = system.ReadStringFromFile(file);
            });
        }
Пример #31
0
        public void CopyFiles()
        {
            var path = ".".ToFullPath().ParentDirectory().ParentDirectory().ParentDirectory()
                       .AppendPath("Storyteller.Samples", "Specs");

            thePath = ".".ToFullPath().AppendPath(Guid.NewGuid().ToString());
            var fileSystem = new FileSystem();

            var files = fileSystem.FindFiles(path, FileSet.Deep("*.xml"));

            files.Each(file =>
            {
                var relativePath = file.PathRelativeTo(path);
                var destination  = Path.Combine(thePath, relativePath);

                fileSystem.Copy(file, destination);
            });
        }
Пример #32
0
        public void find_does_not_wig_out_when_the_exclude_pattern_is_an_invalid_directory()
        {
            writeFile("config/a.config");
            writeFile("config/b.config");
            writeFile("config/zeppelin.yaml");
            writeFile("hitchhiker.config");

            new FileSystem().DeleteDirectory("data");

            theFileSet = new FileSet()
            {
                Include = "*.as*x;*.master;Content{0}*.*;*.config".ToFormat(Path.DirectorySeparatorChar),
                Exclude = "data/*"
            };


            includedFiles().ShouldHaveTheSameElementsAs("a.config", "b.config", "hitchhiker.config");
        }
Пример #33
0
        public void UploadFiles(bool withBaseDir)
        {
            SetLoginExpectations();
            ExpectCommand("MKD /dest");
            SetResponse(FtpReturnCode.Created);
            ExpectCommand("MKD /dest/dest2");
            SetResponse(FtpReturnCode.Created);
            ExpectCommand("PASV");
            SetResponse(FtpReturnCode.EnteringPassiveMode, "(10,20,30,40,1,2)");
            dataChannel.Expect(x => x.Connect(new byte[] { 10, 20, 30, 40 }, 258));
            ExpectCommand("STOR /dest/dest2/file1.txt");
            SetResponse(FtpReturnCode.FileStatusOk);
            fileSystem.Stub(x => x.ReadFileAsBytes(@"d:\files\file1.txt")).Return(new byte[10]);
            dataChannel.Expect(x => x.Send(null)).IgnoreArguments().Return(10);
            SetResponse(FtpReturnCode.ClosingDataConnection);

            //ExpectCommand("PASV");
            SetResponse(FtpReturnCode.EnteringPassiveMode, "(10,20,30,40,1,2)");
            dataChannel.Expect(x => x.Connect(new byte[] { 10, 20, 30, 40 }, 258));
            ExpectCommand("STOR /dest/dest2/file2.txt");
            SetResponse(FtpReturnCode.FileStatusOk);
            fileSystem.Stub(x => x.ReadFileAsBytes(@"d:\files\file2.txt")).Return(new byte[10]);
            SetResponse(FtpReturnCode.ClosingDataConnection);

            FtpConnectionData connectionData = ConstructConnectionData();

            session.BeginSession(connectionData);

            List <string> createdDirs = new List <string>();
            List <KeyValuePair <string, string> > uploadedFiles = new List <KeyValuePair <string, string> >();
            FileSet files = new FileSet(withBaseDir ? @"d:\files" : null, new[] { @"d:\files\file1.txt", @"d:\files\file2.txt" });

            session.UploadFiles(
                null,
                files,
                "/dest/dest2",
                createdDirs.Add,
                (l, r) => uploadedFiles.Add(new KeyValuePair <string, string>(l, r)));

            Assert.AreEqual(2, createdDirs.Count);
            Assert.AreEqual(2, uploadedFiles.Count);

            communicator.VerifyAllExpectations();
        }
Пример #34
0
        public async void One_to_one()
        {
            using (var testStore = SqliteTestStore.GetOrCreateShared("OneToOne").AsTransient())
            {
                testStore.ExecuteNonQuery(@"
CREATE TABLE IF NOT EXISTS Principal ( 
    Id INTEGER PRIMARY KEY AUTOINCREMENT
);
CREATE TABLE IF NOT EXISTS Dependent (
    Id INT,
    PrincipalId INT NOT NULL UNIQUE,
    PRIMARY KEY (Id),
    FOREIGN KEY (PrincipalId) REFERENCES Principal (Id)
);
");
                testStore.Transaction.Commit();

                var results = await Generator.GenerateAsync(new ReverseEngineeringConfiguration
                {
                    Provider         = MetadataModelProvider,
                    ConnectionString = testStore.Connection.ConnectionString,
                    Namespace        = "E2E.Sqlite",
                    OutputPath       = "testout"
                });

                AssertLog(new LoggerMessages());

                var expectedFileSet = new FileSet(new FileSystemFileService(), "ReverseEngineering/Expected/OneToOne")
                {
                    Files =
                    {
                        "ModelContext.expected",
                        "Dependent.expected",
                        "Principal.expected"
                    }
                };
                var actualFileSet = new FileSet(InMemoryFiles, "testout")
                {
                    Files = results.Select(Path.GetFileName).ToList()
                };
                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
Пример #35
0
        public async Task MatchOnFolderAfterStarStarWithAnotherStarStar()
        {
            var          sys             = new MemoryFileSystemFake();
            const string folderToMatchOn = "FolderToMatchOn";
            const string foundFileName1  = "IncludedFile.1zz";
            const string foundFileName2  = "IncludedFile.2zz";
            const string foundFileName3  = "IncludedFile.3zz";
            const string foundFileName4  = "IncludedFile.4zz";
            string       foundFilePath1  = PortablePath.Combine("B", "C", folderToMatchOn, foundFileName1);
            string       foundFilePath2  = PortablePath.Combine("B", "C", folderToMatchOn, "D", foundFileName2);
            string       foundFilePath3  = PortablePath.Combine("B", "C", folderToMatchOn, "D", "E", foundFileName3);
            string       foundFilePath4  = PortablePath.Combine("B", "C", folderToMatchOn, "F", foundFileName4);

            sys.AddFilesAndFolders(x => x
                                   .Folder("A", a => a
                                           .File("ExcludedFile.txt"))
                                   .Folder("B", b => b
                                           .File("ExcludedFile.xzz")
                                           .Folder("C", c => c
                                                   .Folder(folderToMatchOn, d => d
                                                           .File(foundFileName1)
                                                           .Folder("D", e => e
                                                                   .File("ExcludedFile.a1z")
                                                                   .File(foundFileName2)
                                                                   .Folder("E", f => f
                                                                           .File(foundFileName3)))
                                                           .Folder("F", f => f
                                                                   .File("ExcludedFile.txt")
                                                                   .File(foundFileName4))
                                                           .File("AnotherExcludedFile.txt")
                                                           )))
                                   .Folder("Z", z => z
                                           .File("ExcludedFile.txt")));
            var fs = new FileSet(sys, "/");

            fs.Include(@"**\" + folderToMatchOn + @"\**\*.?zz");
            List <string> files = (await fs.GetFilesAsync()).ToList();

            Assert.That(files.Count, Is.EqualTo(4));
            Assert.That(files, Has.Member(foundFilePath1));
            Assert.That(files, Has.Member(foundFilePath2));
            Assert.That(files, Has.Member(foundFilePath3));
            Assert.That(files, Has.Member(foundFilePath4));
        }
Пример #36
0
        public async Task CaseInsensitiveFolderMatchGettingFolders()
        {
            var          sys              = new MemoryFileSystemFake();
            const string ignoredFileName  = "IncludedFile.Txt";
            string       foundFolderPath1 = PortablePath.Combine("A", "zxcASDFqwe");
            string       foundFolderPath2 = PortablePath.Combine("A", "qweASDFzxc");
            string       foundFolderPath3 = PortablePath.Combine("C", "zxcASDFqwe");
            string       foundFolderPath4 = PortablePath.Combine("C", "zxcASDFqwe", "zzzASDFzzz");
            string       foundFolderPath5 = PortablePath.Combine("C", "zxcASDFqwe", "qweASDFzxc");

            sys.AddFilesAndFolders(x => x
                                   .File(ignoredFileName)
                                   .Folder("A", a => a
                                           .File(ignoredFileName)
                                           .Folder("zxcASDFqwe", zxc => zxc
                                                   .File(ignoredFileName))
                                           .Folder("B", b => b
                                                   .File(ignoredFileName))
                                           .Folder("qweASDFzxc", qwe => qwe
                                                   .File(ignoredFileName)))
                                   .Folder("C", c => c
                                           .File(ignoredFileName)
                                           .Folder("zxcASDFqwe", zxc => zxc
                                                   .File(ignoredFileName)
                                                   .Folder("zzzASDFzzz", zzz => zzz
                                                           .File(ignoredFileName))
                                                   .Folder("D", d => d
                                                           .File(ignoredFileName))
                                                   .Folder("qweASDFzxc", qwe => qwe
                                                           .File(ignoredFileName))))
                                   .Folder("Z", z => z
                                           .File("ExcludedFile.txt")));
            var fs = new FileSet(sys, "/");

            fs.Include(@"**\*asdf*");
            List <string> folders = (await fs.GetFoldersAsync()).ToList();

            Assert.That(folders.Count, Is.EqualTo(5));
            Assert.That(folders, Has.Member(foundFolderPath1));
            Assert.That(folders, Has.Member(foundFolderPath2));
            Assert.That(folders, Has.Member(foundFolderPath3));
            Assert.That(folders, Has.Member(foundFolderPath4));
            Assert.That(folders, Has.Member(foundFolderPath5));
        }
Пример #37
0
        private static void findProjectVersion(string bottleName, string folder, ProjectRoot project)
        {
            if (bottleName == "Application")
            {
                return;                              // hokey, but it stops an error.
            }
            var assemblyFileName = bottleName + ".dll";

            var file = new FileSystem().FindFiles(folder, FileSet.Deep(assemblyFileName)).FirstOrDefault();

            if (file != null)
            {
                try
                {
                    var assembly = Assembly.ReflectionOnlyLoadFrom(file);
                    if (assembly != null)
                    {
                        project.Version = assembly.GetName().Version.ToString().Split('.').Take(3).Join(".");
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to find a version for assembly at " + file);
                }
            }

            if (project.Version.IsNotEmpty())
            {
                return;
            }

            try
            {
                var assembly = Assembly.Load(bottleName);
                if (assembly != null)
                {
                    project.Version = assembly.GetName().Version.ToString();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Could not load the assembly for " + bottleName);
            }
        }
Пример #38
0
        public void SetRole(string role)
        {
            Role = role;



            switch (role)
            {
            case BottleRoles.Config:
                ConfigFileSet = new FileSet()
                {
                    Include = "*.*", DeepSearch = true
                };
                ContentFileSet = null;
                DataFileSet    = null;
                RemoveAllAssemblies();
                break;

            case BottleRoles.Binaries:
                ConfigFileSet  = null;
                ContentFileSet = null;
                DataFileSet    = null;
                break;

            case BottleRoles.Data:
                ConfigFileSet  = null;
                ContentFileSet = null;
                RemoveAllAssemblies();
                DataFileSet = new FileSet()
                {
                    DeepSearch = true, Include = "*.*"
                };
                break;

            default:
                DataFileSet    = new FileSet();
                ContentFileSet = new FileSet()
                {
                    Include = "*.as*x;*.master;Content{0}*.*;*.config".ToFormat(Path.DirectorySeparatorChar),
                    Exclude = "data/*"
                };
                break;
            }
        }
Пример #39
0
        private static void writeIndexPageIfNecessary(string directory)
        {
            var hasIndex = fileSystem.FindFiles(directory, FileSet.Shallow("index.*")).Any();

            if (!hasIndex)
            {
                var guessedTitle = Path.GetFileNameWithoutExtension(directory).Replace(".Docs", "");

                var text = @"<!--Title: {0}-->
<ProjectSummary />
<TableOfContents />
".ToFormat(guessedTitle);

                var indexFile = directory.AppendPath("index.spark");
                Console.WriteLine("Writing project root file to " + indexFile);

                fileSystem.WriteStringToFile(indexFile, text);
            }
        }
Пример #40
0
        public void Test_SharedMetadataReferencesWithAliases()
        {
            var projPath1 = @"CSharpProject\CSharpProject_ExternAlias.csproj";
            var projPath2 = @"CSharpProject\CSharpProject_ExternAlias2.csproj";
            var files = new FileSet(new Dictionary<string, object>
            {
                { projPath1, GetResourceText("CSharpProject_CSharpProject_ExternAlias.csproj") },
                { projPath2, GetResourceText("CSharpProject_CSharpProject_ExternAlias2.csproj") },
                { @"CSharpProject\CSharpExternAlias.cs", GetResourceText("CSharpProject_CSharpExternAlias.cs") },
            });

            CreateFiles(files);

            var fullPath1 = Path.Combine(this.SolutionDirectory.Path, projPath1);
            var fullPath2 = Path.Combine(this.SolutionDirectory.Path, projPath2);
            using (var ws = MSBuildWorkspace.Create())
            {
                var proj1 = ws.OpenProjectAsync(fullPath1).Result;
                var proj2 = ws.OpenProjectAsync(fullPath2).Result;

                var p1Sys1 = GetMetadataReferenceByAlias(proj1, "Sys1");
                var p1Sys2 = GetMetadataReferenceByAlias(proj1, "Sys2");
                var p2Sys1 = GetMetadataReferenceByAlias(proj2, "Sys1");
                var p2Sys3 = GetMetadataReferenceByAlias(proj2, "Sys3");

                Assert.NotNull(p1Sys1);
                Assert.NotNull(p1Sys2);
                Assert.NotNull(p2Sys1);
                Assert.NotNull(p2Sys3);

                // same filepath but different alias so they are not the same instance
                Assert.NotSame(p1Sys1, p1Sys2);
                Assert.NotSame(p2Sys1, p2Sys3);

                // same filepath and alias so they are the same instance
                Assert.Same(p1Sys1, p2Sys1);

                var mdp1Sys1 = GetMetadata(p1Sys1);
                var mdp1Sys2 = GetMetadata(p1Sys2);
                var mdp2Sys1 = GetMetadata(p2Sys1);
                var mdp2Sys3 = GetMetadata(p2Sys1);

                Assert.NotNull(mdp1Sys1);
                Assert.NotNull(mdp1Sys2);
                Assert.NotNull(mdp2Sys1);
                Assert.NotNull(mdp2Sys3);

                // all references to System.dll share the same metadata bytes
                Assert.Same(mdp1Sys1.Id, mdp1Sys2.Id);
                Assert.Same(mdp1Sys1.Id, mdp2Sys1.Id);
                Assert.Same(mdp1Sys1.Id, mdp2Sys3.Id);
            }
        }
Пример #41
0
 public void Scan(ScanRequest request)
 {
     var fileSet = new FileSet { Include = request.Filters, DeepSearch = false };
     scannedDirectories = new List<string>();
     request.Roots.ForEach(root => Scan(root, root, fileSet, request.OnFound, request.ExcludedDirectories));
 }
Пример #42
0
        public void ShouldRemoveWholeFolder()
        {
            var fileset = new FileSet();
            fileset.Add(new List<File>
            {
                new File(@"M:\Shows\Lost\101.avi"),
                new File(@"M:\Shows\Lost\102.avi"),
                new File(@"M:\Shows\Dexter\121.avi"),
            });

            fileset.Remove(@"M:\Shows\Lost");
            Assert.AreEqual(1, fileset.Files.Count());
            Assert.NotNull(fileset.Files.SingleOrDefault(f => f.Path == @"M:\Shows\Dexter\121.avi"));
        }
Пример #43
0
        public void TestOpenSolution_SolutionFileHasMissingEndProject()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { @"TestSolution1.sln", GetResourceText("TestSolution_MissingEndProject1.sln") },
                { @"TestSolution2.sln", GetResourceText("TestSolution_MissingEndProject2.sln") },
                { @"TestSolution3.sln", GetResourceText("TestSolution_MissingEndProject3.sln") }
            });

            CreateFiles(files);

            var solution1 = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution1.sln")).Result;
            var solution2 = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution2.sln")).Result;
            var solution3 = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution3.sln")).Result;
        }
Пример #44
0
        public void TestOpenSolution_SolutionFileHasEmptyLinesAndWhitespaceOnlyLines()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { @"TestSolution.sln", GetResourceText("TestSolution_CSharp_EmptyLines.sln") },
                { @"CSharpProject\CSharpProject.csproj", GetResourceText("CSharpProject_CSharpProject.csproj") },
                { @"CSharpProject\CSharpClass.cs", GetResourceText("CSharpProject_CSharpClass.cs") },
                { @"CSharpProject\Properties\AssemblyInfo.cs", GetResourceText("CSharpProject_AssemblyInfo.cs") }
            });

            CreateFiles(files);

            var solution = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result;
            var project = solution.Projects.First();
        }
Пример #45
0
        public FileSet GetPendingOrderFileSet(bool forceRefresh)
        {
            FileSet fs = new FileSet();
            var allPendingOrders = this.GetAllPendingOrders(forceRefresh);

            foreach (var order in allPendingOrders.Values)
            {
                var file = CooToPendingOrderFile(order);
                fs.Add(order.FileKey, file);
            }
            return fs;
        }
Пример #46
0
 public static List<string> GetFileListFromFileSet(FileSet fileSet)
 {
     List<string> files = new List<string>();
     foreach (FileItem file in fileSet.FileItems)
     {
         files.Add(file.FileName);
     }
     return files;
 }
Пример #47
0
        private FileSet AssertFileSetFilesAndDirectories(string baseDir, ArrayList includes, ArrayList excludes,
            ArrayList expectedFiles, ArrayList expectedDirectories)
        {
            excludes.Add("**/.svn/**");
            expectedFiles = PrepareExpected(expectedFiles);
            expectedDirectories = PrepareExpected(expectedDirectories);
            FileSet fs = new FileSet(baseDir);
            fs.Includes = includes;
            fs.Excludes = excludes;
            fs.Load();

            Compare(expectedFiles, fs.Files);
            Compare(expectedDirectories, fs.Directories);
            return fs;
        }
Пример #48
0
        public void ShouldNotAddIgnoredFilesWithUpperCaseExtension()
        {
            var fileset = new FileSet();
            fileset.Add(new List<File>
            {
                new File(@"M:\Shows\Lost\lost.TXT"),
                new File(@"M:\Shows\Lost\101.avi"),
            });

            Assert.AreEqual(1, fileset.Files.Count());
            Assert.NotNull(fileset.Files.SingleOrDefault(f => f.Path == @"M:\Shows\Lost\101.avi"));
        }
Пример #49
0
        public void TestCSharpExternAlias()
        {
            var projPath = @"CSharpProject\CSharpProject_ExternAlias.csproj";
            var files = new FileSet(new Dictionary<string, object>
            {
                { projPath, GetResourceText("CSharpProject_CSharpProject_ExternAlias.csproj") },
                { @"CSharpProject\CSharpExternAlias.cs", GetResourceText("CSharpProject_CSharpExternAlias.cs") },
            });

            CreateFiles(files);

            var fullPath = Path.Combine(this.SolutionDirectory.Path, projPath);
            using (var ws = MSBuildWorkspace.Create())
            {
                var proj = ws.OpenProjectAsync(fullPath).Result;
                var comp = proj.GetCompilationAsync().Result;
                comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
            }
        }
Пример #50
0
        public void MSBuildProjectShouldHandleCodePageProperty()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { "Encoding.csproj", GetResourceText("Encoding.csproj").Replace("<CodePage>ReplaceMe</CodePage>", "<CodePage>1254</CodePage>") },
                { "class1.cs", "//\u201C" }
            });

            CreateFiles(files);

            var projPath = Path.Combine(this.SolutionDirectory.Path, "Encoding.csproj");
            var project = MSBuildWorkspace.Create().OpenProjectAsync(projPath).Result;

            var text = project.Documents.First(d => d.Name == "class1.cs").GetTextAsync().Result;
            Assert.Equal(Encoding.GetEncoding(1254), text.Encoding);

            // The smart quote (“) in class1.cs shows up as "“" in codepage 1254. Do a sanity
            // check here to make sure this file hasn't been corrupted in a way that would
            // impact subsequent asserts.
            Assert.Equal("//\u00E2\u20AC\u0153".Length, 5);
            Assert.Equal("//\u00E2\u20AC\u0153".Length, text.Length);
        }
Пример #51
0
        private FileSet VisitProjectReferences(FileSet files, Action<XElement> visitProjectReference)
        {
            var result = new List<KeyValuePair<string, object>>();
            foreach (var file in files)
            {
                string text = file.Value.ToString();
                if (file.Key.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
                {
                    text = VisitProjectReferences(text, visitProjectReference);
                }

                result.Add(new KeyValuePair<string, object>(file.Key, text));
            }

            return new FileSet(result);
        }
Пример #52
0
 private void RefreshPanels()
 {
     _fileSet = _fsRepo.GetPendingOrderFileSet(true);
     LoadPanels();
 }
Пример #53
0
        public void TestOpenSolution_SolutionFileHasEmptyLineBetweenProjectBlock()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { @"TestSolution.sln", GetResourceText("TestLoad_SolutionFileWithEmptyLineBetweenProjectBlock.sln") }
            });

            CreateFiles(files);

            var solution = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("TestSolution.sln")).Result;
        }
Пример #54
0
        public void MSBuildWorkspacePreservesEncoding()
        {
            var encoding = Encoding.BigEndianUnicode;
            var fileContent = @"//“
class C { }";
            var files = new FileSet(new Dictionary<string, object>
            {
                { "Encoding.csproj", GetResourceText("Encoding.csproj").Replace("<CodePage>ReplaceMe</CodePage>", string.Empty) },
                { "class1.cs", encoding.GetBytesWithPreamble(fileContent) }
            });

            CreateFiles(files);

            var projPath = Path.Combine(this.SolutionDirectory.Path, "Encoding.csproj");
            var project = MSBuildWorkspace.Create().OpenProjectAsync(projPath).Result;

            var document = project.Documents.First(d => d.Name == "class1.cs");

            // update root without first looking at text (no encoding is known)
            var gen = Editing.SyntaxGenerator.GetGenerator(document);
            var doc2 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU
            var doc2text = doc2.GetTextAsync().Result;
            Assert.Null(doc2text.Encoding);
            var doc2tree = doc2.GetSyntaxTreeAsync().Result;
            Assert.Null(doc2tree.Encoding);
            Assert.Null(doc2tree.GetText().Encoding);

            // observe original text to discover encoding
            var text = document.GetTextAsync().Result;
            Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName);
            Assert.Equal(fileContent, text.ToString());

            // update root blindly again, after observing encoding, see that now encoding is known
            var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU
            var doc3text = doc3.GetTextAsync().Result;
            Assert.NotNull(doc3text.Encoding);
            Assert.Equal(encoding.EncodingName, doc3text.Encoding.EncodingName);
            var doc3tree = doc3.GetSyntaxTreeAsync().Result;
            Assert.Equal(doc3text.Encoding, doc3tree.GetText().Encoding);
            Assert.Equal(doc3text.Encoding, doc3tree.Encoding);

            // change doc to have no encoding, still succeeds at writing to disk with old encoding
            var root = document.GetSyntaxRootAsync().Result;
            var noEncodingDoc = document.WithText(SourceText.From(text.ToString(), encoding: null));
            Assert.Null(noEncodingDoc.GetTextAsync().Result.Encoding);

            // apply changes (this writes the changed document)
            var noEncodingSolution = noEncodingDoc.Project.Solution;
            Assert.True(noEncodingSolution.Workspace.TryApplyChanges(noEncodingSolution));

            // prove the written document still has the same encoding
            var filePath = Path.Combine(this.SolutionDirectory.Path, "Class1.cs");
            using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var reloadedText = EncodedStringText.Create(stream);
                Assert.Equal(encoding.EncodingName, reloadedText.Encoding.EncodingName);
            }
        }
Пример #55
0
        public void TestOpenSolution_WithDuplicatedGuidsBecomeCircularReferential()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { @"DuplicatedGuids.sln", GetResourceText("TestSolution_DuplicatedGuidsBecomeCircularReferential.sln") },
                { @"ReferenceTest\ReferenceTest.csproj", GetResourceText("CSharpProject_DuplicatedGuidsBecomeCircularReferential.csproj") },
                { @"Library1\Library1.csproj", GetResourceText("CSharpProject_DuplicatedGuidLibrary3.csproj") },
                { @"Library2\Library2.csproj", GetResourceText("CSharpProject_DuplicatedGuidLibrary4.csproj") },
            });

            CreateFiles(files);

            var solution = MSBuildWorkspace.Create().OpenSolutionAsync(GetSolutionFileName("DuplicatedGuids.sln")).Result;
            Assert.Equal(3, solution.ProjectIds.Count);

            var testProject = solution.Projects.FirstOrDefault(p => p.Name == "ReferenceTest");
            Assert.NotNull(testProject);
            Assert.Equal(1, testProject.AllProjectReferences.Count);

            var library1Project = solution.Projects.FirstOrDefault(p => p.Name == "Library1");
            Assert.NotNull(library1Project);
            Assert.Equal(1, library1Project.AllProjectReferences.Count);

            var library2Project = solution.Projects.FirstOrDefault(p => p.Name == "Library2");
            Assert.NotNull(library2Project);
            Assert.Equal(0, library2Project.AllProjectReferences.Count);
        }
Пример #56
0
        public void SetUp()
        {
            if (Directory.Exists("target"))
            {
                Directory.Delete("target", true);
            }

            Directory.CreateDirectory("target");

            theFileSet = new FileSet();
        }
Пример #57
0
        public void MSBuildProjectShouldHandleDefaultCodePageProperty()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { "Encoding.csproj", GetResourceText("Encoding.csproj").Replace("<CodePage>ReplaceMe</CodePage>", string.Empty) },
                { "class1.cs", "//\u201C" }
            });

            CreateFiles(files);

            var projPath = Path.Combine(this.SolutionDirectory.Path, "Encoding.csproj");
            var project = MSBuildWorkspace.Create().OpenProjectAsync(projPath).Result;

            var text = project.Documents.First(d => d.Name == "class1.cs").GetTextAsync().Result;
            Assert.Equal(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), text.Encoding);
            Assert.Equal("//\u201C", text.ToString());
        }
Пример #58
0
 public void Make()
 {
     var fileSet = new FileSet(TargetDirectory,_imageProviderFactory);
     var expected = TargetDirectory.GetFiles().Select(f => new FileNode(f, fileSet, BrowserResources.Properties.Resources.Image_File,_imageProviderFactory));
     CollectionAssert.AreEquivalent(expected,fileSet);
 }
Пример #59
0
        public void Test_OpenProjectReferencingPortableProject()
        {
            var files = new FileSet(new Dictionary<string, object>
            {
                { @"CSharpProject\ReferencesPortableProject.csproj", GetResourceText("CSharpProject_ReferencesPortableProject.csproj") },
                { @"CSharpProject\Program.cs", GetResourceText("CSharpProject_CSharpClass.cs") },
                { @"CSharpProject\PortableProject.csproj", GetResourceText("CSharpProject_PortableProject.csproj") },
                { @"CSharpProject\CSharpClass.cs", GetResourceText("CSharpProject_CSharpClass.cs") }
});

            CreateFiles(files);

            var project = MSBuildWorkspace.Create().OpenProjectAsync(GetSolutionFileName(@"CSharpProject\ReferencesPortableProject.csproj")).Result;
            var hasFacades = project.MetadataReferences.OfType<PortableExecutableReference>().Any(r => r.FilePath.Contains("Facade"));
            Assert.True(hasFacades);
        }
Пример #60
0
        public void SetUp()
        {
            Location.CurrentDirectory = BaseDirectory;

            files = new FileSet();
        }