コード例 #1
0
 /// <summary>
 /// 异步创建
 /// </summary>
 /// <param name="assetName">Asset name.</param>
 /// <param name="onCreate">On create.</param>
 public void CreateAsync(string assetName, OnCreate onCreate)
 {
     //当前创建器为空
     if (curAssetCreator == null)
     {
         curAssetCreator           = objAssembly.CreateInstance(curAssetCreatorClass) as AssetCreatorBase;
         curAssetCreator.assetName = assetName;
         curAssetCreator.onCreate  = onCreate;
         curAssetCreator.LoadAsset();
         //StartCoroutine(curAssetCreator.LoadAssetAsync(assetBundle, curAssetCreator.assetName));
     }
     //同名资源追加 回调方法, 当前创建器 assetName
     else if (curAssetCreator.assetName.Equals(assetName))
     {
         curAssetCreator.onCreate += onCreate;
     }
     //检查当前创建器等待队列
     else if (assetLoadingTable.ContainsKey(assetName))
     {
         (assetLoadingTable[assetName] as AssetCreatorBase).onCreate += onCreate;
     }
     else
     {
         //新创建加载器
         //AssetCreatorBase assetCreator = new AssetCreator();
         AssetCreatorBase assetCreator = objAssembly.CreateInstance(curAssetCreatorClass) as AssetCreatorBase;
         assetCreator.assetName   = assetName;
         assetCreator.assetBundle = null;
         assetCreator.onCreate    = onCreate;
         //加入等待队列
         assetLoading.Enqueue(assetCreator);
         //加入等待队列映射
         assetLoadingTable.Add(assetCreator.assetName, assetCreator);
     }
 }
コード例 #2
0
ファイル: FrmMain1.cs プロジェクト: callme119/civil
        private void CreateItem(string title, string @class, object arg)
        {
            if (!SelectItem(title))
            {
                DevComponents.DotNetBar.DockContainerItem dockItem = new DevComponents.DotNetBar.DockContainerItem();
                System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(System.Windows.Forms.Application.ExecutablePath.Replace("\\" + System.Windows.Forms.Application.StartupPath, ""));
                System.Object obj;
                try
                {
                    obj = ass.CreateInstance(@class);
                    obj.GetType().GetProperty("Dock").SetValue(obj, System.Windows.Forms.DockStyle.Fill, null);
                    obj.GetType().GetProperty("Tag").SetValue(obj, arg, null);
                    if (arg != null)
                    {
                        System.Type type    = ass.GetType(@class);
                        object      @object = type.GetField("BtnAdd", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(obj);
                        if (@object != null)
                        {
                            DevComponents.DotNetBar.ButtonX btn = (DevComponents.DotNetBar.ButtonX)@object;
                            btn.Click += new System.EventHandler(delegate(object o, System.EventArgs a)
                            {
                                RefreshChapterTree();
                            });
                        }
                    }
                }
                catch
                {
                    obj = ass.CreateInstance("Framework.Interface.Common.UclError");
                    obj.GetType().GetProperty("Dock").SetValue(obj, System.Windows.Forms.DockStyle.Fill, null);
                }
                if ("".Equals(BarMain.Items[0].Text))
                {
                    DockPanelMain.Controls.Add((System.Windows.Forms.Control)obj);

                    DockItemMain.Text = title;
                }
                else
                {
                    DevComponents.DotNetBar.PanelDockContainer panel = new DevComponents.DotNetBar.PanelDockContainer();
                    panel.Controls.Add((System.Windows.Forms.Control)obj);
                    BarMain.Items.Add(dockItem);
                    BarMain.RecalcLayout();
                    dockItem.Text     = title;
                    dockItem.Control  = panel;
                    dockItem.Selected = true;
                }
            }
        }
コード例 #3
0
 private void button_New_Click(object sender, EventArgs e)
 {
     m_opendFileName = null;
     m_Instance      = m_ServerCommonAssembly.CreateInstance(comboBox_Templates.SelectedItem.ToString());
     if (m_Instance == null)
     {
         m_Instance = m_UIEditorAssembly.CreateInstance(comboBox_Templates.SelectedItem.ToString());
     }
     if (m_Instance == null)
     {
         m_Instance = m_CSCommonAssembly.CreateInstance(comboBox_Templates.SelectedItem.ToString());
     }
     propertyGrid.SelectedObject = m_Instance;
     this.Text = "新建";
 }
コード例 #4
0
        /// <summary>
        /// Prenche um controle ComboBox.
        /// </summary>
        /// <typeparam name="T">Tipo do Objeto.</typeparam>
        /// <param name="pCombo">Combo a ser preenchido.</param>
        /// <param name="pDataSource">Lista para preenchimento.</param>
        /// <param name="pDisplayMember">Texto visivel.</param>
        /// <param name="pValueMember">Código do texto visivel.</param>
        /// <param name="pItemTodos">Indica se serár exibido todos ou selecione como primeiro index.</param>
        public static void PreencherComboBox <T>(ComboBox pCombo, List <T> pDataSource, string pDisplayMember, string pValueMember, bool pItemTodos) where T : BaseOT
        {
            if (pDataSource != null)
            {
                if (pDataSource.Count > 0)
                {
                    System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(pDataSource[0].GetType());

                    BaseOT novoItem = (BaseOT)assembly.CreateInstance(string.Format("{0}.{1}", pDataSource[0].GetType().Namespace, pDataSource[0].GetType().Name));

                    novoItem.Codigo = 0;

                    if (pItemTodos)
                    {
                        novoItem.Nome = " -- TODOS -- ";
                    }
                    else
                    {
                        novoItem.Nome = " -- SELECIONE -- ";
                    }

                    pDataSource.Insert(0, (T)novoItem);
                }

                pCombo.DataSource    = pDataSource;
                pCombo.DisplayMember = pDisplayMember;
                pCombo.ValueMember   = pValueMember;
            }
        }
コード例 #5
0
        public static IIdentityRepository CreateInstance()
        {
            string cnfig = System.Configuration.ConfigurationManager.AppSettings["IdentityRepository"];

            if (string.IsNullOrEmpty(cnfig))
            {
                throw new Exception("请在appSettings配置名称为 IdentityRepository 的IIdentityRepository 接口实现类,例如:\"PWMIS.OAuth2.AuthorizationCenter.Repository.SimpleIdentityRepository,PWMIS.OAuth2.AuthorizationCenter\"");
            }
            string[] arrTemp          = cnfig.Split(',');
            string   providerAssembly = arrTemp[1];
            string   providerType     = arrTemp[0];

            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(providerAssembly);
            object provider = assembly.CreateInstance(providerType);

            if (provider is IIdentityRepository)
            {
                IIdentityRepository result = provider as IIdentityRepository;
                return(result);
            }
            else
            {
                throw new InvalidOperationException("当前指定的的提供程序不是 IIdentityRepository 接口实现类,请确保应用程序进行了正确的配置(在appSettings配置名称为 IdentityRepository 的配置)。");
            }
        }
コード例 #6
0
        public static void AttachBootstrap()
        {
            try {
                var path = ((Environment.OSVersion.Platform == PlatformID.Unix) ? Path.DirectorySeparatorChar.ToString() : "") + System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(Path.DirectorySeparatorChar + "Pluton.Core.dll", "");
                foreach (var file in Directory.GetFiles(path, "Pluton.*.dll"))
                {
                    if (!file.EndsWith("Pluton.Core.dll"))
                    {
                        System.Reflection.Assembly module = System.Reflection.Assembly.LoadFile(file);
                        foreach (var type in module.GetTypes())
                        {
                            if (type.ToString() == file.Split(Path.DirectorySeparatorChar).Last().Replace("dll", "Bootstrap"))
                            {
                                module.CreateInstance(type.ToString());
                            }
                        }
                    }
                }

                DirectoryConfig.GetInstance();
                CoreConfig.GetInstance();
                Config.GetInstance();

                Init();

                PlutonLoaded = true;
                Console.WriteLine($"[v.{Version}] Pluton loaded!");
            } catch (Exception ex) {
                Debug.LogException(ex);
                Debug.Log("[Bootstarp] Error while loading Pluton!");
            }
        }
コード例 #7
0
        // Eval > Evaluates C# sourcelanguage
        public object Eval(string code, Type outType = null, string[] includeNamespaces = null, string[] includeAssemblies = null)
        {
            StringBuilder namespaces   = null;
            object        methodResult = null;

            using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
            {
                ICodeCompiler      codeCompiler  = codeProvider.CreateCompiler();
                CompilerParameters compileParams = new CompilerParameters();
                compileParams.CompilerOptions  = "/t:library";
                compileParams.GenerateInMemory = true;
                if (includeAssemblies != null && includeAssemblies.Any())
                {
                    foreach (string _assembly in includeAssemblies)
                    {
                        compileParams.ReferencedAssemblies.Add(_assembly);
                    }
                }

                if (includeNamespaces != null && includeNamespaces.Any())
                {
                    foreach (string _namespace in includeNamespaces)
                    {
                        namespaces = new StringBuilder();
                        namespaces.Append(string.Format("using {0};\n", _namespace));
                    }
                }
                code = string.Format(
                    @"{1}  
                using System;  
                namespace CSharpCode{{  
                    public class Parser{{  
                        public {2} Eval(){{  
                            {3} {0};  
                        }}  
                    }}  
                }}",
                    code,
                    namespaces != null ? namespaces.ToString() : null,
                    outType != null ? outType.FullName : "void",
                    outType != null ? "return" : string.Empty
                    );
                CompilerResults compileResult = codeCompiler.CompileAssemblyFromSource(compileParams, code);

                if (compileResult.Errors.Count > 0)
                {
                    //throw new Exception(compileResult.Errors[0].ErrorText);
                    //RichTextBox inputBox = inputBox;
                    setString(inputBox, "Syntax Error");
                    return(" ");
                }
                System.Reflection.Assembly assembly = compileResult.CompiledAssembly;
                object classInstance = assembly.CreateInstance("CSharpCode.Parser");
                Type   type          = classInstance.GetType();
                System.Reflection.MethodInfo methodInfo = type.GetMethod("Eval");
                methodResult = methodInfo.Invoke(classInstance, null);
            }

            return(methodResult.ToString());
        }
コード例 #8
0
        private GenericElement GetSelectedElement(Object obj)
        {
            Type elementType = obj.GetType();

            System.Reflection.Assembly assembly = elementType.Assembly;
            return((GenericElement)assembly.CreateInstance(elementType.FullName));
        }
コード例 #9
0
ファイル: FrmMessageSender.cs プロジェクト: Wooyme/HIS-1
        private void sendMsg(string hostIp, int Port, string msg)
        {
            try
            {
                int showType = Convert.ToInt32(new Classes.SystemCfg(0010).Config);
                int showTime = 5;
                if (showType == 0)
                {
                    showTime = Convert.ToInt32(new Classes.SystemCfg(0011).Config);
                }
                else
                {
                    showTime = Convert.ToInt32(new Classes.SystemCfg(0012).Config);
                }

                System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(System.Windows.Forms.Application.StartupPath + "\\TrasenMessage.dll");
                object objMsgCtrl = assembly.CreateInstance("TrasenMessage.MessageController", true, System.Reflection.BindingFlags.CreateInstance, null, null, null, null);
                System.Reflection.MethodInfo mi = objMsgCtrl.GetType().GetMethod("SendTo", new Type[] { typeof(string), typeof(int), typeof(string), typeof(string), typeof(int), typeof(int) });
                string sender = FrmMdiMain.CurrentUser.Name;
                mi.Invoke(objMsgCtrl, System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null,
                          new object[] { hostIp, Port, msg, sender, showType, showTime }, null);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #10
0
        //不受ViewManager管理
        public static FWidget Create(Type cls, Action <FWidget> callback, object args = null)
        {
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            FWidget widget = asm.CreateInstance(cls.FullName) as FWidget;

            if (widget != null)
            {
                string packageName   = widget.package;
                string componentName = widget.component;

                widget.__isCreating = true;
                FComponent.Create <FComponent>(packageName, componentName, widget.isAsync, (fComponent) =>
                {
                    widget.__isCreating = false;
                    if (widget.__isDisposed)
                    {
                        widget.__isDisposed = false;
                        fComponent.Dispose();
                        return;
                    }
                    OnCreateSuccess(fComponent.GetObject(), widget, args);
                    callback?.Invoke(widget);
                });
            }

            return(widget);
        }
コード例 #11
0
        private BaseSpiderManagement LoadPluginCustomize(string name, string type)
        {
            System.Reflection.Assembly assembly      = System.Reflection.Assembly.LoadFile(currentDir + "\\Addon\\" + type + "\\" + name + ".dll");
            BaseSpiderManagement       spiderManager = (BaseSpiderManagement)assembly.CreateInstance(name + "." + type + "Manager");

            return(spiderManager);
        }
コード例 #12
0
        internal List <string> LoadBuiltInSensors()
        {
            System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();

            List <string> availableSensors = new List <string>();

            var tasks = new List <Task <SensorHost> >();

            foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
            {
                if (ti.ImplementedInterfaces.Contains(typeof(ISensor)) && ti.Name != "SensorBase")
                {
                    tasks.Add(Task.Run(() =>
                    {
                        var s = new SensorHost((ISensor)ass.CreateInstance(ti.FullName), _client, this);

                        if (s != null && !this.sensors.TryAdd(s.SensorIdentifier, s))
                        {
                            Log.Verbose($"Skipping built-in sensor [{s.SensorIdentifier}]");
                        }

                        return(s);
                    }));
                }
            }
            Task.WaitAll(tasks.ToArray());

            availableSensors.AddRange(tasks.Select(item => item.Result.SensorIdentifier).Where(ident => ident != null));

            return(availableSensors);
        }
コード例 #13
0
ファイル: AuditForm.cs プロジェクト: daobataotie/EDERP
        private void repositoryItemHyperLinkEdit1_Click(object sender, EventArgs e)
        {
            if (this.bindingSource1.Current != null)
            {
                Model.RoleAuditing roleAuditing = this.bindingSource1.Current as Model.RoleAuditing;
                // string formname = "Settings.ProduceManager.Techonlogy.EidtForm";//wfr.Workflow.Tables.TableCode;
                string formname = roleOperationManager.GetbyTable(roleAuditing.TableName);
                if (roleAuditing != null)
                {
                    Form f = null;
                    foreach (Form form in this.MdiParent.MdiChildren)
                    {
                        if (form.GetType().FullName.EndsWith(formname))
                        {
                            f = form;
                            break;
                        }
                    }

                    if (f == null)
                    {
                        System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                        f = (Form)assembly.CreateInstance(string.Format("{0}.{1}", assembly.GetName().Name, formname), false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { roleAuditing.InvoiceId }, null, null);
                    }

                    f.MdiParent = this.MdiParent;
                    f.Show();
                    f.BringToFront();
                }
            }
        }
コード例 #14
0
        /*public Booking(DateTime startTime, DateTime endTime, Vehicle.VehicleType vehicleType)
         * {
         *  Timeslot = new Timeslot(startTime, endTime);
         *  VehicleType = vehicleType;
         *  BookingId = new Guid().ToString();
         * }*/

        public bool Book(DateTime startTime, DateTime endTime, Vehicle.VehicleType vehicleType, string branchId)
        {
            System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
            bookingStrategies = new List <IBookingStrategy>();
            foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
            {
                if (ti.ImplementedInterfaces.Contains(typeof(IBookingStrategy)))
                {
                    bookingStrategies.Add(ass.CreateInstance(ti.FullName) as IBookingStrategy);
                }
            }

            foreach (var bookingStrategy in bookingStrategies.OrderBy(x => x.Priority))
            {
                var availableInventories = bookingStrategy.GetInventory(branchId, Vehicle.GetSeatingCapacity(vehicleType));
                var availableInventory   = availableInventories.FirstOrDefault(x => x.Count > 0);
                if (availableInventory?.Count == 0)
                {
                    continue;
                }

                if (availableInventory?.Count > 0)
                {
                    Timeslot    = new Timeslot(startTime, endTime);
                    VehicleType = vehicleType;
                    BookingId   = Guid.NewGuid().ToString();
                    return(true);
                }
            }

            return(false);
        }
コード例 #15
0
        public Engine()
        {
            //load up rules from web.config
            System.Collections.Specialized.NameValueCollection SectionIndex =
                (System.Collections.Specialized.NameValueCollection)
                System.Configuration.ConfigurationSettings.GetConfig("RulesEngine/Index");

            if (SectionIndex != null)
            {
                for (int x = 0; x < SectionIndex.Count; x++)
                {
                    string   sectionname = "RulesEngine/" + SectionIndex.Keys[x];
                    string   sectiondata = SectionIndex[x];
                    string[] asmdata     = sectiondata.Split(',');
                    if (asmdata.Length == 2)
                    {
                        string progid  = asmdata[0].Trim();
                        string asmname = asmdata[1].Trim();
                        if (progid != "" && asmname != "")
                        {
                            System.Reflection.Assembly asm  = System.Reflection.Assembly.GetExecutingAssembly();
                            verse.rules.IRules         rule = (verse.rules.IRules)asm.CreateInstance(progid, true);
                            if (rule != null)
                            {
                                this.AddRule(sectionname, rule);
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// 根据类名获取实例
        /// </summary>
        /// <param name="className">类名</param>
        /// <returns>对象实例</returns>
        private static object  GetInstance(string className)
        {
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            Object obj = asm.CreateInstance(className, true);

            return(obj);
        }
コード例 #17
0
        /// <summary>
        /// Loads the AI for the chess player. If the AI is already loaded, it will just return.
        /// </summary>
        /// <param name="player"></param>
        void LoadAI(ChessPlayer player)
        {
            if (player.IsHuman)
            {
                // Player is a human, so we don't need to load an AI.
                return;
            }
            else if (player.AI != null)
            {
                // AI has already been loaded, so return
                return;
            }

            AI tmpAI = null;

            foreach (AI t in DllLoader.AvailableAIs)
            {
                if (t.ShortName == player.AIName)
                {
                    tmpAI = t;
                    break;
                }
            }
            System.Reflection.Assembly assem = System.Reflection.Assembly.LoadFile(tmpAI.FileName);
            IChessAI ai = (IChessAI)assem.CreateInstance(tmpAI.FullName);

            player.AI = ai;
        }
コード例 #18
0
ファイル: ScueMerge.cs プロジェクト: KellySKL/VS_SQ
        /// <summary>
        /// 将反射得到 dictionary 转换为对象
        /// </summary>
        /// <param name="dictionary">反射得到的Dictionary<string, string></param>
        /// <returns>实体类</returns>
        public static T GetEntityDictionaryToEntity <T>(Dictionary <string, string> dictionary)
        {
            //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);
        }
コード例 #19
0
        public TomoFormula CreateFromString(string source)
        {
            TomoFormula retVal       = null;
            bool        isCsharpCode = IsCsharpCode(source);

            if (isCsharpCode)
            { // Expected Language: C#
                Microsoft.CSharp.CSharpCodeProvider csProviderOnEarlyNodeCode = null;
                CompileCS(source, out csProviderOnEarlyNodeCode);
                if (csProviderOnEarlyNodeCode == null)
                {
                    return(null);
                }
                if (results == null)
                {
                    return(null);
                }
                System.Reflection.Assembly mCAssembly = null;
                mCAssembly = results.CompiledAssembly;
                retVal     = (TomoFormula)mCAssembly.CreateInstance("CSTomoFormula");
            }
            else
            { // Exprected Language VB
                Microsoft.VisualBasic.VBCodeProvider vbProviderOnEarlyNodeCode = null;
                CompileVB(source, out vbProviderOnEarlyNodeCode);
                if (vbProviderOnEarlyNodeCode == null)
                {
                    return(null);
                }
                System.Reflection.Assembly mCAssembly = null;
                mCAssembly = results.CompiledAssembly;
                retVal     = (TomoFormula)mCAssembly.CreateInstance("VBTomoFormula");
            }
            return(retVal);
        }
コード例 #20
0
ファイル: UclInsertText.cs プロジェクト: callme119/civil
        private void ShowFrmProfile(Framework.Entity.Model model, System.Reflection.Assembly ass)
        {
            FrmInsertText win = new FrmInsertText(chapter, ass.CreateInstance(model.Class));

            win.CreateModuleIntance += new Framework.Interface.Workbench.FrmInsertText.CreateModuleHandle(CreateModule);
            win.ShowDialog();
        }
コード例 #21
0
        public static object CreateTypeFromDataTable(DataTable DataValues)
        {
            System.Reflection.Assembly asm = CreateAssemblyFromDataTable(DataValues);
            object instance = asm.CreateInstance(DataValues.TableName);

            return(null);
        }
コード例 #22
0
        static void LoadAIsFromFile(string filename)
        {
            try
            {
                System.Reflection.Assembly assem = System.Reflection.Assembly.LoadFile(filename);
                System.Type[] types = assem.GetTypes();

                foreach (System.Type type in types)
                {
                    System.Type[] interfaces = type.GetInterfaces();

                    foreach (System.Type inter in interfaces)
                    {
                        if (inter == typeof(UvsChess.IChessAI))
                        {
                            IChessAI ai  = (IChessAI)assem.CreateInstance(type.FullName);
                            AI       tmp = new AI(ai.Name);
                            tmp.FileName = filename;
                            tmp.FullName = type.FullName;
                            _availableais.Add(tmp);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Chess->MainForm->LoadAI: " + ex.Message);
            }
        }
コード例 #23
0
    public int Evaluate(string expression)
    {
        CSharpCodeProvider codeProvider       = new CSharpCodeProvider();
        CompilerParameters compilerParameters = new CompilerParameters();

        compilerParameters.ReferencedAssemblies.Add("system.dll");
        compilerParameters.CompilerOptions  = "/t:library";
        compilerParameters.GenerateInMemory = true;
        StringBuilder typeDefinition = new StringBuilder("");

        typeDefinition.AppendLine("using System;");
        typeDefinition.AppendLine("namespace Evaluator");
        typeDefinition.AppendLine("{");
        typeDefinition.AppendLine("    public class Evaluator");
        typeDefinition.AppendLine("    {");
        typeDefinition.AppendLine("        public object Evaluate()");
        typeDefinition.AppendLine("        {");
        typeDefinition.AppendLine("            return " + expression + ";");
        typeDefinition.AppendLine("        }");
        typeDefinition.AppendLine("    }");
        typeDefinition.AppendLine("}");
        CompilerResults compilerResult = codeProvider.CompileAssemblyFromSource(compilerParameters, typeDefinition.ToString());

        System.Reflection.Assembly a = compilerResult.CompiledAssembly;
        object     o = a.CreateInstance("Evaluator.Evaluator");
        Type       dynamicEvaluatorType  = o.GetType();
        MethodInfo dynamicEvaluateMethod = dynamicEvaluatorType.GetMethod("Evaluate");

        return((int)dynamicEvaluateMethod.Invoke(o, null));
    }
コード例 #24
0
        /// <summary>
        /// 窗口打开方法,
        /// </summary>
        /// <param name="IOpenForm"></param>
        void OpenForm(IOpenModuleForm IOpenForm, bool ib)
        {
            if (IOpenForm == null)
            {
                Msg.ShowError("窗口打开错误!!您打开的窗口不存在!!请联系系统开发商。错误代码:YIESysOpenForm76");
                return;
            }

            if (String.IsNullOrEmpty(IOpenForm.FormAssembly) || String.IsNullOrEmpty(IOpenForm.FormName))
            {
                Msg.ShowError("窗口打开错误!未设置要打开的窗口!请联系系统开发商。错误代码:YIESysOpenForm82");
                return;
            }
            try
            {
                System.Reflection.Assembly asm = System.Reflection.Assembly.Load(IOpenForm.FormAssembly); //程序集名
                object frmObj    = asm.CreateInstance(IOpenForm.FormAssembly + "." + IOpenForm.FormName); //程序集+form的类名。
                Form   childForm = (Form)frmObj;
                childForm.Tag       = IOpenForm.FormTag;                                                  //tag属性要重新写一次,否则在第二次的时候取不到。原因还不清楚。有知道的望告知。
                childForm.MdiParent = MainFormMDI.MainMDIForm;
                childForm.Show();
                MainFormMDI.MainTabManager.Pages[childForm].Image           = IOpenForm.FormImage16;
                MainFormMDI.MainTabManager.Pages[childForm].ShowCloseButton = DevExpress.Utils.DefaultBoolean.True;
                //if (ib) RegeditMenu(IOpenForm);
            }
            catch (Exception e)
            {
                Msg.ShowException(e);
            }
        }
コード例 #25
0
ファイル: FrmProperty.cs プロジェクト: callme119/civil
 public FrmProperty(Framework.Entity.Chapter chapter)
 {
     InitializeComponent();
     Framework.Entity.Model     model = (Framework.Entity.Model)utilService.FindById(new Framework.Entity.Model(), chapter.Model);
     System.Reflection.Assembly ass   = System.Reflection.Assembly.LoadFrom(System.Windows.Forms.Application.ExecutablePath.Replace("\\" + System.Windows.Forms.Application.StartupPath, ""));
     PropertyGrid.SelectedObject = ass.CreateInstance(model.Class);
     System.Collections.ArrayList templateList = contentService.GetContentTemplateByTitle(chapter.Title);
     foreach (Framework.Entity.Template template in templateList)
     {
         Framework.Class.ComboItem item = new Framework.Class.ComboItem();
         item.Text  = template.Title;
         item.Value = template;
         CbxType.Items.Add(item);
     }
     if (model.Name == "模板工程专项概况")
     {
         CbxType.SelectedIndex = 2;
         CbxType.Visible       = false;
         LbType.Visible        = false;
     }
     else
     {
         CbxType.Items.RemoveAt(2);
         CbxType.SelectedIndex = 0;
     }
 }
コード例 #26
0
ファイル: Program.cs プロジェクト: lharfuch/CSharp-Examples
        static IList <IFizzBuzz> GetConcretClassesIV()
        {
            List <IFizzBuzz> instances = new List <IFizzBuzz>();

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();


            Type[] types = assembly.GetTypes();
            foreach (Type type in types)
            {
                // Does this class support the transport interface?
                Type typeExample = type.GetInterface("IFizzBuzz");
                if (typeExample == null)
                {
                    // Not supported.
                    continue;
                }

                // This class supports the interface. Instantiate it.
                IFizzBuzz example = assembly.CreateInstance(type.FullName) as IFizzBuzz;
                if (example != null)
                {
                    // Successfully created the interface. We are done.
                    instances.Add(example);
                }
            }

            return(instances);
        }
コード例 #27
0
        }     // End Function BuildAssembly

        public static Type GetClassType(Type tt, string strDelimiter)
        {
            string strFullTypeName   = tt.FullName;
            string strTypeUniqueName = System.Guid.NewGuid().ToString() + System.Guid.NewGuid().ToString() + System.Guid.NewGuid().ToString() + System.Guid.NewGuid().ToString();

            strTypeUniqueName = "_" + strTypeUniqueName.Replace("-", "_");

            string xx = @"
                namespace CrapLord
                {
        
                    [FileHelpers.DelimitedRecord(""" + strDelimiter + @""")]
                    public class " + strTypeUniqueName + @" : " + strFullTypeName + @"
                    {
    
                    }
    
                }
    
                ";

            System.Reflection.Assembly a = BuildAssembly(xx);

            var  o = a.CreateInstance("CrapLord." + strTypeUniqueName);
            Type t = o.GetType();

            //System.Reflection.MethodInfo mi = t.GetMethod("EvalCode");
            //var s = mi.Invoke(o, null);

            return(t);
        }
コード例 #28
0
        /// <summary>
        /// 使用動態編譯的時候編譯邏輯判斷
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static object Eval(string expression)
        {
            //创建编译器
            ICodeCompiler      comp      = new CSharpCodeProvider().CreateCompiler();
            CompilerParameters paramerts = new CompilerParameters();

            //设置源代码
            StringBuilder objBuild = new StringBuilder();

            objBuild.Append("using System; \n");
            objBuild.Append("namespace Aptech.Showlin._temp { \n");
            objBuild.Append("  public class _evalTemp { \n");
            objBuild.Append("    public object _get() ");
            objBuild.Append("{ ");
            objBuild.AppendFormat("      return ({0}); ", expression);
            objBuild.Append("}\n");
            objBuild.Append("} }");

            //动态编译
            CompilerResults cr = comp.CompileAssemblyFromSource(paramerts, objBuild.ToString());

            System.Reflection.Assembly objAss = cr.CompiledAssembly;
            object o = objAss.CreateInstance("Aptech.Showlin._temp._evalTemp");

            System.Reflection.MethodInfo mi = o.GetType().GetMethod("_get");
            return(mi.Invoke(o, null));
        }
コード例 #29
0
        private IAop GetFromConfig()
        {
            IAop   aop    = null;
            string aopApp = AppConfig.Aop;

            if (!string.IsNullOrEmpty(aopApp))
            {
                string key = "OuterAop_Instance";
                if (_Cache.Contains(key))
                {
                    aop = _Cache.Get(key) as IAop;
                }
                else
                {
                    #region AOP加载

                    string[] aopItem = aopApp.Split(',');
                    if (aopItem.Length == 2)//完整类名,程序集(dll)名称
                    {
                        if (!_IsLoadCompleted)
                        {
                            try
                            {
                                lock (lockObj)
                                {
                                    if (_IsLoadCompleted)
                                    {
                                        return(GetFromConfig());//重新去缓存里拿。
                                    }
                                    _IsLoadCompleted = true;
                                    System.Reflection.Assembly ass = System.Reflection.Assembly.Load(aopItem[1]);
                                    if (ass != null)
                                    {
                                        object instance = ass.CreateInstance(aopItem[0]);
                                        if (instance != null)
                                        {
                                            _Cache.Set(key, instance, 1440, AppConst.AssemblyPath + aopItem[1].Replace(".dll", "") + ".dll");
                                            aop = instance as IAop;
                                            aop.OnLoad();
                                        }
                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                string errMsg = err.Message + "--Web.config need add a config item,for example:<add key=\"Aop\" value=\"Web.Aop.AopAction,Aop\" />(value format : ClassFullName,AssemblyName) ";
                                Error.Throw(errMsg);
                            }
                        }
                    }
                    #endregion
                }
            }
            if (aop != null)
            {
                IAop cloneAop = aop.Clone();
                return(cloneAop == null ? aop : cloneAop);
            }
            return(null);
        }
コード例 #30
0
        private IAop GetFromConfig()
        {
            IAop aop = null;

            string aopApp = AppConfig.Aop;

            if (!string.IsNullOrEmpty(aopApp))
            {
                if (_Cache.Contains("Aop_Instance"))
                {
                    aop = _Cache.Get("Aop_Instance") as IAop;
                }
                else
                {
                    #region AOP加载

                    string[] aopItem = aopApp.Split(',');
                    if (aopItem.Length == 2)//完整类名,程序集(dll)名称
                    {
                        try
                        {
                            System.Reflection.Assembly ass = System.Reflection.Assembly.Load(aopItem[1]);
                            if (ass != null)
                            {
                                object instance = ass.CreateInstance(aopItem[0]);
                                if (instance != null)
                                {
                                    _Cache.Add("Aop_Instance", instance, AppConst.RunFolderPath + aopItem[1].Replace(".dll", "") + ".dll", 1440);
                                    aop = instance as IAop;
                                    if (!_CallOnLoad)
                                    {
                                        lock (lockObj)
                                        {
                                            if (!_CallOnLoad)
                                            {
                                                _CallOnLoad = true;
                                                aop.OnLoad();
                                            }
                                        }
                                    }
                                    return(aop);
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            string errMsg = err.Message + "--Web.config need add a config item,for example:<add key=\"Aop\" value=\"Web.Aop.AopAction,Aop\" />(value format:namespace.Classname,Assembly name) ";
                            Error.Throw(errMsg);
                        }
                    }
                    #endregion
                }
            }
            if (aop != null)
            {
                return(aop.Clone());
            }
            return(null);
        }