public BenchmarkReport(Benchmark benchmark, IList<BenchmarkRunReport> runs, EnvironmentInfo hostInfo, BenchmarkParameters parameters = null) { Benchmark = benchmark; Runs = runs; Parameters = parameters; HostInfo = hostInfo; }
/// <summary> /// Searches for game mode factories in the specified path, and loads /// any factories that are found into a registry. /// </summary> /// <returns>A registry containing all of the discovered game mode factories.</returns> public static GameModeRegistry DiscoverSupportedGameModes(EnvironmentInfo p_eifEnvironmentInfo) { Trace.TraceInformation("Discovering Game Mode Factories..."); Trace.Indent(); string strGameModesPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "GameModes"); Trace.TraceInformation("Looking in: {0}", strGameModesPath); GameModeRegistry gmrRegistry = new GameModeRegistry(); string[] strAssemblies = Directory.GetFiles(strGameModesPath, "*.dll"); foreach (string strAssembly in strAssemblies) { Trace.TraceInformation("Checking: {0}", Path.GetFileName(strAssembly)); Trace.Indent(); Assembly asmGameMode = Assembly.LoadFrom(strAssembly); try { Type[] tpeTypes = asmGameMode.GetExportedTypes(); foreach (Type tpeType in tpeTypes) { if (typeof(IGameModeFactory).IsAssignableFrom(tpeType) && !tpeType.IsAbstract) { Trace.TraceInformation("Initializing: {0}", tpeType.FullName); Trace.Indent(); ConstructorInfo cifConstructor = tpeType.GetConstructor(new Type[] { typeof(IEnvironmentInfo) }); if (cifConstructor == null) { Trace.TraceInformation("No constructor accepting one argument of type IEnvironmentInfo found."); Trace.Unindent(); continue; } IGameModeFactory gmfGameModeFactory = (IGameModeFactory)cifConstructor.Invoke(new object[] { p_eifEnvironmentInfo }); gmrRegistry.RegisterGameMode(gmfGameModeFactory); Trace.Unindent(); } } } catch (FileNotFoundException e) { Trace.TraceError(String.Format("Cannot load {0}: cannot find dependency {1}", strAssembly, e.FileName)); //some dependencies were missing, so we couldn't load the assembly // given that these are plugins we don't have control over the dependecies: // we may not even know what they (we can get their name, but if it's a custom // dll not part of the client code base, we can't provide it even if we wanted to) // there's nothing we can do, so simply skip the assembly } Trace.Unindent(); } Trace.Unindent(); return gmrRegistry; }
/// <summary> /// Loads the factories for games that have been previously detected as installed. /// </summary> /// <param name="p_gmrSupportedGameModes">A registry containing the factories for all supported game modes.</param> /// <param name="p_eifEnvironmentInfo">The application's envrionment info.</param> /// <returns>A registry containing all of the game mode factories for games that were previously detected as installed.</returns> public static GameModeRegistry LoadInstalledGameModes(GameModeRegistry p_gmrSupportedGameModes, EnvironmentInfo p_eifEnvironmentInfo) { Trace.TraceInformation("Loading Game Mode Factories for Installed Games..."); Trace.Indent(); GameModeRegistry gmrInstalled = new GameModeRegistry(); foreach (string strGameId in p_eifEnvironmentInfo.Settings.InstalledGames) { Trace.Write(String.Format("Loading {0}: ", strGameId)); if (p_gmrSupportedGameModes.IsRegistered(strGameId)) { Trace.WriteLine("Supported"); gmrInstalled.RegisterGameMode(p_gmrSupportedGameModes.GetGameMode(strGameId)); } else Trace.WriteLine("Not Supported"); } Trace.Unindent(); return gmrInstalled; }
public JsonEnvOutputFormatterTests(ITestOutputHelper output, MetricProviderTestFixture fixture) { _output = output; _formatter = new EnvInfoJsonOutputFormatter(); _env = fixture.Env; }
static int DoInstall(string game, string filename, string installationPath, string profilePath, string gamePath, List <string> additionalSearchPaths, string seVersion, ref string errorString) { if (game == null) { errorString = "no game specified"; return(1); } if (filename == null) { errorString = "no file specified"; return(1); } if (profilePath == null) { errorString = "no profile path specified"; return(1); } if (gamePath == null) { errorString = "no game path specified"; return(1); } try { EnvironmentInfo environmentInfo = new EnvironmentInfo(Properties.Settings.Default); string exeLocation = Assembly.GetExecutingAssembly().Location; string exePath = System.IO.Path.GetDirectoryName(exeLocation); string[] gameModes = Directory.GetFiles(Path.Combine(exePath, "GameModes"), String.Format("{0}.dll", game)); if (gameModes.Count() == 0) { errorString = "unknown game"; return(1); } Assembly gameAssembly = Assembly.LoadFrom(gameModes[0]); IGameModeFactory gameModeFactory = null; Type[] exportedTypes = gameAssembly.GetExportedTypes(); foreach (Type type in exportedTypes) { if (typeof(IGameModeFactory).IsAssignableFrom(type) && !type.IsAbstract) { ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EnvironmentInfo) }); gameModeFactory = (IGameModeFactory)constructor.Invoke(new Object[] { environmentInfo }); } } if (gameModeFactory == null) { errorString = "invalid game"; return(1); } string str7zPath = Path.Combine(environmentInfo.ProgrammeInfoDirectory, environmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll"); SevenZipCompressor.SetLibraryPath(str7zPath); FileUtil fileUtil = new NexusFileUtil(environmentInfo); environmentInfo.Settings.InstallationPaths[gameModeFactory.GameModeDescriptor.ModeId] = installationPath; environmentInfo.Settings.ModFolder[gameModeFactory.GameModeDescriptor.ModeId] = installationPath; // environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = environmentInfo.TemporaryPath; environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = Path.Combine(installationPath, "temp"); if (environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] == null) { environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] = new KeyedSettings <string>(); } if (environmentInfo.Settings.DelayedSettings["ALL"] == null) { environmentInfo.Settings.DelayedSettings["ALL"] = new KeyedSettings <string>(); } ViewMessage warning = null; IGameMode gameMode = gameModeFactory.BuildGameMode(fileUtil, out warning); IModCacheManager cacheManager = new NexusModCacheManager(environmentInfo.TemporaryPath, gameMode.GameModeEnvironmentInfo.ModDirectory, fileUtil); IScriptTypeRegistry scriptTypeRegistry = ScriptTypeRegistry.DiscoverScriptTypes(Path.Combine(Path.GetDirectoryName(exeLocation), "ScriptTypes"), gameMode, new List <string>()); if (scriptTypeRegistry.Types.Count == 0) { errorString = "No script types were found."; return(2); } // use a proxy so we can intercept accesses to the IGameMode interface. This allows us to make the additional search paths accessible from // the sandbox and feed in the script extender version even though the nmm lib won't find it. // This has to happen after DiscoverScriptTypes becaus that function tries to localize the assembly which fails for the dynamic assembly // of the proxy. Fortunately DiscoverScriptTypes has no side-effects on the gameMode. // This recreates the gamemode object so it's important no code above modifies gameMode ProxyGenerator generator = new ProxyGenerator(); GameModeInterceptor interceptor = new GameModeInterceptor(additionalSearchPaths, seVersion != null ? new Version(seVersion) : null); gameMode = (IGameMode)generator.CreateClassProxy(gameMode.GetType(), new object[] { environmentInfo, fileUtil }, new IInterceptor[] { interceptor }); IModFormatRegistry formatRegistry = ModFormatRegistry.DiscoverFormats(cacheManager, gameMode.SupportedFormats, scriptTypeRegistry, Path.Combine(Path.GetDirectoryName(exeLocation), "ModFormats")); if (formatRegistry.Formats.Count == 0) { errorString = "No formats were found."; return(2); } // we install the mod from the temporary path. Unfortunately this requires the archive to be copied, otherwise the sandbox will // prevent the installer script from accessing the archive in its original location string fileNameTemporary = Path.Combine(environmentInfo.TemporaryPath, Path.GetFileName(filename)); File.Copy(filename, fileNameTemporary); IMod mod = CreateMod(fileNameTemporary, formatRegistry, gameMode); if (mod == null) { errorString = "failed to initialize mod"; return(3); } System.IO.File.WriteAllText(installationPath + "/__installInfo.txt", mod.ModName + "\n" + mod.HumanReadableVersion + "\n" + mod.Id); if (mod.HasInstallScript) { DummyDataFileUtilFactory dummyFactory = null; IDataFileUtil dataFileUtility; Logger.Info("Detected C# script that relies on files in the actual data folder"); string modlistFile = Path.Combine(profilePath, "modlist.txt"); // ASSUMED mods path is the parent directory of the gameMode.InstallationPath string modsPath = Directory.GetParent(gameMode.InstallationPath).FullName; // Prepare dummy data directory dummyFactory = new DummyDataFileUtilFactory(gameMode.GameModeEnvironmentInfo.InstallationPath, modlistFile, modsPath, gamePath, additionalSearchPaths); dataFileUtility = dummyFactory.CreateDummyDataFileUtil(); TxFileManager fileManager = new TxFileManager(); IInstallLog installLog = new DummyInstallLog(); IIniInstaller iniIniInstaller = new IniInstaller(mod, installLog, fileManager, delegate { return(OverwriteResult.No); }); IPluginManager pluginManager = new DummyPluginManager(Path.Combine(profilePath, "plugins.txt"), gameMode, mod); IGameSpecificValueInstaller gameSpecificValueInstaller = gameMode.GetGameSpecificValueInstaller(mod, installLog, fileManager, new NexusFileUtil(environmentInfo), delegate { return(OverwriteResult.No); }); IModFileInstaller fileInstaller = new ModFileInstaller(gameMode.GameModeEnvironmentInfo, mod, installLog, pluginManager, dataFileUtility, fileManager, delegate { return(OverwriteResult.No); }, false); InstallerGroup installers = new InstallerGroup(dataFileUtility, fileInstaller, iniIniInstaller, gameSpecificValueInstaller, pluginManager); IVirtualModActivator modActivator = new DummyVirtualModActivator(gameMode, environmentInfo); IScriptExecutor executor = mod.InstallScript.Type.CreateExecutor(mod, gameMode, environmentInfo, modActivator, installers, SynchronizationContext.Current); // run the script in a second thread and start the main loop in the main thread to ensure we can handle message boxes and the like ScriptRunner runner = new ScriptRunner(executor, mod.InstallScript); runner.Execute(); runner.TaskEnded += delegate { iniIniInstaller.FinalizeInstall(); gameSpecificValueInstaller.FinalizeInstall(); mod.EndReadOnlyTransaction(); Application.Exit(); }; Application.Run(); switch (runner.Status) { case BackgroundTasks.TaskStatus.Cancelled: return(11); case BackgroundTasks.TaskStatus.Error: return(6); case BackgroundTasks.TaskStatus.Incomplete: return(10); default: return(0); } } else { errorString = "no install script"; return(4); } } catch (Exception e) { Console.WriteLine("exception: " + e.Message); MessageBox.Show(e.Message, "Installation failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return(5); } }
private void It_targets_the_right_framework( string testIdentifier, string targetFramework, string runtimeFrameworkVersion, bool selfContained, bool isExe, string expectedPackageVersion, string expectedRuntimeVersion, string extraMSBuildArguments = null) { string runtimeIdentifier = null; if (selfContained) { runtimeIdentifier = EnvironmentInfo.GetCompatibleRid(targetFramework); } var testProject = new TestProject() { Name = "FrameworkTargetTest", TargetFrameworks = targetFramework, RuntimeFrameworkVersion = runtimeFrameworkVersion, IsExe = isExe, RuntimeIdentifier = runtimeIdentifier }; var extraArgs = extraMSBuildArguments?.Split(' ') ?? Array.Empty <string>(); var testAsset = _testAssetsManager.CreateTestProject(testProject, testIdentifier); NuGetConfigWriter.Write(testAsset.TestRoot, NuGetConfigWriter.DotnetCoreBlobFeed); var buildCommand = new BuildCommand(testAsset); buildCommand .Execute(extraArgs) .Should() .Pass(); var outputDirectory = buildCommand.GetOutputDirectory(targetFramework, runtimeIdentifier: runtimeIdentifier); if (isExe) { // Self-contained apps don't write a framework version to the runtimeconfig, so only check this for framework-dependent apps if (!selfContained) { string runtimeConfigFile = Path.Combine(outputDirectory.FullName, testProject.Name + ".runtimeconfig.json"); string runtimeConfigContents = File.ReadAllText(runtimeConfigFile); JObject runtimeConfig = JObject.Parse(runtimeConfigContents); string actualRuntimeFrameworkVersion = ((JValue)runtimeConfig["runtimeOptions"]["framework"]["version"]).Value <string>(); actualRuntimeFrameworkVersion.Should().Be(expectedRuntimeVersion); } var runtimeconfigDevFileName = testProject.Name + ".runtimeconfig.dev.json"; outputDirectory.Should() .HaveFile(runtimeconfigDevFileName); string devruntimeConfigContents = File.ReadAllText(Path.Combine(outputDirectory.FullName, runtimeconfigDevFileName)); JObject devruntimeConfig = JObject.Parse(devruntimeConfigContents); var additionalProbingPaths = ((JArray)devruntimeConfig["runtimeOptions"]["additionalProbingPaths"]).Values <string>(); // can't use Path.Combine on segments with an illegal `|` character var expectedPath = $"{Path.Combine(FileConstants.UserProfileFolder, ".dotnet", "store")}{Path.DirectorySeparatorChar}|arch|{Path.DirectorySeparatorChar}|tfm|"; additionalProbingPaths.Should().Contain(expectedPath); } LockFile lockFile = LockFileUtilities.GetLockFile(Path.Combine(buildCommand.ProjectRootPath, "obj", "project.assets.json"), NullLogger.Instance); var target = lockFile.GetTarget(NuGetFramework.Parse(targetFramework), null); var netCoreAppLibrary = target.Libraries.Single(l => l.Name == "Microsoft.NETCore.App"); netCoreAppLibrary.Version.ToString().Should().Be(expectedPackageVersion); }
public EnvironmentInfo GetEnvironmentInfo() { if (_environmentInfo != null) { return(_environmentInfo); } var info = new EnvironmentInfo(); ComputerInfo computerInfo = null; try { computerInfo = new ComputerInfo(); } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get computer info. Error message: {0}", ex.Message); } try { if (computerInfo != null) { info.OSName = computerInfo.OSFullName; } if (computerInfo != null) { info.OSVersion = computerInfo.OSVersion; } } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get operating system version. Error message: {0}", ex.Message); } try { if (computerInfo != null) { info.TotalPhysicalMemory = Convert.ToInt64(computerInfo.TotalPhysicalMemory); } if (computerInfo != null) { info.AvailablePhysicalMemory = Convert.ToInt64(computerInfo.AvailablePhysicalMemory); } } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get physical memory. Error message: {0}", ex.Message); } try { info.ProcessorCount = Environment.ProcessorCount; } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get processor count. Error message: {0}", ex.Message); } try { info.MachineName = Environment.MachineName; } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get machine name. Error message: {0}", ex.Message); } try { IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); if (hostEntry != null && hostEntry.AddressList.Any()) { info.IpAddress = String.Join(", ", hostEntry.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).Select(a => a.ToString()).ToArray()); } } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get ip address. Error message: {0}", ex.Message); } try { Process proc = Process.GetCurrentProcess(); info.ProcessMemorySize = proc.PrivateMemorySize64; } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get process memory size. Error message: {0}", ex.Message); } try { info.CommandLine = Environment.CommandLine; } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get command line. Error message: {0}", ex.Message); } try { info.ProcessId = KernelNativeMethods.GetCurrentProcessId().ToString(NumberFormatInfo.InvariantInfo); } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get process id. Error message: {0}", ex.Message); } try { info.ProcessName = GetProcessName(); } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get process name. Error message: {0}", ex.Message); } try { info.ThreadId = KernelNativeMethods.GetCurrentThreadId().ToString(NumberFormatInfo.InvariantInfo); } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get thread id. Error message: {0}", ex.Message); } try { info.Architecture = Is64BitOperatingSystem() ? "x64" : "x86"; } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get CPU architecture. Error message: {0}", ex.Message); } try { info.RuntimeVersion = Environment.Version.ToString(); } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get CLR version. Error message: {0}", ex.Message); } try { info.Data.Add("AppDomainName", AppDomain.CurrentDomain.FriendlyName); } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get AppDomain friendly name. Error message: {0}", ex.Message); } try { info.ThreadName = Thread.CurrentThread.Name; } catch (Exception ex) { _log.FormattedInfo(typeof(EnvironmentInfoCollector), "Unable to get current thread name. Error message: {0}", ex.Message); } _environmentInfo = info; return(_environmentInfo); }
private ResolvedVersionInfo GetResolvedVersions(TestProject testProject, Action <XDocument> projectChanges = null, [CallerMemberName] string callingMethod = null, string identifier = null) { testProject.Name = "ResolvedVersionsTest"; testProject.TargetFrameworks = "netcoreapp3.0"; testProject.IsSdkProject = true; testProject.IsExe = true; testProject.AdditionalProperties["DisableImplicitFrameworkReferences"] = "true"; testProject.RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks); var testAsset = _testAssetsManager.CreateTestProject(testProject, callingMethod, identifier) .WithProjectChanges(project => { var ns = project.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); project.Root.Add(itemGroup); var frameworkReference = new XElement(ns + "FrameworkReference", new XAttribute("Include", "Microsoft.NETCore.APP")); itemGroup.Add(frameworkReference); var knownFrameworkReferenceUpdate = new XElement(ns + "KnownFrameworkReference", new XAttribute("Update", "Microsoft.NETCore.App"), new XAttribute("DefaultRuntimeFrameworkVersion", "3.0.0-defaultversion"), new XAttribute("LatestRuntimeFrameworkVersion", "3.0.0-latestversion"), new XAttribute("TargetingPackVersion", "3.0.0-targetingpackversion")); itemGroup.Add(knownFrameworkReferenceUpdate); var knownAppHostPackUpdate = new XElement(ns + "KnownAppHostPack", new XAttribute("Update", "Microsoft.NETCore.App"), new XAttribute("AppHostPackVersion", "3.0.0-apphostversion")); itemGroup.Add(knownAppHostPackUpdate); string writeResolvedVersionsTarget = @" <Target Name=`WriteResolvedVersions` DependsOnTargets=`PrepareForBuild;ProcessFrameworkReferences`> <ItemGroup> <LinesToWrite Include=`RuntimeFramework%09%(RuntimeFramework.Identity)%09%(RuntimeFramework.Version)`/> <LinesToWrite Include=`PackageDownload%09%(PackageDownload.Identity)%09%(PackageDownload.Version)`/> <LinesToWrite Include=`TargetingPack%09%(TargetingPack.Identity)%09%(TargetingPack.PackageVersion)`/> <LinesToWrite Include=`RuntimePack%09%(RuntimePack.Identity)%09%(RuntimePack.PackageVersion)`/> <LinesToWrite Include=`AppHostPack%09%(AppHostPack.Identity)%09%(AppHostPack.PackageVersion)`/> </ItemGroup> <WriteLinesToFile File=`$(OutputPath)resolvedversions.txt` Lines=`@(LinesToWrite)` Overwrite=`true` Encoding=`Unicode`/> </Target>"; writeResolvedVersionsTarget = writeResolvedVersionsTarget.Replace('`', '"'); project.Root.Add(XElement.Parse(writeResolvedVersionsTarget)); }); if (projectChanges != null) { testAsset = testAsset.WithProjectChanges(projectChanges); } var command = new MSBuildCommand(Log, "WriteResolvedVersions", Path.Combine(testAsset.TestRoot, testProject.Name)); command.Execute() .Should() .Pass(); var outputDirectory = command.GetOutputDirectory(testProject.TargetFrameworks, runtimeIdentifier: testProject.RuntimeIdentifier); var resolvedVersions = ResolvedVersionInfo.ParseFrom(Path.Combine(outputDirectory.FullName, "resolvedversions.txt")); return(resolvedVersions); }
/// <summary> /// Runs the application. /// </summary> /// <param name="appPaths">The app paths.</param> /// <param name="logManager">The log manager.</param> /// <param name="runService">if set to <c>true</c> [run service].</param> /// <param name="options">The options.</param> private static void RunApplication(ServerApplicationPaths appPaths, ILogManager logManager, bool runService, StartupOptions options) { var environmentInfo = new EnvironmentInfo(); var fileSystem = new ManagedFileSystem(logManager.GetLogger("FileSystem"), environmentInfo, appPaths.TempDirectory); FileSystem = fileSystem; _appHost = new WindowsAppHost(appPaths, logManager, options, fileSystem, new PowerManagement(), "emby.windows.zip", environmentInfo, new NullImageEncoder(), new Server.Startup.Common.SystemEvents(logManager.GetLogger("SystemEvents")), new RecyclableMemoryStreamProvider(), new Networking.NetworkManager(logManager.GetLogger("NetworkManager")), GenerateCertificate, () => Environment.UserDomainName); var initProgress = new Progress <double>(); if (!runService) { if (!options.ContainsOption("-nosplash")) { ShowSplashScreen(_appHost.ApplicationVersion, initProgress, logManager.GetLogger("Splash")); } // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX); } var task = _appHost.Init(initProgress); Task.WaitAll(task); if (!runService) { task = InstallVcredist2013IfNeeded(_appHost, _logger); Task.WaitAll(task); // needed by skia task = InstallVcredist2015IfNeeded(_appHost, _logger); Task.WaitAll(task); } // set image encoder here _appHost.ImageProcessor.ImageEncoder = ImageEncoderHelper.GetImageEncoder(_logger, logManager, fileSystem, options, () => _appHost.HttpClient, appPaths); task = task.ContinueWith(new Action <Task>(a => _appHost.RunStartupTasks()), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); if (runService) { StartService(logManager); } else { Task.WaitAll(task); Microsoft.Win32.SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; HideSplashScreen(); ShowTrayIcon(); task = ApplicationTaskCompletionSource.Task; Task.WaitAll(task); } }
public static JToken SampleJson(this EnvironmentInfo env) { return(ExtractJsonFromEmbeddedResource("env")); }
internal static object CalculateFrom(ValueAccessInfo valueAccessInfo, MethodDefinition methodDefinition, InvokeOutput invocationOutput, EnvironmentInfo environmentInfo, Dictionary <string, string> variablesMap) { var input = new CompileSQLOperationInput { MethodDefinition = methodDefinition, MethodParametersInJson = invocationOutput.InvocationParameters, MethodReturnValueInJson = invocationOutput.ExecutionResponseAsJson, SQL = valueAccessInfo.Text.Trim(), VariablesMap = variablesMap }; var sqlOperationOutput = CompileSQLOperation(input); if (valueAccessInfo.FetchFromDatabase == false) { if (sqlOperationOutput.SqlParameters.Count == 1) { if (input.SQL != sqlOperationOutput.SQL) { return(sqlOperationOutput.SqlParameters[0].Value); } var isNamedParameter = input.SQL == "@output" || methodDefinition.Parameters.Any(p => _.IntellisensePrefix + p.Name == input.SQL) || variablesMap.ContainsKey(input.SQL); if (isNamedParameter) { return(sqlOperationOutput.SqlParameters[0].Value); } } return(valueAccessInfo.Text); } if (string.IsNullOrWhiteSpace(valueAccessInfo.DatabaseName)) { return("Hata: DatabaseName is empty"); } var database = Databases.Boa; if (!Enum.TryParse(valueAccessInfo.DatabaseName, true, out database)) { return("Hata: DatabaseName is not recognized." + valueAccessInfo.DatabaseName); } DataTable sqlToDataTable() { var boaContext = new BOAContext(environmentInfo, Console.Write); var command = boaContext.Context.DBLayer.GetDBCommand(database, sqlOperationOutput.SQL, new SqlParameter[0], CommandType.Text); foreach (var item in sqlOperationOutput.SqlParameters) { boaContext.Context.DBLayer.AddInParameter(command, item.Name, item.SqlDbType, item.Value); } var reader = command.ExecuteReader(); var dt = new DataTable(); dt.Load(reader); reader.Close(); boaContext.Dispose(); return(dt); } var dataTable = sqlToDataTable(); if (dataTable.Columns.Count == 1) { var list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(dataTable.Columns[0].DataType)); foreach (DataRow row in dataTable.Rows) { list.Add(row[0]); } if (list.Count == 1) { return(list[0]); } return(list); } return(dataTable); }
private Dictionary <string, string> EM2_CreateConfig(string countryShortName, string outputPath, DataConfig.DataBaseRow dbr, CountryConfig.SystemRow sr, bool useTempCountry = true) { Dictionary <string, string> contentEMConfig = new Dictionary <string, string>(); string emVersion = EM_AppContext.Instance.GetProjectName(); if (emVersion.Trim() == string.Empty) { UserInfoHandler.ShowError($"{DefGeneral.BRAND_TITLE} version is not defined. Please define it via the menu 'Configuration'."); return(null); } //fill EMConfig-entry-list string dateTimePrefix = string.Format("{0:yyyyMMddHHmm}", DateTime.Now); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_ERRLOG_FILE, outputPath + dateTimePrefix + EM_XmlHandler.TAGS.EM2CONFIG_errLogFileName); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_LOG_WARNINGS, DefPar.Value.YES); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_EMVERSION, emVersion); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_UIVERSION, DefGeneral.UI_VERSION); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_PARAMPATH, useTempCountry ? EMPath.AddSlash(EMPath.Folder_Temp(EM_AppContext.FolderEuromodFiles)) : EMPath.AddSlash(Path.Combine(EMPath.Folder_Countries(EM_AppContext.FolderEuromodFiles), countryShortName))); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_CONFIGPATH, EMPath.Folder_Config(EM_AppContext.FolderEuromodFiles)); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_OUTPUTPATH, outputPath); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DATAPATH, EM_AppContext.FolderInput); string executablePath = EnvironmentInfo.GetEM2ExecutableFile(); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_EMCONTENTPATH, EM_AppContext.FolderEuromodFiles); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_HEADER_DATE, dateTimePrefix); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_OUTFILE_DATE, "-"); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_LOG_RUNTIME, DefPar.Value.NO); if (EM_AppContext.Instance.IsPublicVersion()) { contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_ISPUBLICVERSION, DefPar.Value.YES); } contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DECSIGN_PARAM, EM_Helpers.uiDecimalSeparator); string startHH = EM_XmlHandler.TAGS.EM2CONFIG_defaultHHID; string lastHH = EM_XmlHandler.TAGS.EM2CONFIG_defaultHHID; contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_STARTHH, startHH); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_LASTHH, lastHH); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_COUNTRY_FILE, CountryAdministrator.GetCountryFileName(countryShortName)); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DATACONFIG_FILE, CountryAdministrator.GetDataFileName(countryShortName)); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_DATASET_ID, dbr.ID); contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_SYSTEM_ID, sr.ID); //generate for each (available) switchable policy a POLICY_SWITCH-entry Dictionary <string, string> extIDAndPattern = new Dictionary <string, string>(); foreach (GlobLocExtensionRow e in ExtensionAndGroupManager.GetExtensions(countryShortName)) { extIDAndPattern.Add(e.ID, e.ShortName); } List <string> policySwitchEntries = new List <string>(); foreach (var e in extIDAndPattern) { string extID = e.Key, extShortName = e.Value; string policySwitchValue = string.Empty; if (dbr.GetDBSystemConfigRows().Count(x => x.SystemID == sr.ID) > 0) { policySwitchValue = ExtensionAndGroupManager.GetExtensionDefaultSwitch(dbr.GetDBSystemConfigRows().First(x => x.SystemID == sr.ID), extID); } //generate the POLICY_SWITCH-entry //taking into account that there is no need to generate it if the switch is set to n/a (i.e. the switchable policy is not switchable for this db-system-combination or does not even exist) if (policySwitchValue != string.Empty && policySwitchValue != DefPar.Value.NA) { string policySwitchEntry = //the executable needs three pieces of information to overwrite the default value of the policy switch: extShortName //which switchable policy (e.g. BTA_??) + "=" + sr.ID //which system + "=" + policySwitchValue; //and the respective value (on or off) policySwitchEntries.Add(policySwitchEntry); } } //for each (available) switchable policy add a POLICY_SWITCH-entry foreach (string policySwitchEntry in policySwitchEntries) { contentEMConfig.Add(EM_XmlHandler.TAGS.EM2CONFIG_POLICY_SWITCH + Guid.NewGuid().ToString(), policySwitchEntry); } //now actually write the EMConfigXXX.xml files and hand them over to the run-manager string configurationFileNameAndPath = EMPath.Folder_Temp(EM_AppContext.FolderEuromodFiles) + EM_XmlHandler.TAGS.EM2CONFIG_labelEMConfig + Guid.NewGuid().ToString() + ".xml"; using (XmlTextWriter configurationFileWriter = new XmlTextWriter(configurationFileNameAndPath, null)) { configurationFileWriter.Formatting = System.Xml.Formatting.Indented; configurationFileWriter.WriteStartDocument(true); configurationFileWriter.WriteStartElement(EM_XmlHandler.TAGS.EM2CONFIG_labelEMConfig); string runFormInfoText = string.Empty; foreach (string key in contentEMConfig.Keys) { if (key.StartsWith(EM_XmlHandler.TAGS.EM2CONFIG_SYSTEM_ID)) //remove Guid, see above { configurationFileWriter.WriteElementString(EM_XmlHandler.TAGS.EM2CONFIG_SYSTEM_ID, contentEMConfig[key]); } else if (key.StartsWith(EM_XmlHandler.TAGS.EM2CONFIG_POLICY_SWITCH)) //remove Guid, see above { configurationFileWriter.WriteElementString(EM_XmlHandler.TAGS.EM2CONFIG_POLICY_SWITCH, contentEMConfig[key]); } else { configurationFileWriter.WriteElementString(key, contentEMConfig[key]); } } configurationFileWriter.WriteElementString(EM_XmlHandler.TAGS.EM2CONFIG_LAST_RUN, DefPar.Value.NO); configurationFileWriter.WriteEndElement(); configurationFileWriter.WriteEndDocument(); } // EM3 returns the config-dictionary, therefore (mis)use this structure to just store the file-path as the first entry (to avoid extra variables for EM2) return(new Dictionary <string, string>() { { configurationFileNameAndPath, null } }); }
public void ReportEnvironment(EnvironmentInfo environmentInfo) { _buffer.WriteStartMetricType(typeof(EnvironmentInfo)); _buffer.WriteEnvironmentInfo(environmentInfo); }
public void ItRunsAppsDirectlyReferencingAssemblies( string referencerTarget, string dependencyTarget) { if (UsingFullFrameworkMSBuild) { // Disabled on full framework MSBuild until CI machines have VS with bundled .NET Core / .NET Standard versions // See https://github.com/dotnet/sdk/issues/1077 return; } string identifier = referencerTarget.ToString() + "_" + dependencyTarget.ToString(); TestProject dependencyProject = new TestProject() { Name = "Dependency", IsSdkProject = true, TargetFrameworks = dependencyTarget, }; // Skip running test if not running on Windows if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !dependencyProject.BuildsOnNonWindows) { return; } dependencyProject.SourceFiles["Class1.cs"] = @" public class Class1 { public static string GetMessage() { return ""Hello from a direct reference.""; } } "; var dependencyAsset = _testAssetsManager.CreateTestProject(dependencyProject, identifier: identifier); string dependencyAssemblyPath = RestoreAndBuild(dependencyAsset, dependencyProject); TestProject referencerProject = new TestProject() { Name = "Referencer", IsSdkProject = true, TargetFrameworks = referencerTarget, // Need to use a self-contained app for now because we don't use a CLI that has a "2.0" shared framework RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(referencerTarget), IsExe = true, }; referencerProject.References.Add(dependencyAssemblyPath); referencerProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(Class1.GetMessage()); } } "; var referencerAsset = _testAssetsManager.CreateTestProject(referencerProject, identifier: identifier); string applicationPath = RestoreAndBuild(referencerAsset, referencerProject); Command.Create(RepoInfo.DotNetHostPath, new[] { applicationPath }) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from a direct reference."); }
/// <inheritdoc /> public Task WriteAsync(HttpContext context, EnvironmentInfo environmentInfo, CancellationToken token = default) { return(context.Response.WriteAsync("No formatter has been registered. See App.Metrics.Formatters.Ascii for example.", token)); }
// "No build" scenario doesn't currently work: https://github.com/dotnet/sdk/issues/2956 //[InlineData(true)] public void PublishWithRuntimeIdentifier(bool publishNoBuild) { var testProject = new TestProject() { Name = "PublishWithRid", TargetFrameworks = "netcoreapp3.0", IsSdkProject = true, IsExe = true }; var compatibleRid = EnvironmentInfo.GetCompatibleRid(testProject.TargetFrameworks); var runtimeIdentifiers = new[] { "win-x64", "linux-x64", compatibleRid }; testProject.AdditionalProperties["RuntimeIdentifiers"] = string.Join(';', runtimeIdentifiers); // Use a test-specific packages folder testProject.AdditionalProperties["RestorePackagesPath"] = @"$(MSBuildProjectDirectory)\pkg"; var testAsset = _testAssetsManager.CreateTestProject(testProject, identifier: publishNoBuild ? "nobuild" : string.Empty); var buildCommand = new BuildCommand(Log, testAsset.Path, testProject.Name); buildCommand .Execute("/restore") .Should() .Pass(); foreach (var runtimeIdentifier in runtimeIdentifiers) { var publishArgs = new List <string>() { $"/p:RuntimeIdentifier={runtimeIdentifier}" }; if (publishNoBuild) { publishArgs.Add("/p:NoBuild=true"); } var publishCommand = new PublishCommand(Log, Path.Combine(testAsset.Path, testProject.Name)); publishCommand.Execute(publishArgs.ToArray()) .Should() .Pass(); if (runtimeIdentifier == compatibleRid) { var outputDirectory = publishCommand.GetOutputDirectory(testProject.TargetFrameworks, runtimeIdentifier: runtimeIdentifier); var selfContainedExecutable = $"{testProject.Name}{Constants.ExeSuffix}"; string selfContainedExecutableFullPath = Path.Combine(outputDirectory.FullName, selfContainedExecutable); Command.Create(selfContainedExecutableFullPath, new string[] { }) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World!"); } } }
protected override void DoPrepare() { EnvironmentInfo environmentInfo = GetEnvironmentInfo(); _projectInfo = GetProjectInfo <PowerShellScriptProjectInfo>(); IEnumerable <string> targetMachineNames = _projectInfo.GetTargetMachines(environmentInfo); // create a step for downloading the artifacts var downloadArtifactsDeploymentStep = new DownloadArtifactsDeploymentStep( _projectInfo, DeploymentInfo, GetTempDirPath(), _artifactsRepository); AddSubTask(downloadArtifactsDeploymentStep); // create a step for extracting the artifacts var extractArtifactsDeploymentStep = new ExtractArtifactsDeploymentStep( _projectInfo, environmentInfo, DeploymentInfo, downloadArtifactsDeploymentStep.ArtifactsFilePath, GetTempDirPath(), _fileAdapter, _directoryAdapter, _zipFileAdapter); AddSubTask(extractArtifactsDeploymentStep); if (_projectInfo.ArtifactsAreEnvironmentSpecific) { var binariesConfiguratorStep = new ConfigureBinariesStep( environmentInfo.ConfigurationTemplateName, GetTempDirPath()); AddSubTask(binariesConfiguratorStep); } if (_projectInfo.IsRemote == false) { // Run powershell script var runPowerShellScriptStep = new RunPowerShellScriptStep( _projectInfo.IsRemote, null, new Lazy <string>(() => extractArtifactsDeploymentStep.BinariesDirPath), _projectInfo.ScriptName); AddSubTask(runPowerShellScriptStep); return; } foreach (var targetMachineName in targetMachineNames) { // Create temp dir on remote machine var createRemoteTempDirStep = new CreateRemoteTempDirStep(targetMachineName); AddSubTask(createRemoteTempDirStep); // Copy files to remote machine string machineName = targetMachineName; var copyFilesDeploymentStep = new CopyFilesDeploymentStep( _directoryAdapter, srcDirPathProvider: new Lazy <string>(() => extractArtifactsDeploymentStep.BinariesDirPath), dstDirPath: new Lazy <string>(() => EnvironmentInfo.GetNetworkPath(machineName, createRemoteTempDirStep.RemoteTempDirPath))); AddSubTask(copyFilesDeploymentStep); // Run powershell script var runPowerShellScriptStep = new RunPowerShellScriptStep( _projectInfo.IsRemote, targetMachineName, new Lazy <string>(() => createRemoteTempDirStep.RemoteTempDirPath), _projectInfo.ScriptName); AddSubTask(runPowerShellScriptStep); // Delete remote temp dir var removeRemoteDirectory = new RemoveRemoteDirectoryStep( targetMachineName, new Lazy <string>(() => createRemoteTempDirStep.RemoteTempDirPath)); AddSubTask(removeRemoteDirectory); } }
public void ItRunsAppsReferencingAProjectDirectlyReferencingAssembliesWhichReferenceAssemblies( string referencerTarget, string dependencyTarget, string dllDependencyTarget) { string identifier = referencerTarget.ToString() + "_" + dependencyTarget.ToString(); TestProject dllDependencyProjectDependency = new TestProject() { Name = "DllDependencyDependency", IsSdkProject = true, TargetFrameworks = dllDependencyTarget, }; dllDependencyProjectDependency.SourceFiles["Class3.cs"] = @" public class Class3 { public static string GetMessage() { return ""Hello from a reference of an indirect reference.""; } } "; // Skip running test if not running on Windows if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !dllDependencyProjectDependency.BuildsOnNonWindows) { return; } TestProject dllDependencyProject = new TestProject() { Name = "DllDependency", IsSdkProject = true, TargetFrameworks = dllDependencyTarget, }; dllDependencyProject.ReferencedProjects.Add(dllDependencyProjectDependency); dllDependencyProject.SourceFiles["Class2.cs"] = @" public class Class2 { public static string GetMessage() { return Class3.GetMessage(); } } "; var dllDependencyAsset = _testAssetsManager.CreateTestProject(dllDependencyProject, identifier: identifier); string dllDependencyAssemblyPath = RestoreAndBuild(dllDependencyAsset, dllDependencyProject); TestProject dependencyProject = new TestProject() { Name = "Dependency", IsSdkProject = true, TargetFrameworks = dependencyTarget, }; dependencyProject.References.Add(dllDependencyAssemblyPath); dependencyProject.SourceFiles["Class1.cs"] = @" public class Class1 { public static string GetMessage() { return Class2.GetMessage(); } } "; TestProject referencerProject = new TestProject() { Name = "Referencer", IsSdkProject = true, TargetFrameworks = referencerTarget, // Need to use a self-contained app for now because we don't use a CLI that has a "2.0" shared framework RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(referencerTarget), IsExe = true, }; referencerProject.ReferencedProjects.Add(dependencyProject); referencerProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(Class1.GetMessage()); } } "; var referencerAsset = _testAssetsManager.CreateTestProject(referencerProject, identifier: identifier); string applicationPath = RestoreAndBuild(referencerAsset, referencerProject); Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { applicationPath }) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello from a reference of an indirect reference."); }
public void TestParseCommandLineArguments(string commandLine, string[] expected) { var arguments = EnvironmentInfo.ParseCommandLineArguments(commandLine); arguments.Should().BeEquivalentTo(expected); }
public void ItRunsAppsDirectlyReferencingAssembliesWithSatellites( string referencerTarget, string dependencyTarget) { string identifier = referencerTarget.ToString() + "_" + dependencyTarget.ToString(); TestProject dependencyProject = new TestProject() { Name = "Dependency", IsSdkProject = true, TargetFrameworks = dependencyTarget, }; // Skip running test if not running on Windows if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !dependencyProject.BuildsOnNonWindows) { return; } dependencyProject.SourceFiles["Class1.cs"] = @" using System; using System.Globalization; using System.Reflection; using System.Resources; using System.Threading; public class Class1 { public static string GetMessage() { CultureInfo.CurrentUICulture = new CultureInfo(""en-US""); var resources = new ResourceManager(""Dependency.Strings"", typeof(Class1).GetTypeInfo().Assembly); return resources.GetString(""HelloWorld""); } } "; dependencyProject.EmbeddedResources["Strings.en.resx"] = @"<?xml version=""1.0"" encoding=""utf-8""?> <root> <xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xsd:element name=""root"" msdata:IsDataSet=""true""> <xsd:complexType> <xsd:choice maxOccurs=""unbounded""> <xsd:element name=""data""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" /> <xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" /> </xsd:sequence> <xsd:attribute name=""name"" type=""xsd:string"" msdata:Ordinal=""1"" /> <xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" /> <xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" /> </xsd:complexType> </xsd:element> <xsd:element name=""resheader""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" /> </xsd:sequence> <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name=""resmimetype""> <value>text/microsoft-resx</value> </resheader> <resheader name=""version""> <value>1.3</value> </resheader> <resheader name=""reader""> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name=""writer""> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name=""HelloWorld"" xml:space=""preserve""> <value>Hello World from en satellite assembly for a direct reference.</value> </data> </root> "; var dependencyAsset = _testAssetsManager.CreateTestProject(dependencyProject, identifier: identifier); string dependencyAssemblyPath = RestoreAndBuild(dependencyAsset, dependencyProject); TestProject referencerProject = new TestProject() { Name = "Referencer", IsSdkProject = true, TargetFrameworks = referencerTarget, // Need to use a self-contained app for now because we don't use a CLI that has a "2.0" shared framework RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid(referencerTarget), IsExe = true, }; referencerProject.References.Add(dependencyAssemblyPath); referencerProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { Console.WriteLine(Class1.GetMessage()); } } "; var referencerAsset = _testAssetsManager.CreateTestProject(referencerProject, identifier: identifier); string applicationPath = RestoreAndBuild(referencerAsset, referencerProject); Command.Create(TestContext.Current.ToolsetUnderTest.DotNetHostPath, new[] { applicationPath }) .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World from en satellite assembly for a direct reference."); }
public void ResolvedFrameworkReferences_are_generated() { var testProject = new TestProject() { Name = "ResolvedFrameworkReferenceTest", IsSdkProject = true, IsExe = true, TargetFrameworks = "netcoreapp3.0", RuntimeIdentifier = EnvironmentInfo.GetCompatibleRid() }; testProject.FrameworkReferences.Add("Microsoft.AspNetCore.App"); testProject.FrameworkReferences.Add("Microsoft.WindowsDesktop.App"); var testAsset = _testAssetsManager.CreateTestProject(testProject) .Restore(Log, testProject.Name); var projectFolder = Path.Combine(testAsset.TestRoot, testProject.Name); var buildCommand = new BuildCommand(Log, projectFolder); var expectedMetadata = new[] { "OriginalItemSpec", "IsImplicitlyDefined", "TargetingPackName", "TargetingPackVersion", "TargetingPackPath", "RuntimePackName", "RuntimePackVersion", "RuntimePackPath" }; var getValuesCommand = new GetValuesCommand(Log, projectFolder, testProject.TargetFrameworks, "ResolvedFrameworkReference", GetValuesCommand.ValueType.Item); getValuesCommand.DependsOnTargets = "ResolveFrameworkReferences"; getValuesCommand.MetadataNames.AddRange(expectedMetadata); getValuesCommand.Execute().Should().Pass(); var resolvedFrameworkReferences = getValuesCommand.GetValuesWithMetadata(); resolvedFrameworkReferences.Select(rfr => rfr.value) .Should() .BeEquivalentTo( "Microsoft.NETCore.App", "Microsoft.AspNetCore.App", "Microsoft.WindowsDesktop.App"); foreach (var resolvedFrameworkReference in resolvedFrameworkReferences) { foreach (var expectedMetadataName in expectedMetadata) { if (expectedMetadataName == "IsImplicitlyDefined" && resolvedFrameworkReference.value != "Microsoft.NETCore.App") { continue; } resolvedFrameworkReference.metadata[expectedMetadataName] .Should() .NotBeNullOrEmpty(because: $"ResolvedFrameworkReference for {resolvedFrameworkReference.value} should have " + $"{expectedMetadataName} metadata"); } } }
//public static string FindWebConfigFilePath(string rootDirectory, string projectName) //{ // var webConfigFilePath = Path.Combine(rootDirectory, projectName, "Web.config"); // if (File.Exists(webConfigFilePath)) // { // return webConfigFilePath; // } // if (File.Exists(Path.Combine(rootDirectory, "Web.config"))) // { // return null; // } // foreach (var directory in Directory.GetDirectories(rootDirectory)) // { // var configFilePath = GetWebConfigFilePath(directory, projectName); // if (configFilePath != null) // { // return configFilePath; // } // } // return null; //} public static string GetWebConfigFilePath(string interfaceTypeAssemblyQualifiedName, string environment) { interfaceTypeAssemblyQualifiedName = ChangeVersionNumber(interfaceTypeAssemblyQualifiedName, "1.0.0.0"); var environmentInfo = EnvironmentInfo.Parse(environment); var remoteServiceConfigurationUrl = string.Empty; { if (environmentInfo.IsDev) { remoteServiceConfigurationUrl = "http://Srvcardmdlsdev1/Configuration/configuration/management/api"; environment = "Development"; } else if (environmentInfo.IsTest) { remoteServiceConfigurationUrl = "http://Srvcardtest1/Configuration/configuration/management/api"; environment = "Test"; } else if (environmentInfo.IsPrep) { remoteServiceConfigurationUrl = "http://sxlcard1/Configuration/configuration/management/api"; environment = "Preproduction"; } } var sql = $@" SELECT TOP 1 shd.DOMAIN_ID FROM CFG.SERVICE_REGISTRATION sr WITH(NOLOCK) INNER JOIN CFG.SERVICE_HOST_DEF shd WITH(NOLOCK) ON sr.SERVICE_TYPE_ID = shd.SERVICE_TYPE_ID WHERE sr.RESTFUL_CLIENT_INTERFACE = @{nameof(interfaceTypeAssemblyQualifiedName)} AND shd.ENVIRONMENT = @{nameof(environment)} "; var domainId = GetBoaCardDbConnection(environmentInfo).QuerySingleOrDefault <string>(sql, new { interfaceTypeAssemblyQualifiedName, environment }); if (string.IsNullOrWhiteSpace(domainId)) { throw new InvalidOperationException($"DomainId not found. {nameof(interfaceTypeAssemblyQualifiedName)} : {interfaceTypeAssemblyQualifiedName} | {nameof(environment)} : {environment}"); } UserVisibleTrace($"DomainId: {domainId}"); var content = $@" <?xml version='1.0' encoding='utf-8'?> <configuration> <configSections> <section name='boa.card.setup' type='BOA.Card.Core.ServiceBus.Configuration.EverestSetupConfigurationSection, BOA.Card.Core, Culture=neutral, PublicKeyToken=null'/> <section name='log4net' type='log4net.Config.Log4NetConfigurationSectionHandler, log4net'/> </configSections> <log4net> <root> <level value='DEBUG'/> <appender-ref ref='LogFileAppender'/> </root> <appender name='LogFileAppender' type='log4net.Appender.RollingFileAppender'> <param name='File' value='d:\BOA\server\bin\CardServiceLogs\ApiInspector.log'/> <lockingModel type='log4net.Appender.FileAppender+MinimalLock'/> <appendToFile value='true'/> <rollingStyle value='Composite'/> <datePattern value='.yyyy-MM-dd'/> <maxSizeRollBackups value='2'/> <maximumFileSize value='1MB'/> <staticLogFileName value='true'/> <layout type='log4net.Layout.PatternLayout'> <conversionPattern value='%date [%level] [%thread] %ndc %message%newline'/> </layout> </appender> </log4net> <boa.card.setup> <domain id='{domainId}' environment='{environment}'/> <remoteServiceConfiguration uri='{remoteServiceConfigurationUrl}'/> </boa.card.setup> <startup> <supportedRuntime version='v4.0' sku='.NETFramework,Version=v4.6.1'/> </startup> </configuration> "; var projectName = interfaceTypeAssemblyQualifiedName.Substring(0, interfaceTypeAssemblyQualifiedName.IndexOf(',')); var filePath = Path.Combine(ConfigurationDirectoryPath, "CardServiceConfigs", projectName, $"{environment}.config"); WriteToFile(filePath, content.Trim()); UserVisibleTrace($"CardServiceConfigFileExportedTo: {filePath}"); return(filePath); }
} // private void SelectDeployXML() private void btnDeployPackage_Click(object sender, EventArgs e) { try { btnDeployPackage.Enabled = false; envCnt = 0; txtErrMsg.ForeColor = Color.Black; txtErrMsg.Refresh(); sbMsg = new StringBuilder(); Catalog catalog = null; CatalogFolder catalogFolder = null; string varName = string.Empty; bool varSensitive = false; TypeCode typeCode = TypeCode.String; foreach (string env in sEnvironmentTypes) { envCnt++; sEnvironmentType = env; index = deployXML.EnvironmentServerNames.FindIndex(x => x.Name == env); sEnvironmentServerName = deployXML.EnvironmentServerNames[index].Server; deployXML.SetEnvironmentVariablesList(sEnvironmentType); txtEnvType.Text = sEnvironmentType; txtEnvType.Refresh(); switch (sEnvironmentType) { case "Test": sEnvironmentName = "Test"; break; case "Dev": sEnvironmentName = "Dev"; break; case "QA": sEnvironmentName = "QA"; break; case "UATPri": sEnvironmentName = "UAT"; break; case "UATSec": sEnvironmentName = "UAT"; break; case "PRDPri": sEnvironmentName = "PRD"; break; case "PRDSec": sEnvironmentName = "PRD"; break; default: throw new Exception("Unknown Deployment Type Specified In The Config File: " + sEnvironmentType); } // Get the connection strings for the deployment servers, replacing text #EnvironmentServerName#, for the physical server name. sqlConnPkgDeply = ConfigurationManager.ConnectionStrings["SQLConnPkgDeply"].ConnectionString.Replace("#EnvironmentServerName#", sEnvironmentServerName); sqlConnJobScript = ConfigurationManager.ConnectionStrings["SQLConnJobScript"].ConnectionString.Replace("#EnvironmentServerName#", sEnvironmentServerName); txtConnStr.Text = sqlConnPkgDeply; txtConnStr.Refresh(); if (sSQLAgentJobScript.Length > 0) { txtSQLAgentJobConnStr.Text = sqlConnJobScript; txtSQLAgentJobConnStr.Refresh(); } // Adjust the Folder Name if deploying to an SSISDB Catalog where you have multiple environments running. // Meaning you're deploying to a server where you want to maintain separate Dev/QA/UAT environments. // Append the Environment Type to the Folder Name to isolate package code for the environments. if (bMultiEnvPerCatalog == true) { sSSISFolderName = deployXML.SSISFolderName + sEnvironmentName; sSSISFolderDescription = deployXML.SSISFolderDescription + " (" + sEnvironmentName + ")"; txtSSISFolderName.Text = sSSISFolderName; txtSSISFolderName.Refresh(); txtSSISFolderDescription.Text = sSSISFolderDescription; txtSSISFolderDescription.Refresh(); } sbMsg.Append("Deployment for Environment Type: '" + sEnvironmentType + "', Server Name: " + sEnvironmentServerName + ".\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); sbMsg.Append("Multiple Environments Per SSISDB Catalog: " + (bMultiEnvPerCatalog == true ? "True" : "False") + ".\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); // Create the SSIS object: SqlConnection oConnection = new SqlConnection(sqlConnPkgDeply); IntegrationServices integrationServices = new IntegrationServices(oConnection); // Verify there is an SSIS Catalog on the deployment server: if (integrationServices.Catalogs.Count == 0) { throw new Exception("There are no SSIS Catalogs associated with connection string: " + sqlConnPkgDeply + " The default Integration Services Catalog is assumed to be " + sSSISCatalog + "."); } else { catalog = integrationServices.Catalogs[sSSISCatalog]; } // Check to see if the Project folder exists: catalogFolder = catalog.Folders[sSSISFolderName]; if (catalogFolder == null) { // Create a catalog folder and assign description. catalogFolder = new CatalogFolder(catalog, sSSISFolderName, sSSISFolderDescription); catalogFolder.Create(); sbMsg.Append("Folder:" + sSSISFolderName + " has been created in the SSIS Catalog.\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } if (deployXML.UseSSISProjectFilename == true && sSSISProjectFilename.Length > 0) { // Deploy the project packages: sbMsg.Append("Deploying " + sDeployFilePath + sSSISProjectFilename + " project ISPAC file.\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); // Think you can only deploy the entire project, not just individual dtsx files. byte[] projectFile = File.ReadAllBytes(sDeployFilePath + sSSISProjectFilename); catalogFolder.DeployProject(sSSISProjectName, projectFile); sbMsg.Append("SSIS Project (" + sSSISProjectFilename + ") has been successfully deployed!\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } // Create an Environment for the SSIS project: if (deployXML.EnvironmentVariables.Count > 0) { if (catalogFolder.Environments[sEnvironmentName] != null) { catalogFolder.Environments[sEnvironmentName].Drop(); } EnvironmentInfo environment = new EnvironmentInfo(catalogFolder, sEnvironmentName, sSSISFolderName + " Environment Variables (" + sEnvironmentName + ")"); environment.Create(); sbMsg.Append("SSIS '" + sEnvironmentType + "' Environment has been successfully created!\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); // Add variables to the environment: foreach (var projVar in deployXML.EnvironmentVariables) { varName = projVar.Name; varSensitive = projVar.Sensitive.ToLower() == "false" || projVar.Sensitive.ToLower() == "no" ? false : true; switch (projVar.Type.ToUpper()) { case "BOOLEAN": typeCode = TypeCode.Boolean; break; case "BYTE": typeCode = TypeCode.Byte; break; case "CHAR": typeCode = TypeCode.Char; break; case "DATETIME": typeCode = TypeCode.DateTime; break; case "DBNULL": typeCode = TypeCode.DBNull; break; case "DECIMAL": typeCode = TypeCode.Decimal; break; case "DOUBLE": typeCode = TypeCode.Double; break; case "EMPTY": typeCode = TypeCode.Empty; break; case "INT16": typeCode = TypeCode.Int16; break; case "INT32": typeCode = TypeCode.Int32; break; case "INT64": typeCode = TypeCode.Int64; break; case "OBJECT": typeCode = TypeCode.Object; break; case "SBYTE": typeCode = TypeCode.SByte; break; case "SINGLE": typeCode = TypeCode.Single; break; case "STRING": typeCode = TypeCode.String; break; case "UINT16": typeCode = TypeCode.UInt16; break; case "UINT32": typeCode = TypeCode.UInt32; break; case "UINT64": typeCode = TypeCode.UInt64; break; default: throw new Exception("Unknown Type Code Specified In The Environment Variable Config File Section: " + projVar.Type); } environment.Variables.Add(varName, typeCode, projVar.Value, varSensitive, projVar.Description); sbMsg.Append("Added Environment Variable: " + varName + ", Type = " + projVar.Type + ", Value = " + projVar.Value + ", Description = " + projVar.Description + ", Sensitive = " + (varSensitive == false ? "false" : "true") + "\r\n"); } environment.Alter(); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); //Add environment reference to the SSIS project: ProjectCollection SSISProjects = catalogFolder.Projects; ProjectInfo SSISProject = SSISProjects[sSSISProjectName]; if (SSISProject.References.Contains(sEnvironmentName, sSSISFolderName) == true) { SSISProject.References.Remove(sEnvironmentName, sSSISFolderName); } SSISProject.References.Add(sEnvironmentName, sSSISFolderName); SSISProject.Alter(); sbMsg.Append("Environment reference '" + sEnvironmentType + "' has been added to the SSIS Project " + sSSISFolderName + "\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); //Create Credential and Proxy. if ((deployXML.CreateCredential == true && deployXML.CredentialName != string.Empty) || (deployXML.CreateProxy == true && deployXML.SSISProxyName != string.Empty)) { if ((deployXML.SameIdentitySecretForAllEnv == true && envCnt == 1) || deployXML.SameIdentitySecretForAllEnv == false) { using (var credProxy = new CredProxy(sEnvironmentType, deployXML.CredentialName, deployXML.SSISProxyName, deployXML.CreateCredential)) { credProxy.ShowDialog(); sIdentity = credProxy.Identity; sSecret = credProxy.Secret; } } // Run script to create the credential. if (deployXML.CreateCredential == true) { sErrorMsg = string.Empty; SqlParameter[] objParameter = new SqlParameter[4]; objParameter[0] = new SqlParameter("@sCredName", SqlDbType.NVarChar, 128) { Value = deployXML.CredentialName }; objParameter[1] = new SqlParameter("@sIdentity", SqlDbType.NVarChar, 128) { Value = sIdentity }; objParameter[2] = new SqlParameter("@sSecret", SqlDbType.NVarChar, 128) { Value = sSecret }; objParameter[3] = new SqlParameter("@sErrorMsg", SqlDbType.NVarChar, 1000) { Value = sErrorMsg, Direction = ParameterDirection.Output }; ExecuteNonQueryAsText(SQLScripts.ADHOCCreateCredential, objParameter, sqlConnPkgDeply); // Uses Initial Catalog of master. sErrorMsg = objParameter[3].Value.ToString().Trim(); // This gets the value output for sErrorMsg. sbMsg.Append("Script used to create the SQL job CREDENTIAL was run.\r\n"); if (sErrorMsg.Length > 0) { sbMsg.Append("Error running script used to create the job run CREDENTIAL:\r\n" + sErrorMsg + "\r\n"); } txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } // Run script to create the proxy. if (deployXML.CreateProxy == true) { sErrorMsg = string.Empty; SqlParameter[] objParameter = new SqlParameter[4]; objParameter[0] = new SqlParameter("@sCredName", SqlDbType.NVarChar, 128) { Value = deployXML.CredentialName }; objParameter[1] = new SqlParameter("@sProxyName", SqlDbType.NVarChar, 128) { Value = deployXML.SSISProxyName }; objParameter[2] = new SqlParameter("@sIdentity", SqlDbType.NVarChar, 128) { Value = sIdentity }; objParameter[3] = new SqlParameter("@sErrorMsg", SqlDbType.NVarChar, 1000) { Value = sErrorMsg, Direction = ParameterDirection.Output }; ExecuteNonQueryAsText(SQLScripts.ADHOCCreateProxy, objParameter, sqlConnJobScript); // Uses Initial Catalog of msdb. sErrorMsg = objParameter[3].Value.ToString().Trim(); // This gets the value output for sErrorMsg. sbMsg.Append("Script used to create the SQL job PROXY was run.\r\n"); if (sErrorMsg.Length > 0) { sbMsg.Append("Error running script used to create the job run PROXY:\r\n" + sErrorMsg + "\r\n"); } txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } } // Run script to map project parameters to environment variables. if (bMapProjParamsToEnvVar == true) { SqlParameter[] objParameter = new SqlParameter[3]; objParameter[0] = new SqlParameter("@sEnvironmentType", SqlDbType.NVarChar, 50) { Value = sEnvironmentName }; objParameter[1] = new SqlParameter("@sSSISFolderName", SqlDbType.NVarChar, 128) { Value = sSSISFolderName }; objParameter[2] = new SqlParameter("@sSSISProjectName", SqlDbType.NVarChar, 128) { Value = sSSISProjectName }; ExecuteNonQueryAsText(SQLScripts.ADHOCMapProjParamsToEnvVar, objParameter, sqlConnPkgDeply); sbMsg.Append("Script used to map Project Parameters to Environment Variables was run.\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } } // if (htEnvironmentVariables.Count > 0) foreach (string jobScriptFile in sSQLAgentJobScriptList) { sbSQLAgentJobScriptText = new StringBuilder(); sbSQLAgentJobScriptText.Append(System.IO.File.ReadAllText(sDeployFilePath + jobScriptFile)); SqlParameter[] objParameter = new SqlParameter[6]; objParameter[0] = new SqlParameter("@sEnvironmentType", SqlDbType.NVarChar, 50) { Value = sEnvironmentName }; objParameter[1] = new SqlParameter("@bMultiEnvPerCatalog", SqlDbType.Bit) { Value = bMultiEnvPerCatalog }; objParameter[2] = new SqlParameter("@sSSISFolderName", SqlDbType.NVarChar, 128) { Value = sSSISFolderName }; objParameter[3] = new SqlParameter("@sSSISProjectName", SqlDbType.NVarChar, 128) { Value = sSSISProjectName }; objParameter[4] = new SqlParameter("@sSSISProxyName", SqlDbType.NVarChar, 128) { Value = sSSISProxyName }; objParameter[5] = new SqlParameter("@sSSISCatServerName", SqlDbType.NVarChar, 128) { Value = sEnvironmentServerName }; ExecuteNonQueryAsText(sbSQLAgentJobScriptText.ToString(), objParameter, sqlConnJobScript); sbMsg.Append("SQL Agent Job Script File " + sDeployFilePath + jobScriptFile + " was run.\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } // foreach (string jobScriptFile in sSQLAgentJobScriptList) sbMsg.Append("\r\n"); txtErrMsg.Text = sbMsg.ToString(); txtErrMsg.Refresh(); } // foreach (string env in sEnvironmentTypes) btnExit.BackColor = Color.Green; btnExit.Focus(); } catch (Exception ex) { txtErrMsg.Text = sbMsg.ToString() + "\r\n" + ex.Message + (ex.InnerException != null ? "\r\n\r\nInner Exception: " + ex.InnerException.Message : "") + "\r\n"; txtErrMsg.ForeColor = Color.Red; txtErrMsg.Refresh(); } finally { // Create or append run results to the log file. CopyToLogFile(txtErrMsg.Text); } } // private void btnDeployPackage_Click(object sender, EventArgs e)
void Conflicts_are_resolved_when_publishing(bool selfContained, bool ridSpecific, [CallerMemberName] string callingMethod = "") { if (selfContained && !ridSpecific) { throw new ArgumentException("Self-contained apps must be rid specific"); } var targetFramework = "netcoreapp2.0"; if (!EnvironmentInfo.SupportsTargetFramework(targetFramework)) { return; } var rid = ridSpecific ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null; TestProject testProject = new TestProject() { Name = selfContained ? "SelfContainedWithConflicts" : (ridSpecific ? "RidSpecificSharedConflicts" : "PortableWithConflicts"), TargetFrameworks = targetFramework, RuntimeIdentifier = rid, IsExe = true, }; string outputMessage = $"Hello from {testProject.Name}!"; testProject.AdditionalProperties["CopyLocalLockFileAssemblies"] = "true"; testProject.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { TestConflictResolution(); Console.WriteLine(""" + outputMessage + @"""); } " + ConflictResolutionAssets.ConflictResolutionTestMethod + @" } "; var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, testProject.Name) .WithProjectChanges(p => { var ns = p.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); p.Root.Add(itemGroup); foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies) { itemGroup.Add(new XElement(ns + "PackageReference", new XAttribute("Include", dependency.Item1), new XAttribute("Version", dependency.Item2))); } if (!selfContained && ridSpecific) { var propertyGroup = new XElement(ns + "PropertyGroup"); p.Root.Add(propertyGroup); propertyGroup.Add(new XElement(ns + "SelfContained", "false")); } }); var publishCommand = new PublishCommand(testProjectInstance); var publishResult = publishCommand.Execute(); publishResult.Should().Pass(); var publishDirectory = publishCommand.GetOutputDirectory( targetFramework: targetFramework, runtimeIdentifier: rid ?? string.Empty); var outputDirectory = publishDirectory.Parent; DependencyContext dependencyContext; using (var depsJsonFileStream = File.OpenRead(Path.Combine(publishDirectory.FullName, $"{testProject.Name}.deps.json"))) { dependencyContext = new DependencyContextJsonReader().Read(depsJsonFileStream); } dependencyContext.Should() .HaveNoDuplicateRuntimeAssemblies(rid ?? "") .And .HaveNoDuplicateNativeAssets(rid ?? "") .And .OnlyHavePackagesWithPathProperties(); TestCommand runCommand; if (selfContained) { var selfContainedExecutable = testProject.Name + Constants.ExeSuffix; string selfContainedExecutableFullPath = Path.Combine(publishDirectory.FullName, selfContainedExecutable); var libPrefix = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "" : "lib"; var filesPublished = new[] { selfContainedExecutable, $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json", $"{libPrefix}coreclr{FileConstants.DynamicLibSuffix}", $"{libPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{libPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", $"mscorlib.dll", $"System.Private.CoreLib.dll", }; outputDirectory.Should().HaveFiles(filesPublished); publishDirectory.Should().HaveFiles(filesPublished); dependencyContext.Should() .OnlyHaveRuntimeAssembliesWhichAreInFolder(rid, publishDirectory.FullName) .And .OnlyHaveNativeAssembliesWhichAreInFolder(rid, publishDirectory.FullName, testProject.Name); runCommand = new RunExeCommand(Log, selfContainedExecutableFullPath); } else { var filesPublished = new[] { $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json" }; outputDirectory.Should().HaveFiles(filesPublished); publishDirectory.Should().HaveFiles(filesPublished); dependencyContext.Should() .OnlyHaveRuntimeAssemblies(rid ?? "", testProject.Name); runCommand = new DotnetCommand(Log, Path.Combine(publishDirectory.FullName, $"{testProject.Name}.dll")); } runCommand .Execute() .Should() .Pass() .And .HaveStdOutContaining(outputMessage); }
public void RunAppFromOutputFolder(string testName, bool useRid, bool includeConflicts) { if (UsingFullFrameworkMSBuild) { // Disabled on full framework MSBuild until CI machines have VS with bundled .NET Core / .NET Standard versions // See https://github.com/dotnet/sdk/issues/1077 return; } var targetFramework = "netcoreapp2.0"; var runtimeIdentifier = useRid ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null; TestProject project = new TestProject() { Name = testName, IsSdkProject = true, TargetFrameworks = targetFramework, RuntimeIdentifier = runtimeIdentifier, IsExe = true, }; string outputMessage = $"Hello from {project.Name}!"; project.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { TestConflictResolution(); Console.WriteLine(""" + outputMessage + @"""); } " + ConflictResolutionAssets.ConflictResolutionTestMethod + @" } "; var testAsset = _testAssetsManager.CreateTestProject(project, project.Name) .WithProjectChanges(p => { if (includeConflicts) { var ns = p.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); p.Root.Add(itemGroup); foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies) { itemGroup.Add(new XElement(ns + "PackageReference", new XAttribute("Include", dependency.Item1), new XAttribute("Version", dependency.Item2))); } } }) .Restore(project.Name); string projectFolder = Path.Combine(testAsset.Path, project.Name); var buildCommand = new BuildCommand(Stage0MSBuild, projectFolder); buildCommand .Execute() .Should() .Pass(); string outputFolder = buildCommand.GetOutputDirectory(project.TargetFrameworks, runtimeIdentifier: runtimeIdentifier ?? "").FullName; Command.Create(RepoInfo.DotNetHostPath, new[] { Path.Combine(outputFolder, project.Name + ".dll") }) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining(outputMessage); }
public void It_publishes_with_a_publish_profile(bool?selfContained, bool?useAppHost) { var tfm = "netcoreapp2.2"; var rid = EnvironmentInfo.GetCompatibleRid(tfm); var testProject = new TestProject() { Name = "ConsoleWithPublishProfile", TargetFrameworks = tfm, ProjectSdk = "Microsoft.NET.Sdk;Microsoft.NET.Sdk.Publish", IsExe = true, }; var identifer = (selfContained == null ? "null" : selfContained.ToString()) + (useAppHost == null ? "null" : useAppHost.ToString()); var testProjectInstance = _testAssetsManager.CreateTestProject(testProject, identifier: identifer); var projectDirectory = Path.Combine(testProjectInstance.Path, testProject.Name); var publishProfilesDirectory = Path.Combine(projectDirectory, "Properties", "PublishProfiles"); Directory.CreateDirectory(publishProfilesDirectory); File.WriteAllText(Path.Combine(publishProfilesDirectory, "test.pubxml"), $@" <Project> <PropertyGroup> <RuntimeIdentifier>{rid}</RuntimeIdentifier> {(selfContained.HasValue ? $"<SelfContained>{selfContained}</SelfContained>" : "")} {((!(selfContained ?? true) && useAppHost.HasValue) ? $"<UseAppHost>{useAppHost}</UseAppHost>" : "")} </PropertyGroup> </Project> "); var command = new PublishCommand(testProjectInstance); command .Execute("/p:PublishProfile=test") .Should() .Pass(); var output = command.GetOutputDirectory(targetFramework: tfm, runtimeIdentifier: rid); output.Should().HaveFiles(new[] { $"{testProject.Name}.dll", $"{testProject.Name}.pdb", $"{testProject.Name}.deps.json", $"{testProject.Name}.runtimeconfig.json", }); if (selfContained ?? true) { output.Should().HaveFiles(new[] { $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }); } else { output.Should().NotHaveFiles(new[] { $"{FileConstants.DynamicLibPrefix}hostfxr{FileConstants.DynamicLibSuffix}", $"{FileConstants.DynamicLibPrefix}hostpolicy{FileConstants.DynamicLibSuffix}", }); } if ((selfContained ?? true) || (useAppHost ?? true)) { output.Should().HaveFile($"{testProject.Name}{Constants.ExeSuffix}"); } else { output.Should().NotHaveFile($"{testProject.Name}{Constants.ExeSuffix}"); } }
private void RunAppFromOutputFolder(string testName, bool useRid, bool includeConflicts, string targetFramework = "netcoreapp2.0") { var runtimeIdentifier = useRid ? EnvironmentInfo.GetCompatibleRid(targetFramework) : null; TestProject project = new TestProject() { Name = testName, TargetFrameworks = targetFramework, RuntimeIdentifier = runtimeIdentifier, IsExe = true, }; string outputMessage = $"Hello from {project.Name}!"; project.SourceFiles["Program.cs"] = @" using System; public static class Program { public static void Main() { TestConflictResolution(); Console.WriteLine(""" + outputMessage + @"""); } " + ConflictResolutionAssets.ConflictResolutionTestMethod + @" } "; var testAsset = _testAssetsManager.CreateTestProject(project, project.Name) .WithProjectChanges(p => { if (includeConflicts) { var ns = p.Root.Name.Namespace; var itemGroup = new XElement(ns + "ItemGroup"); p.Root.Add(itemGroup); foreach (var dependency in ConflictResolutionAssets.ConflictResolutionDependencies) { itemGroup.Add(new XElement(ns + "PackageReference", new XAttribute("Include", dependency.Item1), new XAttribute("Version", dependency.Item2))); } } }); var buildCommand = new BuildCommand(testAsset); buildCommand .Execute() .Should() .Pass(); string outputFolder = buildCommand.GetOutputDirectory(project.TargetFrameworks, runtimeIdentifier: runtimeIdentifier ?? "").FullName; new DotnetCommand(Log, Path.Combine(outputFolder, project.Name + ".dll")) .Execute() .Should() .Pass() .And .HaveStdOutContaining(outputMessage); }
static int DoInstall(string game, string filename, string installationPath, string profilePath, string gamePath, List<string> additionalSearchPaths, string seVersion, ref string errorString) { if (game == null) { errorString = "no game specified"; return 1; } if (filename == null) { errorString = "no file specified"; return 1; } if (profilePath == null) { errorString = "no profile path specified"; return 1; } if (gamePath == null) { errorString = "no game path specified"; return 1; } try { EnvironmentInfo environmentInfo = new EnvironmentInfo(Properties.Settings.Default); string exeLocation = Assembly.GetExecutingAssembly().Location; string exePath = System.IO.Path.GetDirectoryName(exeLocation); string[] gameModes = Directory.GetFiles(Path.Combine(exePath, "GameModes"), String.Format("{0}.dll", game)); if (gameModes.Count() == 0) { errorString = "unknown game"; return 1; } Assembly gameAssembly = Assembly.LoadFrom(gameModes[0]); IGameModeFactory gameModeFactory = null; Type[] exportedTypes = gameAssembly.GetExportedTypes(); foreach (Type type in exportedTypes) { if (typeof(IGameModeFactory).IsAssignableFrom(type) && !type.IsAbstract) { ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EnvironmentInfo) }); gameModeFactory = (IGameModeFactory)constructor.Invoke(new Object[] { environmentInfo }); } } if (gameModeFactory == null) { errorString = "invalid game"; return 1; } string str7zPath = Path.Combine(environmentInfo.ProgrammeInfoDirectory, environmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll"); SevenZipCompressor.SetLibraryPath(str7zPath); FileUtil fileUtil = new NexusFileUtil(environmentInfo); environmentInfo.Settings.InstallationPaths[gameModeFactory.GameModeDescriptor.ModeId] = installationPath; environmentInfo.Settings.ModFolder[gameModeFactory.GameModeDescriptor.ModeId] = installationPath; // environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = environmentInfo.TemporaryPath; environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = Path.Combine(installationPath, "temp"); if (environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] == null) environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] = new KeyedSettings<string>(); if (environmentInfo.Settings.DelayedSettings["ALL"] == null) environmentInfo.Settings.DelayedSettings["ALL"] = new KeyedSettings<string>(); ViewMessage warning = null; IGameMode gameMode = gameModeFactory.BuildGameMode(fileUtil, out warning); IModCacheManager cacheManager = new NexusModCacheManager(environmentInfo.TemporaryPath, gameMode.GameModeEnvironmentInfo.ModDirectory, fileUtil); IScriptTypeRegistry scriptTypeRegistry = ScriptTypeRegistry.DiscoverScriptTypes(Path.Combine(Path.GetDirectoryName(exeLocation), "ScriptTypes"), gameMode, new List<string>()); if (scriptTypeRegistry.Types.Count == 0) { errorString = "No script types were found."; return 2; } // use a proxy so we can intercept accesses to the IGameMode interface. This allows us to make the additional search paths accessible from // the sandbox and feed in the script extender version even though the nmm lib won't find it. // This has to happen after DiscoverScriptTypes becaus that function tries to localize the assembly which fails for the dynamic assembly // of the proxy. Fortunately DiscoverScriptTypes has no side-effects on the gameMode. // This recreates the gamemode object so it's important no code above modifies gameMode ProxyGenerator generator = new ProxyGenerator(); GameModeInterceptor interceptor = new GameModeInterceptor(additionalSearchPaths, seVersion != null ? new Version(seVersion) : null); gameMode = (IGameMode)generator.CreateClassProxy(gameMode.GetType(), new object[] { environmentInfo, fileUtil }, new IInterceptor[] { interceptor }); IModFormatRegistry formatRegistry = ModFormatRegistry.DiscoverFormats(cacheManager, gameMode.SupportedFormats, scriptTypeRegistry, Path.Combine(Path.GetDirectoryName(exeLocation), "ModFormats")); if (formatRegistry.Formats.Count == 0) { errorString = "No formats were found."; return 2; } // we install the mod from the temporary path. Unfortunately this requires the archive to be copied, otherwise the sandbox will // prevent the installer script from accessing the archive in its original location string fileNameTemporary = Path.Combine(environmentInfo.TemporaryPath, Path.GetFileName(filename)); File.Copy(filename, fileNameTemporary); IMod mod = CreateMod(fileNameTemporary, formatRegistry, gameMode); if (mod == null) { errorString = "failed to initialize mod"; return 3; } System.IO.File.WriteAllText(installationPath + "/__installInfo.txt", mod.ModName + "\n" + mod.HumanReadableVersion + "\n" + mod.Id); if (mod.HasInstallScript) { DummyDataFileUtilFactory dummyFactory = null; IDataFileUtil dataFileUtility; Logger.Info("Detected C# script that relies on files in the actual data folder"); string modlistFile = Path.Combine(profilePath, "modlist.txt"); // ASSUMED mods path is the parent directory of the gameMode.InstallationPath string modsPath = Directory.GetParent(gameMode.InstallationPath).FullName; // Prepare dummy data directory dummyFactory = new DummyDataFileUtilFactory(gameMode.GameModeEnvironmentInfo.InstallationPath, modlistFile, modsPath, gamePath, additionalSearchPaths); dataFileUtility = dummyFactory.CreateDummyDataFileUtil(); TxFileManager fileManager = new TxFileManager(); IInstallLog installLog = new DummyInstallLog(); IIniInstaller iniIniInstaller = new IniInstaller(mod, installLog, fileManager, delegate { return OverwriteResult.No; }); IPluginManager pluginManager = new DummyPluginManager(Path.Combine(profilePath, "plugins.txt"), gameMode, mod); IGameSpecificValueInstaller gameSpecificValueInstaller = gameMode.GetGameSpecificValueInstaller(mod, installLog, fileManager, new NexusFileUtil(environmentInfo), delegate { return OverwriteResult.No; }); IModFileInstaller fileInstaller = new ModFileInstaller(gameMode.GameModeEnvironmentInfo, mod, installLog, pluginManager, dataFileUtility, fileManager, delegate { return OverwriteResult.No; }, false); InstallerGroup installers = new InstallerGroup(dataFileUtility, fileInstaller, iniIniInstaller, gameSpecificValueInstaller, pluginManager); IVirtualModActivator modActivator = new DummyVirtualModActivator(gameMode, environmentInfo); IScriptExecutor executor = mod.InstallScript.Type.CreateExecutor(mod, gameMode, environmentInfo, modActivator, installers, SynchronizationContext.Current); // read-only transactions are waaaay faster, especially for solid archives) because the extractor isn't recreated for every extraction (why exactly would it be otherwise?) mod.BeginReadOnlyTransaction(fileUtil); // run the script in a second thread and start the main loop in the main thread to ensure we can handle message boxes and the like ScriptRunner runner = new ScriptRunner(executor, mod.InstallScript); runner.Execute(); runner.TaskEnded += delegate { iniIniInstaller.FinalizeInstall(); gameSpecificValueInstaller.FinalizeInstall(); mod.EndReadOnlyTransaction(); Application.Exit(); }; Application.Run(); switch (runner.Status) { case BackgroundTasks.TaskStatus.Cancelled: return 11; case BackgroundTasks.TaskStatus.Error: return 6; case BackgroundTasks.TaskStatus.Incomplete: return 10; default: return 0; } } else { errorString = "no install script"; return 4; } } catch (Exception e) { Console.WriteLine("exception: " + e.Message); MessageBox.Show(e.Message, "Installation failed", MessageBoxButtons.OK, MessageBoxIcon.Error); return 5; } }
ScenarioExecuteResponseInfo ExecuteSelectedScenario() { var returnValue = new ScenarioExecuteResponseInfo(); var invocationInfo = InvocationInfo; var environmentInfo = EnvironmentInfo.Parse(invocationInfo.Environment); if (IsEndOfDayMethod(invocationInfo)) { returnValue.InvokeOutput = Invoker.Invoke(environmentInfo, scope.Get(Trace), invocationInfo, null); return(returnValue); } var scenario = scope.Get(SelectedScenario); scope.ClearScenarioExecuteResponse(scenario); scope.Update(VariablesMap, new Dictionary <string, string>()); returnValue.Scenario = scenario; void processAssignmentsBeforeInvoke(AssertionInfo assertionInfo) { var methodDefinition = scope.Get(SelectedMethodDefinition); var env = EnvironmentInfo.Parse(invocationInfo.Environment); var actual = AssertionValueCalculator.CalculateFrom(assertionInfo.Actual, methodDefinition, new InvokeOutput() { InvocationParameters = scenario.MethodParameters.Select(x => x.Value).ToList() }, env, scope.Get(VariablesMap)); var targetPath = assertionInfo.Expected.Text.Trim(); if (IsAssignToVariableOperator(assertionInfo.OperatorName)) { scope.Get(Trace)($"{targetPath} value updated with {actual}"); scope.Get(VariablesMap).AddOrUpdate(targetPath, actual + Empty); } else { if (targetPath.Contains(".")) { foreach (var parameterDefinition in methodDefinition.Parameters) { var prefix = $"{IntellisensePrefix}{parameterDefinition.Name}."; if (targetPath.StartsWith(prefix)) { var instance = DeserializeForMethodParameter(scenario.MethodParameters[parameterDefinition.Index].Value, parameterDefinition.ParameterType.GetDotNetType()); ReflectionUtil.SaveValueToPropertyPath(actual, instance, targetPath.RemoveFromStart(prefix)); scenario.MethodParameters[parameterDefinition.Index] = new InvocationMethodParameterInfo { Value = SerializeForMethodParameter(instance) }; } } } else { foreach (var parameterDefinition in methodDefinition.Parameters) { if (targetPath == IntellisensePrefix + parameterDefinition.Name) { scenario.MethodParameters[parameterDefinition.Index] = new InvocationMethodParameterInfo { Value = SerializeForMethodParameter(actual) }; } } } } returnValue.AssertionExecuteResponses.Add(new AssertionExecuteResponseInfo(assertionInfo)); } foreach (var assertionInfo in scenario.Assertions.Where(IsAssertionInfoShouldProcessBeforeExecutionStart)) { processAssignmentsBeforeInvoke(assertionInfo); } var invokeOutput = returnValue.InvokeOutput = Invoker.Invoke(environmentInfo, scope.Get(Trace), invocationInfo, scenario.MethodParameters); if (!IsSuccess(invokeOutput)) { return(returnValue); } void runAssertions() { var methodDefinition = scope.Get(SelectedMethodDefinition); string runAssertion(AssertionInfo assertionInfo) { var env = EnvironmentInfo.Parse(invocationInfo.Environment); var actual = AssertionValueCalculator.CalculateFrom(assertionInfo.Actual, methodDefinition, invokeOutput, env, scope.Get(VariablesMap)); var expected = AssertionValueCalculator.CalculateFrom(assertionInfo.Expected, methodDefinition, invokeOutput, env, scope.Get(VariablesMap)); var errorMessage = AssertionValueCalculator.RunAssertion(actual, expected, assertionInfo.OperatorName); returnValue.AssertionExecuteResponses.Add(new AssertionExecuteResponseInfo(assertionInfo) { ErrorMessage = errorMessage }); return(errorMessage); } foreach (var assertion in scenario.Assertions.Where(x => !IsAssertionInfoShouldProcessBeforeExecutionStart(x))) { var assertionErrorMessage = runAssertion(assertion); if (assertionErrorMessage != null) { return; } } } runAssertions(); return(returnValue); }
/// <summary> /// Формирует полную инсталляцию для текущего сервера /// </summary> /// <param name="context"></param> /// <returns></returns> public static IJob[] CreateServerInstallation(IBSharpContext context, string logicalServerName = null, string basedir = null) { if (string.IsNullOrWhiteSpace(logicalServerName)) { logicalServerName = Environment.MachineName; } var serverDefinition = FindMatchedServerDefinition(context, logicalServerName); var baseConfig = InitializeBaseConfig(serverDefinition, context, logicalServerName); var root = string.IsNullOrWhiteSpace(basedir) ? EnvironmentInfo.GetRepositoryRoot() : EnvironmentInfo.ResolvePath(basedir); baseConfig["root"] = root; baseConfig["resolveoverrides"] = new Dictionary <string, string> { { "repos", root }, { "bin", Path.Combine(root, ".build/bin/all") }, { "abin", Path.Combine(root, ".build/bin/all") } }; var dbdefs = CollectDbDefinitions(serverDefinition, context, logicalServerName).ToArray(); var jobs = dbdefs.Select(_ => CreateDatabaseInstallation(_, baseConfig)).ToArray(); return(jobs); }
private static void ShouldReturn(EnvironmentsStorage storage, string name, EnvironmentInfo info) { Action assertion = () => { ShouldReturnImmediately(storage, name, info); }; assertion.ShouldPassIn(DefaultTimeout); }
public void ReportEnvironment(EnvironmentInfo environmentInfo) { WriteLine(environmentInfo.Hummanize()); }
private static void ShouldReturnImmediately(EnvironmentsStorage storage, string name, EnvironmentInfo info) { storage.Get(name).Should().BeEquivalentTo(info); }
/// <summary> /// Searches for game mode factories in the specified path, and loads /// any factories that are found into a registry. /// </summary> /// <returns>A registry containing all of the discovered game mode factories.</returns> public static GameModeRegistry DiscoverSupportedGameModes(EnvironmentInfo environmentInfo) { Trace.TraceInformation("Discovering Game Mode Factories..."); Trace.Indent(); var appDirectory = Path.GetDirectoryName(Application.ExecutablePath); var gameModesPath = Path.Combine(appDirectory ?? string.Empty, "GameModes"); if (!Directory.Exists(gameModesPath)) { Directory.CreateDirectory(gameModesPath); } Trace.TraceInformation("Looking in: {0}", gameModesPath); var assemblies = Directory.GetFiles(gameModesPath, "*.dll"); //If there are no assemblies detected then an exception must be thrown //to prevent a divide by zero exception further along if (!assemblies.Any()) { #if DEBUG throw new GameModeRegistryException(gameModesPath, "Compile the Game Modes directory in the solution."); #else throw new GameModeRegistryException(gameModesPath); #endif } var registry = new GameModeRegistry(); foreach (var assembly in assemblies) { Trace.TraceInformation("Checking: {0}", Path.GetFileName(assembly)); Trace.Indent(); var gameMode = Assembly.LoadFrom(assembly); try { var types = gameMode.GetExportedTypes(); foreach (var type in types) { if (!typeof(IGameModeFactory).IsAssignableFrom(type) || type.IsAbstract) { continue; } Trace.TraceInformation("Initializing: {0}", type.FullName); Trace.Indent(); var constructor = type.GetConstructor(new[] { typeof(IEnvironmentInfo) }); if (constructor == null) { Trace.TraceInformation("No constructor accepting one argument of type IEnvironmentInfo found."); Trace.Unindent(); continue; } var gmfGameModeFactory = (IGameModeFactory)constructor.Invoke(new object[] { environmentInfo }); registry.RegisterGameMode(gmfGameModeFactory); Trace.Unindent(); } } catch (FileNotFoundException e) { Trace.TraceError($"Cannot load {assembly}: cannot find dependency {e.FileName}"); // some dependencies were missing, so we couldn't load the assembly // given that these are plugins we don't have control over the dependencies: // we may not even know what they (we can get their name, but if it's a custom // dll not part of the client code base, we can't provide it even if we wanted to) // there's nothing we can do, so simply skip the assembly } Trace.Unindent(); } Trace.Unindent(); return(registry); }