// Expects correct arguments. private CSharpCompilationOptions( OutputKind outputKind, string moduleName, string mainTypeName, string scriptClassName, IEnumerable <string> usings, bool optimize, bool checkOverflow, bool allowUnsafe, string cryptoKeyContainer, string cryptoKeyFile, bool?delaySign, int fileAlignment, ulong baseAddress, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions, bool highEntropyVirtualAddressSpace, DebugInformationKind debugInformationKind, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool concurrentBuild, FileResolver fileResolver, MetadataReferenceProvider metadataReferenceProvider, AssemblyIdentityComparer assemblyIdentityComparer, StrongNameProvider strongNameProvider, MetadataImportOptions metadataImportOptions, IEnumerable <string> features) : base(outputKind, moduleName, mainTypeName, scriptClassName, cryptoKeyContainer, cryptoKeyFile, delaySign, optimize, checkOverflow, fileAlignment, baseAddress, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, highEntropyVirtualAddressSpace, debugInformationKind, subsystemVersion, concurrentBuild, fileResolver, metadataReferenceProvider, assemblyIdentityComparer, strongNameProvider, metadataImportOptions) { Initialize(usings, allowUnsafe, features, runtimeMetadataVersion); }
// Defaults correspond to the compiler's defaults or indicate that the user did not specify when that is significant. // That's significant when one option depends on another's setting. SubsystemVersion depends on Platform and Target. public CSharpCompilationOptions( OutputKind outputKind, string moduleName = null, string mainTypeName = null, string scriptClassName = WellKnownMemberNames.DefaultScriptClassName, IEnumerable <string> usings = null, bool optimize = false, bool checkOverflow = false, bool allowUnsafe = false, string cryptoKeyContainer = null, string cryptoKeyFile = null, bool?delaySign = null, int fileAlignment = 0, ulong baseAddress = 0, Platform platform = Platform.AnyCpu, ReportDiagnostic generalDiagnosticOption = ReportDiagnostic.Default, int warningLevel = 4, IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions = null, bool highEntropyVirtualAddressSpace = false, DebugInformationKind debugInformationKind = DebugInformationKind.None, SubsystemVersion subsystemVersion = default(SubsystemVersion), string runtimeMetadataVersion = null, bool concurrentBuild = true, FileResolver fileResolver = null, MetadataReferenceProvider metadataReferenceProvider = null, AssemblyIdentityComparer assemblyIdentityComparer = null, StrongNameProvider strongNameProvider = null) : this(outputKind, moduleName, mainTypeName, scriptClassName, usings, optimize, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign, fileAlignment, baseAddress, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, highEntropyVirtualAddressSpace, debugInformationKind, subsystemVersion, runtimeMetadataVersion, concurrentBuild, fileResolver, metadataReferenceProvider, assemblyIdentityComparer, strongNameProvider, MetadataImportOptions.Public, features : null) { }
protected override string BeforeMinify(string outputFile, List <string> filePaths) { var outputCss = new StringBuilder(); foreach (string file in filePaths) { string css; if (file.ToLower().EndsWith(".less") || file.ToLower().EndsWith(".less.css")) { css = ProcessLess(file); } else { css = ReadFile(file); } if (ShouldImport) { css = ProcessImport(css); } ICssAssetsFileHasher fileHasher = null; if (ShouldAppendHashForAssets) { var fileResolver = new FileResolver(); fileHasher = new CssAssetsFileHasher(HashKeyName, fileResolver, hasher); } css = CSSPathRewriter.RewriteCssPaths(outputFile, file, css, fileHasher); outputCss.Append(css + "\n"); } return(outputCss.ToString()); }
public void CanResolveFile() { //dealing with working directory on a non-C location var currentDirectory = Environment.CurrentDirectory; var driveLetter = currentDirectory.Substring(0, currentDirectory.IndexOf("\\"));//ignoring UNC paths //resharper doesn't support the TestCase attribute var values = new Dictionary <string, string> { { @"C:\testfile.js", @"C:\testfile.js" }, { @"C:\test\testfile.js", @"C:\test\testfile.js" }, { @"D:\testfile.js", @"D:\testfile.js" }, { @"\testfile.js", driveLetter + @"\testfile.js" }, { @"\test\testfile.js", driveLetter + @"\test\testfile.js" }, { @"\test\test3\testfile.js", driveLetter + @"\test\test3\testfile.js" }, { @"testfile.js", Environment.CurrentDirectory + @"\testfile.js" }, { @"..\testfile.js", Path.GetFullPath(Environment.CurrentDirectory + @"\..\testfile.js") }, { @"..\..\testfile.js", Path.GetFullPath(Environment.CurrentDirectory + @"\..\..\testfile.js") } }; var fileResolver = new FileResolver(); foreach (string key in values.Keys) { var resolvedFile = fileResolver.Resolve(key).ToList(); Assert.AreEqual(values[key], resolvedFile[0], key); } }
public CompilationService(IDiagnosticLogger diagnosticLogger, InvocationContext invocationContext) { this.diagnosticLogger = diagnosticLogger; this.fileResolver = new FileResolver(); this.invocationContext = invocationContext; this.workspace = new Workspace(); }
private static bool RewriteSyntax(IResourceTypeProvider resourceTypeProvider, Workspace workspace, Uri entryUri, Func <SemanticModel, SyntaxRewriteVisitor> rewriteVisitorBuilder) { var hasChanges = false; var fileResolver = new FileResolver(); var syntaxTreeGrouping = SyntaxTreeGroupingBuilder.Build(fileResolver, workspace, entryUri); var compilation = new Compilation(resourceTypeProvider, syntaxTreeGrouping); foreach (var(fileUri, syntaxTree) in workspace.GetActiveSyntaxTrees()) { var entryFile = syntaxTreeGrouping.EntryPoint; var entryModel = compilation.GetEntrypointSemanticModel(); var newProgramSyntax = rewriteVisitorBuilder(compilation.GetSemanticModel(syntaxTree)).Rewrite(syntaxTree.ProgramSyntax); if (!object.ReferenceEquals(syntaxTree.ProgramSyntax, newProgramSyntax)) { hasChanges = true; var newSyntaxTree = new SyntaxTree(fileUri, ImmutableArray <int> .Empty, newProgramSyntax); workspace.UpsertSyntaxTrees(newSyntaxTree.AsEnumerable()); syntaxTreeGrouping = SyntaxTreeGroupingBuilder.Build(fileResolver, workspace, entryUri); compilation = new Compilation(resourceTypeProvider, syntaxTreeGrouping); } } return(hasChanges); }
public void TryReadAsBase64_should_return_expected_results() { var fileResolver = new FileResolver(); var tempFile = Path.Combine(Path.GetTempPath(), $"BICEP_TEST_{Guid.NewGuid()}"); var tempFileUri = PathHelper.FilePathToFileUrl(tempFile); File.WriteAllText(tempFile, "abcd\r\ndef\r\n\r\nghi"); fileResolver.TryReadAsBase64(tempFileUri, out var fileContents, out var failureMessage).Should().BeTrue(); fileContents.Should().Equals("YWJjZA0KZGVmDQoNCmdoaQ=="); failureMessage.Should().BeNull(); fileResolver.TryReadAsBase64(tempFileUri, out fileContents, out failureMessage, 8).Should().BeFalse(); fileContents.Should().BeNull(); failureMessage.Should().NotBeNull(); Core.Diagnostics.DiagnosticBuilder.DiagnosticBuilderInternal diag = new(new Core.Parsing.TextSpan(0, 5)); var err = failureMessage !.Invoke(diag); err.Message.Should().Contain($"{8 / 4 * 3} bytes"); File.Delete(tempFile); fileResolver.TryReadAsBase64(tempFileUri, out fileContents, out failureMessage).Should().BeFalse(); fileContents.Should().BeNull(); failureMessage.Should().NotBeNull(); }
public void ValidBicepTextWriter_TemplateEmiterShouldProduceExpectedTemplate(DataSet dataSet) { var outputDirectory = dataSet.SaveFilesToTestDirectory(TestContext); var bicepFilePath = Path.Combine(outputDirectory, DataSet.TestFileMain); MemoryStream memoryStream = new MemoryStream(); // emitting the template should be successful FileResolver fileResolver = BicepTestConstants.FileResolver; var dispatcher = new ModuleDispatcher(new DefaultModuleRegistryProvider(BicepTestConstants.FileResolver)); var result = this.EmitTemplate(SourceFileGroupingBuilder.Build(fileResolver, dispatcher, new Workspace(), PathHelper.FilePathToFileUrl(bicepFilePath)), memoryStream, BicepTestConstants.DevAssemblyFileVersion); result.Diagnostics.Should().NotHaveErrors(); result.Status.Should().Be(EmitStatus.Succeeded); // normalizing the formatting in case there are differences in indentation // this way the diff between actual and expected will be clean var actual = JToken.ReadFrom(new JsonTextReader(new StreamReader(new MemoryStream(memoryStream.ToArray())))); var compiledFilePath = FileHelper.SaveResultFile(this.TestContext, Path.Combine(dataSet.Name, DataSet.TestFileMainCompiled), actual.ToString(Formatting.Indented)); actual.Should().EqualWithJsonDiffOutput( TestContext, JToken.Parse(dataSet.Compiled !), expectedLocation: DataSet.GetBaselineUpdatePath(dataSet, DataSet.TestFileMainCompiled), actualLocation: compiledFilePath); }
void Awake() { IFileSystem fileSystem; _mConsole = new MiniConsole(scrollRect, text, 100); _rt = ScriptEngine.CreateRuntime(); var fileResolver = new FileResolver(); fileResolver.AddSearchPath("node_modules"); if (fileLoader == FileLoader.Resources) { fileSystem = new ResourcesFileSystem(_mConsole); fileResolver.AddSearchPath("dist"); } else if (fileLoader == FileLoader.HMR) { Debug.LogWarningFormat("功能未完成"); fileSystem = new HttpFileSystem(_mConsole, baseUrl); } else { fileSystem = new DefaultFileSystem(_mConsole); fileResolver.AddSearchPath("Assets/Examples/Scripts/out"); // _rt.AddSearchPath("Assets/Examples/Scripts/dist"); } _rt.withStacktrace = stacktrace; if (sourceMap) { _rt.EnableSourceMap(); } _mConsole.Write(LogLevel.Info, "Init"); _rt.Initialize(fileSystem, fileResolver, this, _mConsole, new ByteBufferPooledAllocator()); }
/// <summary> /// Loads all controls from given directory and its subdirectories. /// </summary> /// <returns></returns> public static WorkspaceTemplateInfo[] Load() { List <WorkspaceTemplateInfo> list = new List <WorkspaceTemplateInfo>(); FileDescriptor[] files = FileResolver.GetFiles(ControlsDir + Path.DirectorySeparatorChar + "Configs", "*.xml"); foreach (FileDescriptor file in files) { string controlDir = Path.GetDirectoryName(file.FilePath); if (!String.IsNullOrEmpty(controlDir)) { string configsDir = Path.DirectorySeparatorChar + ConfigDir; string tempControlDirString = controlDir.EndsWith(Convert.ToString(Path.DirectorySeparatorChar)) ? controlDir.Substring(0, controlDir.Length - 1) : controlDir; if (controlDir.EndsWith(configsDir, true, CultureInfo.InvariantCulture)) { controlDir = controlDir.Substring(0, controlDir.LastIndexOf(configsDir)); } } WorkspaceTemplateInfo wti = McXmlSerializer.GetObjectFromFile <WorkspaceTemplateInfo>(file.FilePath); if (string.IsNullOrEmpty(wti.Uid)) { wti.Uid = Path.GetFileNameWithoutExtension(file.FilePath); } list.Add(wti); } return(list.ToArray()); }
/// <summary> /// Initialises an instances of the <see cref="LibraryMapper"/> class with the functionality to map a DLL from disk into a process /// </summary> public LibraryMapper(Process process, string dllFilePath, MappingFlags mappingFlags = MappingFlags.None) { if (process is null || process.HasExited) { throw new ArgumentException("The provided process is not currently running"); } if (string.IsNullOrWhiteSpace(dllFilePath) || !File.Exists(dllFilePath)) { throw new ArgumentException("The provided file path did not point to a valid file"); } if (!Environment.Is64BitProcess && process.GetArchitecture() == Architecture.X64) { throw new NotSupportedException("The provided process cannot be mapped into from an x86 build"); } _dllBytes = File.ReadAllBytes(dllFilePath); _fileResolver = new FileResolver(process, Path.GetDirectoryName(dllFilePath)); _mappingFlags = mappingFlags; _peImage = new PeImage(_dllBytes.ToArray()); _processContext = new ProcessContext(process); }
public void ShouldReadReleaseTrackFile() { var sut = new FileResolver(); var collection = sut.Resolve(@"..\\..\\scenario1"); Assert.IsTrue(collection.Any()); }
/// <summary> /// Initialises an instances of the <see cref="LibraryMapper"/> class with the functionality to map a DLL from memory into a process /// </summary> public LibraryMapper(Process process, Memory <byte> dllBytes, MappingFlags mappingFlags = MappingFlags.None) { if (process is null || process.HasExited) { throw new ArgumentException("The provided process is not currently running"); } if (dllBytes.IsEmpty) { throw new ArgumentException("The provided DLL bytes were empty"); } if (!Environment.Is64BitProcess && process.GetArchitecture() == Architecture.X64) { throw new NotSupportedException("The provided process cannot be mapped into from an x86 build"); } _dllBytes = dllBytes.ToArray(); _fileResolver = new FileResolver(process, null); _mappingFlags = mappingFlags; _peImage = new PeImage(dllBytes); _processContext = new ProcessContext(process); }
public void CanResolveFile() { //resharper doesn't support the TestCase attribute var values = new Dictionary <string, string>() { { @"C:\testfile.js", @"C:\testfile.js" }, { @"C:\testfile.css", @"C:\testfile.css" }, { @"C:\test\testfile.js", @"C:\test\testfile.js" }, { @"C:\test\testfile.css", @"C:\test\testfile.css" }, { @"D:\testfile.js", @"D:\testfile.js" }, { @"\testfile.js", @"C:\testfile.js" }, { @"\test\testfile.js", @"C:\test\testfile.js" }, { @"\test\test3\testfile.js", @"C:\test\test3\testfile.js" }, { @"testfile.js", Environment.CurrentDirectory + @"\testfile.js" }, { @"..\testfile.js", Path.GetFullPath(Environment.CurrentDirectory + @"\..\testfile.js") }, { @"..\..\testfile.js", Path.GetFullPath(Environment.CurrentDirectory + @"\..\..\testfile.js") } }; var fileResolver = new FileResolver(); foreach (string key in values.Keys) { var resolvedFile = fileResolver.TryResolve(key).ToList(); Assert.AreEqual(values[key], resolvedFile[0]); } }
private static bool RewriteSyntax(IResourceTypeProvider resourceTypeProvider, Workspace workspace, Uri entryUri, Func <SemanticModel, SyntaxRewriteVisitor> rewriteVisitorBuilder) { var hasChanges = false; var fileResolver = new FileResolver(); var dispatcher = new ModuleDispatcher(new DefaultModuleRegistryProvider(fileResolver)); var sourceFileGrouping = SourceFileGroupingBuilder.Build(fileResolver, dispatcher, workspace, entryUri); var compilation = new Compilation(resourceTypeProvider, sourceFileGrouping); foreach (var(fileUri, sourceFile) in workspace.GetActiveSourceFilesByUri()) { if (sourceFile is not BicepFile bicepFile) { throw new InvalidOperationException("Expected a bicep source file."); } var newProgramSyntax = rewriteVisitorBuilder(compilation.GetSemanticModel(bicepFile)).Rewrite(bicepFile.ProgramSyntax); if (!object.ReferenceEquals(bicepFile.ProgramSyntax, newProgramSyntax)) { hasChanges = true; var newFile = new BicepFile(fileUri, ImmutableArray <int> .Empty, newProgramSyntax); workspace.UpsertSourceFile(newFile); sourceFileGrouping = SourceFileGroupingBuilder.Build(fileResolver, dispatcher, workspace, entryUri); compilation = new Compilation(resourceTypeProvider, sourceFileGrouping); } } return(hasChanges); }
private string CompressCss(string outputFilePath, List <string> files, ICssCompressor compressor, bool appendHashToAssets) { var outputCss = new StringBuilder(); foreach (string file in files) { string css; if (file.ToLower().EndsWith(".less") || file.ToLower().EndsWith(".less.css")) { css = ProcessLess(file); } else { css = ReadFile(file); } if (processImports) { css = ProcessImport(css); } ICssAssetsFileHasher fileHasher = null; if (appendHashToAssets) { var fileResolver = new FileResolver(); fileHasher = new CssAssetsFileHasher(hashQueryStringKeyName, fileResolver, hasher); } css = CssPathRewriter.RewriteCssPaths(outputFilePath, file, css, fileHasher); outputCss.Append(css + "\n"); } return(compressor.CompressContent(outputCss.ToString())); }
/** * Constructs a new PatchScript by reading the contents of a PromotionFile. * @param pResolver Resolver for finding the file. * @param pPromotionFile File to be parsed. * @return The new PatchScript. * @throws IOException If the file cannot be read. * @throws ExParser If the file contents or file name cannot be parsed. */ public static PatchScript createFromPromotionFile(FileResolver pResolver, PromotionFile pPromotionFile) { FileInfo lFile = pResolver.resolveFile(pPromotionFile.getFilePath()); String lFileContents = FileUtils.readFileToString(lFile); return(new PatchScript(lFile.getName(), lFileContents, pPromotionFile.getFileHash(), pPromotionFile.getSequencePosition(), pPromotionFile.getFileVersion())); }
public void SetReferenceSearchPaths(ReadOnlyArray <string> paths) { if (paths != fileResolver.AssemblySearchPaths) { FileResolver.ValidateSearchPaths(paths, "paths"); fileResolver = CommonScriptEngine.CreateFileResolver(paths, engine.BaseDirectory); } }
public Template(IFileProvider fileProvider) { this._fileProvider = fileProvider; this._fileResolver = new FileResolver(); this._resolvers = new List<IAssetUriResolver>(); this._resolvers.Add(this._fileResolver); this._resolvers.Add(new MsdnResolver()); }
/// <summary> /// Note that it leaves any calls to contract methods in their original locations, /// i.e., it does *not* extract contracts. That is up to the caller of this method. /// </summary> public static bool FileToUnitAndSourceLocationProvider(IMetadataHost host, string filename, List<string> libPaths, List<string> referencedAssemblies, out IModule module, out ISourceLocationProvider/*?*/ sourceLocationProvider) { var text = File.ReadAllText(filename); CSharpSyntaxTree tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, filename); // This ctor isn't implemented yet. //var mscorlib = new Roslyn.Compilers.AssemblyObjectReference(typeof(object).Assembly); //var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib"); // Roslyn takes care of resolving where it lives. var mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); var refs = new List<MetadataReference>(); refs.Add(mscorlib); foreach (var r in referencedAssemblies) { refs.Add(new MetadataFileReference(Path.GetFileNameWithoutExtension((r)))); } var baseFileName = Path.GetFileNameWithoutExtension(filename); var defaultResolver = FileResolver.Default; var ar = new FileResolver(libPaths.Select(lp => Path.GetFullPath(lp)), defaultResolver.KeyFileSearchPaths, defaultResolver.BaseDirectory); var c = CSharpCompilation.Create( baseFileName , syntaxTrees: new SyntaxTree[] { tree } , references: refs , fileResolver: ar , options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); var diags = c.GetDiagnostics(); if (diags.Count() > 0) { foreach (var diag in diags) { Console.WriteLine(diag.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return false; } } //c = c.AddSyntaxTrees(tree); // Use this form to add another syntax tree to the same compilation (getting a new compilation since they're immutable) var binding = c.GetSemanticModel(tree); diags = binding.GetDiagnostics(); if (diags.Count() > 0) { foreach (var d in diags) { Console.WriteLine(d.ToString()); } if (diags.Any(d => d.Severity == DiagnosticSeverity.Error || d.IsWarningAsError)) { module = Dummy.Module; sourceLocationProvider = null; return false; } } ConvertRoslynToCCI(host, tree, binding, out module, out sourceLocationProvider); return true; }
public void EmptyProgram_SourceFileGrouping_should_be_persisted() { var fileResolver = new FileResolver(); var program = SourceFileGroupingFactory.CreateFromText(DataSets.Empty.Bicep, fileResolver); var compilation = new Compilation(BicepTestConstants.Features, TestTypeHelper.CreateEmptyProvider(), program, BicepTestConstants.BuiltInConfiguration, BicepTestConstants.LinterAnalyzer); compilation.SourceFileGrouping.Should().BeSameAs(program); compilation.GetEntrypointSemanticModel().Should().NotBeNull(); }
public Template(CompositionContainer container) { this._cache = new MemoryCache("TemplateCache"); this._fileResolver = new FileResolver(); this._resolvers = new List<IAssetUriResolver>(); this._resolvers.Add(this._fileResolver); this._resolvers.Add(new MsdnResolver()); this._container = container; }
private FileResolveResult ResolveDestinationFile([NotNull] FileCopyArguments arguments) { var destinationResolver = new FileResolver(Container) { ErrorFileFoundAsDirectory = ErrorFactory.System.TargetIsNotFile }; return(destinationResolver.TryResolveFile(arguments.DestinationPath)); }
private FileEntry ResolveSourceFile([NotNull] AbsolutePath sourcePath) { var sourceResolver = new FileResolver(Root) { ErrorPathIsVolumeRoot = ErrorFactory.System.DirectoryNotFound }; return(sourceResolver.ResolveExistingFile(sourcePath)); }
public void EmptyProgram_SyntaxTreeGrouping_should_be_persisted() { var fileResolver = new FileResolver(); var program = SyntaxTreeGroupingFactory.CreateFromText(DataSets.Empty.Bicep, fileResolver); var compilation = new Compilation(TestTypeHelper.CreateEmptyProvider(), program); compilation.SyntaxTreeGrouping.Should().BeSameAs(program); compilation.GetEntrypointSemanticModel().Should().NotBeNull(); }
public static void Main(string[] args) { var path = FileResolver.ChooseFile(); FileName = path; WriteLine($"File path: {path}"); var serverInit = new LocalServerInitializer(12714, ProcessClientAsync); serverInit.StartListening(); }
public void ShouldIgnoreWhenFileNotFound() { var resolver = new FileResolver(); var mockedEditor = new Mock <IFileEditor>(); mockedEditor.Setup(o => o.Edit(It.IsAny <string>(), It.IsAny <IEnumerable <Release> >())); var sut = new Versioner(resolver, mockedEditor.Object); sut.ApplyTo(""); mockedEditor.Verify(o => o.Edit(string.Empty, null), Times.Never); }
internal Session(CommonScriptEngine engine, object hostObject, Type hostObjectType, bool isCollectible) { this.pendingReferences = engine.GetReferences(); this.pendingNamespaces = engine.GetImportedNamespaces(); this.fileResolver = engine.FileResolver; this.engine = engine; this.submissions = new object[16]; this.hostObject = hostObject; this.hostObjectType = hostObjectType; this.isCollectible = isCollectible; }
/// <summary> /// Loads the entity objects. /// </summary> /// <param name="metaClassName">Name of the meta class.</param> /// <returns></returns> private static EntityObject[] LoadEntityObjects(string metaClassName) { if (metaClassName == null) { throw new ArgumentNullException("metaClassName"); } if (!entityObjectHash.ContainsKey(metaClassName)) { lock (typeof(LocalDiskEntityObjectPlugin)) { if (!entityObjectHash.ContainsKey(metaClassName)) { FileDescriptor[] files = FileResolver.GetFiles(EntityObjectsDirs + Path.DirectorySeparatorChar + metaClassName, "*.xml"); List <EntityObject> items = new List <EntityObject>(); // Load EntityObject From File foreach (FileDescriptor file in files) { PrimaryKeyId pk; if (PrimaryKeyId.TryParse(Path.GetFileNameWithoutExtension(file.FilePath), out pk)) { // Load EntityObject From File EntityObject tmpItem = McXmlSerializer.GetObjectFromFile <EntityObject>(file.FilePath); // Create TEntityObject EntityObject item = BusinessManager.InitializeEntity(metaClassName); // Copy Fields From tmpItem To item foreach (EntityObjectProperty property in tmpItem.Properties) { item[property.Name] = property.Value; } // item.PrimaryKeyId = pk; // Add Abstract Property item[IsLoadDiskEntityPropertyName] = true; items.Add(item); } } entityObjectHash[metaClassName] = items.ToArray(); } } } return(entityObjectHash[metaClassName]); }
public async Task ForceModuleRestoreShouldRestoreAllModules(IEnumerable <ExternalModuleInfo> moduleInfos, int moduleCount) { var dataSet = DataSets.Registry_LF; var outputDirectory = dataSet.SaveFilesToTestDirectory(TestContext); var clientFactory = dataSet.CreateMockRegistryClients(TestContext); var templateSpecRepositoryFactory = dataSet.CreateMockTemplateSpecRepositoryFactory(TestContext); await dataSet.PublishModulesToRegistryAsync(clientFactory, TestContext); var cacheDirectory = FileHelper.GetCacheRootPath(TestContext); Directory.CreateDirectory(cacheDirectory); var features = StrictMock.Of <IFeatureProvider>(); features.Setup(m => m.RegistryEnabled).Returns(true); features.Setup(m => m.CacheRootDirectory).Returns(cacheDirectory); FileResolver fileResolver = new FileResolver(); var dispatcher = new ModuleDispatcher(new DefaultModuleRegistryProvider(fileResolver, clientFactory, templateSpecRepositoryFactory, features.Object)); var configuration = BicepTestConstants.BuiltInConfigurationWithAnalyzersDisabled; var moduleReferences = moduleInfos .OrderBy(m => m.Metadata.Target) .Select(m => dispatcher.TryGetModuleReference(m.Metadata.Target, configuration, out _) ?? throw new AssertFailedException($"Invalid module target '{m.Metadata.Target}'.")) .ToImmutableList(); moduleReferences.Should().HaveCount(moduleCount); // initially the cache should be empty foreach (var moduleReference in moduleReferences) { dispatcher.GetModuleRestoreStatus(moduleReference, configuration, out _).Should().Be(ModuleRestoreStatus.Unknown); } var moduleFileUri = dispatcher.TryGetLocalModuleEntryPointUri(new Uri("file://main.bicep"), moduleReferences[0], configuration, out _) !; moduleFileUri.Should().NotBeNull(); var moduleFilePath = moduleFileUri.LocalPath; var moduleDirectory = Path.GetDirectoryName(moduleFilePath) !; Directory.CreateDirectory(moduleDirectory); (await dispatcher.RestoreModules(BicepTestConstants.BuiltInConfiguration, moduleReferences, forceModulesRestore: true)).Should().BeTrue(); // all other modules should have succeeded foreach (var moduleReference in moduleReferences) { dispatcher.GetModuleRestoreStatus(moduleReference, configuration, out _).Should().Be(ModuleRestoreStatus.Succeeded); } }
public void PathComparer_should_be_ordinal_for_linux_otherwise_ordinal_insensitive() { var fileResolver = new FileResolver(); if (CompilerFlags.IsLinuxBuild) { fileResolver.PathComparer.Should().Be(StringComparer.Ordinal); } else { fileResolver.PathComparer.Should().Be(StringComparer.OrdinalIgnoreCase); } }
public void TryReadAtMostNCharacters_RegardlessFileContentLength_ReturnsAtMostNCharaters(string fileContents, int n, bool expectedResult, string expectedContents) { var fileResolver = new FileResolver(); var tempFile = Path.Combine(Path.GetTempPath(), $"BICEP_TEST_{Guid.NewGuid()}"); var tempFileUri = PathHelper.FilePathToFileUrl(tempFile); File.WriteAllText(tempFile, fileContents); var result = fileResolver.TryReadAtMostNCharaters(tempFileUri, Encoding.UTF8, n, out var readContents); result.Should().Be(expectedResult); readContents.Should().Be(expectedContents); }
private static Compilation GetCompilation(string fileContents) { var fileUri = new Uri("inmemory:///main.bicep"); var workspace = new Workspace(); var syntaxTree = SyntaxTree.Create(fileUri, fileContents); workspace.UpsertSyntaxTrees(syntaxTree.AsEnumerable()); var fileResolver = new FileResolver(); var syntaxTreeGrouping = SyntaxTreeGroupingBuilder.Build(fileResolver, workspace, fileUri); return(new Compilation(resourceTypeProvider, syntaxTreeGrouping)); }