public void InvalidClassNameAndInvalidMethodNameReturnsNull() { var pathToDummyDll = GetMoyaDummyTestProjectDllPath(); assemblyHelper = new AssemblyHelper(pathToDummyDll); const string MethodName = "AFakeMethod"; const string FullClassName = "Moya.Dummy.Test.Project.FakeTestClass"; var method = assemblyHelper.GetMethodFromAssembly(FullClassName, MethodName); Assert.Null(method); }
public void ValidMethodReturnsMethodInfo() { var pathToDummyDll = GetMoyaDummyTestProjectDllPath(); assemblyHelper = new AssemblyHelper(pathToDummyDll); const string MethodName = "AMethod"; const string FullClassName = "Moya.Dummy.Test.Project.TestClass"; var method = assemblyHelper.GetMethodFromAssembly(FullClassName, MethodName); Assert.Equal(MethodName, method.Name); // ReSharper disable once PossibleNullReferenceException Assert.Equal(FullClassName, method.DeclaringType.FullName); }
[InlineData(true, "foo.exe")] // Filter should not match public async Task CmdWithTestShim_ShimNothingRunsChildProcessWithoutShim(bool shimAllProcesses, string processMatch) { var context = BuildXLContext.CreateInstanceForTesting(); string currentCodeFolder = Path.GetDirectoryName(AssemblyHelper.GetAssemblyLocation(Assembly.GetExecutingAssembly())); Contract.Assume(currentCodeFolder != null); string executable = CmdHelper.CmdX64; string shimProgram = Path.Combine(currentCodeFolder, "TestSubstituteProcessExecutionShim.exe"); Assert.True(File.Exists(shimProgram), $"Shim test program not found at {shimProgram}"); var shimProgramPath = AbsolutePath.Create(context.PathTable, shimProgram); var fam = new FileAccessManifest(context.PathTable) { FailUnexpectedFileAccesses = false, IgnoreCodeCoverage = false, ReportFileAccesses = false, ReportUnexpectedFileAccesses = false, MonitorChildProcesses = false, SubstituteProcessExecutionInfo = new SubstituteProcessExecutionInfo( shimProgramPath, shimAllProcesses: false, processMatch == null ? new ShimProcessMatch[0] : new[] { new ShimProcessMatch(PathAtom.Create(context.StringTable, processMatch), PathAtom.Invalid) }) }; Guid sessionId = Guid.NewGuid(); string sessionIdStr = sessionId.ToString("N"); var loggingContext = new LoggingContext(sessionId, "TestSession", new LoggingContext.SessionInfo(sessionIdStr, "env", sessionId)); string childOutput = "Child cmd that should not be shimmed"; string childArgs = $"{executable} /D /C @echo {childOutput}"; string args = "/D /C echo Top-level cmd. Running child process && " + childArgs; var stdoutSb = new StringBuilder(128); var stderrSb = new StringBuilder(); var sandboxedProcessInfo = new SandboxedProcessInfo( context.PathTable, new LocalSandboxedFileStorage(), executable, disableConHostSharing: true, loggingContext: loggingContext, fileAccessManifest: fam) { PipDescription = executable, Arguments = args, WorkingDirectory = Environment.CurrentDirectory, StandardOutputEncoding = Encoding.UTF8, StandardOutputObserver = stdoutStr => stdoutSb.AppendLine(stdoutStr), StandardErrorEncoding = Encoding.UTF8, StandardErrorObserver = stderrStr => stderrSb.AppendLine(stderrStr), EnvironmentVariables = BuildParameters.GetFactory().PopulateFromEnvironment(), Timeout = TimeSpan.FromMinutes(1), }; ISandboxedProcess sandboxedProcess = await SandboxedProcessFactory.StartAsync(sandboxedProcessInfo, forceSandboxing : true) .ConfigureAwait(false); SandboxedProcessResult result = await sandboxedProcess.GetResultAsync().ConfigureAwait(false); Assert.Equal(0, result.ExitCode); string stdout = stdoutSb.ToString(); m_output.WriteLine($"stdout: {stdout}"); string stderr = stderrSb.ToString(); m_output.WriteLine($"stderr: {stderr}"); Assert.Equal(0, stderr.Length); string shimOutput = "TestShim: Entered with command line"; int indexOfShim = stdout.IndexOf(shimOutput, StringComparison.Ordinal); Assert.True(indexOfShim == -1); int indexOfChild = stdout.LastIndexOf(childOutput, StringComparison.Ordinal); Assert.True(indexOfChild > 0, "Child should have run and written output"); }
public async Task Execute(IJobExecutionContext job) { Logger.LogDebug(LoggingEvents.Updater, "Starting Update job"); var settings = await Settings.GetSettingsAsync(); if (!settings.AutoUpdateEnabled && !settings.TestMode) { Logger.LogDebug(LoggingEvents.Updater, "Auto update is not enabled"); return; } var currentLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Logger.LogDebug(LoggingEvents.Updater, "Path: {0}", currentLocation); var productVersion = AssemblyHelper.GetRuntimeVersion(); Logger.LogDebug(LoggingEvents.Updater, "Product Version {0}", productVersion); var serverVersion = string.Empty; try { var productArray = GetVersion(); var version = productArray[0]; Logger.LogDebug(LoggingEvents.Updater, "Version {0}", version); var branch = productArray[1]; Logger.LogDebug(LoggingEvents.Updater, "Branch Version {0}", branch); Logger.LogDebug(LoggingEvents.Updater, "Version {0}", version); Logger.LogDebug(LoggingEvents.Updater, "Branch {0}", branch); Logger.LogDebug(LoggingEvents.Updater, "Looking for updates now"); //TODO this fails because the branch = featureupdater when it should be feature/updater var updates = await Processor.Process(branch); Logger.LogDebug(LoggingEvents.Updater, "Updates: {0}", updates); serverVersion = updates.UpdateVersionString; Logger.LogDebug(LoggingEvents.Updater, "Service Version {0}", updates.UpdateVersionString); if (!serverVersion.Equals(version, StringComparison.CurrentCultureIgnoreCase) || settings.TestMode) { // Let's download the correct zip var desc = RuntimeInformation.OSDescription; var process = RuntimeInformation.ProcessArchitecture; Logger.LogDebug(LoggingEvents.Updater, "OS Information: {0} {1}", desc, process); Downloads download; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Logger.LogDebug(LoggingEvents.Updater, "We are Windows"); if (process == Architecture.X64) { download = updates.Downloads.FirstOrDefault(x => x.Name.Contains("windows.", CompareOptions.IgnoreCase)); } else { download = updates.Downloads.FirstOrDefault(x => x.Name.Contains("windows-32bit", CompareOptions.IgnoreCase)); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Logger.LogDebug(LoggingEvents.Updater, "We are OSX"); download = updates.Downloads.FirstOrDefault(x => x.Name.Contains("osx", CompareOptions.IgnoreCase)); } else { Logger.LogDebug(LoggingEvents.Updater, "We are linux"); if (process == Architecture.Arm) { download = updates.Downloads.FirstOrDefault(x => x.Name.Contains("arm.", CompareOptions.IgnoreCase)); } else if (process == Architecture.Arm64) { download = updates.Downloads.FirstOrDefault(x => x.Name.Contains("arm64.", CompareOptions.IgnoreCase)); } else { download = updates.Downloads.FirstOrDefault(x => x.Name.Contains("linux.", CompareOptions.IgnoreCase)); } } if (download == null) { Logger.LogDebug(LoggingEvents.Updater, "There were no downloads"); return; } Logger.LogDebug(LoggingEvents.Updater, "Found the download! {0}", download.Name); Logger.LogDebug(LoggingEvents.Updater, "URL {0}", download.Url); Logger.LogDebug(LoggingEvents.Updater, "Clearing out Temp Path"); var tempPath = Path.Combine(currentLocation, "TempUpdate"); if (Directory.Exists(tempPath)) { DeleteDirectory(tempPath); } // Temp Path Directory.CreateDirectory(tempPath); if (settings.UseScript && !settings.WindowsService) { RunScript(settings, download.Url); return; } // Download it Logger.LogDebug(LoggingEvents.Updater, "Downloading the file {0} from {1}", download.Name, download.Url); var extension = download.Name.Split('.').Last(); var zipDir = Path.Combine(currentLocation, $"Ombi.{extension}"); Logger.LogDebug(LoggingEvents.Updater, "Zip Dir: {0}", zipDir); try { if (File.Exists(zipDir)) { File.Delete(zipDir); } Logger.LogDebug(LoggingEvents.Updater, "Starting Download"); await DownloadAsync(download.Url, zipDir); Logger.LogDebug(LoggingEvents.Updater, "Finished Download"); } catch (Exception e) { Logger.LogDebug(LoggingEvents.Updater, "Error when downloading"); Logger.LogDebug(LoggingEvents.Updater, e.Message); Logger.LogError(LoggingEvents.Updater, e, "Error when downloading the zip"); throw; } // Extract it Logger.LogDebug(LoggingEvents.Updater, "Extracting ZIP"); Extract(zipDir, tempPath); Logger.LogDebug(LoggingEvents.Updater, "Finished Extracting files"); Logger.LogDebug(LoggingEvents.Updater, "Starting the Ombi.Updater process"); var updaterExtension = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { updaterExtension = ".exe"; } var updaterFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "TempUpdate", "updater", $"Ombi.Updater{updaterExtension}"); // Make sure the file is an executable //ExecLinuxCommand($"chmod +x {updaterFile}"); // There must be an update var start = new ProcessStartInfo { UseShellExecute = false, CreateNoWindow = true, // Ignored if UseShellExecute is set to true FileName = updaterFile, Arguments = GetArgs(settings), WorkingDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "TempUpdate"), }; //if (settings.Username.HasValue()) //{ // start.UserName = settings.Username; //} //if (settings.Password.HasValue()) //{ // start.Password = settings.Password.ToSecureString(); //} using (var proc = new Process { StartInfo = start }) { proc.Start(); } Logger.LogDebug(LoggingEvents.Updater, "Bye bye"); } } catch (Exception e) { Logger.LogError(e, "Exception thrown in the OmbiUpdater, see previous messages"); throw; } }
public virtual void OnUnHandledError() { TaskArgument <TContext> taskArg = new TaskArgument <TContext>(this.Context, this.Type); AssemblyHelper.ExecuteTasks <IUnHandledErrorTask <TaskArgument <TContext> >, TaskArgument <TContext> >(taskArg, true); }
public void CanGetAssembliesInOrder() { var assemblyList = new List <Assembly>(AssemblyHelper.AssembliesOrdered("Disty.Common", null)); Assert.IsTrue(assemblyList[0].FullName.Contains("Disty.Common")); }
string ProjectText(MonoIsland island, Mode mode, Dictionary <string, string> allAssetsProjectParts, ScriptCompilerBase.ResponseFileData responseFileData, List <MonoIsland> allProjectIslands) { var projectBuilder = new StringBuilder(ProjectHeader(island, responseFileData)); var references = new List <string>(); var projectReferences = new List <Match>(); Match match; bool isBuildingEditorProject = island._output.EndsWith("-Editor.dll"); foreach (string file in island._files) { if (!ShouldFileBePartOfSolution(file)) { continue; } var extension = Path.GetExtension(file).ToLower(); var fullFile = EscapedRelativePathFor(file); if (".dll" != extension) { var tagName = "Compile"; projectBuilder.AppendFormat(" <{0} Include=\"{1}\" />{2}", tagName, fullFile, WindowsNewline); } else { references.Add(fullFile); } } string additionalAssetsForProject; var assemblyName = Path.GetFileNameWithoutExtension(island._output); // Append additional non-script files that should be included in project generation. if (allAssetsProjectParts.TryGetValue(assemblyName, out additionalAssetsForProject)) { projectBuilder.Append(additionalAssetsForProject); } var allAdditionalReferenceFilenames = new List <string>(); foreach (string reference in references.Union(island._references).Union(responseFileData.References.Select(r => r.Assembly))) { if (reference.EndsWith("/UnityEditor.dll") || reference.EndsWith("/UnityEngine.dll") || reference.EndsWith("\\UnityEditor.dll") || reference.EndsWith("\\UnityEngine.dll")) { continue; } match = scriptReferenceExpression.Match(reference); if (match.Success) { var language = ScriptCompilers.GetLanguageFromExtension(island.GetExtensionOfSourceFiles()); var targetLanguage = (ScriptingLanguage)Enum.Parse(typeof(ScriptingLanguage), language.GetLanguageName(), true); if (mode == Mode.UnityScriptAsUnityProj || ScriptingLanguage.CSharp == targetLanguage) { // Add a reference to a project except if it's a reference to a script assembly // that we are not generating a project for. This will be the case for assemblies // coming from .assembly.json files in non-internalized packages. var dllName = match.Groups["dllname"].Value; if (allProjectIslands.Any(i => Path.GetFileName(i._output) == dllName)) { projectReferences.Add(match); continue; } } } string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(_projectDirectory, reference); if (!AssemblyHelper.IsManagedAssembly(fullReference)) { continue; } if (AssemblyHelper.IsInternalAssembly(fullReference)) { if (!IsAdditionalInternalAssemblyReference(isBuildingEditorProject, fullReference)) { continue; } var referenceName = Path.GetFileName(fullReference); if (allAdditionalReferenceFilenames.Contains(referenceName)) { continue; } allAdditionalReferenceFilenames.Add(referenceName); } //replace \ with / and \\ with / var escapedFullPath = SecurityElement.Escape(fullReference); escapedFullPath = escapedFullPath.Replace("\\", "/"); escapedFullPath = escapedFullPath.Replace("\\\\", "/"); projectBuilder.AppendFormat(" <Reference Include=\"{0}\">{1}", Path.GetFileNameWithoutExtension(escapedFullPath), WindowsNewline); projectBuilder.AppendFormat(" <HintPath>{0}</HintPath>{1}", escapedFullPath, WindowsNewline); projectBuilder.AppendFormat(" </Reference>{0}", WindowsNewline); } if (0 < projectReferences.Count) { string referencedProject; projectBuilder.AppendLine(" </ItemGroup>"); projectBuilder.AppendLine(" <ItemGroup>"); foreach (Match reference in projectReferences) { var targetAssembly = EditorCompilationInterface.Instance.GetTargetAssemblyDetails(reference.Groups["dllname"].Value); ScriptingLanguage targetLanguage = ScriptingLanguage.None; if (targetAssembly != null) { targetLanguage = (ScriptingLanguage)Enum.Parse(typeof(ScriptingLanguage), targetAssembly.Language.GetLanguageName(), true); } referencedProject = reference.Groups["project"].Value; projectBuilder.AppendFormat(" <ProjectReference Include=\"{0}{1}\">{2}", referencedProject, GetProjectExtension(targetLanguage), WindowsNewline); projectBuilder.AppendFormat(" <Project>{{{0}}}</Project>", ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll")), WindowsNewline); projectBuilder.AppendFormat(" <Name>{0}</Name>", referencedProject, WindowsNewline); projectBuilder.AppendLine(" </ProjectReference>"); } } projectBuilder.Append(ProjectFooter(island)); return(projectBuilder.ToString()); }
public void OnApplicationInitialized() { TaskArgument <TContext> taskArg = new TaskArgument <TContext>(this.Context, this.Type); AssemblyHelper.ExecuteTasks <IApplicationInitializedTask <TaskArgument <TContext> >, TaskArgument <TContext> >(taskArg, true); }
private void MenuItemContributors_OnClick(object sender, RoutedEventArgs e) { Messenger.Default.Send <object>(null, MessageToken.ClearLeftSelected); Messenger.Default.Send(true, MessageToken.FullSwitch); Messenger.Default.Send(AssemblyHelper.CreateInternalInstance($"UserControl.{MessageToken.ContributorsView}"), MessageToken.LoadShowContent); }
static int RunProject(XunitProject project, bool serialize, bool?parallelizeAssemblies, bool?parallelizeTestCollections, int?maxThreadCount, bool diagnosticMessages, bool noColor, bool?noAppDomain) { XElement assembliesElement = null; var clockTime = Stopwatch.StartNew(); var xmlTransformers = TransformFactory.GetXmlTransformers(project); var needsXml = xmlTransformers.Count > 0; var consoleLock = new object(); if (!parallelizeAssemblies.HasValue) { parallelizeAssemblies = project.All(assembly => assembly.Configuration.ParallelizeAssemblyOrDefault); } if (needsXml) { assembliesElement = new XElement("assemblies"); } var originalWorkingFolder = Directory.GetCurrentDirectory(); using (AssemblyHelper.SubscribeResolve()) { if (parallelizeAssemblies.GetValueOrDefault()) { var tasks = project.Assemblies.Select(assembly => Task.Run(() => ExecuteAssembly(consoleLock, assembly, serialize, needsXml, parallelizeTestCollections, maxThreadCount, diagnosticMessages, noColor, noAppDomain, project.Filters))); var results = Task.WhenAll(tasks).GetAwaiter().GetResult(); foreach (var assemblyElement in results.Where(result => result != null)) { assembliesElement.Add(assemblyElement); } } else { foreach (var assembly in project.Assemblies) { var assemblyElement = ExecuteAssembly(consoleLock, assembly, serialize, needsXml, parallelizeTestCollections, maxThreadCount, diagnosticMessages, noColor, noAppDomain, project.Filters); if (assemblyElement != null) { assembliesElement.Add(assemblyElement); } } } clockTime.Stop(); if (completionMessages.Count > 0) { reporterMessageHandler.OnMessage(new TestExecutionSummary(clockTime.Elapsed, completionMessages.OrderBy(kvp => kvp.Key).ToList())); } } Directory.SetCurrentDirectory(originalWorkingFolder); xmlTransformers.ForEach(transformer => transformer(assembliesElement)); return(failed ? 1 : completionMessages.Values.Sum(summary => summary.Failed)); }
private static IEnumerable <IEditorModule> RegisterEditorModulesFromAssembly(Assembly assembly) { return(AssemblyHelper.FindImplementors <IEditorModule>(assembly)); }
internal static IEnumerable <IPlatformSupportModule> RegisterPlatformSupportModulesFromAssembly(Assembly assembly) { return(AssemblyHelper.FindImplementors <IPlatformSupportModule>(assembly)); }
private static bool InitializePackageManager(Assembly assembly, Unity.DataContract.PackageInfo package) { ModuleManager.s_PackageManager = AssemblyHelper.FindImplementors <IPackageManagerModule>(assembly).FirstOrDefault <IPackageManagerModule>(); if (ModuleManager.s_PackageManager == null) { return(false); } string location = assembly.Location; if (package != null) { InternalEditorUtility.SetupCustomDll(Path.GetFileName(location), location); } else { package = new Unity.DataContract.PackageInfo { basePath = Path.GetDirectoryName(location) }; } ModuleManager.s_PackageManager.moduleInfo = package; ModuleManager.s_PackageManager.editorInstallPath = EditorApplication.applicationContentsPath; ModuleManager.s_PackageManager.unityVersion = new PackageVersion(Application.unityVersion); ModuleManager.s_PackageManager.Initialize(); foreach (Unity.DataContract.PackageInfo current in ModuleManager.s_PackageManager.playbackEngines) { BuildTarget buildTarget = BuildTarget.StandaloneWindows; if (ModuleManager.TryParseBuildTarget(current.name, out buildTarget)) { Console.WriteLine("Setting {0} v{1} for Unity v{2} to {3}", new object[] { buildTarget, current.version, current.unityVersion, current.basePath }); foreach (KeyValuePair <string, PackageFileData> current2 in from f in current.files where f.Value.type == PackageFileType.Dll select f) { string path = Path.Combine(current.basePath, current2.Key).NormalizePath(); if (!File.Exists(path)) { UnityEngine.Debug.LogWarningFormat("Missing assembly \t{0} for {1}. Player support may be incomplete.", new object[] { current.basePath, current.name }); } else { InternalEditorUtility.SetupCustomDll(Path.GetFileName(location), location); } } BuildPipeline.SetPlaybackEngineDirectory(buildTarget, BuildOptions.None, current.basePath); InternalEditorUtility.SetPlatformPath(current.basePath); ModuleManager.s_PackageManager.LoadPackage(current); } } return(true); }
/// <summary> /// Reads the Exceptionless configuration from the app.config or web.config files configuration section. /// </summary> /// <param name="config">The configuration object you want to apply the attribute settings to.</param> public static void ReadFromConfigSection(this ExceptionlessConfiguration config) { ExceptionlessSection section = null; try { section = ConfigurationManager.GetSection("exceptionless") as ExceptionlessSection; } catch (Exception ex) { config.Resolver.GetLog().Error(typeof(ExceptionlessExtraConfigurationExtensions), ex, String.Concat("An error occurred while retrieving the configuration section. Exception: ", ex.Message)); } if (section == null) { return; } config.Enabled = section.Enabled; if (IsValidApiKey(section.ApiKey)) { config.ApiKey = section.ApiKey; } if (!String.IsNullOrEmpty(section.ServerUrl)) { config.ServerUrl = section.ServerUrl; } if (section.QueueMaxAge.HasValue) { config.QueueMaxAge = section.QueueMaxAge.Value; } if (section.QueueMaxAttempts.HasValue) { config.QueueMaxAttempts = section.QueueMaxAttempts.Value; } if (!String.IsNullOrEmpty(section.StoragePath)) { config.UseFolderStorage(section.StoragePath); } if (section.EnableLogging.HasValue && section.EnableLogging.Value) { if (!String.IsNullOrEmpty(section.LogPath)) { config.UseFileLogger(section.LogPath); } else if (!String.IsNullOrEmpty(section.StoragePath)) { config.UseFileLogger(Path.Combine(section.StoragePath, "exceptionless.log")); } else if (!config.Resolver.HasRegistration <IExceptionlessLog>()) { config.UseIsolatedStorageLogger(); } } foreach (var tag in section.Tags.SplitAndTrim(',').Where(tag => !String.IsNullOrEmpty(tag))) { config.DefaultTags.Add(tag); } if (section.ExtendedData != null) { foreach (NameValueConfigurationElement setting in section.ExtendedData) { if (!String.IsNullOrEmpty(setting.Name)) { config.DefaultData[setting.Name] = setting.Value; } } } if (section.Settings != null) { foreach (NameValueConfigurationElement setting in section.Settings) { if (!String.IsNullOrEmpty(setting.Name)) { config.Settings[setting.Name] = setting.Value; } } } if (section.Registrations != null && section.Registrations.Count > 0) { var types = AssemblyHelper.GetTypes(config.Resolver.GetLog()); foreach (RegistrationConfigElement resolver in section.Registrations) { if (String.IsNullOrEmpty(resolver.Service) || String.IsNullOrEmpty(resolver.Type)) { continue; } Type resolverInterface = types.FirstOrDefault(t => t.Name.Equals(resolver.Service) || t.FullName.Equals(resolver.Service)); if (resolverInterface == null) { config.Resolver.GetLog().Error(typeof(ExceptionlessExtraConfigurationExtensions), String.Format("An error occurred while retrieving service type \"{0}\".", resolver.Service)); continue; } try { Type implementationType = Type.GetType(resolver.Type); if (!resolverInterface.IsAssignableFrom(implementationType)) { config.Resolver.GetLog().Error(typeof(ExceptionlessExtraConfigurationExtensions), String.Format("Type \"{0}\" does not implement \"{1}\".", resolver.Type, resolver.Service)); continue; } config.Resolver.Register(resolverInterface, implementationType); } catch (Exception ex) { config.Resolver.GetLog().Error(typeof(ExceptionlessExtraConfigurationExtensions), ex, String.Format("An error occurred while registering service \"{0}\" implementation \"{1}\".", resolver.Service, resolver.Type)); } } } }
private void BtnOK_Click(object sender, EventArgs e) { if (!double.TryParse(txtNewBpm.Text, out var bpm) || bpm <= 0) { MessageBox.Show(this, LanguageManager.TryGetString("messages.fspecialnote.bpm_invalid") ?? "Please enter a valid BPM value.", AssemblyHelper.GetTitle(), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } _bpm = bpm; if (cboMeasures.Enabled) { _barIndex = cboMeasures.SelectedIndex; _rowIndex = cboRows.SelectedIndex; } else { _barIndex = _rowIndex = -1; } DialogResult = DialogResult.OK; }
private void CboMeasures_SelectedIndexChanged(object sender, EventArgs e) { var score = _score; if (score == null) { return; } var selectedIndex = cboMeasures.SelectedIndex; var bar = score.Bars.Find(b => b.Basic.Index == selectedIndex); if (bar == null) { MessageBox.Show(LanguageManager.TryGetString("messages.fspecialnote.measures_not_exist") ?? "There are no available measures yet.", AssemblyHelper.GetTitle(), MessageBoxButtons.OK, MessageBoxIcon.Warning); SetManualSelection(false); btnOK.Enabled = false; return; } cboRows.Items.Clear(); cboRows.Items.AddRange(Enumerable.Range(1, bar.GetNumberOfGrids()).Select(n => (object)n.ToString()).ToArray()); if (cboRows.Items.Count > 0) { cboRows.SelectedIndex = 0; } }
// [TestCase(@"http://server/path/to/assembly.dll", "//server/path/to/assembly.dll")] public void GetAssemblyPathFromCodeBase(string uri, string expectedPath) { string localPath = AssemblyHelper.GetAssemblyPathFromCodeBase(uri); Assert.That(localPath, Is.SamePath(expectedPath)); }
/// <summary> /// Deserializes a basic JSON string into object form. It isnt mean to handle complex /// data types. This is just a simple helper. /// </summary> /// <typeparam name="T">Type (or base type) of object were deserializing to</typeparam> /// <param name="rJSON">Content that is being deserialized</param> /// <returns>Object that was deserialized</returns> public static object Deserialize(string rJSON) { JSONNode lNode = JSONNode.Parse(rJSON); if (lNode == null) { return(null); } string lTypeString = lNode["__Type"].Value; if (string.IsNullOrEmpty(lTypeString)) { return(null); } Type lType = AssemblyHelper.ResolveType(lTypeString); if (ReflectionHelper.IsPrimitive(lType)) { JSONNode lValueNode = lNode["__Value"]; return(DeserializeValue(lType, lValueNode)); } if (lType == typeof(string)) { JSONNode lValueNode = lNode["__Value"]; return(DeserializeValue(lType, lValueNode)); } object lObject = null; try { lObject = Activator.CreateInstance(lType); } catch (Exception lException) { Debug.Log(string.Format("JSONSerializer.Deserialize() {0} {1} {2}", lTypeString, lException.Message, lException.StackTrace)); } if (lObject == null) { return(null); } // Cycle through all the properties. Unfortunately Binding flags dont seem to // be working. So, we need to check them all PropertyInfo[] lProperties = lObject.GetType().GetProperties(); foreach (PropertyInfo lProperty in lProperties) { if (!lProperty.CanWrite) { continue; } if (ReflectionHelper.IsDefined(lProperty, typeof(SerializationIgnoreAttribute))) { continue; } JSONNode lValueNode = lNode[lProperty.Name]; if (lValueNode != null) { object lValue = DeserializeValue(lProperty.PropertyType, lValueNode); if (lValue != null) { lProperty.SetValue(lObject, lValue, null); } } } FieldInfo[] lFields = lObject.GetType().GetFields(); foreach (FieldInfo lField in lFields) { if (lField.IsInitOnly) { continue; } if (lField.IsLiteral) { continue; } if (ReflectionHelper.IsDefined(lField, typeof(NonSerializedAttribute))) { continue; } JSONNode lValueNode = lNode[lField.Name]; if (lValueNode != null) { object lValue = DeserializeValue(lField.FieldType, lValueNode); if (lValue != null) { lField.SetValue(lObject, lValue); } } } return(lObject); }
// Internal Execute depends on _textUI and _options having been set already. private int Execute() { _runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder()); #if !PORTABLE InitializeInternalTrace(); #endif try { #if !PORTABLE if (!Directory.Exists(_options.WorkDirectory)) { Directory.CreateDirectory(_options.WorkDirectory); } #endif if (_options.TeamCity) { _teamCity = new TeamCityEventListener(_textUI.Writer); } if (_options.ShowVersion || !_options.NoHeader) { _textUI.DisplayHeader(); } if (_options.ShowHelp) { _textUI.DisplayHelp(); return(TextRunner.OK); } // We already showed version as a part of the header if (_options.ShowVersion) { return(TextRunner.OK); } if (_options.ErrorMessages.Count > 0) { _textUI.DisplayErrors(_options.ErrorMessages); _textUI.Writer.WriteLine(); _textUI.DisplayHelp(); return(TextRunner.INVALID_ARG); } if (_testAssembly == null && _options.InputFile == null) { _textUI.DisplayError("No test assembly was specified."); _textUI.Writer.WriteLine(); _textUI.DisplayHelp(); return(TextRunner.OK); } _textUI.DisplayRuntimeEnvironment(); var testFile = _testAssembly != null ? AssemblyHelper.GetAssemblyPath(_testAssembly) : _options.InputFile; _textUI.DisplayTestFiles(new string[] { testFile }); if (_testAssembly == null) { _testAssembly = AssemblyHelper.Load(testFile); } if (_options.WaitBeforeExit && _options.OutFile != null) { _textUI.DisplayWarning("Ignoring /wait option - only valid for Console"); } var runSettings = MakeRunSettings(_options); // We display the filters at this point so that any exception message // thrown by CreateTestFilter will be understandable. _textUI.DisplayTestFilters(); TestFilter filter = CreateTestFilter(_options); _runner.Load(_testAssembly, runSettings); return(_options.Explore ? ExploreTests(filter) : RunTests(filter, runSettings)); } catch (FileNotFoundException ex) { _textUI.DisplayError(ex.Message); return(FILE_NOT_FOUND); } catch (Exception ex) { _textUI.DisplayError(ex.ToString()); return(UNEXPECTED_ERROR); } finally { if (_options.WaitBeforeExit) { _textUI.WaitForUser("Press Enter key to continue . . ."); } } }
/// <summary> /// Allows us to deserialize into an existing object /// </summary> /// <param name="rJSON"></param> /// <param name="rObject"></param> public static void DeserializeInto(string rJSON, ref object rObject) { if (string.IsNullOrEmpty(rJSON)) { return; } JSONNode lNode = JSONNode.Parse(rJSON); if (lNode == null || lNode.Count == 0) { return; } // If the target is null, instanciate an object if (rObject == null) { string lTypeString = lNode["__Type"].Value; if (string.IsNullOrEmpty(lTypeString)) { return; } try { rObject = Activator.CreateInstance(AssemblyHelper.ResolveType(lTypeString)); } catch (Exception lException) { Log.ConsoleWriteError(string.Format("JSONSerializer.DeserializeInto() {0} {1} {2}", lTypeString, lException.Message, lException.StackTrace)); } if (rObject == null) { return; } } // Cycle through all the properties. Unfortunately Binding flags dont seem to // be working. So, we need to check them all FieldInfo[] lFields = rObject.GetType().GetFields(); foreach (FieldInfo lField in lFields) { if (lField.IsInitOnly) { continue; } if (lField.IsLiteral) { continue; } if (ReflectionHelper.IsDefined(lField, typeof(NonSerializedAttribute))) { continue; } JSONNode lValueNode = lNode[lField.Name]; if (lValueNode != null) { object lValue = DeserializeValue(lField.FieldType, lValueNode); if (lValue != null) { lField.SetValue(rObject, lValue); } } } PropertyInfo[] lProperties = rObject.GetType().GetProperties(); foreach (PropertyInfo lProperty in lProperties) { if (!lProperty.CanWrite) { continue; } if (ReflectionHelper.IsDefined(lProperty, typeof(SerializationIgnoreAttribute))) { continue; } JSONNode lValueNode = lNode[lProperty.Name]; if (lValueNode != null) { object lValue = DeserializeValue(lProperty.PropertyType, lValueNode); if (lValue != null) { lProperty.SetValue(rObject, lValue, null); } } } }
public static bool IsManagedAssembly(string file) { return(AssemblyHelper.IsManagedAssembly(file)); }
public void GetLatestVersion() { var version = AssemblyHelper.GetLatestVersion(Assembly.GetExecutingAssembly()); Assert.That(version, Is.Not.Null); }
public virtual void OnApplicationRequestEnded() { TaskArgument <TContext> taskArg = new TaskArgument <TContext>(this.Context, this.Type); AssemblyHelper.ExecuteTasks <IApplicationRequestEndedTask <TaskArgument <TContext> >, TaskArgument <TContext> >(taskArg, true); }
void AnalyzeMethodBody(AssemblyInfo assemblyInfo, MethodDefinition caller, Action <CallInfo> onCallFound, Action <ProjectIssue> onIssueFound) { if (!caller.DebugInformation.HasSequencePoints) { return; } Profiler.BeginSample("ScriptAuditor.AnalyzeMethodBody"); var callerNode = new CallTreeNode(caller); var perfCriticalContext = IsPerformanceCriticalContext(caller); foreach (var inst in caller.Body.Instructions.Where(i => m_OpCodes.Contains(i.OpCode))) { SequencePoint s = null; for (var i = inst; i != null; i = i.Previous) { s = caller.DebugInformation.GetSequencePoint(i); if (s != null) { break; } } Location location = null; if (s != null) { location = new Location(AssemblyHelper.ResolveAssetPath(assemblyInfo, s.Document.Url), s.StartLine); callerNode.location = location; } else { // sequence point not found. Assuming caller.IsHideBySig == true } if (inst.OpCode == OpCodes.Call || inst.OpCode == OpCodes.Callvirt) { onCallFound(new CallInfo { callee = (MethodReference)inst.Operand, caller = caller, location = location, perfCriticalContext = perfCriticalContext }); } foreach (var analyzer in m_InstructionAnalyzers) { if (analyzer.GetOpCodes().Contains(inst.OpCode)) { var projectIssue = analyzer.Analyze(caller, inst); if (projectIssue != null) { projectIssue.dependencies.perfCriticalContext = perfCriticalContext; projectIssue.dependencies.AddChild(callerNode); projectIssue.location = location; projectIssue.SetCustomProperties(new[] { assemblyInfo.name }); onIssueFound(projectIssue); } } } } Profiler.EndSample(); }
public virtual void Config <IApp>(IApp app) { TaskArgument <IApp> taskArg = new TaskArgument <IApp>(app, this.Type); AssemblyHelper.ExecuteTasks <IConfigAppTask <TaskArgument <IApp> >, TaskArgument <IApp> >(taskArg, true); }
public void Audit(Action <ProjectIssue> onIssueFound, Action onComplete, IProgressBar progressBar = null) { if (m_ProblemDescriptors == null) { throw new Exception("Issue Database not initialized."); } if (m_Config.AnalyzeInBackground && m_AssemblyAnalysisThread != null) { m_AssemblyAnalysisThread.Join(); } var compilationHelper = new AssemblyCompilationHelper(); var callCrawler = new CallCrawler(); Profiler.BeginSample("ScriptAuditor.Audit.Compilation"); var assemblyInfos = compilationHelper.Compile(m_Config.AnalyzeEditorCode, progressBar); Profiler.EndSample(); var issues = new List <ProjectIssue>(); var localAssemblyInfos = assemblyInfos.Where(info => !info.readOnly).ToArray(); var readOnlyAssemblyInfos = assemblyInfos.Where(info => info.readOnly).ToArray(); var assemblyDirectories = new List <string>(); assemblyDirectories.AddRange(AssemblyHelper.GetPrecompiledAssemblyDirectories()); assemblyDirectories.AddRange(AssemblyHelper.GetPrecompiledEngineAssemblyDirectories()); var onCallFound = new Action <CallInfo>(pair => { callCrawler.Add(pair); }); var onCompleteInternal = new Action <IProgressBar>(bar => { compilationHelper.Dispose(); callCrawler.BuildCallHierarchies(issues, bar); onComplete(); }); var onIssueFoundInternal = new Action <ProjectIssue>(issue => { issues.Add(issue); onIssueFound(issue); }); Profiler.BeginSample("ScriptAuditor.Audit.Analysis"); // first phase: analyze assemblies generated from editable scripts AnalyzeAssemblies(localAssemblyInfos, assemblyDirectories, onCallFound, onIssueFoundInternal, null, progressBar); var enableBackgroundAnalysis = m_Config.AnalyzeInBackground; #if !UNITY_2019_3_OR_NEWER enableBackgroundAnalysis = false; #endif // second phase: analyze all remaining assemblies, in a separate thread if enableBackgroundAnalysis is enabled if (enableBackgroundAnalysis) { m_AssemblyAnalysisThread = new Thread(() => AnalyzeAssemblies(readOnlyAssemblyInfos, assemblyDirectories, onCallFound, onIssueFound, onCompleteInternal)); m_AssemblyAnalysisThread.Name = "Assembly Analysis"; m_AssemblyAnalysisThread.Priority = ThreadPriority.BelowNormal; m_AssemblyAnalysisThread.Start(); } else { Profiler.BeginSample("ScriptAuditor.Audit.AnalysisReadOnly"); AnalyzeAssemblies(readOnlyAssemblyInfos, assemblyDirectories, onCallFound, onIssueFoundInternal, onCompleteInternal, progressBar); Profiler.EndSample(); } Profiler.EndSample(); }
public async Task CmdWithStartQuoteOnlyFailsToRunFullCommandLine() { var context = BuildXLContext.CreateInstanceForTesting(); string currentCodeFolder = Path.GetDirectoryName(AssemblyHelper.GetAssemblyLocation(Assembly.GetExecutingAssembly())); Contract.Assume(currentCodeFolder != null); string shimProgram = Path.Combine(currentCodeFolder, "TestSubstituteProcessExecutionShim.exe"); Assert.True(File.Exists(shimProgram), $"Shim test program not found at {shimProgram}"); var shimProgramPath = AbsolutePath.Create(context.PathTable, shimProgram); var fam = new FileAccessManifest(context.PathTable) { FailUnexpectedFileAccesses = false, IgnoreCodeCoverage = false, ReportFileAccesses = false, ReportUnexpectedFileAccesses = false, MonitorChildProcesses = false, SubstituteProcessExecutionInfo = new SubstituteProcessExecutionInfo( shimProgramPath, shimAllProcesses: true, new ShimProcessMatch[0]) }; Guid sessionId = Guid.NewGuid(); string sessionIdStr = sessionId.ToString("N"); var loggingContext = new LoggingContext(sessionId, "TestSession", new LoggingContext.SessionInfo(sessionIdStr, "env", sessionId)); string executable = CmdHelper.CmdX64; string childExecutable = '"' + executable; // Only an open quote string childOutput = "Child cmd that should be shimmed"; string childArgs = $"{childExecutable} /D /C @echo {childOutput}"; string args = "/D /C echo Top-level cmd. Running child process && " + childArgs; var stdoutSb = new StringBuilder(128); var stderrSb = new StringBuilder(); var sandboxedProcessInfo = new SandboxedProcessInfo( context.PathTable, new LocalSandboxedFileStorage(), executable, disableConHostSharing: true, loggingContext: loggingContext, fileAccessManifest: fam) { PipDescription = executable, Arguments = args, WorkingDirectory = Environment.CurrentDirectory, StandardOutputEncoding = Encoding.UTF8, StandardOutputObserver = stdoutStr => stdoutSb.AppendLine(stdoutStr), StandardErrorEncoding = Encoding.UTF8, StandardErrorObserver = stderrStr => stderrSb.AppendLine(stderrStr), EnvironmentVariables = BuildParameters.GetFactory().PopulateFromEnvironment(), Timeout = TimeSpan.FromMinutes(1), }; ISandboxedProcess sandboxedProcess = await SandboxedProcessFactory.StartAsync(sandboxedProcessInfo, forceSandboxing : true) .ConfigureAwait(false); SandboxedProcessResult result = await sandboxedProcess.GetResultAsync().ConfigureAwait(false); string stdout = stdoutSb.ToString(); m_output.WriteLine($"stdout: {stdout}"); string stderr = stderrSb.ToString(); m_output.WriteLine($"stderr: {stderr}"); Assert.Equal(1, result.ExitCode); Assert.Equal("The system cannot find the path specified.\r\n", stderr); }
/// <summary> /// 添加数据库上下文 /// </summary> private static void AddDbContext(this IServiceCollection services, IModuleDescriptor module, DbModuleOptions options, DbOptions dbOptions) { var dbContextType = module.AssemblyDescriptor.Infrastructure.GetTypes().FirstOrDefault(m => m.Name.EqualsIgnoreCase(options.Name + "DbContext")); if (dbContextType != null) { //加载实体列表 LoadEntityTypes(module, options); var dbContextOptionsAssemblyName = AssemblyHelper.GetCurrentAssemblyName().Replace("Integration", "") + dbOptions.Dialect; var dbContextOptionsTypeName = dbOptions.Dialect + "DbContextOptions"; var dbContextOptionsType = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(dbContextOptionsAssemblyName)).GetType($"{dbContextOptionsAssemblyName}.{dbContextOptionsTypeName}"); var sp = services.BuildServiceProvider(); //日志工厂 var loggerFactory = dbOptions.Logging ? sp.GetService <ILoggerFactory>() : null; //登录信息 var loginInfo = sp.GetService <ILoginInfo>(); //数据库上下文配置项 var contextOptions = (IDbContextOptions)Activator.CreateInstance(dbContextOptionsType, dbOptions, options, loggerFactory, loginInfo); //数据库创建事件 var createDatabaseEvent = module.AssemblyDescriptor.Infrastructure.GetTypes().FirstOrDefault(m => typeof(IDatabaseCreateEvents).IsAssignableFrom(m)); if (createDatabaseEvent != null) { contextOptions.DatabaseCreateEvents = (IDatabaseCreateEvents)Activator.CreateInstance(createDatabaseEvent); } //创建数据库上下文实例 var dbContext = (IDbContext)Activator.CreateInstance(dbContextType, contextOptions); #region ==执行初始化脚本== //当开启初始化脚本 && 开启自动创建数据库 && 数据库不存在 if (dbOptions.InitData && dbOptions.CreateDatabase && !dbContext.DatabaseExists) { var dbScriptPath = ""; switch (dbOptions.Dialect) { case SqlDialect.SqlServer: dbScriptPath = module.InitDataScriptDescriptor.SqlServer; break; case SqlDialect.MySql: dbScriptPath = module.InitDataScriptDescriptor.MySql; break; case SqlDialect.SQLite: dbScriptPath = module.InitDataScriptDescriptor.SQLite; break; case SqlDialect.PostgreSQL: dbScriptPath = module.InitDataScriptDescriptor.PostgreSQL; break; case SqlDialect.Oracle: dbScriptPath = module.InitDataScriptDescriptor.Oracle; break; } if (dbScriptPath.NotNull() && File.Exists(dbScriptPath)) { using var sr = new StreamReader(dbScriptPath); var sql = sr.ReadToEnd(); if (sql.NotNull()) { if (dbOptions.Dialect == SqlDialect.PostgreSQL) { sql = sql.Replace("[nm_database_name]", options.Database); } //此处不能使用IDbContext的NewConnection方法创建连接 var con = dbContext.Options.NewConnection(); con.Execute(sql); } } } #endregion //注入数据库上下文 services.AddSingleton(dbContextType, dbContext); services.AddRepositories(module, dbContext, dbOptions); } }
[InlineData(false, "cmd.exe")] // Filter should match child public async Task CmdWithTestShim(bool useQuotesForChildCmdExe, string processMatch) { var context = BuildXLContext.CreateInstanceForTesting(); string currentCodeFolder = Path.GetDirectoryName(AssemblyHelper.GetAssemblyLocation(Assembly.GetExecutingAssembly())); Contract.Assume(currentCodeFolder != null); string executable = CmdHelper.CmdX64; string childExecutable = executable; string quotedExecutable = '"' + executable + '"'; if (useQuotesForChildCmdExe) { childExecutable = quotedExecutable; } string shimProgram = Path.Combine(currentCodeFolder, "TestSubstituteProcessExecutionShim.exe"); Assert.True(File.Exists(shimProgram), $"Shim test program not found at {shimProgram}"); var shimProgramPath = AbsolutePath.Create(context.PathTable, shimProgram); var fam = new FileAccessManifest(context.PathTable) { FailUnexpectedFileAccesses = false, IgnoreCodeCoverage = false, ReportFileAccesses = false, ReportUnexpectedFileAccesses = false, MonitorChildProcesses = false, SubstituteProcessExecutionInfo = new SubstituteProcessExecutionInfo( shimProgramPath, shimAllProcesses: processMatch == null, // When we have a process to match, make the shim list opt-in to ensure a match processMatch == null ? new ShimProcessMatch[0] : new[] { new ShimProcessMatch(PathAtom.Create(context.StringTable, processMatch), PathAtom.Invalid) }) }; Guid sessionId = Guid.NewGuid(); string sessionIdStr = sessionId.ToString("N"); var loggingContext = new LoggingContext(sessionId, "TestSession", new LoggingContext.SessionInfo(sessionIdStr, "env", sessionId)); string childOutput = "Child cmd that should be shimmed"; string childArgs = $"{childExecutable} /D /C @echo {childOutput}"; // Detours logic should wrap the initial cmd in quotes for easier parsing by shim logic. // However, since we're indirecting through a cmd.exe command line it gets dropped along the way. string childShimArgs = $"/D /C @echo {childOutput}"; string args = "/D /C echo Top-level cmd. Running child process && " + childArgs; var stdoutSb = new StringBuilder(128); var stderrSb = new StringBuilder(); var sandboxedProcessInfo = new SandboxedProcessInfo( context.PathTable, new LocalSandboxedFileStorage(), executable, disableConHostSharing: true, loggingContext: loggingContext, fileAccessManifest: fam) { PipDescription = executable, Arguments = args, WorkingDirectory = Environment.CurrentDirectory, StandardOutputEncoding = Encoding.UTF8, StandardOutputObserver = stdoutStr => stdoutSb.AppendLine(stdoutStr), StandardErrorEncoding = Encoding.UTF8, StandardErrorObserver = stderrStr => stderrSb.AppendLine(stderrStr), EnvironmentVariables = BuildParameters.GetFactory().PopulateFromEnvironment(), Timeout = TimeSpan.FromMinutes(1), }; ISandboxedProcess sandboxedProcess = await SandboxedProcessFactory.StartAsync(sandboxedProcessInfo, forceSandboxing : true) .ConfigureAwait(false); SandboxedProcessResult result = await sandboxedProcess.GetResultAsync().ConfigureAwait(false); string stdout = stdoutSb.ToString(); m_output.WriteLine($"stdout: {stdout}"); string stderr = stderrSb.ToString(); m_output.WriteLine($"stderr: {stderr}"); Assert.Equal(0, result.ExitCode); Assert.Equal(0, stderr.Length); // The shim is an exe on netframework, dll in a temp dir on netcore, so don't try to match it. const string shimOutput = "TestShim: Entered with command line: "; int indexOfShim = stdout.IndexOf(shimOutput, StringComparison.Ordinal); Assert.True(indexOfShim > 0, shimOutput); m_output.WriteLine($"Expecting shim args: {childShimArgs}"); int indexOfShimArgs = stdout.LastIndexOf(childShimArgs); Assert.True(indexOfShimArgs > indexOfShim); }
public void Run( User user, Patient patient, Image image, StructureSet structureSet, PlanSetup planSetup, IEnumerable <PlanSetup> planSetupsInScope, IEnumerable <PlanSum> planSumsInScope, Window mainWindow) { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string scriptVersion = fvi.FileVersion; string temp = System.Environment.GetEnvironmentVariable("TEMP"); string eclipseVersion = System.Reflection.Assembly.GetAssembly (typeof(VMS.TPS.Common.Model.API.Application)).GetName().Version.ToString(); if (planSumsInScope == null && planSetup == null) { mainWindow.Title = "No plans open"; mainWindow.Content = "Please open a plan or plansum"; } if (planSumsInScope.Count() > 1 && planSetup == null) //plansums and/or plan(s) are in the scope window { var planSelectViewModel = new PlanSelectViewModel(user, patient, scriptVersion, planSetup, planSetupsInScope, planSumsInScope, mainWindow); var planSelectView = new PlanSelectView(planSelectViewModel); mainWindow.Title = "Select a plan and constraint template"; mainWindow.Content = planSelectView; } else { PlanningItem selectedPlanningItem; if (planSumsInScope.Count() == 1 && planSetup == null) //only one plansum in scope window { selectedPlanningItem = planSumsInScope.FirstOrDefault(); } else //only plansetups are in scope window { selectedPlanningItem = planSetup; } DirectoryInfo constraintDir = new DirectoryInfo(Path.Combine(AssemblyHelper.GetAssemblyDirectory(), "ConstraintTemplates")); string firstFileName = constraintDir.GetFiles().FirstOrDefault().ToString(); string firstConstraintFilePath = Path.Combine(constraintDir.ToString(), firstFileName); var activeConstraintPath = new ConstraintViewModel(firstConstraintFilePath); var planningItemList = PlanningItemListViewModel.GetPlanningItemList(planSetupsInScope, planSumsInScope); var mainViewModel = new MainViewModel(user, patient, scriptVersion, planningItemList, new PlanningItemViewModel(selectedPlanningItem)); mainWindow.Title = mainViewModel.Title; var mainView = new MainView(mainViewModel); mainWindow.Content = mainView; } }
/// <summary> /// Helper to get where the test files are deployed /// </summary> protected string GetTestExecutionLocation() { return(Path.GetDirectoryName(AssemblyHelper.GetAssemblyLocation(Assembly.GetCallingAssembly()))); }
private static Type DoActualCompilation(string source, string name, string queryText, OrderedPartCollection <AbstractDynamicCompilationExtension> extensions, string basePath, string indexFilePath) { var provider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); var currentAssembly = typeof(QueryParsingUtils).Assembly; var assemblies = new HashSet <string> { typeof(SystemTime).Assembly.Location, typeof(AbstractViewGenerator).Assembly.Location, typeof(NameValueCollection).Assembly.Location, typeof(Enumerable).Assembly.Location, typeof(Binder).Assembly.Location, AssemblyHelper.GetExtractedAssemblyLocationFor(typeof(Field), currentAssembly), }; foreach (var extension in extensions) { foreach (var assembly in extension.Value.GetAssembliesToReference()) { assemblies.Add(assembly); } } var compilerParameters = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = false, IncludeDebugInformation = Debugger.IsAttached, OutputAssembly = indexFilePath }; if (basePath != null) { compilerParameters.TempFiles = new TempFileCollection(basePath, false); } foreach (var assembly in assemblies) { compilerParameters.ReferencedAssemblies.Add(assembly); } CompilerResults compileAssemblyFromFile; if (indexFilePath != null) { var sourceFileName = indexFilePath + ".cs"; File.WriteAllText(sourceFileName, source); compileAssemblyFromFile = provider.CompileAssemblyFromFile(compilerParameters, sourceFileName); } else { compileAssemblyFromFile = provider.CompileAssemblyFromSource(compilerParameters, source); } var results = compileAssemblyFromFile; if (results.Errors.HasErrors) { var sb = new StringBuilder() .AppendLine("Compilation Errors:") .AppendLine(); foreach (CompilerError error in results.Errors) { sb.AppendFormat("Line {0}, Position {1}: Error {2} - {3}\n", error.Line, error.Column, error.ErrorNumber, error.ErrorText); } sb.AppendLine(); sb.AppendLine("Source code:") .AppendLine(queryText) .AppendLine(); throw new InvalidOperationException(sb.ToString()); } var asm = Assembly.Load(File.ReadAllBytes(indexFilePath)); // avoid locking the file // ReSharper disable once AssignNullToNotNullAttribute File.SetCreationTime(indexFilePath, DateTime.UtcNow); CodeVerifier.AssertNoSecurityCriticalCalls(asm); Type result = asm.GetType(name); if (result == null) { throw new InvalidOperationException( "Could not get compiled index type. This probably means that there is something wrong with the assembly load context."); } return(result); }