public IEnumerable <IAutoquitFunction> LoadModule(IDynamicModule <IAutoquitModule> module) { if (module == null) { yield break; } foreach (var type in module.GetExportedTypes()) { if (!(module.CreateInstance(type) is IAutoquitModule actualModule)) { continue; } if (!actualModule.Load(out var functionList)) { continue; } foreach (var function in functionList) { if (function != null) { function.Id = string.Join('.', module.AssemblyName, CombineUniqueNamespace(function)); function.AssemblyName = module.AssemblyName; yield return(function); } } } }
public void Register(IDynamicModule module) { if (module == null) { Debug.LogError("module is null, ignore"); return; } string moduleId = module.GetModuleId(); if (string.IsNullOrEmpty(moduleId)) { Debug.LogError("moduleId is null, ignore"); return; } if (moduleDict == null) { moduleDict = new Dictionary <string, IDynamicModule>(); } if (moduleDict.ContainsKey(moduleId)) { Debug.LogError("moduleId:" + moduleId + " exist, ignore."); return; } Debug.Log("Registering module:" + module.GetModuleId()); //notify other modules foreach (var kvp in moduleDict) { kvp.Value.OnRegisterModule(module, this); } //register module moduleDict.Add(moduleId, module); //notify registered module.OnRegister(this); }
public void Register(IDynamicModule module) { if (module == null) { Debug.LogError("module is null, ignore"); return; } string moduleId = module.GetModuleId(); if (string.IsNullOrEmpty(moduleId)) { Debug.LogError("moduleId is null, ignore"); return; } if (moduleDict == null) { moduleDict = new Dictionary<string, IDynamicModule>(); } if (moduleDict.ContainsKey(moduleId)) { Debug.LogError("moduleId:" + moduleId + " exist, ignore."); return; } Debug.Log("Registering module:" + module.GetModuleId()); //notify other modules foreach (var kvp in moduleDict) { kvp.Value.OnRegisterModule(module, this); } //register module moduleDict.Add(moduleId, module); //notify registered module.OnRegister(this); }
private bool LoadDynamicModules(Assembly assemblyToUse) { var types = assemblyToUse.GetExportedTypes(); var dynamicModuleTypes = types.Where(type => typeof(IDynamicModule).IsAssignableFrom(type)); bool retVal = true; foreach (var dynamicModuleType in dynamicModuleTypes) { try { IDynamicModule module = (IDynamicModule)Activator.CreateInstance(dynamicModuleType); modules.Add(module); } catch (Exception e) { //log exception details retVal = false; } } return(retVal); }
void IModuleManager.SetupModuleMenu(IDynamicModule module) { InnerSetupModuleMenu(module); }
/// <summary> /// Запускаем выполнение модуля /// </summary> private bool TryToExecuteModule(IDynamicModule module, ExecuteCommand command, string file, Guid context, PatientData patient = null) { bool result = true; try { module.Execute(command, context, file, patient); } catch (Exception) { result = false; } return result; }
static void Main() { System.Reflection.Emit.pro String assemblyName = "RVJ.Core.Person"; IDynamicBuilder personBuilder = new DynamicBuilder(assemblyName); /* * * Defines a dynamic .NET Assembly. * The method automatically defines a dynamic .NET Module with the same name. * */ IDynamicAssembly personDynamicAssembly = personBuilder.DefineDynamicAssembly(); /* * * Defines a dynamic .NET Module. * */ IDynamicModule personDynamicModule = personDynamicAssembly.DefineDynamicModule(); /* * * Defines a dynamic .NET Type. * */ IDynamicType personDynamicType = personDynamicModule.DefineDynamicType(assemblyName, ClassTypeFlags.Public, typeof(System.Object)); personDynamicType.DefineDynamicField("_id", typeof(System.UInt32), FieldFlags.Private); personDynamicType.DefineDynamicField("_name", typeof(System.String), FieldFlags.Private); personDynamicType.DefineDynamicField("_age", typeof(System.UInt32), FieldFlags.Private); /* * * Creates an instance of the RVJ.Core.Person dynamic .NET Type. * */ Object person = personDynamicType.CreateAnInstance("RVJ.Core.Person"); /* * * Gets an instance of a dynamic .NET Field. * The search that the System.Type.GetGetField() instance method does, is case-sensitive. * */ Type personType = person.GetType(); FieldInfo personFieldId = personType.GetField("_id", (BindingFlags.NonPublic | BindingFlags.Instance)); FieldInfo personFieldName = personType.GetField("_name", (BindingFlags.NonPublic | BindingFlags.Instance)); FieldInfo personFieldAge = personType.GetField("_age", (BindingFlags.NonPublic | BindingFlags.Instance)); /* * * Shows the dynamic .NET Field values before assigning new values. * */ UInt32 newId = ( UInt32 )personFieldId.GetValue(person); String newName = ( String )personFieldName.GetValue(person); UInt32 newAge = ( UInt32 )personFieldAge.GetValue(person); if (newName == null) { newName = String.Empty; } Console.WriteLine("Before new values...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); newId = 100; newName = "New Name!!!"; newAge = 25; personFieldId.SetValue(person, newId); personFieldName.SetValue(person, newName); personFieldAge.SetValue(person, newAge); newId = ( UInt32 )personFieldId.GetValue(person); newName = ( String )personFieldName.GetValue(person); newAge = ( UInt32 )personFieldAge.GetValue(person); Console.WriteLine("After new values assigned...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); Console.ReadLine(); Console.WriteLine("Press <ENTER> to finish..."); }
private Guid GetAssociationAttributeIdFromModuleByFileExtension(IDynamicModule module, String extension) { return (from ModuleAssociationAttribute attribute in module.GetType().Assembly.GetCustomAttributes(typeof(ModuleAssociationAttribute), true) where (attribute as ModuleAssociationAttribute).FileExtension == extension select attribute.OID).FirstOrDefault(); }
private IEnumerable<ModuleAssociationAttribute> GetModuleAssociationAttibute(IDynamicModule module) { var attrubutes = from attribute in module.GetType().Assembly.GetCustomAttributes(typeof(ModuleAssociationAttribute), true) where (attribute as ModuleAssociationAttribute).AssociationType == "ExaminationType" select attribute as ModuleAssociationAttribute; return attrubutes; }
private void ExecuteModule(IDynamicModule module, ExecuteCommand command, IObjectSpace os, IExamination examination) { // Определяем идентификатор приложения которое будет открывать файл обследования // Для модулей которые могут работать с несколькими приложениями Guid soft = examination.ExaminationSoftType.ExaminationSoftTypeId; // Получаем имя РЕАЛЬНОГО файла обследования из базы !!! string file = examination.ExaminationFile.RealFileName; Guid context = (examination as DevExpress.ExpressApp.DC.DCBaseObject).Oid; if (System.IO.File.Exists(file) == true) {// если файл удалось найти в том месте, где он должен быть if (FileWatcher.GetFileState(file) == FileState.Close) {// если файл никем не используется т.е закрыт if (new FileInfo(file).Length == 0) {// если файл обследования по какой то причине пустой, то открываем его как новый // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; PatientData data = GetFromExamination(examination); if (TryToExecuteModule(module, ExecuteCommand.New, file, context, data) == false) {// если при запуске приложения возникла ошибка // удаляем обследование если его можно удалять if (examination.AllowEmptyOrNotExistsFile == false) os.Delete(examination); string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } if (os.IsModified == true) os.CommitChanges(); } else {// Если файл не пустой // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; if (TryToExecuteModule(module, command, file, context) == false) { string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } if (os.IsModified == true) os.CommitChanges(); } } else {// если файл в момент записи открыт где то еще string message = "Ошибка доступа к файлу обследования!\nВозможно файл открыт внешним приложением или нет прав доступа"; //CaptionHelper.GetLocalizedText("Warnings", "RequiredExaminationIsAlreadyLaunched"); XtraMessageBox.Show(message, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return; } } else // АХТУНГ !!! НАДО УДАЛЯТЬ ОБСЛЕДОВАНИЯ СОДЕРЖАШИЕ УДАЛЕННЫЕ ФАЙЛЫ ИЛИ НЕ НАДО ?!!?!?!? {// если реального файла нет - создаем новый пустой файл using (Stream stream = File.Create(file)) { }; // Проверяем готовность модуля if (ModuleIsReady(module, soft, command) == false) return; PatientData data = GetFromExamination(examination); TryToExecuteModule(module, ExecuteCommand.New, file, context, data); } os.Refresh(); }
/// <summary> /// Метод запускает новое обследование /// </summary> /// <param name="module"></param> /// <param name="examination"></param> /// <param name="patient"></param> protected void NewExaminationExecute(IDynamicModule module, Guid id, IPatient patient, ExaminationType type = null, bool block = false) { ExecuteCommand command = ExecuteCommand.New; // Проверяем готовность модуля if (ModuleIsReady(module, id, command) == false) return; // Получаем представление содержащие объекты IExamination ListView list = GetListViewFromControllerByType(this, typeof(IExamination)); // Получаем объектное пространство для данного представления IObjectSpace os = list.ObjectSpace; bool allowEmpty = (bool)module.DoVerb(VerboseCommand.AllowEmptyFile); // Создаем новое обследование IExamination examination = CreateNewExamination(list.ObjectSpace, patient, id, type, allowEmpty); ExecuteModule(module, command, os, examination); // переводим фокус на новый объект int count = list.CollectionSource.List.Count - 1; if (count > 0) list.CurrentObject = list.CollectionSource.List[count]; //list.ObjectSpace.Refresh(); // Блокируем доступ в БД если надо if (block == true) { WindowsFormsModule owner = Application.Modules.FirstOrDefault(form => form is WindowsFormsModule) as WindowsFormsModule; //owner.BlockingAccessToDatabase(module, context); } }
static void Main() { Program.UsingCodeDOM(); String assemblyName = "RVJ.Core.Person"; IDynamicBuilder personBuilder = new DynamicBuilder(assemblyName); /* * * Defines a dynamic .NET Assembly. * The method automatically defines a dynamic .NET Module with the same name. * */ IDynamicAssembly personDynamicAssembly = personBuilder.DefineDynamicAssembly(); /* * * Defines a dynamic .NET Module. * */ IDynamicModule personDynamicModule = personDynamicAssembly.DefineDynamicModule(); /* * * Defines a dynamic .NET Type. * */ IDynamicType personDynamicType = personDynamicModule.DefineDynamicType(assemblyName, ClassTypeFlags.Public, typeof(System.Object)); IDynamicField _id_DynamicField = personDynamicType.DefineDynamicField("_id", typeof(System.UInt32), FieldFlags.Private); IDynamicField _name_DynamicField = personDynamicType.DefineDynamicField("_name", typeof(System.String), FieldFlags.Private); IDynamicField _age_DynamicField = personDynamicType.DefineDynamicField("_age", typeof(System.UInt32), FieldFlags.Private); /* * * A dynamic .NET Property is associated with a dynamic .NET Field. * By default, the implementation of IDynamicField.DefineDynamicProperty method defines both, get and set accessor methods. * We should use RVJ.Core.PropertyFlags enum option to indicates if characteristics of a dynamic .NET Property. * */ _id_DynamicField.DefineDynamicProperty("Id", typeof(System.UInt32), PropertyFlags.Public | PropertyFlags.ReadAndWrite); _name_DynamicField.DefineDynamicProperty("Name", typeof(System.String), PropertyFlags.Public | PropertyFlags.ReadAndWrite); _age_DynamicField.DefineDynamicProperty("Age", typeof(System.UInt32), PropertyFlags.Public | PropertyFlags.ReadAndWrite); /* * * Creates an instance of the RVJ.Core.Person dynamic .NET Type. * */ Object person = personDynamicType.CreateAnInstance("RVJ.Core.Person"); /* * * Gets an instance of a dynamic .NET Field. * The search that the System.Type.GetField() instance method does, is case-sensitive. * */ Type personType = person.GetType(); FieldInfo personFieldId = personType.GetField("_id", (BindingFlags.NonPublic | BindingFlags.Instance)); FieldInfo personFieldName = personType.GetField("_name", (BindingFlags.NonPublic | BindingFlags.Instance)); FieldInfo personFieldAge = personType.GetField("_age", (BindingFlags.NonPublic | BindingFlags.Instance)); /* * * Shows the dynamic .NET Field values before assigning new values. * */ UInt32 newId = ( UInt32 )personFieldId.GetValue(person); String newName = ( String )personFieldName.GetValue(person); UInt32 newAge = ( UInt32 )personFieldAge.GetValue(person); if (newName == null) { newName = String.Empty; } Console.WriteLine("Before new values...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); newId = 100; newName = "New Name!!!"; newAge = 25; personFieldId.SetValue(person, newId); personFieldName.SetValue(person, newName); personFieldAge.SetValue(person, newAge); newId = ( UInt32 )personFieldId.GetValue(person); newName = ( String )personFieldName.GetValue(person); newAge = ( UInt32 )personFieldAge.GetValue(person); Console.WriteLine("After new values assigned...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); Program.Pause(); /* * * Now, we are using the dynamic .NET Properties defined for each dynamic .NET Field, to do the same operations of "get" and "set" values. * */ newId = ( UInt32 )personType.InvokeMember("Id", BindingFlags.GetProperty, null, person, null); newName = ( String )personType.InvokeMember("Name", BindingFlags.GetProperty, null, person, null); newAge = ( UInt32 )personType.InvokeMember("Age", BindingFlags.GetProperty, null, person, null); Console.WriteLine("Before new values assigned...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); newId = 200; newName = "New Name using a dynamic .NET Property!!!"; newAge = 35; personType.InvokeMember("Id", BindingFlags.SetProperty, null, person, new Object[] { newId }); personType.InvokeMember("Name", BindingFlags.SetProperty, null, person, new Object[] { newName }); personType.InvokeMember("Age", BindingFlags.SetProperty, null, person, new Object[] { newAge }); Console.WriteLine("After new values...\nperson._id: {0}\nperson._name: {1}\nperson._age: {2}\n", newId.ToString(), newName, newAge.ToString()); Program.Pause(true); }
private bool ModuleHasLaunchedProcesses(IDynamicModule module) { return (bool)module.DoVerb(VerboseCommand.HasLaunchedProcess, null); }
public virtual void OnRegisterModule(IDynamicModule module, DynamicModuleManager mgr) { }
public virtual void OnRegisterModule(IDynamicModule module , DynamicModuleManager mgr) { }
protected virtual void AttachModuleProfile(IDynamicModule module) { }
protected virtual void InnerSetupModuleMenu(IDynamicModule module) { }
private IEnumerable<ModuleActionInformation> ModuleGetModeInformationDoVerb(IDynamicModule module) { return module.DoVerb(VerboseCommand.GetModeInformation) as IEnumerable<ModuleActionInformation>; }
private bool ModuleCanCreateDoVerb(IDynamicModule module) { bool? result = module.DoVerb(VerboseCommand.CanCreate) as bool?; return result ?? false; }
/// <summary> /// Проверяем готовность модуля /// </summary> private bool ModuleIsReady(IDynamicModule module, Guid id, ExecuteCommand command) { bool result = true; try { result = ModuleIsReadyDoVerb(module, id, command); } catch (Exception ex) { //string message = CaptionHelper.GetLocalizedText("Exceptions", "TheExecutableFileOfRequestedApplicationWasNotFound"); string message = ex.Message; string title = CaptionHelper.GetLocalizedText("Captions", "ApplicationLaunchError"); XtraMessageBox.Show(message, title, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); result = false; } return result; }
/// <summary> /// Метод проверяет готовность модуля к работе /// </summary> private bool ModuleIsReadyDoVerb(IDynamicModule module, Guid oid, ExecuteCommand command = ExecuteCommand.Null) { bool? result = module.DoVerb(VerboseCommand.CheckReady, command) as bool?; return result ?? false; }
//private DoVerbResult ModuleIsReadyDoVerb(IDynamicModule module, Guid oid, ExecuteCommand command = ExecuteCommand.Null) //{ // DoVerbResult result = module.DoVerb(VerboseCommand.CheckReady, command) as DoVerbResult; // return result ?? new DoVerbResult {IsSuccess =false}; //} private bool ModuleSupportMultiModeDoVerb(IDynamicModule module) { bool? result = module.DoVerb(VerboseCommand.SupportMultiMode) as bool?; return result ?? false; }
/// <summary> /// !!! ВСЕ ЭТО НАДО ПЕРЕДЕЛАТЬ КАК ЗДЕСЬ --> http://www.devexpress.com/Support/Center/Example/Details/E1487 /// </summary> private void ImportExamination_Execute(object sender, EventArgs e) { importPatient = null; importExamination = null; isImportCompleted = false; importWizard = null; showWelcomePage = true; OpenFileDialog openFileDialog = new OpenFileDialog() { CheckFileExists = true, Multiselect = true, //false, CheckPathExists = true, Filter = GetDialogFilter(), //CaptionHelper.GetLocalizedText("CustomFomrsMessages", "importFileDialogFileter"), Title = CaptionHelper.GetLocalizedText("CustomFomrsMessages", "importFiledialogTitle") }; if (openFileDialog.ShowDialog() == DialogResult.OK) { //importFileFullName = openFileDialog.FileName; var importFiles= openFileDialog.FileNames; int totalFiles = importFiles.Count(); int currentNumber = 0; foreach (string file in importFiles) { if (importWizard != null) { if (importWizard.Canceled == true) return; } currentNumber++; importFileFullName = file; // находим модуль по расширению файла string extension = Path.GetExtension(importFileFullName); dynamicModule = GetModuleByAssociationAttributeFileExtension(extension); if (dynamicModule == null) { string error = String.Format(CaptionHelper.GetLocalizedText("CustomFomrsMessages", "FileImportError"), importFileFullName); string desctiption = CaptionHelper.GetLocalizedText("CustomFomrsMessages", "ImportModuleError"); XtraMessageBox.Show(String.Format("{0}\n{1}",error, desctiption),"",MessageBoxButtons.OK, MessageBoxIcon.Error); continue; //return; } XElement header = null; // получаем данные пациента из файла try { header = dynamicModule.DoVerb(VerboseCommand.ExtractData, importFileFullName) as XElement; } catch (Exception ex) { if (ex.Message == "ExaminationImportNoPatientDataFound") { header = null; //XtraMessageBox.Show(CaptionHelper.GetLocalizedText("Exceptions", "ExaminationImportNoPatientDataFound")); } else { string error = String.Format(CaptionHelper.GetLocalizedText("CustomFomrsMessages", "FileImportError"), importFileFullName); string desctiption = CaptionHelper.GetLocalizedText("Exceptions", "ExaminationImportWrongFileType"); XtraMessageBox.Show(String.Format("{0}\n{1}", error, desctiption),"",MessageBoxButtons.OK, MessageBoxIcon.Error); isImportCompleted = false; continue; //return; } } importData = CreateImportData(header); //проверяем дату if (importData.StartExaminationDateTime == DateTime.MinValue) {// если дату из файла извлеч не удалось то ставим дату создания файла FileInfo info = new FileInfo(importFileFullName); importData.StartExaminationDateTime = info.CreationTime; } // Запускаем мастер импорта обследования в БД importWizard = new ImportWizardForm(); string fullName = String.Format("{0} {1} {2}", importData.LastName, importData.FirstName, importData.MiddleName); string title = String.Format("{0} ({1}/{2})", importFileFullName, currentNumber, totalFiles); importWizard.SetTitle(title); importWizard.SetMessage(string.Format(CaptionHelper.GetLocalizedText("CustomFomrsMessages", "ImportPatientCaptionSearch"), fullName), 1); importWizard.SetMessage(CaptionHelper.GetLocalizedText("CustomFomrsMessages", "ImportPatientClosiestMatch"), 2); importWizard.isLocalized = true; // Коллекция пациентов для мастера импорта XPCollection patientsCollection = (XPCollection)Application.MainWindow.View.ObjectSpace.CreateCollection(typeof(IPatient)); importWizard.WelcomePage.Visible = (showWelcomePage == true);// скрываем страницу приветствия если она уже показывалась importWizard.DisplayPatientCollection(patientsCollection, fullName); importWizard.WizardControl.NextClick += new WizardCommandButtonClickEventHandler(importWizardControl_NextClick); importWizard.WizardControl.SelectedPageChanging += new WizardPageChangingEventHandler(importWizardControl_SelectedPageChanging); importWizard.WizardControl.CustomizeCommandButtons += (o,a) => { if (currentNumber != totalFiles) {// если файл не последний CompletionWizardPage page = a.Page as CompletionWizardPage; if (page != null) {// см. Предложение #4587 page.AllowCancel = true; page.ProceedText = CaptionHelper.GetLocalizedText("CustomFomrsMessages", "DataImportMasterProceed"); a.FinishButton.Text = a.NextButton.Text; //"Далее >"; } } }; importWizard.WizardControl.CancelClick += (o, a) => { }; importWizard.WizardCompleted += (args) => { isImportCompleted = args; }; importWizard.ShowDialog(); } } }
public void SetupModuleMenu(IDynamicModule module) { }