/// <summary> /// Gets the assemblies in the current application domain. /// </summary> /// <returns></returns> public Assembly[] GetAssemblies() { if (_loadedAssemblies == null) { _loadedAssemblies = new List<Assembly>(); var folder = Package.Current.InstalledLocation; var operation = folder.GetFilesAsync(); var task = operation.AsTask(); task.Wait(); foreach (var file in task.Result) { if (file.FileType == ".dll" || file.FileType == ".exe") { var filename = file.Name.Substring(0, file.Name.Length - file.FileType.Length); var name = new AssemblyName { Name = filename }; var asm = Assembly.Load(name); _loadedAssemblies.Add(asm); } } } return _loadedAssemblies.ToArray(); }
static int Main(string[] args) { Options options = new Options(); List<Export> exports = new List<Export>(); if (!ParseArgs(args, options) || !ParseDefFile(options.deffile, exports)) { return 1; } AssemblyName name = new AssemblyName(Path.GetFileNameWithoutExtension(options.outputFile)); name.Version = options.version; name.KeyPair = options.key; AssemblyBuilder ab = universe.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save); ModuleBuilder modb = ab.DefineDynamicModule(name.Name, options.outputFile); foreach (Export exp in exports) { ExportMethod(modb, exp); } modb.CreateGlobalFunctions(); if (options.win32res != null) { ab.DefineUnmanagedResource(options.win32res); } else { if (options.description != null) { ab.SetCustomAttribute(new CustomAttributeBuilder(universe.Import(typeof(System.Reflection.AssemblyTitleAttribute)).GetConstructor(new Type[] { universe.Import(typeof(string)) }), new object[] { options.description })); } ab.DefineVersionInfoResource(options.product, options.version.ToString(), options.company, options.copyright, null); } ab.Save(options.outputFile, options.peKind, options.machine); return 0; }
private static void _Startup() { AssemblyName[] referencAssemblyNames = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); AssemblyName[] allAssemblyNames = new AssemblyName[referencAssemblyNames.Length + 1]; referencAssemblyNames.CopyTo(allAssemblyNames, 1); allAssemblyNames[0] = Assembly.GetExecutingAssembly().GetName(); foreach (AssemblyName assemblyName in allAssemblyNames) { Assembly assembly = Assembly.Load(assemblyName); Type[] types = assembly.GetTypes(); foreach (Type type in types) { if(typeLookupTable.ContainsKey(type.FullName)) continue; typeLookupTable.Add(type.FullName, type); if (type.IsDefined(typeof (OldName), false)) { OldName oldNameInfo = (OldName) type.GetCustomAttributes(typeof (OldName), false)[0]; oldNameLookupTable.Add(oldNameInfo.Name, type.FullName); } } } }
static void NotCreated () { AssemblyName assemblyName = new AssemblyName (); assemblyName.Name = "Lib"; AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly ( assemblyName, AssemblyBuilderAccess.RunAndSave, AppDomain.CurrentDomain.BaseDirectory); ModuleBuilder module = assembly.DefineDynamicModule ("Lib"); TypeBuilder tb = module.DefineType ("Foo", TypeAttributes.Class, null, new Type [] { typeof (IBar) }); tb.DefineGenericParameters ("T"); Type typeBarOfInt32 = tb.MakeGenericType (typeof (int)); Assert.IsFalse (typeof (IComparable).IsAssignableFrom (typeBarOfInt32), "#A1"); Assert.IsFalse (typeof (IBar).IsAssignableFrom (typeBarOfInt32), "#A2"); tb.CreateType (); typeBarOfInt32 = tb.MakeGenericType (typeof (int)); Assert.IsFalse (typeof (IComparable).IsAssignableFrom (typeBarOfInt32), "#A3"); Assert.IsFalse (typeof (IBar).IsAssignableFrom (typeBarOfInt32), "#A4"); }
public int QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref AssemblyName.ASSEMBLY_INFO pAsmInfo) { pAsmInfo = new AssemblyName.ASSEMBLY_INFO(); pAsmInfo.cbAssemblyInfo = 1; // just needs to be nonzero for our purposes // All they need here is pszCurrentAssemblyPathBuf to be filled out. // pszAssemblyName is the strong name (as returned from MonoAssemblyName.GetDisplayName), // like "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" // // Mono stores them in monoDir\lib\mono\gac\ASSEMBLY_NAME\VERSION__PUBLICKEYTOKEN\ASSEMBLY_NAME.dll // // .. so this strong name : "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" // .. would be located here: monoDir\lib\mono\gac\System.Core\4.0.0.0__b77a5c561934e089\System.Core.dll string [] parts = pszAssemblyName.Split( new string[] {", "}, StringSplitOptions.RemoveEmptyEntries ); string sAssemblyName = parts[0]; string sVersion = parts[1].Split( new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries )[1]; string sPublicKeyToken = parts[3].Split( new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries )[1]; string sGACDir = MonoGACHelpers.GetGACDir(); sGACDir = Path.Combine( sGACDir, sAssemblyName ); sGACDir = Path.Combine( sGACDir, sVersion + "__" + sPublicKeyToken ); pAsmInfo.pszCurrentAssemblyPathBuf = Path.Combine( sGACDir, sAssemblyName + ".dll" ); Debug.Assert( false ); return 0; }
public void TestSetCustomAttribute2() { string name = "Assembly1"; AssemblyName asmname = new AssemblyName(); asmname.Name = name; AssemblyBuilder asmbuild = AssemblyBuilder.DefineDynamicAssembly(asmname, AssemblyBuilderAccess.Run); ModuleBuilder modbuild = TestLibrary.Utilities.GetModuleBuilder(asmbuild, "Module1"); TypeBuilder tpbuild = modbuild.DefineType("C1"); MethodBuilder methbuild = tpbuild.DefineMethod("method1", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { typeof(int) }); ParameterBuilder parambuild = methbuild.DefineParameter(1, ParameterAttributes.HasDefault, "testParam"); ILGenerator ilgen = methbuild.GetILGenerator(); ilgen.Emit(OpCodes.Ret); parambuild.SetCustomAttribute(typeof(MBMyAttribute3).GetConstructor(new Type[] { typeof(bool)}), new byte[] { 01,00,01,00,00}); Type tp = tpbuild.CreateTypeInfo().AsType(); MethodInfo md = tp.GetMethod("method1"); ParameterInfo pi = md.GetParameters()[0]; // VERIFY object[] attribs = pi.GetCustomAttributes(false).Select(a => (object)a).ToArray(); Assert.Equal(1, attribs.Length); MBMyAttribute3 obj = (MBMyAttribute3)attribs[0]; Assert.True(obj.booleanValue); }
public void CreateDynamicMethod() { #if SAVE_ASSEMBLY if (_assemblyBuilder == null) { AssemblyName assemblyName = new AssemblyName("ExpressionAssembly"); _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, "I:\\Trash"); _moduleBuilder = _assemblyBuilder.DefineDynamicModule("ExpressionModule", "ExpressionModule.module"); } string typeName = String.Format("Expression{0}", _typeCount); _typeCount++; _typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public); FieldBuilder filedBuilder = _typeBuilder.DefineField("Source", typeof(string), FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal); filedBuilder.SetConstant(_source); _methodBuilder = _typeBuilder.DefineMethod("Evaluate", MethodAttributes.Public | MethodAttributes.Static, typeof(object), new Type[] { typeof(object[]) }); _ilGenerator = _methodBuilder.GetILGenerator(); #else _dynamicMethod = new DynamicMethod("Expression", typeof(object), new Type[] { typeof(object[]) }, GetType().Module); _ilGenerator = _dynamicMethod.GetILGenerator(); #endif }
public static void Main() { AssemblyName name = new AssemblyName(); name.Name="HelloWorld"; //.assembly HelloWorld{} AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name,AssemblyBuilderAccess.RunAndSave); ModuleBuilder mod = asmBuilder.DefineDynamicModule ("HelloWorld","HelloWorld.exe");//.module HelloWorld.exe //.class private auto ansi initbeforefield Helloworld TypeBuilder myClass = mod.DefineType("HelloWorld",TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit,null,PackingSize.Unspecified); //.method public hidebysig static void Main() cil managed MethodBuilder method = myClass.DefineMethod("Main",MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig ,CallingConventions.Standard,typeof(void),null); ILGenerator ilGen = method.GetILGenerator(); ilGen.Emit(OpCodes.Ldstr,"Hello World"); //ldstr "Hello World" MethodInfo writeLineInfo = typeof(System.Console).GetMethod ( "WriteLine" , BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, CallingConventions.Any | CallingConventions.VarArgs , new Type[] {typeof(string)},null ); ilGen.EmitCall(OpCodes.Call,writeLineInfo,null);//call void [mscorlib]System.Console::Write(string) ilGen.Emit(OpCodes.Ret);//ret asmBuilder.SetEntryPoint(method);//make .entrypoint myClass.CreateType(); Console.WriteLine("Run before save:"); myClass.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public ,null, null,null); asmBuilder.Save("HelloWorld.exe"); Console.WriteLine("HelloWorld.exe saved...\nRun after save:"); AppDomain.CurrentDomain.ExecuteAssembly("HelloWorld.exe"); }
private AssemblyName GetNameImpl(ref AssemblyTable.Record rec) { AssemblyName name = new AssemblyName(); name.Name = manifestModule.GetString(rec.Name); name.Version = new Version(rec.MajorVersion, rec.MinorVersion, rec.BuildNumber, rec.RevisionNumber); if (rec.PublicKey != 0) { name.SetPublicKey(manifestModule.GetBlobCopy(rec.PublicKey)); } else { name.SetPublicKey(Empty<byte>.Array); } if (rec.Culture != 0) { name.Culture = manifestModule.GetString(rec.Culture); } else { name.Culture = ""; } name.HashAlgorithm = (AssemblyHashAlgorithm)rec.HashAlgId; name.CodeBase = this.CodeBase; name.RawFlags = (AssemblyNameFlags)rec.Flags; return name; }
static void Main(string[] args) { AssemblyName an = new AssemblyName(); an.Name = "HelloWorld"; AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave); ModuleBuilder module = ab.DefineDynamicModule("b.dll"); TypeBuilder tb = module.DefineType("type", TypeAttributes.Public | TypeAttributes.Class); MethodBuilder mb = tb.DefineMethod("test", MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.Public, typeof(void), null); ILGenerator ig = mb.GetILGenerator(); // // This is the actual test: // Generate a method signature that contains modopts and modreqs // and call that. It has no name or anything, not sure how this // is actually used, but we at least generate the stuff // SignatureHelper sh = SignatureHelper.GetMethodSigHelper (module, CallingConventions.HasThis, typeof(int)); sh.AddArgument (typeof (bool)); Type [] req = new Type [] { typeof (System.Runtime.CompilerServices.IsBoxed) }; sh.AddArgument (typeof (string), req, null); Type [] opt = new Type [] { typeof (System.Runtime.CompilerServices.IsConst) }; sh.AddArgument (typeof (byte), null, opt); sh.AddArgument (typeof (int), null, opt); sh.AddArgument (typeof (long), null, opt); ig.Emit (OpCodes.Call, sh); ig.Emit(OpCodes.Ret); tb.CreateType(); ab.Save ("b.dll"); }
public static int Main() { try { Console.WriteLine ("expect a FileLoadException"); AssemblyName assemblyName = new AssemblyName("System, PublicKeyToken=00000000000000000400000000000000"); Console.WriteLine(assemblyName.FullName); } catch (FileLoadException e) { Console.WriteLine (e); Console.WriteLine ("expected exception!"); Console.WriteLine ("test pass"); return 100; } catch (Exception e) { Console.WriteLine (e); Console.WriteLine ("unexpected exception"); Console.WriteLine ("test fails"); return 1; } Console.WriteLine ("no exception"); Console.WriteLine ("test fails"); return 1; }
public static int Main() { try { #if DESKTOP Assembly a = Assembly.Load("system, processorArchitecture=somebadvalue"); #else AssemblyName an = new AssemblyName("system, processorArchitecture=somebadvalue"); #endif } catch(System.IO.FileLoadException e) { if(e.ToString().ToUpper().IndexOf("UNKNOWN ERROR") == -1) { //we didn't get "Unknown error" in the exception text Console.WriteLine("Pass"); return 100; } else { Console.WriteLine("Wrong exception text: " + e.ToString()); Console.WriteLine("FAIL"); return 101; } } Console.WriteLine("Didn't catch FileLoadException. FAIL"); return 99; }
public static int Check(AssemblyName asmN){ String strVersion = asmN.ToString(); int index = strVersion.ToLower().IndexOf("version="); if(asmN.Version==null){ if(index==-1){ Console.WriteLine("Passed: both asmName.ToString() version and asmName.Version are null."); return 100; }else{ Console.WriteLine("Failed: asmName.Version != asmName.ToString() Version"); Console.WriteLine ("\tasmName.Version = \"{0}\"", asmN.Version); Console.WriteLine ("\tasmName.ToString() = \"{0}\"", strVersion); return 101; } }else{ strVersion = strVersion.Substring(index+8,7); if(strVersion.Equals(asmN.Version.ToString())){ Console.WriteLine("Passed: asmName.Version == asmName.ToString() Version"); return 100; }else{ Console.WriteLine("Failed: asmName.Version != asmName.ToString() Version"); Console.WriteLine ("\tasmName.Version = \"{0}\"", asmN.Version); Console.WriteLine ("\tasmName.ToString() = \"{0}\"", strVersion); return 101; } } }
public static Assembly ResolveAssembly(string assemblyName) { if (nullCache.ContainsKey(assemblyName)) { return null; } var requestedAssemblyName = new AssemblyName(assemblyName); var assembly = Common.ReadExistingAssembly(requestedAssemblyName); if (assembly != null) { return assembly; } Common.Log("Loading assembly '{0}' into the AppDomain", requestedAssemblyName); assembly = Common.ReadFromEmbeddedResources(assemblyNames, symbolNames, requestedAssemblyName); if (assembly == null) { nullCache.Add(assemblyName, true); // Handles retargeted assemblies like PCL if (requestedAssemblyName.Flags == AssemblyNameFlags.Retargetable) { assembly = Assembly.Load(requestedAssemblyName); } } return assembly; }
public static void Main(string[] args) { string basedir = AppDomain.CurrentDomain.BaseDirectory; using (FileStream fs = File.Open (Path.Combine (basedir, "key.snk"), FileMode.Open)) { AssemblyName asmname = new AssemblyName (); asmname.Name = "snafu2"; asmname.KeyPair = new StrongNameKeyPair (fs); AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly (asmname, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mod = asm.DefineDynamicModule (asmname.Name + ".dll"); TypeBuilder type = mod.DefineType ("bar", TypeAttributes.Public); MethodBuilder meth = type.DefineMethod ("foo", MethodAttributes.Static | MethodAttributes.Public, typeof (string), Type.EmptyTypes); ILGenerator il = meth.GetILGenerator (); il.Emit (OpCodes.Newobj, typeof (other.MainClass).GetConstructor (Type.EmptyTypes)); il.Emit (OpCodes.Call, typeof (other.MainClass).GetMethod ("Main", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)); il.Emit (OpCodes.Ret); Type t = type.CreateType (); asm.Save (asmname.Name + ".dll"); Assembly baked = Assembly.LoadFrom (Path.Combine (basedir, asmname.Name + ".dll")); Assert.AreEqual ("internal", baked.GetType ("bar").GetMethod ("foo").Invoke (null, null), "#1"); Assert.AreEqual ("internal", t.GetMethod ("foo").Invoke (null, null), "#2"); } }
ResolveEventHandler CreateEventHandler(string assemblyPath) { var basePath = Path.GetDirectoryName (assemblyPath); return (obj, args) => { try { var assemblyFullName = new AssemblyName(args.Name); var assemblyShortName = assemblyFullName.Name; var location = Path.Combine(basePath, args.Name); if (File.Exists(location + ".dll")) { return Assembly.LoadFile(location + ".dll"); } if (File.Exists(location + ".exe")) { return Assembly.LoadFile(location + ".exe"); } return null; } catch { return null; } }; }
internal static void Parse(AssemblyName blank, String s) { if (s == null) throw new ArgumentNullException(); RuntimeAssemblyName runtimeAssemblyName = Parse(s); runtimeAssemblyName.CopyToAssemblyName(blank); }
public InvalidAssemblyRenameMessage(AssemblyName sourceName, AssemblyName existTargetName, AssemblyName newTargetName) : base(null, Severity.Error, "1003") { SourceName = sourceName; ExistTargetName = existTargetName; NewTargetName = newTargetName; }
public static int Main () { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "customMod"; assemblyName.Version = new Version (1, 2, 3, 4); AssemblyBuilder assembly = Thread.GetDomain().DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder module = assembly.DefineDynamicModule("res.exe", "res.exe"); TypeBuilder genericFoo = module.DefineType ("GenericFoo", TypeAttributes.Public, typeof (object)); genericArgs = genericFoo.DefineGenericParameters ("T"); fooOpenInst = genericFoo.MakeGenericType (genericArgs); EmitCtor (genericFoo); EmitTargetMethod (genericFoo); EmitTestEvents (genericFoo); TypeBuilder moduletype = module.DefineType ("ModuleType", TypeAttributes.Public, typeof (object)); MethodBuilder main = moduletype.DefineMethod ("Main", MethodAttributes.Public | MethodAttributes.Static, typeof (void), null); ILGenerator il = main.GetILGenerator (); Type strInst = genericFoo.MakeGenericType (typeof (string)); il.Emit (OpCodes.Newobj, TypeBuilder.GetConstructor (strInst, ctor)); il.Emit (OpCodes.Callvirt, TypeBuilder.GetMethod (strInst, testEvents)); il.Emit (OpCodes.Ret); genericFoo.CreateType (); Type res = moduletype.CreateType (); res.GetMethod ("Main").Invoke (null, null); return 0; }
/// <summary> /// Returns the original location of the corresponding assembly if available, otherwise returns the location of the shadow copy. /// If the corresponding assembly is not in the GAC, null is returned. /// </summary> public static string GetLocation(AssemblyReference assemblyReference){ if (assemblyReference == null) { Debug.Fail("assemblyReference == null"); return null; } lock(GlobalAssemblyCache.Lock){ if (!GlobalAssemblyCache.FusionLoaded){ GlobalAssemblyCache.FusionLoaded = true; System.Reflection.Assembly systemAssembly = typeof(object).Assembly; //^ assume systemAssembly != null && systemAssembly.Location != null; string dir = Path.GetDirectoryName(systemAssembly.Location); //^ assume dir != null; GlobalAssemblyCache.LoadLibrary(Path.Combine(dir, "fusion.dll")); } IAssemblyEnum assemblyEnum; CreateAssemblyEnum(out assemblyEnum, null, null, ASM_CACHE.GAC, 0); if (assemblyEnum == null) return null; IApplicationContext applicationContext; IAssemblyName currentName; while (assemblyEnum.GetNextAssembly(out applicationContext, out currentName, 0) == 0){ //^ assume currentName != null; AssemblyName aName = new AssemblyName(currentName); if (assemblyReference.Matches(aName.Name, aName.Version, aName.Culture, aName.PublicKeyToken)){ string codeBase = aName.CodeBase; if (codeBase != null && codeBase.StartsWith("file:///")) return codeBase.Substring(8); return aName.GetLocation(); } } return null; } }
/// <param name="codeBaseUri">Uri pointing to the assembly</param> public static bool Contains(Uri codeBaseUri){ if (codeBaseUri == null) { Debug.Fail("codeBaseUri == null"); return false; } lock(GlobalAssemblyCache.Lock){ if (!GlobalAssemblyCache.FusionLoaded){ GlobalAssemblyCache.FusionLoaded = true; System.Reflection.Assembly systemAssembly = typeof(object).Assembly; //^ assume systemAssembly != null && systemAssembly.Location != null; string dir = Path.GetDirectoryName(systemAssembly.Location); //^ assume dir != null; GlobalAssemblyCache.LoadLibrary(Path.Combine(dir, "fusion.dll")); } IAssemblyEnum assemblyEnum; int rc = GlobalAssemblyCache.CreateAssemblyEnum(out assemblyEnum, null, null, ASM_CACHE.GAC, 0); if (rc < 0 || assemblyEnum == null) return false; IApplicationContext applicationContext; IAssemblyName currentName; while (assemblyEnum.GetNextAssembly(out applicationContext, out currentName, 0) == 0){ //^ assume currentName != null; AssemblyName assemblyName = new AssemblyName(currentName); string scheme = codeBaseUri.Scheme; if (scheme != null && assemblyName.CodeBase.StartsWith(scheme)){ try{ Uri foundUri = new Uri(assemblyName.CodeBase); if (codeBaseUri.Equals(foundUri)) return true; #if !FxCop }catch(Exception){ #else }finally{ #endif } } } return false; } }
public static int Main() { try { AssemblyName an = new AssemblyName("noname,PublicKeyToken=null"); int expected = 0; if (an.GetPublicKeyToken() == null) { Console.WriteLine("!!!ERROR-001: Public key token unexpectedly null. Expected length: " + expected.ToString()); Console.WriteLine("FAIL"); return 98; } if (an.GetPublicKeyToken().Length != expected) { Console.WriteLine("!!!ERROR-002: Public key token length not as expected. Expected: " + expected.ToString() + ", Actual: " + an.GetPublicKeyToken().Length.ToString()); Console.WriteLine("FAIL"); return 99; } } catch (Exception e) { Console.WriteLine("!!!ERROR-XXX: Unexpected exception : " + e); Console.WriteLine("FAIL"); return 101; } Console.WriteLine("Pass"); return 100; }
public static int test_0_load_dynamic() { AssemblyName an = new AssemblyName(); an.Name = "NOT.EXISTS"; AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = ab.DefineDynamicModule("NOT.EXISTS"); Assembly b = Assembly.LoadWithPartialName ("NOT.EXISTS"); if (b == null) return 0; else return 1; }
public static Assembly ResolveAssembly(object sender, ResolveEventArgs args) { var name = new AssemblyName(args.Name).Name.ToLowerInvariant(); var existingAssembly = ReadExistingAssembly(name); if (existingAssembly != null) { return existingAssembly; } var prefix = string.Concat("costura.", name); var executingAssembly = Assembly.GetExecutingAssembly(); byte[] assemblyData; using (var assemblyStream = GetAssemblyStream(executingAssembly, prefix)) { if (assemblyStream == null) { return null; } assemblyData = ReadStream(assemblyStream); } using (var pdbStream = GetDebugStream(executingAssembly, prefix)) { if (pdbStream != null) { var pdbData = ReadStream(pdbStream); return Assembly.Load(assemblyData, pdbData); } } return Assembly.Load(assemblyData); }
public AboutViewModel() { string name = Assembly.GetExecutingAssembly().FullName; AssemblyName assemblyName = new AssemblyName(name); Version = assemblyName.Version.ToString(); }
private Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) { var name = new AssemblyName(args.Name).Name; var searchPaths = new[] { "", Path.Combine(name, "bin", "net45") }; var basePath = _originalApplicationBase ?? AppDomain.CurrentDomain.SetupInformation.ApplicationBase; foreach (var searchPath in searchPaths) { var path = Path.Combine(basePath, searchPath, name + ".dll"); if (File.Exists(path)) { return Assembly.LoadFile(path); } } return null; }
public void CanAddAttribute() { var type = typeof (SomeClass); AssemblyName aName = new AssemblyName("SomeNamespace"); AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); TypeBuilder tb = mb.DefineType(type.Name, TypeAttributes.Public, type); TypeDescriptor.AddAttributes(type); Type[] attrCtorParams = {typeof (string)}; ConstructorInfo attrCtorInfo = typeof (DynamicAttribute).GetConstructor(attrCtorParams); if (attrCtorInfo != null) { CustomAttributeBuilder attrBuilder = new CustomAttributeBuilder(attrCtorInfo, new object[] {"Some Value"}); tb.SetCustomAttribute(attrBuilder); } Type newType = tb.CreateType(); SomeClass instance = (SomeClass) Activator.CreateInstance(newType); DynamicAttribute attr = (DynamicAttribute) instance.GetType().GetCustomAttributes(typeof (DynamicAttribute), false).SingleOrDefault(); Assert.AreEqual("Test", instance.Value); Assert.IsNotNull(attr); Assert.AreEqual(attr.Value, "Some Value"); }
private static Assembly CurrentDomainOnAssemblyResolve(object sender, ResolveEventArgs args) { string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var name = new AssemblyName(args.Name).Name; var path = Path.Combine(dir, name + ".dll"); Assembly assembly = Assembly.LoadFile(path); return assembly; }
static ModuleBuilder CreateModule (string name) { AppDomain myDomain = System.Threading.Thread.GetDomain (); AssemblyName myAsmName = new AssemblyName (); myAsmName.Name = name; AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly (myAsmName, AssemblyBuilderAccess.RunAndSave); return myAsmBuilder.DefineDynamicModule (name, name + ".dll"); }
public AssemblyResultTests() { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = assembly; AppDomain appDomain = Thread.GetDomain(); builder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); }
public Assembly Load(AssemblyName assemblyName) { return(AssemblyHelper.LoadAssembly(assemblyName)); }
public static void Main(string[] args) { AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => { var resourceName = new AssemblyName(eventArgs.Name).Name + ".dll"; var programDirectory = Assembly.GetExecutingAssembly().Location; if (File.Exists(Path.Combine(programDirectory, resourceName))) { return(Assembly.Load(File.ReadAllBytes(Path.Combine(programDirectory, resourceName)))); } var text = Array.Find(typeof(BitsByte).Assembly.GetManifestResourceNames(), element => element.EndsWith(resourceName)); if (text == null) { return(null); } using (var manifestResourceStream = typeof(BitsByte).Assembly.GetManifestResourceStream(text)) { if (manifestResourceStream == null) { return(null); } var data = new byte[manifestResourceStream.Length]; manifestResourceStream.Read(data, 0, data.Length); return(Assembly.Load(data)); } }; AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { var sb = new StringBuilder("Unhandled Exception") .AppendLine() .Append("================\r\n") .AppendFormat("{0}: Unhandled Exception\r\nCulture: {1}\r\nException: {2}\r\n", DateTime.Now, Thread.CurrentThread.CurrentCulture.Name, eventArgs.ExceptionObject.ToString()) .Append("================\r\n"); Logger.Error(sb); Environment.Exit(1); }; ConfigureLogger(); #if DEBUG //Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("zh-CN"); #endif if (args.Length == 0) { args = new[] { #if DEBUG "--mode", "patch", "-f", "ThoriumMod", "-l", "English", "Test.tmod", #else "-h" #endif }; } Logger.Debug(Strings.ProgramVersion, typeof(Program).Namespace, typeof(Program).Assembly.GetName().Version); if (ParseCliArguments(args)) { Process(); Logger.Fatal(Strings.ProcessComplete); } #if DEBUG Console.ReadLine(); #endif }
public void DefineDynamicAssembly_AssemblyName_AssemblyBuilderAccess_CustomAttributeBuilder(AssemblyName name, AssemblyBuilderAccess access, IEnumerable <CustomAttributeBuilder> attributes) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, access, attributes); VerifyAssemblyBuilder(assembly, name, attributes); }
internal static void __Initialize__() { // Only perform this for entry assembly (which is null during module .ctor) if (Assembly.GetEntryAssembly() != null) { return; } // Make sure our nuget local store is added to nuget config var folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string strideFolder = null; while (folder != null) { if (File.Exists(Path.Combine(folder, @"build\Stride.sln"))) { strideFolder = folder; var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null); // Remove non-existing sources: https://github.com/stride3d/stride/issues/338 RemoveDeletedSources(settings, "Stride"); CheckPackageSource(settings, $"Stride Dev {strideFolder}", Path.Combine(strideFolder, @"bin\packages")); settings.SaveToDisk(); break; } folder = Path.GetDirectoryName(folder); } // Note: we perform nuget restore inside the assembly resolver rather than top level module ctor (otherwise it freezes) AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => { if (!assembliesResolved) { lock (assembliesLock) { // Note: using NuGet will try to recursively resolve NuGet.*.resources.dll, so set assembliesResolved right away so that it bypasses everything assembliesResolved = true; var logger = new Logger(); var previousSynchronizationContext = SynchronizationContext.Current; try { // Since we execute restore synchronously, we don't want any surprise concerning synchronization context (i.e. Avalonia one doesn't work with this) SynchronizationContext.SetSynchronizationContext(null); // Determine current TFM var framework = Assembly .GetEntryAssembly()? .GetCustomAttribute <TargetFrameworkAttribute>()? .FrameworkName ?? ".NETFramework,Version=v4.7.2"; var nugetFramework = NuGetFramework.ParseFrameworkName(framework, DefaultFrameworkNameProvider.Instance); // Only allow this specific version var versionRange = new VersionRange(new NuGetVersion(StrideVersion.NuGetVersion), true, new NuGetVersion(StrideVersion.NuGetVersion), true); var(request, result) = RestoreHelper.Restore(logger, nugetFramework, "win", Assembly.GetExecutingAssembly().GetName().Name, versionRange).Result; if (!result.Success) { throw new InvalidOperationException($"Could not restore NuGet packages"); } assemblies = RestoreHelper.ListAssemblies(request, result); } catch (Exception e) { var logFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".txt"; var logText = $@"Error restoring NuGet packages! ==== Exception details ==== {e} ==== Log ==== {string.Join(Environment.NewLine, logger.Logs.Select(x => $"[{x.Level}] {x.Message}"))} "; File.WriteAllText(logFile, logText); #if STRIDE_NUGET_RESOLVER_UX // Write log to file System.Windows.Forms.MessageBox.Show($"{e.Message}{Environment.NewLine}{Environment.NewLine}Please see details in {logFile} (which will be automatically opened)", "Error restoring NuGet packages"); Process.Start(logFile); #else // Display log in console Console.WriteLine(logText); #endif Environment.Exit(1); } finally { SynchronizationContext.SetSynchronizationContext(previousSynchronizationContext); } } } if (assemblies != null) { var aname = new AssemblyName(eventArgs.Name); if (aname.Name.StartsWith("Microsoft.Build") && aname.Name != "Microsoft.Build.Locator") { return(null); } var assemblyPath = assemblies.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x) == aname.Name); if (assemblyPath != null) { return(Assembly.LoadFrom(assemblyPath)); } } return(null); }; }
public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { options.MinimumSameSitePolicy = SameSiteMode.Unspecified; options.OnAppendCookie = cookieContext => CheckSameSite(cookieContext.Context, cookieContext.CookieOptions); options.OnDeleteCookie = cookieContext => CheckSameSite(cookieContext.Context, cookieContext.CookieOptions); }); var stsConfig = Configuration.GetSection("StsConfig"); var useLocalCertStore = Convert.ToBoolean(Configuration["UseLocalCertStore"]); var certificateThumbprint = Configuration["CertificateThumbprint"]; var x509Certificate2 = GetCertificates(_environment, Configuration).GetAwaiter().GetResult(); AddLocalizationConfigurations(services); services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder .AllowCredentials() .WithOrigins( "https://localhost:44311", "https://localhost:44352", "https://localhost:44372", "https://localhost:44378", "https://localhost:44390") .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod(); }); }); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection"))); services.Configure <StsConfig>(Configuration.GetSection("StsConfig")); services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings")); services.AddSingleton <LocService>(); services.AddLocalization(options => options.ResourcesPath = "Resources"); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddErrorDescriber <StsIdentityErrorDescriber>() .AddDefaultTokenProviders() .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2"); services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>(); services.AddTransient <IEmailSender, EmailSender>(); services.AddAntiforgery(options => { options.SuppressXFrameOptionsHeader = true; options.Cookie.SameSite = SameSiteMode.Strict; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; }); services.AddAuthentication() .AddOpenIdConnect("aad", "Login with Azure AD", options => { options.Authority = $"https://login.microsoftonline.com/common"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false }; options.ClientId = "99eb0b9d-ca40-476e-b5ac-6f4c32bfb530"; options.CallbackPath = "/signin-oidc"; }); services.AddAuthorization(); services.AddControllersWithViews(options => { options.Filters.Add(new SecurityHeadersAttribute()); }) .AddViewLocalization() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => { var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName); return(factory.Create("SharedResource", assemblyName.Name)); }; }) .AddNewtonsoftJson(); services.AddIdentityServer() .AddSigningCredential(x509Certificate2.ActiveCertificate) .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryApiScopes(Config.GetApiScopes()) .AddInMemoryClients(Config.GetClients(stsConfig)) .AddAspNetIdentity <ApplicationUser>() .AddProfileService <IdentityWithAdditionalClaimsProfileService>(); services.Configure <Fido2Configuration>(Configuration.GetSection("fido2")); services.AddScoped <Fido2Storage>(); // Adds a default in-memory implementation of IDistributedCache. services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(2); options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.None; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; }); }
private static Assembly TryResolveAssemblyFromPaths_NoLock(AssemblyLoadContext context, AssemblyName assemblyName, string searchPath) { foreach (var cultureSubfolder in string.IsNullOrEmpty(assemblyName.CultureName) // If no culture is specified, attempt to load directly from // the known dependency paths. ? new[] { string.Empty } // Search for satellite assemblies in culture subdirectories // of the assembly search directories, but fall back to the // bare search directory if that fails. : new[] { assemblyName.CultureName, string.Empty }) { foreach (var extension in s_extensions) { var candidatePath = Path.Combine( searchPath, cultureSubfolder, $"{assemblyName.Name}.{extension}"); var isAssemblyLoaded = s_pathsToAssemblies.ContainsKey(candidatePath); if (isAssemblyLoaded || !File.Exists(candidatePath)) { continue; } var candidateAssemblyName = AssemblyLoadContext.GetAssemblyName(candidatePath); if (candidateAssemblyName.Version < assemblyName.Version) { continue; } return(LoadAndCache_NoLock(context, candidatePath)); } } return(null); }
private static void Main() { mutex二重起動防止用 = new Mutex(false, "DTXManiaMutex"); if (mutex二重起動防止用.WaitOne(0, false)) { string newLine = Environment.NewLine; bool bDLLnotfound = false; Trace.WriteLine("Current Directory: " + Environment.CurrentDirectory); Trace.WriteLine("EXEのあるフォルダ: " + Path.GetDirectoryName(Application.ExecutablePath)); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; #region [DLLの存在チェック] if (!tDLLの存在チェック("dll\\SlimDX" + TJAPlayer3.SLIMDXDLL + ".dll", "SlimDX" + TJAPlayer3.SLIMDXDLL + ".dll またはその依存するdllが存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "SlimDX" + TJAPlayer3.SLIMDXDLL + ".dll, or its depended DLL, is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\FDK.dll", "FDK.dll またはその依存するdllが存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "FDK.dll, or its depended DLL, is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\xadec.dll", "xadec.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "xadec.dll is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\SoundDecoder.dll", "SoundDecoder.dll またはその依存するdllが存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "SoundDecoder.dll, or its depended DLL, is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック(TJAPlayer3.D3DXDLL, TJAPlayer3.D3DXDLL + " が存在しません。" + newLine + "DirectX Redist フォルダの DXSETUP.exe を実行し、" + newLine + "必要な DirectX ランタイムをインストールしてください。", TJAPlayer3.D3DXDLL + " is not found." + newLine + "Please execute DXSETUP.exe in \"DirectX Redist\" folder, to install DirectX runtimes required for DTXMania.", true )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\bass.dll", "bass.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "baas.dll is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\Bass.Net.dll", "Bass.Net.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "Bass.Net.dll is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\bassmix.dll", "bassmix.dll を読み込めません。bassmix.dll か bass.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "bassmix.dll is not loaded. bassmix.dll or bass.dll must not exist." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\bassasio.dll", "bassasio.dll を読み込めません。bassasio.dll か bass.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "bassasio.dll is not loaded. bassasio.dll or bass.dll must not exist." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\basswasapi.dll", "basswasapi.dll を読み込めません。basswasapi.dll か bass.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "basswasapi.dll is not loaded. basswasapi.dll or bass.dll must not exist." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\bass_fx.dll", "bass_fx.dll を読み込めません。bass_fx.dll か bass.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "bass_fx.dll is not loaded. bass_fx.dll or bass.dll must not exist." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } if (!tDLLの存在チェック("dll\\DirectShowLib-2005.dll", "DirectShowLib-2005.dll が存在しません。" + newLine + "DTXManiaをダウンロードしなおしてください。", "DirectShowLib-2005.dll is not found." + newLine + "Please download DTXMania again." )) { bDLLnotfound = true; } #endregion if (!bDLLnotfound) { #if DEBUG && TEST_ENGLISH Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); #endif DWM.EnableComposition(false); // Disable AeroGrass temporally // BEGIN #23670 2010.11.13 from: キャッチされない例外は放出せずに、ログに詳細を出力する。 // BEGIM #24606 2011.03.08 from: DEBUG 時は例外発生箇所を直接デバッグできるようにするため、例外をキャッチしないようにする。 #if !DEBUG try #endif { using (var mania = new TJAPlayer3()) mania.Run(); Trace.WriteLine(""); Trace.WriteLine("遊んでくれてありがとう!"); } #if !DEBUG catch (Exception e) { Trace.WriteLine(""); Trace.Write(e.ToString()); Trace.WriteLine(""); Trace.WriteLine("エラーだゴメン!(涙"); AssemblyName asmApp = Assembly.GetExecutingAssembly().GetName(); MessageBox.Show("エラーが発生しました。\n" + "原因がわからない場合は、以下のエラー文を添えて、エラー送信フォームに送信してください。\n" + e.ToString(), asmApp.Name + " Ver." + asmApp.Version.ToString().Substring(0, asmApp.Version.ToString().Length - 2) + " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // #23670 2011.2.28 yyagi to show error dialog DialogResult result = MessageBox.Show("エラー送信フォームを開きますか?(ブラウザが起動します)", asmApp.Name + " Ver." + asmApp.Version.ToString().Substring(0, asmApp.Version.ToString().Length - 2), MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (result == DialogResult.Yes) { Process.Start("https://docs.google.com/forms/d/e/1FAIpQLScr_Oqs9WKnonQyxpEVt7gZYPcjjIfN3SjgqWPvxfw95nAQ6g/viewform?usp=pp_url&entry.60593436=" + System.Web.HttpUtility.UrlEncode(e.ToString())); } } #endif // END #24606 2011.03.08 from // END #23670 2010.11.13 from if (Trace.Listeners.Count > 1) { Trace.Listeners.RemoveAt(1); } } // BEGIN #24615 2011.03.09 from: Mutex.WaitOne() が true を返した場合は、Mutex のリリースが必要である。 mutex二重起動防止用.ReleaseMutex(); mutex二重起動防止用 = null; // END #24615 2011.03.09 from } else // DTXManiaが既に起動中 { // → 引数が0個の時はそのまま終了 // 1個( コンパクトモード or DTXV -S) か2個 (DTXV -Nxxx ファイル名)のときは、そのプロセスにコマンドラインを丸々投げて終了する for (int i = 0; i < 5; i++) // 検索結果のハンドルがZeroになることがあるので、200ms間隔で5回リトライする { #region [ 既に起動中のDTXManiaプロセスを検索する。] // このやり方だと、ShowInTaskbar=falseでタスクバーに表示されないパターンの時に検索に失敗するようだが // DTXManiaでそのパターンはない?のでこのままいく。 // FindWindowを使えばこのパターンにも対応できるが、C#でビルドするアプリはウインドウクラス名を自前指定できないので、これは使わない。 Process current = Process.GetCurrentProcess(); Process[] running = Process.GetProcessesByName(current.ProcessName); Process target = null; //IntPtr hWnd = FindWindow( null, "DTXMania .NET style release " + CDTXMania.VERSION ); foreach (Process p in running) { if (p.Id != current.Id) // プロセス名は同じでかつ、プロセスIDが自分自身とは異なるものを探す { if (p.MainModule.FileName == current.MainModule.FileName && p.MainWindowHandle != IntPtr.Zero) { target = p; break; } } } #endregion #region [ 起動中のDTXManiaがいれば、そのプロセスにコマンドラインを投げる ] if (target != null) { string[] commandLineArgs = Environment.GetCommandLineArgs(); if (commandLineArgs != null && commandLineArgs.Length > 1) { string arg = null; for (int j = 1; j < commandLineArgs.Length; j++) { if (j == 1) { arg += commandLineArgs[j]; } else { arg += " " + "\"" + commandLineArgs[j] + "\""; } } //Trace.TraceInformation( "Message=" + arg + ", len(w/o null)=" + arg.Length ); if (arg != null) { FDK.CSendMessage.sendmessage(target.MainWindowHandle, current.MainWindowHandle, arg); } } break; } #endregion else { Trace.TraceInformation("メッセージ送信先のプロセスが見つからず。5回リトライします。"); Thread.Sleep(200); } } } }
public PluginBase LoadPlugin(string fullName) { Assembly pluginAssembly; try { new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, fullName).Assert(); pluginAssembly = AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(fullName)); } catch (BadImageFormatException) { /* Skip not managed dll files */ return(null); } finally { CodeAccessPermission.RevertAssert(); } var pluginType = pluginAssembly.GetTypes().FirstOrDefault(x => x.BaseType == typeof(PluginBase)); if (pluginType == null) { throw new InvalidOperationException("Plugin's type has not been found in the specified assembly!"); } var pluginInstance = Activator.CreateInstance(pluginType) as PluginBase; plugins.Add(pluginAssembly, pluginInstance); var pluginConfigurationType = pluginAssembly.GetTypes().FirstOrDefault(x => x.BaseType == typeof(ConfigurationBase)); if (pluginConfigurationType != null) { string processPath = String.Empty; try { new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); processPath = Process.GetCurrentProcess().MainModule.FileName; } finally { CodeAccessPermission.RevertAssert(); } try { var pset = new PermissionSet(PermissionState.None); pset.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); pset.AddPermission(new ConfigurationPermission(PermissionState.Unrestricted)); pset.Assert(); pluginInstance.Configuration = typeof(ConfigurationBase) .GetMethod("Open") .MakeGenericMethod(pluginConfigurationType) .Invoke(null, new object[] { Path.GetFileNameWithoutExtension(fullName), processPath }) as ConfigurationBase; } finally { CodeAccessPermission.RevertAssert(); } } return(pluginInstance); }
private Assembly OnAssemblyLoadContextResolving(AssemblyLoadContext context, AssemblyName assemblyName) { if (handlerReturn == HandlerReturn.Exception) { throw new Exception("Exception in handler for AssemblyLoadContext.Resolving"); } Assembly asm = ResolveAssembly(context, assemblyName); var invocation = new HandlerInvocation() { AssemblyName = assemblyName, HandlerName = nameof(OnAssemblyLoadContextResolving), AssemblyLoadContext = context == AssemblyLoadContext.Default ? context.Name : context.ToString(), }; if (asm != null) { invocation.ResultAssemblyName = asm.GetName(); invocation.ResultAssemblyPath = asm.Location; } Invocations.Add(invocation); return(asm); }
public static Assembly Load(this Assembly ass, string name) { AssemblyName assName = new AssemblyName(name); return(Assembly.Load(assName)); }
static TypeAccessor CreateNew(Type type, bool allowNonPublicAccessors) { #if !NO_DYNAMIC #if WINDOWS_PHONE_APP if (typeof(IDynamicMetaObjectProvider).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) #else if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type)) #endif { return(DynamicAccessor.Singleton); } #endif #if WINDOWS_PHONE_APP PropertyInfo[] props = type.GetRuntimeProperties().ToArray(); FieldInfo[] fields = type.GetRuntimeFields().ToArray(); #else PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); #endif Dictionary <string, int> map = new Dictionary <string, int>(StringComparer.Ordinal); List <MemberInfo> members = new List <MemberInfo>(props.Length + fields.Length); int i = 0; foreach (var prop in props) { if (!map.ContainsKey(prop.Name) && prop.GetIndexParameters().Length == 0) { map.Add(prop.Name, i++); members.Add(prop); } } foreach (var field in fields) { if (!map.ContainsKey(field.Name)) { map.Add(field.Name, i++); members.Add(field); } } ConstructorInfo ctor = null; #if WINDOWS_PHONE_APP if (type.GetTypeInfo().IsClass&& !type.GetTypeInfo().IsAbstract) { ctor = type.GetTypeInfo().DeclaredConstructors.FirstOrDefault(); } #else if (type.IsClass && !type.IsAbstract) { ctor = type.GetConstructor(Type.EmptyTypes); } #endif #if !__IOS__ && !WINDOWS_PHONE_APP ILGenerator il; if (!IsFullyPublic(type, props, allowNonPublicAccessors)) { DynamicMethod dynGetter = new DynamicMethod(type.FullName + "_get", typeof(object), new Type[] { typeof(int), typeof(object) }, type, true), dynSetter = new DynamicMethod(type.FullName + "_set", null, new Type[] { typeof(int), typeof(object), typeof(object) }, type, true); WriteMapImpl(dynGetter.GetILGenerator(), type, members, null, allowNonPublicAccessors, true); WriteMapImpl(dynSetter.GetILGenerator(), type, members, null, allowNonPublicAccessors, false); DynamicMethod dynCtor = null; if (ctor != null) { dynCtor = new DynamicMethod(type.FullName + "_ctor", typeof(object), Type.EmptyTypes, type, true); il = dynCtor.GetILGenerator(); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Ret); } return(new DelegateAccessor( map, (Func <int, object, object>)dynGetter.CreateDelegate(typeof(Func <int, object, object>)), (Action <int, object, object>)dynSetter.CreateDelegate(typeof(Action <int, object, object>)), dynCtor == null ? null : (Func <object>)dynCtor.CreateDelegate(typeof(Func <object>)), type)); } // note this region is synchronized; only one is being created at a time so we don't need to stress about the builders if (assembly == null) { AssemblyName name = new AssemblyName("FastMember_dynamic"); //assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); module = assembly.DefineDynamicModule(name.Name); } TypeBuilder tb = module.DefineType("FastMember_dynamic." + type.Name + "_" + Interlocked.Increment(ref counter), (typeof(TypeAccessor).Attributes | TypeAttributes.Sealed | TypeAttributes.Public) & ~(TypeAttributes.Abstract | TypeAttributes.NotPublic), typeof(RuntimeTypeAccessor)); il = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(Dictionary <string, int>) }).GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg_1); FieldBuilder mapField = tb.DefineField("_map", typeof(Dictionary <string, int>), FieldAttributes.InitOnly | FieldAttributes.Private); il.Emit(OpCodes.Stfld, mapField); il.Emit(OpCodes.Ret); PropertyInfo indexer = typeof(TypeAccessor).GetProperty("Item"); MethodInfo baseGetter = indexer.GetGetMethod(), baseSetter = indexer.GetSetMethod(); MethodBuilder body = tb.DefineMethod(baseGetter.Name, baseGetter.Attributes & ~MethodAttributes.Abstract, typeof(object), new Type[] { typeof(object), typeof(string) }); il = body.GetILGenerator(); WriteMapImpl(il, type, members, mapField, allowNonPublicAccessors, true); tb.DefineMethodOverride(body, baseGetter); body = tb.DefineMethod(baseSetter.Name, baseSetter.Attributes & ~MethodAttributes.Abstract, null, new Type[] { typeof(object), typeof(string), typeof(object) }); il = body.GetILGenerator(); WriteMapImpl(il, type, members, mapField, allowNonPublicAccessors, false); tb.DefineMethodOverride(body, baseSetter); MethodInfo baseMethod; if (ctor != null) { baseMethod = typeof(TypeAccessor).GetProperty("CreateNewSupported").GetGetMethod(); body = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes, baseMethod.ReturnType, Type.EmptyTypes); il = body.GetILGenerator(); il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(body, baseMethod); baseMethod = typeof(TypeAccessor).GetMethod("CreateNew"); body = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes, baseMethod.ReturnType, Type.EmptyTypes); il = body.GetILGenerator(); il.Emit(OpCodes.Newobj, ctor); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(body, baseMethod); } baseMethod = typeof(RuntimeTypeAccessor).GetProperty("Type", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true); body = tb.DefineMethod(baseMethod.Name, baseMethod.Attributes & ~MethodAttributes.Abstract, baseMethod.ReturnType, Type.EmptyTypes); il = body.GetILGenerator(); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); il.Emit(OpCodes.Ret); tb.DefineMethodOverride(body, baseMethod); try { //var accessor = (TypeAccessor)Activator.CreateInstance(tb.CreateType(), map); var accessor = (TypeAccessor)Activator.CreateInstance(tb.CreateTypeInfo(), map); return(accessor); } catch (TargetInvocationException vex) { var _getter = new Func <int, object, object>((index, obj) => { return(obj.GetType().GetProperties()[index].GetValue(obj)); }); var _setter = new Action <int, object, object>((index, obj, value) => { try { obj.GetType().GetProperties()[index].SetValue(obj, value); } catch (ArgumentException icex) { throw new InvalidCastException(icex.Message, icex); } catch (Exception ex) { throw new Exception(ex.Message, ex); } }); return(new DelegateAccessor(map, _getter, _setter, delegate { return ctor.Invoke(null); }, type)); } catch (Exception ex) { throw new Exception(ex.Message, ex); } #else var _getter = new Func <int, object, object>((index, obj) => { #if WINDOWS_PHONE_APP return(obj.GetType().GetRuntimeProperties().ToArray()[index].GetValue(obj)); #else return(obj.GetType().GetProperties()[index].GetValue(obj)); #endif }); var _setter = new Action <int, object, object>((index, obj, value) => { try { #if WINDOWS_PHONE_APP obj.GetType().GetRuntimeProperties().ToArray()[index].SetValue(obj, value); #else obj.GetType().GetProperties()[index].SetValue(obj, value); #endif } catch (ArgumentException icex) { throw new InvalidCastException(icex.Message, icex); } catch (Exception ex) { throw new Exception(ex.Message, ex); } }); return(new DelegateAccessor(map, _getter, _setter, delegate { return ctor.Invoke(null); }, type)); //RuntimeTypeAccessor() (TypeAccessor) Activator.CreateInstance(type); //return (TypeAccessor)Activator.CreateInstance(type); #endif }
protected override Assembly Load(AssemblyName assemblyName) { Assembly ass; //Assemblies with a different case of the Name are considered the same assembly. string assemblyLowerName = assemblyName.Name.ToLower(); lock (syncRoot) { loadedAssemblies.TryGetValue(assemblyLowerName, out ass); if (ass != null) { return(ass); } try { var deps = DependencyContext.Default; var res = deps.CompileLibraries.Where(d => d.Name.Equals(assemblyName.Name, StringComparison.OrdinalIgnoreCase)).ToList(); if (res.Count > 0) { ass = Assembly.Load(new AssemblyName(res.First().Name)); loadedAssemblies[assemblyLowerName] = ass; return(ass); } else { var runtimeLibs = deps.RuntimeLibraries.Where(d => d.Name.Equals(assemblyName.Name, StringComparison.OrdinalIgnoreCase)).ToList(); if (runtimeLibs.Count > 0) { ass = Assembly.Load(new AssemblyName(runtimeLibs.First().Name)); loadedAssemblies[assemblyLowerName] = ass; return(ass); } else { var foundDlls = Directory.GetFileSystemEntries(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), assemblyName.Name + ".dll", SearchOption.AllDirectories); if (foundDlls.Any()) { ass = LoadFromAssemblyPath(foundDlls[0]); loadedAssemblies[assemblyLowerName] = ass; return(ass); } return(Assembly.Load(assemblyName)); } } } catch (FileNotFoundException) //>ExecutingAssembly>.deps.json does not exist (p.e. deployed procs command line) { var assemblyPath = Path.Combine(folderPath, assemblyName.Name + ".dll"); if (File.Exists(assemblyPath)) { ass = Default.LoadFromAssemblyPath(assemblyPath); if (ass != null) { loadedAssemblies[assemblyLowerName] = ass; return(ass); } } return(null); } } }
public static Type Generate(string functionAssemblyName, string typeName, Collection <FunctionDescriptor> functions) { if (functions == null) { throw new ArgumentNullException("functions"); } AssemblyName assemblyName = new AssemblyName(functionAssemblyName); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder mb = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll"); TypeBuilder tb = mb.DefineType(typeName, TypeAttributes.Public); foreach (FunctionDescriptor function in functions) { MethodBuilder methodBuilder = tb.DefineMethod(function.Name, MethodAttributes.Public | MethodAttributes.Static); Type[] types = function.Parameters.Select(p => p.Type).ToArray(); methodBuilder.SetParameters(types); methodBuilder.SetReturnType(typeof(Task)); if (function.CustomAttributes != null) { foreach (CustomAttributeBuilder attributeBuilder in function.CustomAttributes) { methodBuilder.SetCustomAttribute(attributeBuilder); } } for (int i = 0; i < function.Parameters.Count; i++) { ParameterDescriptor parameter = function.Parameters[i]; ParameterBuilder parameterBuilder = methodBuilder.DefineParameter(i + 1, parameter.Attributes, parameter.Name); if (parameter.CustomAttributes != null) { foreach (CustomAttributeBuilder attributeBuilder in parameter.CustomAttributes) { parameterBuilder.SetCustomAttribute(attributeBuilder); } } } _invokerMap[function.Name] = function.Invoker; MethodInfo invokeMethod = function.Invoker.GetType().GetMethod("Invoke"); MethodInfo getInvoker = typeof(FunctionGenerator).GetMethod("GetInvoker", BindingFlags.Static | BindingFlags.Public); ILGenerator il = methodBuilder.GetILGenerator(); LocalBuilder argsLocal = il.DeclareLocal(typeof(object[])); LocalBuilder invokerLocal = il.DeclareLocal(typeof(IFunctionInvoker)); il.Emit(OpCodes.Nop); // declare an array for all parameter values il.Emit(OpCodes.Ldc_I4, function.Parameters.Count); il.Emit(OpCodes.Newarr, typeof(object)); il.Emit(OpCodes.Stloc, argsLocal); // copy each parameter into the arg array for (int i = 0; i < function.Parameters.Count; i++) { ParameterDescriptor parameter = function.Parameters[i]; il.Emit(OpCodes.Ldloc, argsLocal); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldarg, i); // For Out and Ref types, need to do an indirection. if (parameter.Type.IsByRef) { il.Emit(OpCodes.Ldind_Ref); } // Box value types if (parameter.Type.IsValueType) { il.Emit(OpCodes.Box, parameter.Type); } il.Emit(OpCodes.Stelem_Ref); } // get the invoker instance il.Emit(OpCodes.Ldstr, function.Name); il.Emit(OpCodes.Call, getInvoker); il.Emit(OpCodes.Stloc, invokerLocal); // now call the invoker, passing in the args il.Emit(OpCodes.Ldloc, invokerLocal); il.Emit(OpCodes.Ldloc, argsLocal); il.Emit(OpCodes.Callvirt, invokeMethod); if (function.Parameters.Any(p => p.Type.IsByRef)) { LocalBuilder taskLocal = il.DeclareLocal(typeof(Task)); LocalBuilder taskAwaiterLocal = il.DeclareLocal(typeof(TaskAwaiter)); // We need to wait on the function's task if we have any out/ref // parameters to ensure they have been populated before we copy them back // Store the result into a local Task // and load it onto the evaluation stack il.Emit(OpCodes.Stloc, taskLocal); il.Emit(OpCodes.Ldloc, taskLocal); // Call "GetAwaiter" on the Task il.Emit(OpCodes.Callvirt, typeof(Task).GetMethod("GetAwaiter", Type.EmptyTypes)); // Call "GetResult", which will synchonously wait for the Task to complete il.Emit(OpCodes.Stloc, taskAwaiterLocal); il.Emit(OpCodes.Ldloca, taskAwaiterLocal); il.Emit(OpCodes.Call, typeof(TaskAwaiter).GetMethod("GetResult")); // Copy back out and ref parameters for (int i = 0; i < function.Parameters.Count; i++) { var param = function.Parameters[i]; if (!param.Type.IsByRef) { continue; } il.Emit(OpCodes.Ldarg, i); il.Emit(OpCodes.Ldloc, argsLocal); il.Emit(OpCodes.Ldc_I4, i); il.Emit(OpCodes.Ldelem_Ref); il.Emit(OpCodes.Castclass, param.Type.GetElementType()); il.Emit(OpCodes.Stind_Ref); } il.Emit(OpCodes.Ldloc, taskLocal); } il.Emit(OpCodes.Ret); } Type t = tb.CreateType(); return(t); }
protected override Assembly Load(AssemblyName assemblyName) { throw new NotImplementedException(); }
/// <summary> /// Last effort to find a suitable dll for an assembly that could otherwise not be loaded. /// Search for a suitable .dll in the specified fallback locations. /// Does not load any dependencies. /// </summary> private Assembly?OnResolving(AssemblyLoadContext context, AssemblyName name) { var path = this.ResolveFromFallbackPaths(name); return(path == null ? null : this.LoadFromAssemblyPath(path)); }
protected override Assembly Load(AssemblyName assemblyName) { return(Assembly.Load(assemblyName)); }
// the private method which emits the assembly // using op codes private Assembly EmitAssembly(int theValue) { // Create an assembly name AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "DoSumAssembly"; // Create a new assembly with one module AssemblyBuilder newAssembly = Thread.GetDomain().DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder newModule = newAssembly.DefineDynamicModule("Sum"); // Define a public class named "BruteForceSums " // in the assembly. TypeBuilder myType = newModule.DefineType( "BruteForceSums", TypeAttributes.Public); // Mark the class as implementing IComputer. myType.AddInterfaceImplementation( typeof(IComputer)); // Define a method on the type to call. Pass an // array that defines the types of the parameters, // the type of the return type, the name of the // method, and the method attributes. Type[] paramTypes = new Type[0]; Type returnType = typeof(int); MethodBuilder simpleMethod = myType.DefineMethod( "ComputeSum", MethodAttributes.Public | MethodAttributes.Virtual, returnType, paramTypes); // Get an ILGenerator. This is used // to emit the IL that you want. ILGenerator generator = simpleMethod.GetILGenerator(); // Emit the IL that you'd get if you // compiled the code example // and then ran ILDasm on the output. // Push zero onto the stack. For each 'i' // less than 'theValue', // push 'i' onto the stack as a constant // add the two values at the top of the stack. // The sum is left on the stack. generator.Emit(OpCodes.Ldc_I4, 0); for (int i = 1; i <= theValue; i++) { generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Add); } // return the value generator.Emit(OpCodes.Ret); //Encapsulate information about the method and //provide access to the method's metadata MethodInfo computeSumInfo = typeof(IComputer).GetMethod("ComputeSum"); // specify the method implementation. // Pass in the MethodBuilder that was returned // by calling DefineMethod and the methodInfo // just created myType.DefineMethodOverride(simpleMethod, computeSumInfo); // Create the type. myType.CreateType(); return(newAssembly); }
public DllResourceStore(AssemblyName name) : this(Assembly.Load(name)) { }
protected override Assembly Load(AssemblyName name) { return(null !); }
private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList <string> inputFiles = Array.Empty <string>(); IReadOnlyList <string> referenceFiles = Array.Empty <string>(); bool optimize = false; bool optimizeSpace = false; bool optimizeTime = false; bool waitForDebugger = false; AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOption("o|out", ref _outputFilePath, "Output file path"); syntax.DefineOption("O", ref optimize, "Enable optimizations"); syntax.DefineOption("Os", ref optimizeSpace, "Enable optimizations, favor code space"); syntax.DefineOption("Ot", ref optimizeTime, "Enable optimizations, favor code speed"); syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information"); syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation"); syntax.DefineOption("wasm", ref _isWasmCodegen, "Compile for WebAssembly code-generation"); syntax.DefineOption("nativelib", ref _nativeLib, "Compile as static or shared library"); syntax.DefineOption("exportsfile", ref _exportsFile, "File to write exported method definitions"); syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML"); syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis"); syntax.DefineOption("scandgmllog", ref _scanDgmlLogFileName, "Save result of scanner dependency analysis as DGML"); syntax.DefineOption("scanfulllog", ref _generateFullScanDgmlLog, "Save detailed log of scanner dependency analysis"); syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging"); syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)"); syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)"); syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger"); syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option"); syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation"); syntax.DefineOption("rootallapplicationassemblies", ref _rootAllApplicationAssemblies, "Consider all non-framework assemblies dynamically used"); syntax.DefineOption("map", ref _mapFileName, "Generate a map file"); syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file"); syntax.DefineOption("nometadatablocking", ref _noMetadataBlocking, "Ignore metadata blocking for internal implementation details"); syntax.DefineOption("disablereflection", ref _disableReflection, "Disable generation of reflection metadata"); syntax.DefineOption("completetypemetadata", ref _completeTypesMetadata, "Generate complete metadata for types"); syntax.DefineOption("scanreflection", ref _scanReflection, "Scan IL for reflection patterns"); syntax.DefineOption("scan", ref _useScanner, "Use IL scanner to generate optimized code (implied by -O)"); syntax.DefineOption("noscan", ref _noScanner, "Do not use IL scanner to generate optimized code"); syntax.DefineOption("ildump", ref _ilDump, "Dump IL assembly listing for compiler-generated IL"); syntax.DefineOption("stacktracedata", ref _emitStackTraceData, "Emit data to support generating stack trace strings at runtime"); syntax.DefineOption("methodbodyfolding", ref _methodBodyFolding, "Fold identical method bodies"); syntax.DefineOptionList("initassembly", ref _initAssemblies, "Assembly(ies) with a library initializer"); syntax.DefineOptionList("appcontextswitch", ref _appContextSwitches, "System.AppContext switches to set"); syntax.DefineOptionList("runtimeopt", ref _runtimeOptions, "Runtime options to set"); syntax.DefineOptionList("removefeature", ref _removedFeatures, "Framework features to remove"); syntax.DefineOption("singlethreaded", ref _singleThreaded, "Run compilation on a single thread"); syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation"); syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation"); syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type"); syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method"); syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); if (waitForDebugger) { Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue"); Console.ReadLine(); } _optimizationMode = OptimizationMode.None; if (optimizeSpace) { if (optimizeTime) { Console.WriteLine("Warning: overriding -Ot with -Os"); } _optimizationMode = OptimizationMode.PreferSize; } else if (optimizeTime) { _optimizationMode = OptimizationMode.PreferSpeed; } else if (optimize) { _optimizationMode = OptimizationMode.Blended; } foreach (var input in inputFiles) { Helpers.AppendExpandedPaths(_inputFilePaths, input, true); } foreach (var reference in referenceFiles) { Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); } return(argSyntax); }
public static int Main(string [] args) { bool showHelp = false; bool showVersion = false; string outputPath = null; var options = new OptionSet { { "h|help", "show this help message and exit", v => showHelp = v != null }, { "v|version", "show program's version number and exit", v => showVersion = v != null }, { "o|output=", "{PATH} to write the service definitions to. If unspecified, the output is written to stanadard output.", (string v) => outputPath = v } }; List <string> positionalArgs = options.Parse(args); if (showHelp) { Help(options); return(0); } if (showVersion) { var assembly = Assembly.GetEntryAssembly(); var info = FileVersionInfo.GetVersionInfo(assembly.Location); var version = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}", info.FileMajorPart, info.FileMinorPart, info.FileBuildPart); Console.Error.WriteLine("ServiceDefinitions.exe version " + version); return(0); } if (positionalArgs.Count < 2) { Console.Error.WriteLine("Not enough arguments"); foreach (string s in positionalArgs) { Console.Error.WriteLine(" " + s); } return(1); } Logger.Enabled = true; Logger.Level = Logger.Severity.Warning; var service = positionalArgs [0]; for (var i = 1; i < positionalArgs.Count; i++) { var path = positionalArgs [i]; try { AssemblyName name = AssemblyName.GetAssemblyName(path); Assembly.Load(name); } catch (FileNotFoundException) { Console.Error.WriteLine("Assembly '" + path + "' not found."); return(1); } catch (FileLoadException e) { Console.Error.WriteLine("Failed to load assembly '" + path + "'."); Console.Error.WriteLine(e.Message); if (e.InnerException != null) { Console.Error.WriteLine(e.InnerException.Message); } return(1); } catch (BadImageFormatException) { Console.Error.WriteLine("Failed to load assembly '" + path + "'. Bad image format."); return(1); } catch (SecurityException) { Console.Error.WriteLine("Failed to load assembly '" + path + "'. Security exception."); return(1); } catch (PathTooLongException) { Console.Error.WriteLine("Failed to load assembly '" + path + "'. File name too long."); return(1); } } var services = KRPC.Service.Scanner.Scanner.GetServices(); if (!services.ContainsKey(service)) { Console.Error.WriteLine("Service " + service + " not found"); return(1); } services = new Dictionary <string, KRPC.Service.Scanner.ServiceSignature> { { service, services [service] } }; string output = JsonConvert.SerializeObject(services, Formatting.Indented); if (outputPath != null) { File.WriteAllText(outputPath, output); } else { Console.Write(output); } return(0); }
public static Type DynamicPointTypeGen() { Type pointType = null; Type[] ctorParams = new Type[] { typeof(int), typeof(int), typeof(int) }; AppDomain myDomain = Thread.GetDomain(); AssemblyName myAsmName = new AssemblyName(); myAsmName.Name = "MyDynamicAssembly"; AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder pointModule = myAsmBuilder.DefineDynamicModule("PointModule", "Point.dll"); TypeBuilder pointTypeBld = pointModule.DefineType("Point", TypeAttributes.Public); FieldBuilder xField = pointTypeBld.DefineField("x", typeof(int), FieldAttributes.Public); FieldBuilder yField = pointTypeBld.DefineField("y", typeof(int), FieldAttributes.Public); FieldBuilder zField = pointTypeBld.DefineField("z", typeof(int), FieldAttributes.Public); Type objType = Type.GetType("System.Object"); ConstructorInfo objCtor = objType.GetConstructor(new Type[0]); ConstructorBuilder pointCtor = pointTypeBld.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, ctorParams); ILGenerator ctorIL = pointCtor.GetILGenerator(); // NOTE: ldarg.0 holds the "this" reference - ldarg.1, ldarg.2, and ldarg.3 // hold the actual passed parameters. ldarg.0 is used by instance methods // to hold a reference to the current calling object instance. Static methods // do not use arg.0, since they are not instantiated and hence no reference // is needed to distinguish them. ctorIL.Emit(OpCodes.Ldarg_0); // Here, we wish to create an instance of System.Object by invoking its // constructor, as specified above. ctorIL.Emit(OpCodes.Call, objCtor); // Now, we'll load the current instance ref in arg 0, along // with the value of parameter "x" stored in arg 1, into stfld. ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Ldarg_1); ctorIL.Emit(OpCodes.Stfld, xField); // Now, we store arg 2 "y" in the current instance with stfld. ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Ldarg_2); ctorIL.Emit(OpCodes.Stfld, yField); // Last of all, arg 3 "z" gets stored in the current instance. ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Ldarg_3); ctorIL.Emit(OpCodes.Stfld, zField); // Our work complete, we return. ctorIL.Emit(OpCodes.Ret); // Now, let's create three very simple methods so we can see our fields. string[] mthdNames = new string[] { "GetX", "GetY", "GetZ" }; foreach (string mthdName in mthdNames) { MethodBuilder getFieldMthd = pointTypeBld.DefineMethod( mthdName, MethodAttributes.Public, typeof(int), null); ILGenerator mthdIL = getFieldMthd.GetILGenerator(); mthdIL.Emit(OpCodes.Ldarg_0); switch (mthdName) { case "GetX": mthdIL.Emit(OpCodes.Ldfld, xField); break; case "GetY": mthdIL.Emit(OpCodes.Ldfld, yField); break; case "GetZ": mthdIL.Emit(OpCodes.Ldfld, zField); break; } mthdIL.Emit(OpCodes.Ret); } // Finally, we create the type. pointType = pointTypeBld.CreateType(); // Let's save it, just for posterity. myAsmBuilder.Save("Point.dll"); return(pointType); }
private RequestDelegate BuildApplication() { try { _applicationServicesException?.Throw(); EnsureServer(); var builderFactory = _applicationServices.GetRequiredService <IApplicationBuilderFactory>(); var builder = builderFactory.CreateBuilder(Server.Features); builder.ApplicationServices = _applicationServices; var startupFilters = _applicationServices.GetService <IEnumerable <IStartupFilter> >(); Action <IApplicationBuilder> configure = _startup.Configure; foreach (var filter in startupFilters.Reverse()) { configure = filter.Configure(configure); } configure(builder); return(builder.Build()); } catch (Exception ex) { if (!_options.SuppressStatusMessages) { // Write errors to standard out so they can be retrieved when not in development mode. Console.WriteLine("Application startup exception: " + ex.ToString()); } var logger = _applicationServices.GetRequiredService <ILogger <WebHost> >(); logger.ApplicationError(ex); if (!_options.CaptureStartupErrors) { throw; } EnsureServer(); // Generate an HTML error page. var hostingEnv = _applicationServices.GetRequiredService <IHostEnvironment>(); var showDetailedErrors = hostingEnv.IsDevelopment() || _options.DetailedErrors; var model = new ErrorPageModel { RuntimeDisplayName = RuntimeInformation.FrameworkDescription }; var systemRuntimeAssembly = typeof(System.ComponentModel.DefaultValueAttribute).GetTypeInfo().Assembly; var assemblyVersion = new AssemblyName(systemRuntimeAssembly.FullName).Version.ToString(); var clrVersion = assemblyVersion; model.RuntimeArchitecture = RuntimeInformation.ProcessArchitecture.ToString(); var currentAssembly = typeof(ErrorPage).GetTypeInfo().Assembly; model.CurrentAssemblyVesion = currentAssembly .GetCustomAttribute <AssemblyInformationalVersionAttribute>() .InformationalVersion; model.ClrVersion = clrVersion; model.OperatingSystemDescription = RuntimeInformation.OSDescription; model.ShowRuntimeDetails = showDetailedErrors; if (showDetailedErrors) { var exceptionDetailProvider = new ExceptionDetailsProvider( hostingEnv.ContentRootFileProvider, logger, sourceCodeLineCount: 6); model.ErrorDetails = exceptionDetailProvider.GetDetails(ex); } else { model.ErrorDetails = new ExceptionDetails[0]; } var errorPage = new ErrorPage(model); return(context => { context.Response.StatusCode = 500; context.Response.Headers[HeaderNames.CacheControl] = "no-cache,no-store"; context.Response.Headers[HeaderNames.Pragma] = "no-cache"; return errorPage.ExecuteAsync(context); }); } }
void CreateMarshalMethodAssembly(string path) { var assembly = Assembly.LoadFile(Path.GetFullPath(path)); var baseName = Path.GetFileNameWithoutExtension(path); var assemblyName = new AssemblyName(baseName + "-JniMarshalMethods"); var destPath = assemblyName.Name + ".dll"; var builder = CreateExportedMemberBuilder(); var matchType = typeNameRegexes.Count > 0; if (Verbose) { ColorWriteLine($"Preparing marshal method assembly '{assemblyName}'", ConsoleColor.Cyan); } var da = AppDomain.CurrentDomain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Save, Path.GetDirectoryName(path)); var dm = da.DefineDynamicModule("<default>", destPath); var ad = resolver.GetAssembly(path); PrepareTypeMap(ad.MainModule); Type[] types = null; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { types = e.Types; foreach (var le in e.LoaderExceptions) { Warning($"Type Load exception{Environment.NewLine}{le}"); } } foreach (var systemType in types) { if (systemType == null) { continue; } var type = systemType.GetTypeInfo(); if (matchType) { var matched = false; foreach (var r in typeNameRegexes) { matched |= r.IsMatch(type.FullName); } if (!matched) { continue; } } if (type.IsGenericType || type.IsGenericTypeDefinition) { continue; } var td = FindType(type); if (td == null) { if (Verbose) { Warning($"Unable to find cecil's TypeDefinition of type {type}"); } continue; } if (!td.ImplementsInterface("Java.Interop.IJavaPeerable")) { continue; } var existingMarshalMethodsType = td.GetNestedType(TypeMover.NestedName); if (existingMarshalMethodsType != null && !forceRegeneration) { Warning($"Marshal methods type '{existingMarshalMethodsType.GetAssemblyQualifiedName ()}' already exists. Skipped generation of marshal methods in assembly '{assemblyName}'. Use -f to force regeneration when desired."); return; } if (Verbose) { ColorWriteLine($"Processing {type} type", ConsoleColor.Yellow); } var registrationElements = new List <Expression> (); var targetType = Expression.Variable(typeof(Type), "targetType"); TypeBuilder dt = null; var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; var methods = type.GetMethods(flags); Array.Sort(methods, new MethodsComparer(type, td)); addedMethods.Clear(); foreach (var method in methods) { // TODO: Constructors var export = method.GetCustomAttribute <JavaCallableAttribute> (); string signature = null; string name = null; string methodName = method.Name; if (export == null) { if (method.IsGenericMethod || method.ContainsGenericParameters || method.IsGenericMethodDefinition || method.ReturnType.IsGenericType) { continue; } if (method.DeclaringType != type) { continue; } var md = td.GetMethodDefinition(method); if (md == null) { if (Verbose) { Warning($"Unable to find cecil's MethodDefinition of method {method}"); } continue; } if (!md.NeedsMarshalMethod(resolver, method, ref name, ref methodName, ref signature)) { continue; } } if (dt == null) { dt = GetTypeBuilder(dm, type); } if (addedMethods.Contains(methodName)) { continue; } if (Verbose) { Console.Write("Adding marshal method for "); ColorWriteLine($"{method}", ConsoleColor.Green); } var mb = dt.DefineMethod( methodName, System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static); var lambda = builder.CreateMarshalToManagedExpression(method); lambda.CompileToMethod(mb); if (export != null) { name = export.Name; signature = export.Signature; } if (signature == null) { signature = builder.GetJniMethodSignature(method); } registrationElements.Add(CreateRegistration(name, signature, lambda, targetType, methodName)); addedMethods.Add(methodName); } if (dt != null) { AddRegisterNativeMembers(dt, targetType, registrationElements); } } foreach (var tb in definedTypes) { tb.Value.CreateType(); } da.Save(destPath); if (Verbose) { ColorWriteLine($"Marshal method assembly '{assemblyName}' created", ConsoleColor.Cyan); } var dstAssembly = resolver.GetAssembly(destPath); if (!string.IsNullOrEmpty(outDirectory)) { path = Path.Combine(outDirectory, Path.GetFileName(path)); } var mover = new TypeMover(dstAssembly, ad, path, definedTypes, resolver); mover.Move(); if (!keepTemporary) { FilesToDelete.Add(dstAssembly.MainModule.FileName); } }
/// Called when an assembly could not be resolved private static Assembly OnAssemblyResolving(AssemblyLoadContext context, AssemblyName assembly) { return(context.LoadFromAssemblyPath(Path.Combine(lambdaTaskRoot, $"{assembly.Name}.dll"))); }
public AppInfo() { assemblyName = Assembly.GetEntryAssembly().GetName(); }
public void DefineDynamicAssembly_AssemblyName_AssemblyBuilderAccess(AssemblyName name, AssemblyBuilderAccess access) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, access); VerifyAssemblyBuilder(assembly, name, new CustomAttributeBuilder[0]); }
/// <inheritdoc/> protected override Assembly?Load(AssemblyName name) { var path = this.resolver.ResolveAssemblyToPath(name); return(path == null ? null : this.LoadFromAssemblyPath(path)); }
public static Type GetType(AssemblyName assemblyName, string typeName) { var assembly = Assembly.Load(assemblyName); return assembly.GetType(typeName); }
public void GetAssemblyIdentities() { AssemblyIdentity[] names; names = GlobalAssemblyCache.GetAssemblyIdentities(new AssemblyName("mscorlib")).ToArray(); Assert.True(names.Length >= 1, "At least 1 mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = GlobalAssemblyCache.GetAssemblyIdentities(new AssemblyName("mscorlib"), ImmutableArray.Create(ProcessorArchitecture.MSIL, ProcessorArchitecture.X86)).ToArray(); Assert.True(names.Length >= 1, "At least one 32bit mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = GlobalAssemblyCache.GetAssemblyIdentities("mscorlib").ToArray(); Assert.True(names.Length >= 1, "At least 1 mscorlib"); foreach (var name in names) { Assert.Equal("mscorlib", name.Name); } names = GlobalAssemblyCache.GetAssemblyIdentities("System.Core, Version=4.0.0.0").ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core", name.Name); Assert.Equal(new Version(4, 0, 0, 0), name.Version); Assert.True(name.GetDisplayName().Contains("PublicKeyToken=b77a5c561934e089"), "PublicKeyToken matches"); } names = GlobalAssemblyCache.GetAssemblyIdentities("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", name.GetDisplayName()); } var n = new AssemblyName("System.Core"); n.Version = new Version(4, 0, 0, 0); n.SetPublicKeyToken(new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 }); names = GlobalAssemblyCache.GetAssemblyIdentities(n).ToArray(); Assert.True(names.Length >= 1, "At least System.Core"); foreach (var name in names) { Assert.Equal("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", name.GetDisplayName()); } names = GlobalAssemblyCache.GetAssemblyIdentities("x\u0002").ToArray(); Assert.Equal(0, names.Length); names = GlobalAssemblyCache.GetAssemblyIdentities("\0").ToArray(); Assert.Equal(0, names.Length); names = GlobalAssemblyCache.GetAssemblyIdentities("xxxx\0xxxxx").ToArray(); Assert.Equal(0, names.Length); // fusion API CreateAssemblyEnum returns S_FALSE for this name names = GlobalAssemblyCache.GetAssemblyIdentities("nonexistingassemblyname" + Guid.NewGuid().ToString()).ToArray(); Assert.Equal(0, names.Length); }