public void AssemblyReflectionOnlyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(AssemblyPathHelper.GetAssemblyLocation(assembly)); Assert.Throws <PlatformNotSupportedException>(() => Assembly.ReflectionOnlyLoad(aBytes)); }
public void PinnedAndUnpinnedLocals() { using (FileStream stream = File.OpenRead(AssemblyPathHelper.GetAssemblyLocation(typeof(PinnedAndUnpinnedLocalsToDecode).GetTypeInfo().Assembly))) using (var peReader = new PEReader(stream)) { MetadataReader reader = peReader.GetMetadataReader(); var provider = new DisassemblingTypeProvider(); TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, typeof(PinnedAndUnpinnedLocalsToDecode)); TypeDefinition typeDef = reader.GetTypeDefinition(typeDefHandle); MethodDefinition methodDef = reader.GetMethodDefinition(typeDef.GetMethods().First()); Assert.Equal("DoSomething", reader.GetString(methodDef.Name)); MethodBodyBlock body = peReader.GetMethodBody(methodDef.RelativeVirtualAddress); StandaloneSignature localSignature = reader.GetStandaloneSignature(body.LocalSignature); ImmutableArray <string> localTypes = localSignature.DecodeLocalSignature(provider, genericContext: null); // Compiler can generate temporaries or re-order so just check the ones we expect are there. // (They could get optimized away too. If that happens in practice, change this test to use hard-coded signatures.) Assert.Contains("uint8[] pinned", localTypes); Assert.Contains("uint8[]", localTypes); } }
public void Do() { string filePath = AssemblyPathHelper.GetAssemblyPath() + "Resource/210311990023-20180712.txt"; if (!File.Exists(filePath)) { return; } try { int offSet = 0; byte[] billsByte = File.ReadAllBytes(filePath); string bills = Encoding.GetEncoding("UTF-8").GetString(billsByte); int lines = bills.Count(item => item == '\n'); Console.WriteLine(bills); BillCheckingSummary summary = TextAnalysor.AnalyseToBillCheckingSummary(billsByte, ref offSet); List <BillCheckingDetail> details = TextAnalysor.AnalyseToBillCheckingDetails(billsByte, summary.CheckCount, offSet); } catch (Exception e) { Console.WriteLine(e.StackTrace); } }
public void ShouldNotContainNonImpl() { List <Type> types = AssemblyPathHelper.GetAllAssemblies() .AllTypesAssignableTo <IProfile>() .ToList(); Assert.IsFalse(types.Any(x => x.Name == "ClassNotImplementing")); }
public void ShouldNotContainSelf() { List <Type> types = AssemblyPathHelper.GetAllAssemblies() .AllTypesAssignableTo <IProfile>() .ToList(); Assert.IsFalse(types.Any(x => x.Name == "IProfile")); }
public void GetFiles() { Assert.NotNull(typeof(AssemblyTests).Assembly.GetFiles()); Assert.Equal(1, typeof(AssemblyTests).Assembly.GetFiles().Length); string name = AssemblyPathHelper.GetAssemblyLocation(typeof(AssemblyTests).Assembly); Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles()[0].Name, name); }
public void StackTraceSymbolsDoNotLockFile() { var asmPath = AssemblyPathHelper.GetAssemblyLocation(typeof(StackTraceSymbolsTests).Assembly); var pdbPath = Path.ChangeExtension(asmPath, ".pdb"); Assert.True(File.Exists(pdbPath)); new StackTrace(true).GetFrames(); File.Move(pdbPath, pdbPath); }
protected override Assembly Load(AssemblyName assemblyName) { // Override the assembly that was loaded in DefaultContext. string dirName = Path.GetDirectoryName(AssemblyPathHelper.GetAssemblyLocation(typeof(string).Assembly)); string assemblyPath = Path.Combine(dirName, assemblyName.Name + ".dll"); Assembly assembly = LoadFromAssemblyPath(assemblyPath); LoadedFromContext = true; return(assembly); }
public void LoadFrom_SameIdentityAsAssemblyWithDifferentPath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.LoadFrom(AssemblyPathHelper.GetAssemblyLocation(typeof(AssemblyTests).Assembly)); Assert.Equal(assembly1, typeof(AssemblyTests).Assembly); Assembly assembly2 = Assembly.LoadFrom(LoadFromTestPath); Assert.Equal(assembly1, assembly2); }
public static void Scenario_GetAssemblyName() { // Ensure you can do all this without resolving dependencies. using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(AssemblyPathHelper.GetAssemblyLocation(typeof(GenericClass1 <>).Assembly)); AssemblyName assemblyName = a.GetName(); Console.WriteLine(assemblyName.FullName); } }
public void AssemblyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(AssemblyPathHelper.GetAssemblyLocation(assembly)); Assembly loadedAssembly = Assembly.Load(aBytes); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); }
public void GetFile() { Assert.Throws <ArgumentNullException>(() => typeof(AssemblyTests).Assembly.GetFile(null)); AssertExtensions.Throws <ArgumentException>(null, () => typeof(AssemblyTests).Assembly.GetFile("")); Assert.Null(typeof(AssemblyTests).Assembly.GetFile("NonExistentfile.dll")); Assert.NotNull(typeof(AssemblyTests).Assembly.GetFile("System.Reflection.Tests.dll")); string name = AssemblyPathHelper.GetAssemblyLocation(typeof(AssemblyTests).Assembly); Assert.Equal(typeof(AssemblyTests).Assembly.GetFile("System.Reflection.Tests.dll").Name, name); }
public void CompiledAssembly_GetWithPathToAssemblySet_ReturnsExpectedAssembly() { var results = new CompilerResults(null) { PathToAssembly = AssemblyPathHelper.GetAssemblyLocation(typeof(CompilerResultsTests).Assembly) }; Assert.NotNull(results.CompiledAssembly); Assert.Equal(typeof(CompilerResultsTests).Assembly.FullName, results.CompiledAssembly.FullName); Assert.Same(results.CompiledAssembly, results.CompiledAssembly); }
public static void CoreGetTypeCacheCoverage3() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { // Make sure the tricky corner case of a null/empty namespace is covered. Assembly a = lc.LoadFromAssemblyPath(AssemblyPathHelper.GetAssemblyLocation(typeof(TopLevelType).Assembly)); Type t = a.GetType("TopLevelType", throwOnError: true, ignoreCase: false); Assert.Null(t.Namespace); Assert.Equal("TopLevelType", t.Name); } }
public void ShouldContainAllImplementations() { List <Type> types = AssemblyPathHelper.GetAllAssemblies() .AllTypesAssignableTo <IProfile>() .ToList(); Assert.IsTrue(types.Any(x => x.Name == "ClassChild")); Assert.IsTrue(types.Any(x => x.Name == "IInterfaceChild")); Assert.IsTrue(types.Any(x => x.Name == "Abstract")); Assert.IsTrue(types.Any(x => x.Name == "Concrete")); }
public void FullyQualifiedName() { var loc = AssemblyPathHelper.GetAssemblyLocation(Assembly.GetExecutingAssembly()); // Browser will include the path (/), so strip it if (PlatformDetection.IsBrowser && loc.Length > 1) { loc = loc.Substring(1); } Assert.Equal(loc, Module.FullyQualifiedName); }
public void AssemblyLoadFromBytesWithSymbols() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(AssemblyPathHelper.GetAssemblyLocation(assembly)); byte[] symbols = System.IO.File.ReadAllBytes((System.IO.Path.ChangeExtension(AssemblyPathHelper.GetAssemblyLocation(assembly), ".pdb"))); Assembly loadedAssembly = Assembly.Load(aBytes, symbols); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); }
public static void Scenario_EnumerateDependencies() { // Ensure you can do all this without resolving dependencies. using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(AssemblyPathHelper.GetAssemblyLocation(typeof(GenericClass1 <>).Assembly)); foreach (AssemblyName name in a.GetReferencedAssemblies()) { Console.WriteLine(name.FullName); } } }
public void TestCustomAttributeDecoderGenericArray() { Type type = typeof(HasGenericArrayAttributes); using (FileStream stream = File.OpenRead(AssemblyPathHelper.GetAssemblyLocation(type.GetTypeInfo().Assembly))) using (PEReader peReader = new PEReader(stream)) { MetadataReader reader = peReader.GetMetadataReader(); CustomAttributeTypeProvider provider = new CustomAttributeTypeProvider(); TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, type); IList <CustomAttributeData> attributes = type.GetCustomAttributesData(); foreach (CustomAttributeHandle attributeHandle in reader.GetCustomAttributes(typeDefHandle)) { CustomAttribute attribute = reader.GetCustomAttribute(attributeHandle); CustomAttributeValue <string> value = attribute.DecodeValue(provider); if (value.FixedArguments.Length == 2) { Assert.Equal(2, value.FixedArguments.Length); ImmutableArray <CustomAttributeTypedArgument <string> > array1 = (ImmutableArray <CustomAttributeTypedArgument <string> >)(value.FixedArguments[0].Value); Assert.Equal("int32[]", value.FixedArguments[0].Type); Assert.Equal(1, array1[0].Value); Assert.Equal(3, array1[2].Value); ImmutableArray <CustomAttributeTypedArgument <string> > array2 = (ImmutableArray <CustomAttributeTypedArgument <string> >)(value.FixedArguments[1].Value); Assert.Equal("uint8[]", value.FixedArguments[1].Type); Assert.Equal((byte)4, array2[0].Value); Assert.Equal((byte)5, array2[1].Value); Assert.Empty(value.NamedArguments); } else { Assert.Equal(1, value.FixedArguments.Length); Assert.Equal("uint8", value.FixedArguments[0].Type); Assert.Equal((byte)1, value.FixedArguments[0].Value); Assert.Equal(2, value.NamedArguments.Length); Assert.Equal("uint8", value.NamedArguments[0].Type); Assert.Equal((byte)2, value.NamedArguments[0].Value); ImmutableArray <CustomAttributeTypedArgument <string> > array = (ImmutableArray <CustomAttributeTypedArgument <string> >)(value.NamedArguments[1].Value); Assert.Equal("uint8[]", value.NamedArguments[1].Type); Assert.Equal((byte)3, array[0].Value); } } } }
public static void TestRestrictions() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(AssemblyPathHelper.GetAssemblyLocation(typeof(TopLevelType).Assembly)); #pragma warning disable SYSLIB0012 Assert.Throws <NotSupportedException>(() => a.CodeBase); Assert.Throws <NotSupportedException>(() => a.EscapedCodeBase); #pragma warning restore SYSLIB0012 Assert.Throws <NotSupportedException>(() => a.GetObjectData(null, default)); Assert.Throws <NotSupportedException>(() => a.GetSatelliteAssembly(null)); Assert.Throws <NotSupportedException>(() => a.GetSatelliteAssembly(null, null)); foreach (TypeInfo t in a.DefinedTypes) { Assert.Throws <InvalidOperationException>(() => t.IsSecurityCritical); Assert.Throws <InvalidOperationException>(() => t.IsSecuritySafeCritical); Assert.Throws <InvalidOperationException>(() => t.IsSecurityTransparent); foreach (MemberInfo mem in t.GetMember("*", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)) { ICustomAttributeProvider icp = mem; Assert.Throws <InvalidOperationException>(() => icp.GetCustomAttributes(inherit: false)); Assert.Throws <InvalidOperationException>(() => icp.GetCustomAttributes(null, inherit: false)); Assert.Throws <InvalidOperationException>(() => icp.IsDefined(null, inherit: false)); if (mem is ConstructorInfo c) { Assert.Throws <InvalidOperationException>(() => c.Invoke(Array.Empty <object>())); Assert.Throws <InvalidOperationException>(() => c.Invoke(default(BindingFlags), null, Array.Empty <object>(), null)); Assert.Throws <InvalidOperationException>(() => c.Invoke(null, Array.Empty <object>())); Assert.Throws <InvalidOperationException>(() => c.Invoke(null, default(BindingFlags), null, Array.Empty <object>(), null)); Assert.Throws <InvalidOperationException>(() => c.MethodHandle); Assert.Throws <InvalidOperationException>(() => c.IsSecurityCritical); Assert.Throws <InvalidOperationException>(() => c.IsSecuritySafeCritical); Assert.Throws <InvalidOperationException>(() => c.IsSecurityTransparent); } if (mem is EventInfo e) { Assert.Throws <InvalidOperationException>(() => e.AddEventHandler(null, null)); Assert.Throws <InvalidOperationException>(() => e.RemoveEventHandler(null, null)); } if (mem is FieldInfo f) { Assert.Throws <InvalidOperationException>(() => f.FieldHandle); Assert.Throws <InvalidOperationException>(() => f.GetValue(null)); Assert.Throws <InvalidOperationException>(() => f.GetValueDirect(default));
public void FullyQualifiedName() { #if SINGLE_FILE_TEST_RUNNER Assert.Equal("<Unknown>", Module.FullyQualifiedName); #else var loc = AssemblyPathHelper.GetAssemblyLocation(Assembly.GetExecutingAssembly()); // Browser will include the path (/), so strip it if (PlatformDetection.IsBrowser && loc.Length > 1) { loc = loc.Substring(1); } Assert.Equal(loc, Module.FullyQualifiedName); #endif }
public static void CoreGetTypeCacheCoverage2() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(AssemblyPathHelper.GetAssemblyLocation(typeof(SampleMetadata.NS0.SameNamedType).Assembly)); // Create big hash collisions in GetTypeCoreCache. for (int i = 0; i < 16; i++) { string ns = "SampleMetadata.NS" + i; string name = "SameNamedType"; string fullName = ns + "." + name; Type t = a.GetType(fullName, throwOnError: true); Assert.Equal(fullName, t.FullName); } } }
public void TestCustomAttributeDecoderGenericUsingReflection() { Type type = typeof(HasGenericAttributes); using (FileStream stream = File.OpenRead(AssemblyPathHelper.GetAssemblyLocation(type.GetTypeInfo().Assembly))) using (PEReader peReader = new PEReader(stream)) { MetadataReader reader = peReader.GetMetadataReader(); CustomAttributeTypeProvider provider = new CustomAttributeTypeProvider(); TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, type); IList <CustomAttributeData> attributes = type.GetCustomAttributesData(); int i = 0; foreach (CustomAttributeHandle attributeHandle in reader.GetCustomAttributes(typeDefHandle)) { CustomAttribute attribute = reader.GetCustomAttribute(attributeHandle); CustomAttributeValue <string> value = attribute.DecodeValue(provider); CustomAttributeData reflectionAttribute = attributes[i++]; Assert.Equal(reflectionAttribute.ConstructorArguments.Count, value.FixedArguments.Length); Assert.Equal(reflectionAttribute.NamedArguments.Count, value.NamedArguments.Length); int j = 0; foreach (CustomAttributeTypedArgument <string> arguments in value.FixedArguments) { Assert.Equal(TypeToString(reflectionAttribute.ConstructorArguments[j].ArgumentType), arguments.Type); if (reflectionAttribute.ConstructorArguments[j].Value.ToString() != arguments.Value.ToString()) { Assert.Equal(reflectionAttribute.ConstructorArguments[j].Value, arguments.Value); } j++; } j = 0; foreach (CustomAttributeNamedArgument <string> arguments in value.NamedArguments) { Assert.Equal(TypeToString(reflectionAttribute.NamedArguments[j].TypedValue.ArgumentType), arguments.Type); if (reflectionAttribute.NamedArguments[j].TypedValue.Value.ToString() != arguments.Value.ToString()) { Assert.Equal(reflectionAttribute.NamedArguments[j].TypedValue.Value, arguments.Value); } j++; } } } }
public void GetFiles() { var asm = typeof(AssemblyTests).Assembly; if (asm.Location.Length > 0) { Assert.NotNull(asm.GetFiles()); Assert.Equal(1, asm.GetFiles().Length); string name = AssemblyPathHelper.GetAssemblyLocation(asm); Assert.Equal(asm.GetFiles()[0].Name, name); } else { Assert.Throws <FileNotFoundException>(() => asm.GetFiles()); } }
public static void PathAssemblyResolverBasicPathWithRunningAssemblies() { string coreAssemblyPath = TestUtils.GetPathToCoreAssembly(); // Obtain this test class string thisAssemblyPath = AssemblyPathHelper.GetAssemblyLocation(typeof(MetadataLoadContextTests).Assembly); var resolver = new PathAssemblyResolver(new string[] { coreAssemblyPath, thisAssemblyPath }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver, TestUtils.GetNameOfCoreAssembly())) { AssemblyName thisAssemblyName = typeof(MetadataLoadContextTests).Assembly.GetName(); Assembly assembly = lc.LoadFromAssemblyName(thisAssemblyName); Type t = assembly.GetType(typeof(MetadataLoadContextTests).FullName, throwOnError: true); Assert.Equal(t.FullName, typeof(MetadataLoadContextTests).FullName); Assert.Equal(t.Assembly.Location, thisAssemblyPath); } }
public void WrongSignatureType() { using (FileStream stream = File.OpenRead(AssemblyPathHelper.GetAssemblyLocation(typeof(VarArgsToDecode).GetTypeInfo().Assembly))) using (var peReader = new PEReader(stream)) { MetadataReader reader = peReader.GetMetadataReader(); var provider = new DisassemblingTypeProvider(); var decoder = new SignatureDecoder <string, DisassemblingGenericContext>(provider, reader, genericContext: null); BlobReader fieldSignature = reader.GetBlobReader(reader.GetFieldDefinition(MetadataTokens.FieldDefinitionHandle(1)).Signature); BlobReader methodSignature = reader.GetBlobReader(reader.GetMethodDefinition(MetadataTokens.MethodDefinitionHandle(1)).Signature); BlobReader propertySignature = reader.GetBlobReader(reader.GetPropertyDefinition(MetadataTokens.PropertyDefinitionHandle(1)).Signature); Assert.Throws <BadImageFormatException>(() => decoder.DecodeMethodSignature(ref fieldSignature)); Assert.Throws <BadImageFormatException>(() => decoder.DecodeFieldSignature(ref methodSignature)); Assert.Throws <BadImageFormatException>(() => decoder.DecodeLocalSignature(ref propertySignature)); } }
public void AssemblyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(AssemblyPathHelper.GetAssemblyLocation(assembly)); Assembly loadedAssembly = Assembly.Load(aBytes); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); System.Runtime.Loader.AssemblyLoadContext alc = System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(loadedAssembly); string expectedName = "Assembly.Load(byte[], ...)"; Assert.Equal(expectedName, alc.Name); Assert.Contains(expectedName, alc.ToString()); Assert.Contains("System.Runtime.Loader.IndividualAssemblyLoadContext", alc.ToString()); }
public void GetFile() { var asm = typeof(AssemblyTests).Assembly; if (asm.Location.Length > 0) { Assert.Throws <ArgumentNullException>(() => asm.GetFile(null)); Assert.Throws <ArgumentException>(() => asm.GetFile("")); Assert.Null(asm.GetFile("NonExistentfile.dll")); Assert.NotNull(asm.GetFile("System.Reflection.Tests.dll")); string name = AssemblyPathHelper.GetAssemblyLocation(asm); Assert.Equal(asm.GetFile("System.Reflection.Tests.dll").Name, name); } else { Assert.Throws <FileNotFoundException>(() => asm.GetFile("System.Reflection.Tests.dll")); } }
/// <summary> /// Attempts to find and load an <see cref="Assembly"/> when the requesting <see cref="Assembly"/> /// is known. /// </summary> /// <remarks> /// This method differs from <see cref="ResolveForUnknownRequestor(string)"/> in a couple of ways. /// First, we only attempt to handle the load if the requesting assembly is one we've loaded. /// If it isn't one of ours, then presumably some other component is hooking <see cref="AppDomain.AssemblyResolve"/> /// and will have a better idea of how to load the assembly. /// Second, we only look immediately next to the requesting assembly, instead of next to all the assemblies /// we've previously loaded. An analyzer needs to ship with all of its dependencies, and if it doesn't we don't /// want to mask the problem. /// </remarks> private static Assembly ResolveForKnownRequestor(string requestedAssemblyName, Assembly requestingAssembly) { lock (s_guard) { string requestingAssemblyName = requestingAssembly.FullName; string requestingAssemblyFullPath; if (!s_filesFromAssemblyNames.TryGetValue(requestingAssemblyName, out requestingAssemblyFullPath)) { // The requesting assembly is not one of ours; don't try to satisfy the request. return(null); } string nameWithPolicyApplied = AppDomain.CurrentDomain.ApplyPolicy(requestedAssemblyName); Assembly assembly; if (s_assembliesFromNames.TryGetValue(nameWithPolicyApplied, out assembly)) { // We've already loaded an assembly by this name; use that. return(assembly); } AssemblyIdentity assemblyIdentity; if (!AssemblyIdentity.TryParseDisplayName(nameWithPolicyApplied, out assemblyIdentity)) { return(null); } string directoryPath = Path.GetDirectoryName(requestingAssemblyFullPath); string assemblyFullPath = AssemblyPathHelper.GetCandidatePath(directoryPath, assemblyIdentity); if (!File.Exists(assemblyFullPath)) { return(null); } assembly = LoadCore(assemblyFullPath); s_requestingFilesFromFiles[assemblyFullPath] = requestingAssemblyFullPath; return(assembly); } }
private void AnalyseSwiftpassPayResponse() { string filePath = AssemblyPathHelper.GetAssemblyPath() + "Resource/SwiftPayResponse.xml"; if (!File.Exists(filePath)) { Console.WriteLine("File not exist"); } XmlDocument doc = new XmlDocument(); doc.Load(filePath); XmlNode nodes = doc.FirstChild; string status = nodes.SelectSingleNode("status").InnerText; string resultCode = nodes.SelectSingleNode("result_code").InnerText; string payInfoNodeJson = nodes.SelectSingleNode("pay_info").InnerText; JObject payInfoObj = (JObject)JsonConvert.DeserializeObject(payInfoNodeJson); }