/*метод, запускающий процесс на сиполнение и * сохраняющий объект, который его описывает*/ void RunProcess(string AssamblyName) { //запускаем процесс на соновании ичполняемого файла Process proc = Process.Start(AssamblyName); //добавляем процесс в список Processes.Add(proc); /*проверяем, стал ли созданный процесс дочерним, * по отношению к текущему и, если стал, выводим MessageBox*/ if (Process.GetCurrentProcess().Id == GetParentProcessId(proc.Id)) { MessageBox.Show(proc.ProcessName + " действительно дочерний процесс текущего процесса!"); } /*указываем, что процесс должен генерировать собития*/ proc.EnableRaisingEvents = true; //добавляем обработчик на событие завершения процесса proc.Exited += proc_Exited; /*устанавливаем новый текст главному окну дочернего процесса*/ SetChildWindowText(proc.MainWindowHandle, "Chils process #" + (++Counter)); /*проверяем, запускали ли мы экземпляр такого приложения * и, елси нет, то добавляем в список запущенных приложений*/ StartedAssemblies.Invoke((Action) delegate() { if (!StartedAssemblies.Items.Contains(proc.ProcessName)) { StartedAssemblies.Items.Add(proc.ProcessName); } }); /*убираем приложение из списка лдоступных приложений*/ AvailableAssemblies.Invoke((Action) delegate() { AvailableAssemblies.Items.Remove(AvailableAssemblies.SelectedItem); }); }
/// <summary> /// This will try to resolve the requested assembly by looking into the cache /// </summary> /// <param name="sender">object</param> /// <param name="resolveEventArgs">ResolveEventArgs</param> /// <returns>Assembly</returns> private Assembly AssemblyResolve(object sender, ResolveEventArgs resolveEventArgs) { var assemblyName = new AssemblyName(resolveEventArgs.Name); // Fail fast for resolving .resources requests if (assemblyName.Name.EndsWith(".resources")) { return(null); } if (Log.IsVerboseEnabled()) { Log.Verbose().WriteLine("Resolving {0}", assemblyName.FullName); } if (_resolving.Contains(assemblyName.Name)) { Log.Warn().WriteLine("Ignoring recursive resolve event for {0}", assemblyName.Name); return(null); } if (LoadedAssemblies.TryGetValue(assemblyName.Name, out var assemblyResult)) { if (Log.IsVerboseEnabled()) { Log.Verbose().WriteLine("Returned {0} from cache.", assemblyName.Name); } return(assemblyResult); } try { _resolving.Add(assemblyName.Name); if (!AvailableAssemblies.TryGetValue(assemblyName.Name, out var assemblyLocationInformation)) { return(null); } if (Log.IsVerboseEnabled()) { Log.Verbose().WriteLine("Found {0} at {1}.", assemblyName.Name, assemblyLocationInformation.ToString()); } return(LoadAssembly(assemblyLocationInformation)); } finally { _resolving.Remove(assemblyName.Name); } }
//void GetAssemblies() //{ // string partMark = // (string)cb_partitions.SelectedValue + // (string)cb_host_marks.SelectedValue; // ISet<string> assemblies; // if (partMark != null && // m_hostMarksAssemblies.TryGetValue( // partMark, // out assemblies)) // { // cb_assemblies.ItemsSource = assemblies; // } // else // { // cb_assemblies.ItemsSource = string.Empty; // } // cb_assemblies.SelectedIndex = 0; //} void GetAssembliesListBox() { if (cb_host_marks.IsEnabled) { AvailableAssemblies.Clear(); string partMark = (string)cb_partitions.SelectedValue + (string)cb_host_marks.SelectedValue; ISet <string> assemblies; if (partMark != null && m_hostMarksAssemblies.TryGetValue( partMark, out assemblies)) { foreach (string asmbl in assemblies) { AvailableAssemblies.Add(asmbl); } } } else { string part = (string)cb_partitions.SelectedValue; if (part != null) { AvailableAssemblies.Clear(); ICollection <string> partsHosts = m_hostMarksAssemblies.Keys; IEnumerator <string> itr = partsHosts.GetEnumerator(); while (itr.MoveNext()) { if (itr.Current.StartsWith(part)) { ISet <string> asmMarks = m_hostMarksAssemblies[itr.Current]; IEnumerator <string> it = asmMarks.GetEnumerator(); while (it.MoveNext()) { AvailableAssemblies.Add(it.Current); } } } } } }
/// <summary> /// Load a named assembly /// </summary> /// <param name="assemblyName">string</param> /// <returns>Assembly</returns> public Assembly LoadAssembly(string assemblyName) { // Check if the simple name can be found in the cache if (LoadedAssemblies.TryGetValue(assemblyName, out var assembly)) { Log.Info().WriteLine("Returned {0} from cache.", assemblyName); return(assembly); } if (AvailableAssemblies.TryGetValue(assemblyName, out var assemblyLocationInformation)) { return(LoadAssembly(assemblyLocationInformation)); } return(Assembly.Load(assemblyName)); }
private void OpenProject(string projectFile) { tsMainProgressBar.Visible = true; try { tsMainProgressBar.Maximum = 0; //foreach (string dir in System.IO.Directory.GetDirectories(System.IO.Path.GetDirectoryName(projectFile), "spectra", System.IO.SearchOption.AllDirectories)) // tsMainProgressBar.Maximum += System.IO.Directory.GetFiles(dir, "*.*", System.IO.SearchOption.TopDirectoryOnly).Length; //} IProject project = AvailableAssemblies.getProject(projectFile, new ReturnAttributeValue(delegate(string name, string value) { if (name == "spectraCount") { tsMainProgressBar.Maximum = int.Parse(value); } })); CreateProjectWindow(project); tsMainProgressBar.Value = tsMainProgressBar.Maximum; //adding to recent projects list refreshRecentProjectsList(projectFile); appendProjectToRecoveryFile(projectFile); } catch (SpectrumLoadException sle) { MessageBox.Show(sle.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (System.Reflection.TargetInvocationException tiex) { Exception finalException = Evel.share.Utilities.findException(tiex); if (finalException.GetType() == typeof(FileNotFoundException) || finalException.GetType() == typeof(SpectrumLoadException) || finalException.GetType() == typeof(IOException)) { MessageBox.Show(finalException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ExceptionSendForm exForm = new ExceptionSendForm(finalException); exForm.ShowDialog(); } } catch (System.IO.FileNotFoundException fnfe) { MessageBox.Show(fnfe.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (System.IO.DirectoryNotFoundException dnfe) { MessageBox.Show(dnfe.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.Message, "LT10", MessageBoxButtons.OK, MessageBoxIcon.Error); ExceptionSendForm exForm = new ExceptionSendForm(ex); exForm.ShowDialog(); } tsMainProgressBar.Visible = false; }
public void CreateNewProject(WizardEventHandler wizardEventHandler) { NewProjectDialog npd = new NewProjectDialog(null); npd = new NewProjectDialog(null); if (this.CurrentWizard != null) { this.CurrentWizard.DialogOpened(npd); } toolStripStatusLabel.Text = "Creating new project"; if (npd.ShowDialog() == DialogResult.OK) { //OpeningSpectraCount = 0; tsMainProgressBar.Maximum = 0; tsMainProgressBar.Visible = true; //toolStripStatusLabel.Text = String.Format("Creating Project {0}...", npd.projectNameTextBox.Text); foreach (SpectraContainerDescription scd in npd.ContainerDescriptions) { tsMainProgressBar.Maximum += scd.spectraPaths.Length; } string defaultProjectName = getDefaultProjectName(); IProject project = AvailableAssemblies.getProject( npd.ProjectType.ToString(), new object[] { defaultProjectName, //npd.projectNameTextBox.Text, npd.ContainerDescriptions }); //project.Save(System.IO.Path.Combine(npd.projectPathTextBox.Text, npd.projectNameTextBox.Text), false); ProjectForm form = CreateProjectWindow(project); form.NotSavedChanges = true; tsMainProgressBar.Visible = false; if (wizardEventHandler != null) { wizardEventHandler(this, new WizardEventArgs(form, WizardEventType.Created)); } } if (CurrentWizard != null) { CurrentWizard.DialogClosed(); } npd.Dispose(); toolStripStatusLabel.Text = "Ready"; }
private void ModelTreeNodeClick(object sender, EventArgs e) { ModelChooserDialog mcd = new ModelChooserDialog(_projectType); //if (Program.MainWindow.CurrentWizard != null) // Program.MainWindow.CurrentWizard.DialogOpened(mcd); DialogResult result = mcd.ShowDialog(); if (result == DialogResult.OK) { this._description.model = AvailableAssemblies.getModel(mcd.Selection.plugin.className); ((ButtonTreeNode)this.Nodes[1]).Value = this._description.model; ((Button)sender).Text = ButtonTreeNode.getButtonString(this._description.model); this.ProjectType = this._description.model.ProjectType; } //if (Program.MainWindow.CurrentWizard != null) // Program.MainWindow.CurrentWizard.DialogClosed(); mcd.Dispose(); this.TreeView.Invalidate(); }
/*обработчик события Exited класса Process*/ void proc_Exited(object sender, EventArgs e) { Process proc = sender as Process; //убираем процесс из списка запущенных приложений StartedAssemblies.Invoke((Action) delegate() { StartedAssemblies.Items.Remove(proc.ProcessName); }); //добавляем процесс в список доступных приложений AvailableAssemblies.Invoke((Action) delegate() { AvailableAssemblies.Items.Add(proc.ProcessName); }); //убираем процесс из списка дочерних процессов Processes.Remove(proc); //уменьшаем счётчик дочерних процессов на 1 Counter--; int index = 0; /*меняем текст для главных окон всех дочерних процессов*/ foreach (var p in Processes) { SetChildWindowText(p.MainWindowHandle, "Child process #" + ++index); } }
public ModelChooserDialog(Type ProjectType) { InitializeComponent(); _models = new Hashtable(); //create groups Hashtable groups = new Hashtable(); for (int i = 0; i < AvailableAssemblies.AvailableModels.Count; i++) { if (ProjectType == null || ProjectType == AvailableAssemblies.AvailableModels[i].projectType) { if (!groups.Contains(AvailableAssemblies.AvailableModels[i].projectType)) { ListViewGroup group = new ListViewGroup( String.Format("{0} models", AvailableAssemblies.GetProjectDesription(AvailableAssemblies.AvailableModels[i].projectType).experimentalMethodName)); groups.Add(AvailableAssemblies.AvailableModels[i].projectType, group); listView1.Groups.Add(group); } } } for (int i = 0; i < AvailableAssemblies.AvailableModels.Count; i++) { if (groups.ContainsKey(AvailableAssemblies.AvailableModels[i].projectType)) { ListViewItem item = new ListViewItem( AvailableAssemblies.AvailableModels[i].name, (ListViewGroup)groups[AvailableAssemblies.AvailableModels[i].projectType]); _models.Add(item, AvailableAssemblies.AvailableModels[i]); listView1.Items.Add(item); } } }
public static IEnumerable <Type> GetAllTypesAssignableTo <T>() { return(AvailableAssemblies.SelectMany(a => a.GetTypes()) .Where(t => typeof(T).IsAssignableFrom(t) && t != typeof(T)) .ToList()); }
public List <IParameterSet> parameters; //single parameterSet holds parameters for all interesting groups public ImportedModel(string modelClass, string name) { this.model = AvailableAssemblies.getModel(modelClass); this.name = name; this.parameters = new List <IParameterSet>(); }
static void Main(string[] args) { Console.WriteLine("Program for testing NEED capabilities. (31 May 2011)"); CultureInfo culture = new CultureInfo(CultureInfo.CurrentCulture.LCID); culture.NumberFormat.NumberDecimalSeparator = "."; Thread.CurrentThread.CurrentCulture = culture; AvailableAssemblies.LibraryDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); ReturnAttributeValue rav = null; try { if (args.Length == 1) { project = AvailableAssemblies.getProject(args[0], rav); } } catch (Exception) { Console.WriteLine("Project not found"); } string command = ""; string[] commandArgs; int docId = 0; while ((command = GetCommand(out commandArgs)) != "exit") { try { switch (command) { case "commands": Console.WriteLine("load\nunload\ntest1\nIntsChange\ndocuments\nprompt\nfsearch\nssearch\nspecdb"); break; case "load": project = AvailableAssemblies.getProject(commandArgs[1], rav); break; case "unload": project = null; break; case "test1": Test.Run <Test1>(commandArgs, project); break; case "IntsChange": Test.Run <IntsChangeTest>(commandArgs, project); break; case "prompt": Test.Run <PromptTest>(commandArgs, project); break; case "fsearch": Test.Run <SearchTest>(commandArgs, project); break; case "ssearch": Test.Run <SeriesSearchTest>(commandArgs, project); break; case "specdb": Test.Run <ParametersDBTest>(commandArgs, project); break; case "documents": if (project != null) { foreach (ISpectraContainer container in project.Containers) { Console.WriteLine("\t{0}: {1}\t{2}\n\t\t{3}\n\t\tSpectra: {4}", docId++, container.Name, (container.Enabled) ? "" : "Disabled", container.Model.Name, container.Spectra[0].Name + " (" + (container.Spectra.Count - 1).ToString() + " more)"); } } else { Console.WriteLine("No project is loaded!"); } break; default: Console.WriteLine("Unknown command"); break; } } catch (IndexOutOfRangeException) { Console.WriteLine("This command requires arguments!"); //System.Diagnostics.Debug.WriteLine(String.Format("{0}\n{1}", e.Message, e.StackTrace)); } catch (TestException e) { Console.WriteLine("Test has thrown exception:\n{0}\n{1}", e.InnerException.Message, e.InnerException.StackTrace); } catch (Exception e) { Console.WriteLine(e.Message); } } }
/// <summary> /// This is called when a new assembly is loaded, we need to know this /// </summary> /// <param name="sender">object</param> /// <param name="args">AssemblyLoadEventArgs</param> private void AssemblyLoad(object sender, AssemblyLoadEventArgs args) { var loadedAssembly = args.LoadedAssembly; var assemblyName = loadedAssembly.GetName().Name; if (Log.IsVerboseEnabled()) { Log.Verbose().WriteLine("Loaded {0}", assemblyName); } LoadedAssemblies[assemblyName] = loadedAssembly; if (!_applicationConfig.ScanForEmbeddedAssemblies) { return; } // Ignore resource checking on certain assemblies if (AssembliesToIgnore.IsMatch(assemblyName)) { return; } string[] resources; try { resources = Resources.GetCachedManifestResourceNames(loadedAssembly); } catch (Exception ex) { Log.Warn().WriteLine(ex, "Couldn't retrieve resources from {0}", loadedAssembly.GetName().Name); return; } foreach (var resource in resources) { var resourceMatch = _assemblyResourceNameRegex.Match(resource); if (!resourceMatch.Success) { continue; } var embeddedAssemblyName = resourceMatch.Groups["assembly"].Value; if (LoadedAssemblies.ContainsKey(embeddedAssemblyName)) { // Ignoring already loaded assembly, as we cannot unload. continue; } var newAssemblyLocation = new AssemblyLocationInformation(embeddedAssemblyName, loadedAssembly, resource); if (AvailableAssemblies.TryGetValue(embeddedAssemblyName, out var availableAssemblyLocationInformation)) { if (availableAssemblyLocationInformation.FileDate > newAssemblyLocation.FileDate) { continue; } } if (Log.IsVerboseEnabled()) { Log.Verbose().WriteLine("Detected additional assembly {0} in {1}", embeddedAssemblyName, loadedAssembly.GetName().Name); } AvailableAssemblies[embeddedAssemblyName] = newAssemblyLocation; } }