private CreateInstance ( string typeName ) : object | ||
typeName | string | |
리턴 | object |
/// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ public static object CreateClassInstance(Assembly assembly, string className, object[] args) { try { // First, take a stab at creating the instance with the specified name. object instance = assembly.CreateInstance(className, false, BindingFlags.CreateInstance, null, args, null, null); if (instance != null) return instance; Type[] types = assembly.GetTypes(); // At this point, we know we failed to instantiate a class with the // specified name, so try to find a type with that name and attempt // to instantiate the class using the full namespace. foreach (Type type in types) { if (type.Name == className) { return assembly.CreateInstance(type.FullName, false, BindingFlags.CreateInstance, null, args, null, null); } } } catch { } return null; }
/// <summary> /// Creates the form instance. /// </summary> /// <param name="formFile">The form file.</param> /// <param name="optionalParameter">The optional parameter.</param> /// <param name="currentWorkItemName">Name of the current work item.</param> /// <param name="parentWorkItem">The parent work item.</param> /// <returns>The generated form instance.</returns> private Form CreateFormInstance(string formFile, object[] optionalParameter, string currentWorkItemName, WorkItem parentWorkItem) { string assemblyName = string.Empty; WorkItem currentWorkItem = new WorkItem(); Form currentForm = new Form(); if (!string.IsNullOrEmpty(formFile)) { assemblyName = formFile.Remove(formFile.LastIndexOf(".")); assemblyName = string.Concat(assemblyName, ".dll"); //// load the module and get the loaded assembly to create the instance for current form and current workitem. System.Reflection.Assembly assembly = this.LoadModule(assemblyName, parentWorkItem); currentWorkItem = (WorkItem)assembly.CreateInstance(currentWorkItemName); if (optionalParameter != null) { currentForm = (Form)assembly.CreateInstance(formFile, true, BindingFlags.CreateInstance, null, optionalParameter, System.Globalization.CultureInfo.CurrentUICulture, null); } else { currentForm = (Form)assembly.CreateInstance(formFile); } //// add the current workitem to the parent workitem parentWorkItem.Items.Add(currentWorkItem, currentWorkItemName); //// add the current form to the current workitem currentWorkItem.Items.Add(currentForm, formFile); } return(currentForm); }
public static Deflater CreateDeflater() { if (asm == null) { throw new System.IO.FileNotFoundException("Can not load ICSharpCode.SharpZipLib.dll"); } return(new Deflater(asm.CreateInstance("ICSharpCode.SharpZipLib.Zip.Compression.Deflater"))); }
public static Deflater CreateDeflater() { if (asm == null) { throw new System.IO.FileNotFoundException("Can not load ICSharpCode.SharpZipLib.dll"); } #if !NETSTANDARD2_0 return(new Deflater(asm.CreateInstance("ICSharpCode.SharpZipLib.Zip.Compression.Deflater"))); #else var type = asm.GetType("ICSharpCode.SharpZipLib.Zip.Compression.Deflater"); return(new Deflater(Activator.CreateInstance(type))); #endif }
IEnumerator WWWLoadAssembly() { yield return(null); string path = CDirectory.MakeCachePath(_DllPath); if (!File.Exists(path)) { using (var www = new WWW(CDirectory.MakeWWWStreamPath(_DllPath))) { yield return(www); if (!string.IsNullOrEmpty(www.error)) { throw new Exception(string.Format("WWW download:" + www.error + " path : " + www.url)); } Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path, www.bytes); } } System.Reflection.Assembly assembly = null; #if ZTK assembly = ZToolKit.LoadAssembly(path); #else FileStream stream = File.Open(path, FileMode.Open); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); stream.Close(); assembly = System.Reflection.Assembly.Load(buffer); #endif this.game = (IGame)assembly.CreateInstance("CGame"); this.game.StartGame(); }
public System.Data.Common.DbConnection GetConn(System.Reflection.Assembly driverAssembly, string dbConnectionStr) { return ((DbConnection) driverAssembly.CreateInstance("Oracle.ManagedDataAccess.Client.OracleConnection", true, BindingFlags.Default, null, new object[] { dbConnectionStr }, null, null)); }
//======================================================================= //======================================================================= public static bool TryLoadClass(Assembly assembly, string className, out string message, out object instance) { instance = null; if (assembly == null) { message = "Assembly must not be null"; return false; } try { instance = assembly.CreateInstance(className); message = "Class loaded successfully"; return true; } catch (MissingMethodException) { message = "Error loading class, constructor not found."; return false; } catch (Exception ex) { message = ("Class load error: " + ex.Message); return false; } }
public AspectInfo(string assemblyName, string className, string deployModell, string pointCutType, string actionPosition, string matchClass, string matchMethod, string matchPattern) { _AssemblyName = assemblyName; _ClassName = className; _DeployModell = deployModell; _PointCutType = pointCutType; _ActionPosition = actionPosition; _MatchClass = matchClass; _MatchMethod = matchMethod; _MatchPattern = matchPattern; if (DeployModell.Equals("Singleton")) { string filePath = InjectionManager.ASSEMBLY_PATH; if (filePath.LastIndexOf(@"\") < filePath.Length - 1) { filePath += @"\"; } filePath += assemblyName; if (System.IO.File.Exists(filePath)) { System.Reflection.Assembly DLL = System.Reflection.Assembly.LoadFrom(filePath); System.Type t = DLL.GetType(); SingletonAspect = DLL.CreateInstance(className, true, BindingFlags.Default, null, null, null, null) as IInjection; } else { throw new Exception(string.Format("Injecttion 配置有误,配件{0}找不到!", filePath)); } } }
public static object Eval(string sExpression) { CSharpCodeProvider c = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("namespace CSCodeEvaler{ \n"); sb.Append("public class CSCodeEvaler{ \n"); sb.Append("public object EvalCode(){\n"); sb.Append("return " + sExpression + "; \n"); sb.Append("} \n"); sb.Append("} \n"); sb.Append("}\n"); CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { throw new InvalidExpressionException( string.Format("Error ({0}) evaluating: {1}", cr.Errors[0].ErrorText, sExpression)); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("EvalCode"); object s = mi.Invoke(o, null); return(s); }
public T[] GetMembers <T>() { Type t = typeof(T); List <T> res = new List <T>(); //アセンブリを読み込む System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(this.FileName); foreach (Type type in asm.GetTypes()) { try { if (type.IsClass && t.IsPublic && !type.IsAbstract && (type.GetInterface(t.FullName) != null || type.IsSubclassOf(t))) { //クラス名からインスタンスを作成する res.Add((T)asm.CreateInstance(type.FullName)); } } catch { } } return(res.ToArray()); }
public static object Eval(string sCSCode) { CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = (ICodeCompiler)c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append(sCSCode); CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { Console.Write("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code"); return(null); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("Cgi.Cgi"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("main"); object s = mi.Invoke(o, null); return(s); }
//private void LoadLanguage() //{ // byte[] bytes = File.ReadAllBytes(CDirectory.MakeFilePath(language)); // Localization.language = "language"; // Localization.LoadCSV(bytes); //} void LoadAssembly() { string mdb_path; string path = GetAssemblyPath(out mdb_path); System.Reflection.Assembly assembly = null; if (path.IndexOf(_DllPath) == -1) { FileStream stream = File.Open(path, FileMode.Open); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); stream.Close(); if (string.IsNullOrEmpty(mdb_path) && File.Exists(mdb_path)) { FileStream mdb_stream = File.Open(mdb_path, FileMode.Open); byte[] mdb_buffer = new byte[mdb_stream.Length]; mdb_stream.Read(mdb_buffer, 0, (int)mdb_stream.Length); mdb_stream.Close(); assembly = System.Reflection.Assembly.Load(buffer, mdb_buffer); } else { assembly = System.Reflection.Assembly.Load(buffer); } } else { #if ZTK assembly = ZToolKit.LoadAssembly(path); #endif } this.game = (IGame)assembly.CreateInstance("CGame"); this.game.StartGame(); }
public void ProcessRequest(HttpContext ctx) { // Code for calculating tax is provided as unvalidated user input string taxFormula = ctx.Request.QueryString["tax_formula"]; // Used to create C# StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class TaxCalc {\n"); sourceCode.Append("\tpublic int CalculateTax(int value){\n"); sourceCode.Append("\t\treturn " + taxFormula + "; \n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); // BAD: This compiles the sourceCode, containing unvalidated user input CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = icc.CompileAssemblyFromSource(cp, sourceCode.ToString()); // Compiled input is loaded, and an instance of the class is constructed System.Reflection.Assembly a = cr.CompiledAssembly; object taxCalc = a.CreateInstance("TaxCalc"); // Unsafe code is executed Type taxCalcType = o.GetType(); MethodInfo mi = type.GetMethod("CalculateTax"); int value = int.Parse(ctx.Request.QueryString["value"]); int s = (int)mi.Invoke(o, new object[] { value }); // Result is returned to the user ctx.Response.Write("Tax value is: " + s); }
/// <summary> /// 加载方法/函数 /// </summary> /// <param name="asmFile">待反射文件的路径(相对路径或绝对路径)</param> /// <param name="asmClass">要反射的类的全名(包括命名空间)</param> /// <param name="methodName">要调用的方法/函数名称</param> /// <param name="paramter">函数需要使用的参数数组</param> /// <returns></returns> public static object LoadMethod(string asmFile, string asmClass, string methodName, object[] paramter) { try { //if (!File.Exists(asmFile)) return null; //读取为Byte[]防止出现文件占用 //byte[] fileData = System.IO.File.ReadAllBytes(asmFile); //加载程序集(EXE 或 DLL) System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(asmFile); //调用方法 Type type = assembly.GetType(asmClass); object obj = assembly.CreateInstance(asmClass); System.Reflection.MethodInfo methodInfo = type.GetMethod(methodName); //所调用方法需要用到的参数 //object[] paramter = new object[1]; //paramter[0] = "test"; return(methodInfo.Invoke(obj, paramter)); } catch (Exception ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw ex; } }
private IEnumerable<ICommand> GetCommandsFromAssembly(Assembly assembly) { try { return assembly .GetTypes() .Where(type => { return type.IsClass; }) .Where(type => { return type.GetInterface("ShellMe.CommandLine.CommandHandling.ICommand") != null; }) .Select(type => { try { return (ICommand) assembly.CreateInstance(type.ToString()); } catch (Exception) { return null; } }) .Where(command => command != null); } catch (Exception exception) { return Enumerable.Empty<ICommand>(); } }
// codebase/idl/idl.somename.dll contains generated API wrapper for somename // codebase/api/api.somename.dll contains actual user-written code for API private ApiInstance(string name, string codepath) { path = Path.Combine(Path.Combine(codepath, "idl"), "idl." + name + ".dll"); // todo: for runtime code replacement, use appdomains and refcount active requests assy = Assembly.LoadFile(path); if (assy == null) { throw new FileNotFoundException("Could not find assembly: " + path); } Console.WriteLine("Loaded {0} from {1}", name, path); foreach (Type t in assy.GetExportedTypes()) { Console.WriteLine("Examining type {0}", t.Name); if ((t.Name == name || t.Name == "idl." + name) && typeof(WrapperBase).IsAssignableFrom(t)) { Console.WriteLine("Found type {0}", t.Name); wrapper = (WrapperBase)assy.CreateInstance(t.FullName); wrapper.CodePath = codepath; wrapper.Initialize(); break; } } if (wrapper == null) { throw new FileNotFoundException("Could not instantiate wrapper type: " + path); } api_counter.Count(); }
private void GetCommands() { try { System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(this.assemblyPath); if (assembly != null) { System.Type[] types = assembly.GetTypes(); System.Type[] array = types; for (int i = 0; i < array.Length; i++) { System.Type type = array[i]; if (type.GetInterface("ICommand") != null) { ICommand command = assembly.CreateInstance(type.FullName) as ICommand; if (command != null) { this.commandList.Add(command); } } } } } catch (System.Exception) { } }
/// <summary> /// Create the instance of the asked type contained in the compiled assembly /// </summary> /// <param name="ObjectType"></param> /// <returns>true if object is created</returns> public bool GetInstanceOfObject(string ObjectType) { if (_assembly == null) { return(false); } try { _objType = _assembly.GetType(ObjectType); if (_objType != null) { _objInstance = _assembly.CreateInstance(ObjectType); return(true); } else { return(false); } } catch { return(false); } }
private void cmdOK_Click(object sender, EventArgs e) { if (!File.Exists(txtPath.Text)) { MessageBox.Show("You must specify a valid path to an assembly!", "Path", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } try { System.Reflection.Assembly agentAssembly = System.Reflection.Assembly.LoadFile(txtPath.Text); IAgent agent = (IAgent)agentAssembly.CreateInstance(cboClass.Text); if (agent == null) { MessageBox.Show("Invalid class specified!", "Class", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } agent = null; agentAssembly = null; } catch (Exception ex) { MessageBox.Show("Error loading assembly or accessing class!\r\n" + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } AgentRegistration.Name = txtName.Text; AgentRegistration.AssemblyPath = txtPath.Text; AgentRegistration.ClassName = cboClass.Text; AgentRegistration.IsCollector = optCollector.Checked; AgentRegistration.IsNotifier = optNotifier.Checked; DialogResult = DialogResult.OK; Close(); }
public override void _runLoad(string nUrl) { UrlParser urlParser_ = new UrlParser(nUrl); string assemblyPath_ = urlParser_._returnResult(); AssemblyName assemblyName_ = AssemblyName.GetAssemblyName(assemblyPath_); AppDomain appDomain_ = AppDomain.CurrentDomain; Assembly[] assemblies_ = appDomain_.GetAssemblies(); foreach (Assembly i in assemblies_) { if (string.Compare(i.FullName, assemblyName_.FullName) == 0) { mAssembly = i; } } if (null == mAssembly) { mAssembly = Assembly.LoadFrom(assemblyPath_); string namespace_ = assemblyName_.Name; string pluginClass_ = namespace_ + ".Plugin"; IPlugin plugin_ = mAssembly.CreateInstance(pluginClass_) as IPlugin; if (null != plugin_) { plugin_._startupPlugin(); } } base._runLoad(nUrl); }
/// <summary> /// 将反射得到字符串转换为对象 /// </summary> /// <param name="str">反射得到的字符串</param> /// <returns>实体类</returns> public static T GetEntityStringToEntity(string str) { string[] array = str.Split(','); string[] temp = null; Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (string s in array) { temp = s.Split(':'); dictionary.Add(temp[0], temp[1]); } System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(T)); T entry = (T)assembly.CreateInstance(typeof(T).FullName); System.Text.StringBuilder sb = new StringBuilder(); Type type = entry.GetType(); System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties(); for (int i = 0; i < propertyInfos.Length; i++) { foreach (string key in dictionary.Keys) { if (propertyInfos[i].Name == key.ToString()) { propertyInfos[i].SetValue(entry, GetObject(propertyInfos[i], dictionary[key]), null); break; } } } return(entry); }
public System.Data.Common.DbConnection GetConn(System.Reflection.Assembly driverAssembly, string dbConnectionStr) { return ((DbConnection) driverAssembly.CreateInstance("Npgsql.NpgsqlConnection", true, BindingFlags.Default, null, new object[] { dbConnectionStr }, null, null)); }
static DataAccessProviderFactory() { string providerName = ConfigurationManager.AppSettings["DataProvider"]; string providerFactoryName = ConfigurationManager.AppSettings["DataProviderFactory"]; activeProvider = Assembly.Load(providerName); activeDataProviderFactory = (IDataProviderFactory)activeProvider.CreateInstance(providerFactoryName); }
public static string ExeAssembly(string[] arguments) { var consoleout = new StringWriter(); try { // https://exord66.github.io/csharp-in-memory-assemblies Console.SetOut(consoleout); byte[] decode_assembly = Convert.FromBase64String(arguments[1]); //decode base64 System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(decode_assembly); //Find the Entrypoint or "Main" method MethodInfo method = assembly.EntryPoint; string[] Split_Arguments = arguments.Skip(2).ToArray(); object[] Args_Object = new[] { Split_Arguments }; if (method != null) { object Obj_Parameters = assembly.CreateInstance(method.Name); method.Invoke(Obj_Parameters, Args_Object); } var stdout = Console.Out; Console.SetOut(stdout); } catch (Exception ex) { return(ex.Message); } return(consoleout.ToString()); }
public static Object GetObjectByDllName(string dllFullPathName, string classFullName) { try { if (!System.IO.File.Exists(dllFullPathName)) { string exeFullPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string Path = exeFullPath.Substring(0, exeFullPath.LastIndexOf(System.IO.Path.DirectorySeparatorChar)); dllFullPathName = System.IO.Path.Combine(Path, dllFullPathName); if (!System.IO.File.Exists(dllFullPathName)) { MessageBox.Show("DLL文件不存在"); return(null); } } System.Reflection.Assembly dllAssemblly = System.Reflection.Assembly.LoadFrom(dllFullPathName); object obj = dllAssemblly.CreateInstance(classFullName); return(obj); //某个dll下 //System.Reflection.Assembly //某个名称空间下 //某个类(Form窗体) } catch (Exception ex) { MessageBox.Show(ex.StackTrace); return(null); } }
public static object ExecuteCode(string scode, dynamic param) { ICodeCompiler compiler = (new CSharpCodeProvider()).CreateCompiler(); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.ReferencedAssemblies.Add("system.dll"); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; StringBuilder code = new StringBuilder(); code.Append("using System; \n"); code.Append("namespace Eval { \n"); code.Append(" public class Evaluator { \n"); code.Append(" public bool Execute(dynamic x) {\n"); code.Append(" " + scode + ";\n"); code.Append(" }\n"); code.Append(" }\n"); code.Append("}\n"); CompilerResults cr = compiler.CompileAssemblyFromSource(compilerParameters, code.ToString()); System.Reflection.Assembly assembly = cr.CompiledAssembly; object compiled = assembly.CreateInstance("Eval.Evaluator"); MethodInfo mi = compiled.GetType().GetMethod("Execute"); return(mi.Invoke(compiled, new object[] { param })); }
/// <summary> /// Compila una clase dado su código /// </summary> /// <param name="Code">Codigo de la clase</param> /// <param name="ClassName">Nombre de la clase</param> /// <param name="Assemblies">Ensamblados necesarios</param> /// <param name="Usings">Usings utilizados</param> /// <returns>Objecto de la clase compilada</returns> public static object CompileClass(string Code, string ClassName, List <string> Assemblies = null, List <string> Usings = null) { CSharpCodeProvider c = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); SetReferences(cp, Assemblies); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); SetUsings(sb, Usings); sb.Append("namespace DNOTA{ \n"); sb.Append(Code + "\n"); sb.Append("}\n"); CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { //MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText,"Error evaluating cs code", MessageBoxButtons.OK,MessageBoxIcon.Error); throw new Exception(cr.Errors[0].ErrorText); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("ESKPE." + ClassName); return(o); }
/// <summary> /// Original method taken from http://www.codeproject.com/KB/cs/evalcscode.aspx /// </summary> /// <param name="sCSCode"></param> /// <returns></returns> public static object Eval(string sCSCode) { CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); Assembly thisAssembly = Assembly.GetExecutingAssembly(); Assembly fuzzyFrameworkAssembly = Assembly.GetAssembly(typeof(FuzzyFramework.FuzzyRelation)); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.ReferencedAssemblies.Add(thisAssembly.Location); cp.ReferencedAssemblies.Add(fuzzyFrameworkAssembly.Location); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("using System.Xml;\n"); sb.Append("using System.Data;\n"); sb.Append("using System.Data.SqlClient;\n"); sb.Append("using System.Windows.Forms;\n"); sb.Append("using System.Drawing;\n"); sb.Append("namespace CSCodeEvaler{ \n"); sb.Append("public class CSCodeEvaler{ \n"); sb.Append("public object EvalCode(){\n"); sb.Append("return " + sCSCode + "; \n"); sb.Append("} \n"); sb.Append("} \n"); sb.Append("}\n"); CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText, "Error evaluating cs code", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler"); Type t = o.GetType(); System.Reflection.MethodInfo mi = t.GetMethod("EvalCode"); object s = mi.Invoke(o, null); return(s); }
public static string Eval(string sCSCode, dynamic Variables, dynamic Solution, dynamic SolutionProject, dynamic Environment) { CSharpCodeProvider c = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.core.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); string path = (new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath; cp.ReferencedAssemblies.Add(path); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("using System.IO;\n"); sb.Append("using System.Xml;\n"); sb.Append("using System.Data;\n"); sb.Append("using Topics.Core.Models;\n"); sb.Append("using System.Dynamic;\n"); sb.Append("namespace CSCodeEvaler{ \n"); sb.Append("public class CSCodeEvaler{ \n"); sb.Append("private string _underscore_ = \"_\";"); sb.Append("public object EvalCode(dynamic Variables, dynamic Solution, dynamic SolutionProject, dynamic Environment){\n"); sb.Append("try { \n"); sb.Append("return " + sCSCode + "; \n"); sb.Append("} catch(Exception ex) { return ex.Message; } \n"); sb.Append("} \n"); sb.Append("} \n"); sb.Append("}\n"); CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { return("ERROR: " + cr.Errors[0].ErrorText); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("EvalCode"); object s = mi.Invoke(o, new object[] { Variables, Solution, SolutionProject, Environment }); return(s.ToString()); }
private static IDriver CreateDriverInstance(string assemblyName, Assembly assembly) { IDriver driver = null; if (assembly != null) { driver = assembly.CreateInstance(assemblyName + ".Driver") as IDriver; } return driver; }
/// <summary> /// Load a module giving and assembly name and an interface name. /// </summary> /// <param name="assemblyFilename">Name of assembly to look in</param> /// <param name="interfaceType">Fullname of the interface to look for</param> /// <param name="modName">Name of the module to manage it under. If null, the module /// will not be managed by this module manager.</param> /// <returns></returns> public Object LoadModule(string assemblyFilename, string interfaceType, string modName) { string fullfile = new System.IO.FileInfo(assemblyFilename).FullName; Object obj = null; try { System.Reflection.Assembly assem = System.Reflection.Assembly.LoadFile(fullfile); foreach (Type type in assem.GetTypes()) { if (!type.IsClass || type.IsNotPublic) { continue; } Type[] interfaces = type.GetInterfaces(); for (int ii = 0; ii < interfaces.Length; ii++) { if (interfaces[ii].FullName.Equals(interfaceType)) { //Object[] parms = { modName , modParams } ; obj = assem.CreateInstance(type.FullName, true, System.Reflection.BindingFlags.Default, null, null, null, null); // null, parms, null, null); m_log.Log(LogLevel.DMODULE, "CreateInstance of " + type.FullName); ((IModule)obj).OnLoad(modName, m_lgb); if (modName != null) { ManageModule(obj, modName); } break; } } if (obj != null) { break; } } } catch (System.Reflection.ReflectionTypeLoadException e) { m_log.Log(LogLevel.DBADERROR, "Failed to load type {0}. Exceptions follow", interfaceType); foreach (Exception ee in e.LoaderExceptions) { m_log.Log(LogLevel.DBADERROR, "LoaderException:" + ee.ToString()); } } catch (Exception e) { m_log.Log(LogLevel.DBADERROR, "Failed to load type {0} from {1}: {2}", interfaceType, assemblyFilename, e.ToString()); obj = null; } if (obj == null) { m_log.Log(LogLevel.DBADERROR, "Failed to load type {0} from {1}", interfaceType, assemblyFilename); throw new LookingGlassException("Could not load module " + interfaceType + " from " + assemblyFilename); } return(obj); }
internal object method_3(string string_3) { System.Reflection.Assembly assembly = this.method_2(); if (assembly == null) { return(null); } return(assembly.CreateInstance(string_3)); }
public ItemBuilder(Assembly asm, string namespce, string klass) { string full_name = String.Format ("{0}.{1}", namespce, klass); item = asm.CreateInstance (full_name) as Item; if (item == null) throw new ApplicationException (String.Format ("Unable to create instance of {0}", full_name)); }
static SkillBase CreateSkill(SkillData data) { string myCore = "MyCore."; System.Reflection.Assembly assembly = Assembly.GetExecutingAssembly(); SkillBase skill = assembly.CreateInstance(myCore + data.ClassName) as SkillBase; return(skill); }
public object Eval(string sExpression, string Declaracion, ref string msg, string Parametros) { try { if (sExpression != "") { CSharpCodeProvider c = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.CompilerOptions = "/optimize"; cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; cp.GenerateExecutable = false; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("namespace CSCodeEvaler{ \n"); sb.Append("public class CSCodeEvaler{ \n"); sb.Append("public Double EvalCode(" + Parametros + "){\n"); sb.Append(" " + Declaracion + " \n"); sb.Append("return " + sExpression + "; \n"); //sb.Append("return rs; \n"); sb.Append("} \n"); sb.Append("} \n"); sb.Append("}\n"); CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { return("0"); } System.Reflection.Assembly a = cr.CompiledAssembly; InstanciaDeFuncion = a.CreateInstance("CSCodeEvaler.CSCodeEvaler"); Type t = InstanciaDeFuncion.GetType(); mi = t.GetMethod("EvalCode"); return(Funcion); } else { msg = "Ingrese una formula correcta para poder evaluarla"; return(null); } } catch (Exception ex) { Core.Erp.Info.Log_Exception.LoggingManager.Logger.Log(Core.Erp.Info.Log_Exception.LoggingCategory.Error, ex.Message); throw new Core.Erp.Info.Log_Exception.DalException(string.Format("", "Eval", ex.Message), ex) { EntityType = typeof(ro_calculos_formula_IESS_bus) }; } }
//Essa classe cria uma classe a partir de string *ALTAMENTE COMPLEXO* //Explicaçao: A partir de um compilador dentro de uma classe, a gente usa uma String com todo o codigo de uma classe Completa para emular uma classe alteravel em tempo de uso. public object CodigoDinamico(string sCSCode, object oParam) { CSharpCodeProvider c = new CSharpCodeProvider(); ICodeCompiler icc = c.CreateCompiler(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.ReferencedAssemblies.Add("Softsong.exe"); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("using System.Xml;\n"); sb.Append("using System.Data;\n"); sb.Append("using System.Data.SqlClient;\n"); sb.Append("using System.Windows.Forms;\n"); sb.Append("using System.Drawing;\n"); sb.Append("using SoftSong.Interfaces;\n"); sb.Append("using SoftSong.Popups;\n"); sb.Append("namespace CSSoftSong{ \n"); sb.Append("public class CSSoftSong{ \n"); sb.Append("public object AbrirUser(Control.ControlCollection Controles){\n"); sb.Append("object o = new object(); \n"); sb.Append(sCSCode + " \n"); sb.Append("return o; \n"); sb.Append("} \n"); sb.Append("} \n"); sb.Append("}\n"); //Debug.WriteLine(sb.ToString())// ' look at this to debug your eval string CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { MessageBox.Show("ERRO: " + cr.Errors[0].ErrorText, "Erro compilando esse codigo", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSSoftSong.CSSoftSong"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("AbrirUser"); object[] oParams = new object[1]; oParams[0] = oParam; object s = mi.Invoke(o, oParams); return(s); }
public string LoadPlugin(string Path, string ClassName, bool DoRun) { string result = "OK"; try { System.Reflection.Assembly plugindll = System.Reflection.Assembly.LoadFrom(Path); Type plugin; //retrieve the nodoinfo foreach (System.Type objType in plugindll.GetTypes()) { //Only look at public, non abstract types if (objType.IsPublic && !objType.IsAbstract) { //See if this type implements our interface plugin = objType.GetInterface("VVVV.PluginInterfaces.V1.IPlugin"); if (plugin != null) { PropertyInfo pi = objType.GetProperty("PluginInfo"); object a = pi.GetValue(null, null); IPluginInfo info = (IPluginInfo)a; FNodeInfoName = info.Name; break; } } } FNodeName = System.IO.Path.GetFileName(Path) + "|" + ClassName; FHostedPlugin = plugindll.CreateInstance(ClassName) as IPlugin; //hand the host over to the plugin FHostedPlugin.SetPluginHost(this); if (DoRun) { OnPinCountChanged(); } } catch (Exception e) { result = "ERROR: " + e.Message; } //save starttime HighPerfTimer.Update(); FStartTime = HighPerfTimer.Ticks / 1000D; if ((FHostedPlugin != null) && (DoRun)) { FTimer.Enabled = true; } return(result); }
public static object Evaluate(string code) { Assembly engineAssembly = Assembly.GetAssembly(typeof(QAliber.Engine.Controls.UIControlBase)); CSharpCodeProvider c = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("system.dll"); cp.ReferencedAssemblies.Add("system.xml.dll"); cp.ReferencedAssemblies.Add("system.data.dll"); cp.ReferencedAssemblies.Add("system.drawing.dll"); cp.ReferencedAssemblies.Add("system.windows.forms.dll"); //TODO : test for x86 , x64 cp.ReferencedAssemblies.Add(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll"); cp.ReferencedAssemblies.Add(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationTypes.dll"); cp.ReferencedAssemblies.Add(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationClient.dll"); cp.ReferencedAssemblies.Add(engineAssembly.Location); cp.CompilerOptions = "/t:library"; cp.GenerateInMemory = true; StringBuilder sb = new StringBuilder(""); sb.Append("using System;\n"); sb.Append("using System.IO;\n"); sb.Append("using System.Xml;\n"); sb.Append("using System.Data;\n"); sb.Append("using System.Windows.Forms;\n"); sb.Append("using System.Windows;\n"); sb.Append("using QAliber.Engine.Controls;\n"); sb.Append("using QAliber.Engine.Controls.UIA;\n"); sb.Append("namespace CSCodeEvaler{ \n"); sb.Append("public class CSCodeEvaler{ \n"); sb.Append("public object EvalCode(){\n"); sb.Append(code); sb.Append("}\n"); sb.Append("}\n"); sb.Append("}\n"); CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString()); if (cr.Errors.Count > 0) { throw new ArgumentException("The expression '" + code + "' does not compile to C#, or does not return bool"); } System.Reflection.Assembly a = cr.CompiledAssembly; object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler"); Type t = o.GetType(); MethodInfo mi = t.GetMethod("EvalCode"); return(mi.Invoke(o, null)); }
static void Method(Assembly plugin) { //This cast fails because the two MyPlugin types are incompatible. //The MyPlugin type which appears in the code is resolved by the JIT //to the load context, but the Plugin.MyPlugin type which is created //using reflection (Assembly.CreateInstance) is resolved to the //load-from context. The exception message (as of .NET 3.5) discloses //the problem right away. MyPlugin myPlugin2 = (MyPlugin)plugin.CreateInstance("Plugin.MyPlugin"); }
public Migrator(Assembly assembly, IMigrationFormatter formatter) { this.repository = new MigrationRepository(formatter); this.migrations = new List<Migration>(); foreach (var t in assembly.GetTypes()) { if (t != typeof(Migration) && typeof(Migration).IsAssignableFrom(t)) { var m = (Migration)assembly.CreateInstance(t.ToString()); migrations.Add(m); } } }
IPluginActivator GetPluginActivator(Assembly assembly) { foreach (var type in assembly.GetTypes()) { if (!typeof(IPluginActivator).IsAssignableFrom(type)) continue; return assembly.CreateInstance(type.FullName) as IPluginActivator; } // TODO: 例外を投げたい return null; }
/// <summary> /// Creates a Controller based on the route values from the URL. /// </summary> /// <param name="requestContext"></param> /// <returns></returns> public Controller CreateController(Assembly assembly, string controllerName) { controllerName = controllerName.ToLower() + "controller"; var nameSpace = assembly.GetName().Name; var type = assembly.GetTypes().Where(t => t.FullName.ToLower().Contains(controllerName)).FirstOrDefault(); Controller controller = (Controller)assembly.CreateInstance(type.FullName); return controller; }
public static Delegate CreateDelegate(Assembly dynamicAssembly) { var dynamicObject = dynamicAssembly.CreateInstance(DYNAMIC_CLASS_NAME); if (dynamicObject == null) throw new TypeLoadException(DYNAMIC_CLASS_NAME); var dynamicMethod = dynamicObject.GetType().GetMethod(DYNAMIC_METHOD_NAME); if (dynamicMethod == null) throw new MissingMethodException(DYNAMIC_METHOD_NAME); return GetDelegate(dynamicObject, dynamicMethod); }
protected void RegisterAssemblyParselets(Assembly asm) { ID900Parselet parselet; foreach (Type t in asm.GetTypes()) { if (t.GetInterface(typeof(ID900Parselet).Name) != null) { parselet = (asm.CreateInstance(t.FullName, true) as ID900Parselet); this.RegisterParselet(parselet); } } }
/// <summary> /// Initializes a new instance of a component resolver /// based on the implementation located in a component /// package's designer assembly. /// </summary> /// <param name="asm"></param> /// <param name="type"></param> public AfxComponentResolver(Assembly asm, Type type) { var identityAttribute = GetIdentityAttribute(type); if (identityAttribute != null) { this.Id = new Guid(identityAttribute.Id); this.Name = identityAttribute.Name; } // Create an instance of the resolver interface // implementation and assign it to the internal // reference for future use: _instance = asm.CreateInstance(type.FullName) as IAfxComponentResolver; }
private void LoadAssembly() { var ant = GetConfig().GetData("ant"); _fileName = ant.Value<string>("file"); _className = ant.Value<string>("class"); if (_fileName == "" || _className == "") throw new Exception("Ant를 로드할 수 없습니다."); _assembly = Assembly.LoadFrom(_fileName); _localAnt = _assembly.CreateInstance(_className) as AntModel; if (_localAnt == null) throw new Exception("AntModel을 로드 할 수 없습니다."); }
private static void LoadFommScriptObject() { var data = Compile(@" using System; using fomm.Scripting; using Fomm.PackageManager; class ScriptRunner { public static bool RunScript(string script, ModInstaller p_midInstaller) { return fommScript.Execute(script, p_midInstaller); } }"); fommScriptRunner = AppDomain.CurrentDomain.Load(data); fommScriptObject = fommScriptRunner.CreateInstance("ScriptRunner"); }
public override void _runLoad(string nUrl) { base._runLoad(nUrl); string assemblyInfoUrl_ = nUrl + @"*$assembly.xml"; mAssemblyInfo._runLoad(assemblyInfoUrl_); UdlHeadstream udlHeadstream_ = this._getUdlHeadstream(); string fileName_ = udlHeadstream_._getFileName(); UrlParser urlParser_ = new UrlParser(nUrl); string assemblyPath_ = urlParser_._urlFile(fileName_); AssemblyName assemblyName_ = AssemblyName.GetAssemblyName(assemblyPath_); AppDomain appDomain_ = AppDomain.CurrentDomain; Assembly[] assemblies_ = appDomain_.GetAssemblies(); foreach (Assembly i in assemblies_) { if (string.Compare(i.FullName, assemblyName_.FullName) == 0) { mAssembly = i; return; } } UidSingleton uidSingleton_ = __singleton<UidSingleton>._instance(); IEnumerable<Uid> uids_ = mAssemblyDescriptor._getUids(); foreach (Uid i in uids_) { uidSingleton_._addUid(i); Uid uid_ = i._getUid(); string uidUrl_ = uid_._getOptimal(); this._loadAssembly(uidUrl_); } IEnumerable<Rid> rids_ = mAssemblyDescriptor._getRids(); foreach (Rid i in rids_) { uidSingleton_._addRid(i); } IEnumerable<string> dependences_ = mAssemblyDescriptor._getDependences(); foreach (string i in dependences_) { this._loadAssembly(i); } mAssembly = Assembly.LoadFrom(assemblyPath_); string namespace_ = assemblyName_.Name; string pluginClass_ = namespace_ + ".Plugin"; IPlugin plugin_ = mAssembly.CreateInstance(pluginClass_) as IPlugin; if (null != plugin_) { plugin_._startupPlugin(); } }
public static void Instantiate(Assembly a, Interpreter interp) { Hashtable table = interp.VarTable; try { CodeChunk chunk = (CodeChunk)a.CreateInstance("CsiChunk"); chunk.Go(table); // we display the type and value of expressions. The variable $_ is // always set, which is useful if you want to save the result of the last // calculation. if (interp.returnsValue && DumpingValue) { string stype; object val = table["_"]; if (val == null) { stype = null; } else { Type type = val.GetType(); stype = interp.GetPublicRuntimeTypeName(type, true); stype = "(" + (stype ?? interp.GetTypeName(type, true)) + ")"; } if (val == null) { Print("null"); } else if (val is string) { Print(stype, "'" + val + "'"); } else if (val is IEnumerable) { Print(stype); Dumpl((IEnumerable)val); } else Print(stype, val); } } catch (Exception ex) { Print(ex.GetType() + " was thrown: " + ex.Message); } }
public object GetServiceProxy(Assembly webServiceAssembly, string serviceName) { object proxy = webServiceAssembly.CreateInstance(serviceName); if (proxy == null) throw new Exception("Cannot create proxy instance"); if (_modifier == null) return proxy; var factory = new ProxyFactory(proxy) { ProxyTargetType = true }; factory.AddAdvice(new WebRequestModifyInterceptor(_modifier)); var result = factory.GetProxy(); SetUpMissingValues(proxy, result); return result; }
/// <summary> /// Получить объект правила из сборки /// </summary> /// <param name="a">Сборка</param> /// <returns></returns> private static AbstractExperiment GetExperimentModeFromAssembly(Assembly a) { string className = a.GetName().Name + ".Experiment"; object o = a.CreateInstance(className); var experiment = o as AbstractExperiment; if (experiment == null) throw new InvalidExperimentAssemblyException(); if (Properties.Settings.Default.PluginCaption == experiment.ToString()) { AppSettings.Mode = experiment; AppSettings.Mode.LoadSettings(Properties.Settings.Default.SettingsFileName); } return experiment; }
public override MethodInfo GetMainMethodAndOwnerInstance(Assembly assembly, out object owner) { foreach (Type type in assembly.GetTypes()) { BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; MethodInfo methodInfo = type.GetMethod("Main", flags); if (methodInfo != null) { owner = assembly.CreateInstance(type.FullName); return methodInfo; } } owner = null; return null; }
/// <summary> /// Searches through the compiled assembly a, and looks at all classes contained within it. /// If it finds any that implement the FileTranslator interface, it will register them with /// the FileTranslatorManager /// </summary> /// <param name="a"> The compiled assembly </param> /// <returns> void </returns> private static void InvokeAssembly(Assembly a) { // search all classes in the compiled assembly foreach (Type t in a.GetTypes()) { // check to see if this type has the FileTranslator interface if (null != t.GetInterface("FileTranslator")) { // create an instance of it object result = a.CreateInstance(t.FullName); FileTranslator ft = (FileTranslator)result; if (ft != null) { FileTranslatorManager.RegisterTranslator(ft); } } } }
/// <summary> /// 加载子系统完成事件 /// </summary> /// <param name="MenuCode"></param> public void LoadChildSystemModule(string MenuCode) { var entityMenu = (from ent in Context.CacheMenuAll where ent.MENUCODE == MenuCode select ent).FirstOrDefault(); menuInfo = entityMenu; var systemTypeDic=(from ent in Context.CacheSystemType where ent.DICTIONARYVALUE.Value.ToString() == entityMenu.SYSTEMTYPE select ent).FirstOrDefault(); strSystemType = systemTypeDic.SYSTEMNEED; MainPageManeger.LoadXapName = systemTypeDic.SYSTEMNEED; if (Context.allChildSystemAssembly.ContainsKey(systemTypeDic.SYSTEMNEED)) { FrameworkElement MenuPage; if (Context.CacheMenuUIElement.ContainsKey(menuInfo.MENUCODE)) { MenuPage = Context.CacheMenuUIElement[menuInfo.MENUCODE] as FrameworkElement; } else { asmMain = Context.allChildSystemAssembly[systemTypeDic.SYSTEMNEED] as Assembly; string pageObjName = strSystemType.Replace(".xap", "") + ".Views" + menuInfo.URLADDRESS.Replace("/", "."); MenuPage = asmMain.CreateInstance(pageObjName) as FrameworkElement; Context.CacheMenuUIElement.Add(menuInfo.MENUCODE, MenuPage); } if (OnSystemLoadXapPacketCompleted != null) { LoadModuleEventArgs arg = new LoadModuleEventArgs(MenuPage, menuInfo, null); this.OnSystemLoadXapPacketCompleted(null, arg); } } else { MainPageManeger.VertionFileName = systemTypeDic.SYSTEMNEED + ".xml"; MainPageManeger.dllVersionUpdataCheck(); } }
private void RunCode(Assembly assembly) { try { Type[] types = assembly.GetExportedTypes(); foreach (Type type in types) { Type interfaceType = type.GetInterface("NOToolsTests.CSharpTextEditor1.IScriptComponent"); if (null != interfaceType) { IScriptComponent component = assembly.CreateInstance(type.FullName) as IScriptComponent; component.Execute(); return; } } } catch (Exception exception) { System.CodeDom.Compiler.CompilerErrorCollection collection = new System.CodeDom.Compiler.CompilerErrorCollection(); System.CodeDom.Compiler.CompilerError error = new System.CodeDom.Compiler.CompilerError("", 0, 0, "0", exception.Message); collection.Add(error); codeEditorControl1.ShowErrors(collection); } }
public bool Load(string filepath) { //on vérifie que l'assembly à charger existe if (!File.Exists(filepath)) { errorMessage = "Le fichier n'existe pas."; return false; } //on charge l'assemby en prenant soin de s'assurer qu'elle est valide avec un try catch try { asm = Assembly.LoadFrom(filepath); } catch { errorMessage = "Le fichier assembly est corrompu. Le fichier doit être une dll .net afin d'être chargé correctement."; return false; } //on récupère tous les types contenus dans l'assembly //type = class, enum, interface, delegate et struct Type[] types = asm.GetTypes(); //on extrait l'info de l'assembly en récupérant l'attribut ModuleInfo ExtractInfo(); //ce booléan nous informe si oui ou non on a trouvé au moins une classe qui implèmente //l'interface IFormAddOn ou IMenuAddOn bool foundInterface = false; if (moduleInfo != null) { //if (MessageBox.Show("On ne dispose d'aucune information sur ce module. Voulez-vous continuer le chargement ?", "Aucune Information", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) // return false; //2 - Vérifier si on a la licence string xmlData = Config.Load(); string key = Config.GetInnerTextValue(xmlData, "//alf-solution/plugins/" + moduleInfo.Name + "/key"); if (string.IsNullOrEmpty(key)) { key = Utils.GetKey(moduleInfo.Name, Config.PublicKey(), Config.Nom(), Config.Email()); xmlData = Config.SetValue(xmlData, "plugins/" + moduleInfo.Name, "key", key); Config.Save(xmlData); } // Vérifier si la clé est bonne Vigenere oVigenere = new Vigenere(System.Environment.MachineName.ToLower()); string tmpPluginName = Config.PublicKey(); if (moduleInfo.Name.Length < 25) { tmpPluginName = moduleInfo.Name + tmpPluginName.Substring(tmpPluginName.Length - (25 - moduleInfo.Name.Length)); } if (oVigenere.Encrypt(tmpPluginName) == key) { for (int i = 0; i < types.Length; i++) { Type IFormAddOnType = types[i].GetInterface("IFormAddOn"); Type IMenuAddOnType = types[i].GetInterface("IMenuAddOn"); Type ITabPageAddOnType = types[i].GetInterface("ITabPageAddOn"); Type ITabPageLeftAddOnType = types[i].GetInterface("ITabPageLeftAddOn"); Type IGroupBoxAddOnType = types[i].GetInterface("IGroupBoxAddOn"); //si notre type (une classe ici) implémente l'une de ces deux interfaces alosr... object obj = null; if (IFormAddOnType != null) { //1 - instancier la classe if (obj == null) obj = asm.CreateInstance(types[i].FullName); IFormAddOn formAddOn = obj as IFormAddOn; //2 - invoker la méthode d'installation formAddOn.Install(form); foundInterface = true; } if (IMenuAddOnType != null) { //1 - instancier la classe if (obj == null) obj = asm.CreateInstance(types[i].FullName); IMenuAddOn menuAddOn = obj as IMenuAddOn; //2 - invoker la méthode d'installation menuAddOn.Install(menuStrip); menuAddOn.EventPlug(this.plugEvent); foundInterface = true; } if (ITabPageAddOnType != null) { //1 - instancier la classe if (obj == null) obj = asm.CreateInstance(types[i].FullName); ITabPageAddOn tabPageAddOn = obj as ITabPageAddOn; //2 - invoker la méthode d'installation tabPageAddOn.Install(tabControl); tabPageAddOn.EventPlug(this.plugEvent); foundInterface = true; } if (ITabPageLeftAddOnType != null) { //1 - instancier la classe if (obj == null) obj = asm.CreateInstance(types[i].FullName); ITabPageLeftAddOn tabPageLeftAddOn = obj as ITabPageLeftAddOn; //2 - invoker la méthode d'installation tabPageLeftAddOn.Install(tabControlLeft); tabPageLeftAddOn.EventPlug(this.plugEvent); foundInterface = true; } if (IGroupBoxAddOnType != null) { //1 - instancier la classe if (obj == null) obj = asm.CreateInstance(types[i].FullName); IGroupBoxAddOn groupBoxAddOn = obj as IGroupBoxAddOn; //3 - invoker la méthode d'installation TabPage tp = null; foreach (TabPage tabPage in tabControl.TabPages) { if (tabPage.Text == m_ResourceManager.GetString("Fiche")) tp = tabPage; } if (tp == null) { tp = new TabPage(m_ResourceManager.GetString("Fiche")); tp.AutoScroll = true; // Add the new tab page to the TabControl of the main window's application tabControl.TabPages.Add(tp); } groupBoxAddOn.Install(tp); groupBoxAddOn.EventPlug(this.plugEvent); object[] VersionInfo = asm.GetCustomAttributes(typeof (AssemblyFileVersionAttribute), false); if (VersionInfo.Length > 0) { string version = ((AssemblyFileVersionAttribute) VersionInfo[0]).Version; string versionDll = Config.GetInnerTextValue(xmlData, "//alf-solution/plugins/" + moduleInfo.Name + "/version"); if (string.IsNullOrEmpty(versionDll) || !versionDll.Equals(versionDll)) { //xmlData = Config.SetValue(xmlData, "plugins", moduleInfo.Name, ""); xmlData = Config.SetValue(xmlData, "plugins/" + moduleInfo.Name, "version", version); Config.Save(xmlData); } Console.Out.WriteLine(version); } foundInterface = true; } } } else { errorMessage = string.Format("Votre clé est invalide pour le module {0}", moduleInfo.Name); return false; } } else { foundInterface = false; //ModuleInfoForm moduleInfoForm = new ModuleInfoForm(); //moduleInfoForm.setInfo(moduleInfo); //if (moduleInfoForm.ShowDialog() == DialogResult.No) return false; //string xmlData = Config.Load(); //xmlData = Config.SetValue(xmlData, "plugins", moduleInfo.Name, ""); //xmlData = Config.SetValue(xmlData, "plugins/" + moduleInfo.Name, "Path", filepath); //xmlData = Config.SetValue(xmlData, "plugins/" + moduleInfo.Name, "Author", moduleInfo.Author); //xmlData = Config.SetValue(xmlData, "plugins/" + moduleInfo.Name, "Language", moduleInfo.Language); //xmlData = Config.SetValue(xmlData, "plugins/" + moduleInfo.Name, "Description", moduleInfo.Description); //Config.Save(xmlData); } if (foundInterface) { return true; } else { errorMessage = "L'assemby spécifié ne contient aucun module."; return false; } }
private static IPersistableImageFormat ExamineAssembly(Assembly assembly) { IPersistableImageFormat imageFormatPlugin = null; try { //Enumerate through the assembly object // foreach (Type testType in assembly.GetTypes()) { //Look for public types and ignore abstract classes // if (testType.IsPublic && testType.Attributes != TypeAttributes.Abstract) { //Does the type implement the proper interface // if ((testType.GetInterface(PluginInterfaceName, true)) != null && testType.IsClass && !testType.IsAbstract) { object pluginObject = assembly.CreateInstance(testType.FullName); imageFormatPlugin = (IPersistableImageFormat)pluginObject; } } } } catch (ReflectionTypeLoadException) { } catch (FileLoadException) { } return imageFormatPlugin; }
private void CacheTargets(Assembly assm) { foreach(Type t in assm.GetTypes()) { TargetAttribute ta = (TargetAttribute)Helper.CheckType(t, typeof(TargetAttribute), typeof(ITarget)); if(ta == null) continue; if (t.IsAbstract) continue; ITarget target = (ITarget)assm.CreateInstance(t.FullName); if (target == null) { throw new MissingMethodException("Could not create ITarget instance"); } m_Targets[ta.Name] = target; } }
void Init() { lock (this) { if (_UseCompression != -1) return; _UseCompression = 0; // assume failure try { // Load the assembly _Assembly = XmlUtil.AssemblyLoadFrom(_CodeModule); // Load up a test stream to make sure it will work object[] args = new object[] {new MemoryStream()}; Stream so = _Assembly.CreateInstance(_ClassName, false, BindingFlags.CreateInstance, null, args, null,null) as Stream; if (so != null) { // we've successfully inited so.Close(); _UseCompression = 1; } else _Assembly = null; if (_Finish != null) { Type theClassType= so.GetType(); this._FinishMethodInfo = theClassType.GetMethod(_Finish); } } catch (Exception e) { _ErrorMsg = e.InnerException == null? e.Message: e.InnerException.Message; } } }
private List<IBackend> GetBackendsFromAssembly(Assembly asm) { List<IBackend> backends = new List<IBackend> (); Type[] types = null; try { types = asm.GetTypes (); } catch (Exception e) { Logger.Warn ("Exception reading types from assembly '{0}': {1}", asm.ToString (), e.Message); return backends; } foreach (Type type in types) { if (!type.IsClass) { continue; // Skip non-class types } if (type.GetInterface ("Tasque.Backends.IBackend") == null) { continue; } Logger.Debug ("Found Available Backend: {0}", type.ToString ()); IBackend availableBackend = null; try { availableBackend = (IBackend) asm.CreateInstance (type.ToString ()); } catch (Exception e) { Logger.Warn ("Could not instantiate {0}: {1}", type.ToString (), e.Message); continue; } if (availableBackend != null) { backends.Add (availableBackend); } } return backends; }