/// <inheritdoc /> public bool Start() { // Sets up the configMgr // If a config file path was passed, use it literally. // This ensures it's working-directory relative // (for people passing config file through the terminal or something). // Otherwise use the one next to the executable. if (_commandLineArgs?.ConfigFile != null) { _config.LoadFromFile(_commandLineArgs.ConfigFile); } else { var path = PathHelpers.ExecutableRelativeFile("server_config.toml"); if (File.Exists(path)) { _config.LoadFromFile(path); } else { _config.SetSaveFile(path); } } //Sets up Logging _config.RegisterCVar("log.path", "logs", CVar.ARCHIVE); _config.RegisterCVar("log.format", "log_%(date)s-%(time)s.txt", CVar.ARCHIVE); _config.RegisterCVar("log.level", LogLevel.Info, CVar.ARCHIVE); var logPath = _config.GetCVar <string>("log.path"); var logFormat = _config.GetCVar <string>("log.format"); var logFilename = logFormat.Replace("%(date)s", DateTime.Now.ToString("yyyyMMdd")).Replace("%(time)s", DateTime.Now.ToString("hhmmss")); var fullPath = Path.Combine(logPath, logFilename); if (!Path.IsPathRooted(fullPath)) { logPath = PathHelpers.ExecutableRelativeFile(fullPath); } fileLogHandler = new FileLogHandler(logPath); _log.RootSawmill.Level = _config.GetCVar <LogLevel>("log.level"); _log.RootSawmill.AddHandler(fileLogHandler); // Has to be done early because this guy's in charge of the main thread Synchronization Context. _taskManager.Initialize(); LoadSettings(); var netMan = IoCManager.Resolve <IServerNetManager>(); try { netMan.Initialize(true); netMan.StartServer(); } catch (Exception e) { var port = netMan.Port; Logger.Fatal("Unable to setup networking manager. Check port {0} is not already in use and that all binding addresses are correct!\n{1}", port, e); return(true); } var dataDir = _commandLineArgs?.DataDir ?? PathHelpers.ExecutableRelativeFile("data"); // Set up the VFS _resources.Initialize(dataDir); #if FULL_RELEASE _resources.MountContentDirectory(@"./Resources/"); #else // Load from the resources dir in the repo root instead. // It's a debug build so this is fine. _resources.MountContentDirectory($@"{ContentRootDir}RobustToolbox/Resources/"); _resources.MountContentDirectory($@"{ContentRootDir}bin/Content.Server/", new ResourcePath("/Assemblies/")); _resources.MountContentDirectory($@"{ContentRootDir}Resources/"); #endif // Default to en-US. // Perhaps in the future we could make a command line arg or something to change this default. _localizationManager.LoadCulture(new CultureInfo("en-US")); //mount the engine content pack // _resources.MountContentPack(@"EngineContentPack.zip"); //mount the default game ContentPack defined in config // _resources.MountDefaultContentPack(); //identical code in game controller for client if (!_modLoader.TryLoadAssembly <GameShared>(_resources, $"Content.Shared")) { Logger.FatalS("eng", "Could not load any Shared DLL."); return(true); } if (!_modLoader.TryLoadAssembly <GameServer>(_resources, $"Content.Server")) { Logger.FatalS("eng", "Could not load any Server DLL."); return(true); } // HAS to happen after content gets loaded. // Else the content types won't be included. // TODO: solve this properly. _serializer.Initialize(); // Initialize Tier 2 services _stateManager.Initialize(); _entities.Initialize(); IoCManager.Resolve <IPlayerManager>().Initialize(MaxPlayers); _mapManager.Initialize(); IoCManager.Resolve <IPlacementManager>().Initialize(); IoCManager.Resolve <IViewVariablesHost>().Initialize(); // Call Init in game assemblies. _modLoader.BroadcastRunLevel(ModRunLevel.Init); // because of 'reasons' this has to be called after the last assembly is loaded // otherwise the prototypes will be cleared var prototypeManager = IoCManager.Resolve <IPrototypeManager>(); prototypeManager.LoadDirectory(new ResourcePath(@"/Prototypes")); prototypeManager.Resync(); IoCManager.Resolve <IConsoleShell>().Initialize(); IoCManager.Resolve <IConGroupController>().Initialize(); _entities.Startup(); _modLoader.BroadcastRunLevel(ModRunLevel.PostInit); IoCManager.Resolve <IStatusHost>().Start(); return(false); }
public void PathHelpers_RelativeDirectory_BasicTesting() { Assert.AreEqual(@"First\Second\thing.xml", PathHelpers.GenerateRelativePath(@"C:\Test\", @"C:\Test\First\Second\thing.xml")); Assert.AreEqual(@".\First\Second\thing.xml", PathHelpers.GenerateRelativePath(@"C:\Test\", @"C:\Test\First\Second\thing.xml", prefix: ".\\")); Assert.AreEqual("First/Second/thing.xml", PathHelpers.GenerateRelativePath(@"C:\Test\", @"C:\Test\First\Second\thing.xml", separatorChar: '/', prefix: null)); }
public void PathHelpers_Normalize_BasicTesting() { Assert.AreEqual(@"c:\dude\this\is\backwards.txt", PathHelpers.Normalize(@"C:\dude/this\is\super\..\backwards.txt")); }
public FileSystemInfo ToFileSystemInfo() => FileSystemInfo.Create(PathHelpers.CombineNoChecks(Directory, FileName), ref this);
static void Main(string[] args) { try { using (var mutex = new Mutex(true, MutexName)) { if (!mutex.WaitOne(MutexTimeout)) { MessageBox.Show(Resources.SingleInstanceMessage, Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } // install services NLog.GlobalDiagnosticsContext.Set("logDirectory", PathHelpers.GetLogPath()); Container.Install(new KFlearningModulesInstaller()); _logger = Container.Resolve <ILogger>(); // find vscode var path = Container.Resolve <IPathManager>(); if (!path.IsVscodeInstalled) { _logger.Debug("Visual Studio Code not found"); MessageBox.Show(Resources.VscodeNotInstalled, Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } // find mingw if (!path.IsKfMingwInstalled) { _logger.Debug("KF-MinGW not found"); MessageBox.Show(Resources.KfmingwNotInstalled, Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } // enable TLS _logger.Debug("Enabling TLS support"); ApiHelpers.EnableTls(); // app exit handler Application.ApplicationExit += Application_ApplicationExit; // bootstrapper _logger.Debug("Bootstrapping application"); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Container.Resolve <KFlearningApplicationContext>()); } } catch (Exception e) { _logger.Fatal("Application shutdown unexpectedly", e); MessageBox.Show("Aplikasi mengalami crash dan harus ditutup. Harap laporkan kepada asprak.", Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { NLog.LogManager.Shutdown(); } }
public void Test_InvalidInputRelativePathNull() { Assert.IsFalse(PathHelpers.IsValidRelativeFilePath(null)); IFilePath filePath = PathHelpers.ToRelativeFilePath(null); }
private static int GenCsMeta(NameValueCollection parameters) { var connectionString = parameters["connection-string"]; var resultAssemblyFullPath = parameters["result-assembly-full-path"]; var namespaceRoot = parameters["namespace-root"]; var scanItems = (parameters["scan-items"] ?? "").Split(','); var sourcePath = parameters["source-path"]; var csprojFilePath = parameters["csproj-file-path"]; var parametersAreValid = !string.IsNullOrEmpty(connectionString) && (!string.IsNullOrEmpty(resultAssemblyFullPath) || !string.IsNullOrEmpty(sourcePath)) && !string.IsNullOrEmpty(namespaceRoot) && scanItems.Length > 0; if (!parametersAreValid) { Console.Out.WriteLine("Invalid arguments"); Console.Out.WriteLine( "Usage: Generator.exe -cmd gen-cs-meta -connection-string <string> [-result-assembly-full-path <path>] -namespace-root <namespace> -scanItems Справочник.Банки,Документ.СписаниеСРасчетногоСчета [-source-path <sourcePath>] [-csproj-file-path]"); return(-1); } object globalContext = null; LogHelpers.LogWithTiming(string.Format("connecting to [{0}]", connectionString), () => globalContext = new GlobalContextFactory().Create(connectionString)); sourcePath = sourcePath ?? GetTemporaryDirectoryFullPath(); if (Directory.Exists(sourcePath)) { Directory.Delete(sourcePath, true); } string[] fileNames = null; LogHelpers.LogWithTiming(string.Format("generating code into [{0}]", sourcePath), () => { var generator = new ObjectModelGenerator(globalContext, scanItems, namespaceRoot, sourcePath); fileNames = generator.Generate().ToArray(); }); if (!string.IsNullOrEmpty(csprojFilePath)) { csprojFilePath = Path.GetFullPath(csprojFilePath); if (!File.Exists(csprojFilePath)) { Console.Out.WriteLine("proj file [{0}] does not exist, create it manually for the first time", csprojFilePath); return(-1); } LogHelpers.LogWithTiming(string.Format("patching proj file [{0}]", csprojFilePath), () => { var updater = new CsProjectFileUpdater(csprojFilePath, sourcePath); updater.Update(); }); } if (!string.IsNullOrEmpty(resultAssemblyFullPath)) { LogHelpers.LogWithTiming(string.Format("compiling [{0}] to assembly [{1}]", sourcePath, resultAssemblyFullPath), () => { var cSharpCodeProvider = new CSharpCodeProvider(); var compilerParameters = new CompilerParameters { OutputAssembly = resultAssemblyFullPath, GenerateExecutable = false, GenerateInMemory = false, IncludeDebugInformation = false }; var linqTo1CFilePath = PathHelpers.AppendBasePath("Simple1C.dll"); compilerParameters.ReferencedAssemblies.Add(linqTo1CFilePath); var compilerResult = cSharpCodeProvider.CompileAssemblyFromFile(compilerParameters, fileNames); if (compilerResult.Errors.Count > 0) { Console.Out.WriteLine("compile errors"); foreach (CompilerError error in compilerResult.Errors) { Console.Out.WriteLine(error); Console.Out.WriteLine("==================="); } } }); } return(0); }
public AvatarArchive LoadAvatarArchive(string fileName, UUID principalID) { AvatarArchive archive = new AvatarArchive(); UserAccount account = userAccountService.GetUserAccount(null, principalID); if (account == null) { MainConsole.Instance.Error("[Avatar Archiver]: User not found!"); return(null); } // need to be smart here... fileName = PathHelpers.VerifyReadFile(fileName, ".aa", m_storeDirectory); if (!File.Exists(fileName)) { MainConsole.Instance.Error("[Avatar Archiver]: Unable to load from file: file does not exist!"); return(null); } MainConsole.Instance.Info("[Avatar Archiver]: Loading archive from " + fileName); archive.FromOSD((OSDMap)OSDParser.DeserializeLLSDXml(File.ReadAllText(fileName))); AvatarAppearance appearance = ConvertXMLToAvatarAppearance(archive.BodyMap); appearance.Owner = principalID; InventoryFolderBase AppearanceFolder = inventoryService.GetFolderForType(account.PrincipalID, InventoryType.Wearable, FolderType.Clothing); if (AppearanceFolder == null) { AppearanceFolder = new InventoryFolderBase(); // does not exist so... AppearanceFolder.Owner = account.PrincipalID; AppearanceFolder.ID = UUID.Random(); AppearanceFolder.Type = (short)FolderType.Clothing; } List <InventoryItemBase> items; InventoryFolderBase folderForAppearance = new InventoryFolderBase( UUID.Random(), archive.FolderName, account.PrincipalID, (short)FolderType.None, AppearanceFolder.ID, 1); inventoryService.AddFolder(folderForAppearance); folderForAppearance = inventoryService.GetFolder(folderForAppearance); try { LoadAssets(archive.AssetsMap); appearance = CopyWearablesAndAttachments(account.PrincipalID, UUID.Zero, appearance, folderForAppearance, account.PrincipalID, archive.ItemsMap, out items); } catch (Exception ex) { MainConsole.Instance.Warn("[AvatarArchiver]: Error loading assets and items, " + ex); } /* implement fully if we need to * // inform the client if needed * * ScenePresence SP; * MainConsole.Instance.ConsoleScenes[0].TryGetScenePresence(account.PrincipalID, out SP); * if (SP == null) * return; // nobody home! * * SP.ControllingClient.SendAlertMessage("Appearance loading in progress..."); * SP.ControllingClient.SendBulkUpdateInventory(folderForAppearance); */ MainConsole.Instance.Info("[Avatar Archiver]: Loaded archive from " + fileName); archive.Appearance = appearance; return(archive); }
/// <summary> /// Read the config for the data loader /// </summary> /// <param name="simBase"></param> protected virtual void ReadConfig(ISimulationBase simBase) { IConfig config = simBase.ConfigSource.Configs["FileBasedSimulationData"]; if (config != null) { m_saveChanges = config.GetBoolean("SaveChanges", m_saveChanges); m_timeBetweenSaves = config.GetInt("TimeBetweenSaves", m_timeBetweenSaves); m_keepOldSave = config.GetBoolean("SavePreviousBackup", m_keepOldSave); // directories are references from the bin directory // As of V0.9.2 the data is saved relative to the bin dirs m_oldSaveDirectory = PathHelpers.ComputeFullPath(config.GetString("PreviousBackupDirectory", m_oldSaveDirectory)); m_storeDirectory = PathHelpers.ComputeFullPath(config.GetString("StoreBackupDirectory", m_storeDirectory)); if (m_storeDirectory == "") { m_storeDirectory = Constants.DEFAULT_DATA_DIR + "/Region"; } if (m_oldSaveDirectory == "") { m_oldSaveDirectory = Constants.DEFAULT_DATA_DIR + "/RegionBak"; } m_removeArchiveDays = config.GetInt("ArchiveDays", m_removeArchiveDays); // verify the necessary paths exist if (!Directory.Exists(m_storeDirectory)) { Directory.CreateDirectory(m_storeDirectory); } if (!Directory.Exists(m_oldSaveDirectory)) { Directory.CreateDirectory(m_oldSaveDirectory); } string regionNameSeed = config.GetString("RegionNameSeed", ""); if (regionNameSeed != "") { m_regionNameSeed = regionNameSeed.Split(','); } m_saveBackupChanges = config.GetBoolean("SaveTimedPreviousBackup", m_keepOldSave); m_timeBetweenBackupSaves = config.GetInt("TimeBetweenBackupSaves", m_timeBetweenBackupSaves); } if (m_saveChanges && m_timeBetweenSaves != 0) { m_saveTimer = new Timer(m_timeBetweenSaves * 60 * 1000); m_saveTimer.Elapsed += m_saveTimer_Elapsed; m_saveTimer.Start(); } if (m_saveChanges && m_timeBetweenBackupSaves != 0) { m_backupSaveTimer = new Timer(m_timeBetweenBackupSaves * 60 * 1000); m_backupSaveTimer.Elapsed += m_backupSaveTimer_Elapsed; m_backupSaveTimer.Start(); } }
/// <summary> /// Renders the directory where NLog is located and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var path = PathHelpers.CombinePaths(tempDir, this.Dir, this.File); builder.Append(path); }
public override string GetFullPath() { return(PathHelpers.CombinePaths(_directoryEntry?.Name, _fileEntry.Name)); }
/// <summary> /// Setup RequireJS to be used in layouts /// </summary> /// <param name="html"> /// The html. /// </param> /// <param name="baseUrl"> /// scripts base url /// </param> /// <param name="requireUrl"> /// requirejs.js url /// </param> /// <param name="urlArgs"> /// </param> /// <param name="configsList"> /// RequireJS.config files path /// </param> /// <param name="entryPointRoot"> /// Scripts folder relative path ex. ~/Scripts/ /// </param> /// <param name="logger"> /// The logger. /// </param> /// <returns> /// The <see cref="MvcHtmlString"/>. /// </returns> public static MvcHtmlString RenderRequireJsSetup( this HtmlHelper html, string baseUrl, string requireUrl, string urlArgs, IList <string> configsList, string entryPointRoot = "~/Scripts/", IRequireJsLogger logger = null, bool loadOverrides = true) { var entryPointPath = html.RequireJsEntryPoint(entryPointRoot); if (entryPointPath == null) { return(new MvcHtmlString(string.Empty)); } if (configsList == null || !configsList.Any()) { throw new Exception("No config files to load."); } var processedConfigs = configsList.Select(r => { var resultingPath = html.ViewContext.HttpContext.MapPath(r); PathHelpers.VerifyFileExists(resultingPath); return(resultingPath); }).ToList(); var loader = new ConfigLoader(processedConfigs, logger, new ConfigLoaderOptions { LoadOverrides = loadOverrides }); var resultingConfig = loader.Get(); var overrider = new ConfigOverrider(); overrider.Override(resultingConfig, entryPointPath.ToString().ToModuleName()); var outputConfig = new JsonConfig { BaseUrl = baseUrl, Locale = html.CurrentCulture(), UrlArgs = urlArgs, Paths = resultingConfig.Paths.PathList.ToDictionary(r => r.Key, r => r.Value), Shim = resultingConfig.Shim.ShimEntries.ToDictionary( r => r.For, r => new JsonRequireDeps { Dependencies = r.Dependencies.Select(x => x.Dependency).ToList(), Exports = r.Exports }), Map = resultingConfig.Map.MapElements.ToDictionary( r => r.For, r => r.Replacements.ToDictionary(x => x.OldKey, x => x.NewKey)) }; var options = new JsonRequireOptions { Locale = html.CurrentCulture(), PageOptions = html.ViewBag.PageOptions, WebsiteOptions = html.ViewBag.GlobalOptions }; var configBuilder = new JavaScriptBuilder(); configBuilder.AddStatement(JavaScriptHelpers.SerializeAsVariable(options, "requireConfig")); configBuilder.AddStatement(JavaScriptHelpers.SerializeAsVariable(outputConfig, "require")); var requireRootBuilder = new JavaScriptBuilder(); requireRootBuilder.AddAttributesToStatement("src", requireUrl); var requireMethodParams = new List <string>(resultingConfig.StaticDependencies.Dependencies.Select(x => x.Dependency)); requireMethodParams.Add(entryPointPath.ToString()); var requireEntryPointBuilder = new JavaScriptBuilder(); requireEntryPointBuilder.AddStatement( JavaScriptHelpers.MethodCall( "require", requireMethodParams)); return(new MvcHtmlString( configBuilder.Render() + Environment.NewLine + requireRootBuilder.Render() + Environment.NewLine + requireEntryPointBuilder.Render())); }
/// <summary> /// Copy the value at specified location to the target location. Will result in, for example: /// { "op": "copy", "from": "/a/b/c", "path": "/a/b/e" } /// </summary> /// <param name="from">source location</param> /// <param name="path">target location</param> /// <returns>The <see cref="JsonPatchDocument"/> for chaining.</returns> public JsonPatchDocument Copy(string from, string path) { if (from == null) { throw new ArgumentNullException(nameof(from)); } if (path == null) { throw new ArgumentNullException(nameof(path)); } Operations.Add(new Operation("copy", PathHelpers.ValidateAndNormalizePath(path), PathHelpers.ValidateAndNormalizePath(from))); return(this); }
public static ExecutionStatusCode LoadModule(Host host, string moduleName, bool forceCompilation, out CompiledModule module) { module = null; var moduleFolder = Path.Combine(host.ModulesFolder, moduleName); if (!Directory.Exists(moduleFolder)) { host.HostLogger.Write(LogEventLevel.Fatal, "can't find the module folder: {Folder}", moduleFolder); return(ExecutionStatusCode.ModuleLoadError); } // read back actual folder name casing moduleFolder = Directory .GetDirectories(host.ModulesFolder, moduleName, SearchOption.TopDirectoryOnly) .FirstOrDefault(); moduleName = Path.GetFileName(moduleFolder); var startedOn = Stopwatch.StartNew(); var useAppDomain = !forceCompilation && Debugger.IsAttached; if (useAppDomain) { host.HostLogger.Information("loading module directly from AppDomain where namespace ends with '{Module}'", moduleName); ForceLoadLocalDllsToAppDomain(); var appDomainTasks = FindTypesFromAppDomain <IEtlTask>(moduleName); var startup = LoadInstancesFromAppDomain <IStartup>(moduleName).FirstOrDefault(); var instanceConfigurationProviders = LoadInstancesFromAppDomain <IInstanceArgumentProvider>(moduleName); var defaultConfigurationProviders = LoadInstancesFromAppDomain <IDefaultArgumentProvider>(moduleName); host.HostLogger.Debug("finished in {Elapsed}", startedOn.Elapsed); module = new CompiledModule() { Name = moduleName, Folder = moduleFolder, Startup = startup, InstanceArgumentProviders = instanceConfigurationProviders, DefaultArgumentProviders = defaultConfigurationProviders, TaskTypes = appDomainTasks.Where(x => x.Name != null).ToList(), LoadContext = null, }; host.HostLogger.Debug("{FlowCount} flows(s) found: {Task}", module.TaskTypes.Count(x => x.IsAssignableTo(typeof(AbstractEtlFlow))), module.TaskTypes.Where(x => x.IsAssignableTo(typeof(AbstractEtlFlow))).Select(task => task.Name).ToArray()); host.HostLogger.Debug("{TaskCount} task(s) found: {Task}", module.TaskTypes.Count(x => !x.IsAssignableTo(typeof(AbstractEtlFlow))), module.TaskTypes.Where(x => !x.IsAssignableTo(typeof(AbstractEtlFlow))).Select(task => task.Name).ToArray()); return(ExecutionStatusCode.Success); } host.HostLogger.Information("compiling module from {Folder}", PathHelpers.GetFriendlyPathName(moduleFolder)); var metadataReferences = host.GetReferenceAssemblyFileNames() .Select(fn => MetadataReference.CreateFromFile(fn)) .ToArray(); var csFileNames = Directory.GetFiles(moduleFolder, "*.cs", SearchOption.AllDirectories).ToList(); var globalCsFileName = Path.Combine(host.ModulesFolder, "Global.cs"); if (File.Exists(globalCsFileName)) { csFileNames.Add(globalCsFileName); } var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10); var syntaxTrees = csFileNames .Select(fn => SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(fn)), parseOptions, fn)) .ToArray(); using (var assemblyStream = new MemoryStream()) { var id = Interlocked.Increment(ref _moduleAutoincrementId); var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default); var compilation = CSharpCompilation.Create("compiled_" + id.ToString("D", CultureInfo.InvariantCulture) + ".dll", syntaxTrees, metadataReferences, compilationOptions); var result = compilation.Emit(assemblyStream); if (!result.Success) { var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); foreach (var error in failures) { host.HostLogger.Write(LogEventLevel.Fatal, "syntax error in module: {ErrorMessage}", error.ToString()); } return(ExecutionStatusCode.ModuleLoadError); } assemblyStream.Seek(0, SeekOrigin.Begin); var assemblyLoadContext = new AssemblyLoadContext(null, isCollectible: true); var assembly = assemblyLoadContext.LoadFromStream(assemblyStream); var compiledTasks = FindTypesFromAssembly <IEtlTask>(assembly); var compiledStartup = LoadInstancesFromAssembly <IStartup>(assembly).FirstOrDefault(); var instanceConfigurationProviders = LoadInstancesFromAssembly <IInstanceArgumentProvider>(assembly); var defaultConfigurationProviders = LoadInstancesFromAssembly <IDefaultArgumentProvider>(assembly); host.HostLogger.Debug("compilation finished in {Elapsed}", startedOn.Elapsed); module = new CompiledModule() { Name = moduleName, Folder = moduleFolder, Startup = compiledStartup, InstanceArgumentProviders = instanceConfigurationProviders, DefaultArgumentProviders = defaultConfigurationProviders, TaskTypes = compiledTasks.Where(x => x.Name != null).ToList(), LoadContext = assemblyLoadContext, }; host.HostLogger.Debug("{FlowCount} flows(s) found: {Task}", module.TaskTypes.Count(x => x.IsAssignableTo(typeof(AbstractEtlFlow))), module.TaskTypes.Where(x => x.IsAssignableTo(typeof(AbstractEtlFlow))).Select(task => task.Name).ToArray()); host.HostLogger.Debug("{TaskCount} task(s) found: {Task}", module.TaskTypes.Count(x => !x.IsAssignableTo(typeof(AbstractEtlFlow))), module.TaskTypes.Where(x => !x.IsAssignableTo(typeof(AbstractEtlFlow))).Select(task => task.Name).ToArray()); return(ExecutionStatusCode.Success); } }
/// <summary> /// Creates a temporary response file based on settings /// </summary> /// <returns>Path to a respose file</returns> private string MakeResponseFile() { var responseFileString = new StringBuilder(); var compileSymbols = string.Join(";", CompileSymbols); var rspFilePath = PathHelpers.Combine(MakeTempDir(), TempResponseFileName); // append arguments if (BuildTargetCompileSymbols != BuildTarget.NoTarget) { var buildTargetCompileSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildPipeline.GetBuildTargetGroup(BuildTargetCompileSymbols)); if (!string.IsNullOrEmpty(buildTargetCompileSymbols)) { compileSymbols += ";" + buildTargetCompileSymbols; } } responseFileString.AppendLine(string.Format("-out:\"{0}\"", OutputPath)); responseFileString.AppendLine("-target:library"); if (compileSymbols.Length > 0) { responseFileString.AppendLine(string.Format("-define:\"{0}\"", compileSymbols)); } if (Optimize) { responseFileString.AppendLine("-optimize"); } if (Unsafe) { responseFileString.AppendLine("-unsafe"); } // append additional arguments foreach (var additionalArgument in AdditionalArguments) { responseFileString.AppendLine(additionalArgument); } // append resources if (Resources.Length > 0) { responseFileString.AppendLine(); foreach (var resource in Resources) { responseFileString.AppendLine(string.Format("-resource:\"{0}\"", resource)); } } responseFileString.AppendLine(); // append base references responseFileString.AppendLine("-reference:\"System.dll\""); responseFileString.AppendLine("-reference:\"System.Core.dll\""); var referencesMap = new Dictionary <string, string>(); var unityLibPaths = PathHelpers.ResolvePaths(string.Format("{0}/Data/Managed/UnityEngine/*.dll", Path.GetDirectoryName(EditorApplication.applicationPath))); var projectLibPaths = PathHelpers.ResolvePaths(string.Format("{0}/*.dll", ProjectScriptAssembliesDirectory)); // process project library paths foreach (var path in projectLibPaths) { var libName = Path.GetFileName(path) ?? string.Empty; if (string.IsNullOrEmpty(libName) || !libName.Contains("Unity") || referencesMap.ContainsKey(libName)) { continue; } referencesMap.Add(libName, path); } // process unity library paths foreach (var path in unityLibPaths) { var libName = Path.GetFileName(path) ?? string.Empty; if (string.IsNullOrEmpty(libName) || referencesMap.ContainsKey(libName)) { continue; } referencesMap.Add(libName, path); } // process additional references foreach (var path in AdditionalReferences) { var libName = Path.GetFileName(path) ?? string.Empty; if (string.IsNullOrEmpty(libName) || referencesMap.ContainsKey(libName)) { continue; } referencesMap.Add(libName, path); } // add all references to .rsp file foreach (var reference in referencesMap.Values) { responseFileString.AppendLine(string.Format("-reference:\"{0}\"", reference)); } #if NET_STANDARD_2_0 var netstandard = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"); responseFileString.AppendLine(string.Format("-reference:\"{0}\"", netstandard.Location)); #endif responseFileString.AppendLine(); // append assembly info script file if (IncludeAssemblyInfo) { responseFileString.AppendLine(string.Format("\"{0}\"", MakeAssemblyInfoFile())); } // append all script file paths foreach (var scriptPath in ScriptPaths) { responseFileString.AppendLine(string.Format("\"{0}\"", scriptPath)); } File.WriteAllText(rspFilePath, responseFileString.ToString(), Encoding.UTF8); return(rspFilePath); }
/// <summary> /// Handles loading of an avatar archive. /// </summary> /// <param name="scene">Scene.</param> /// <param name="cmdparams">Cmdparams.</param> protected void HandleLoadAvatarArchive(IScene scene, string[] cmdparams) { string userName; string fileName; if (cmdparams.Length < 5) { userName = MainConsole.Instance.Prompt("Avatar name for archive upload (<first> <last>)", ""); if (userName == "") { return; } } else { userName = cmdparams [3] + " " + cmdparams [4]; } UserAccount account = userAccountService.GetUserAccount(null, userName); if (account == null) { MainConsole.Instance.Info("[AvatarArchive]: Sorry, unable to find an account for " + userName + "!"); return; } // filename to load if (cmdparams.Length < 6) { do { fileName = MainConsole.Instance.Prompt("Avatar archive filename to load (? for list)", ""); if (fileName == "?") { var archives = GetAvatarArchiveFilenames(); MainConsole.Instance.CleanInfo(" Available archives are : "); foreach (string avatar in archives) { MainConsole.Instance.CleanInfo(" " + avatar); } } } while (fileName == "?"); if (fileName == "") { return; } } else { fileName = cmdparams [5]; } //some file sanity checks fileName = PathHelpers.VerifyReadFile(fileName, ".aa", m_storeDirectory); if (fileName == "") { return; } AvatarArchive archive = LoadAvatarArchive(fileName, account.PrincipalID); if (archive != null) { avatarService.SetAppearance(account.PrincipalID, archive.Appearance); } }
private void Startup() { ThreadUtility.MainThread = Thread.CurrentThread; InitIoC(); SetupLogging(); // Set up custom synchronization context. // Sorry Godot. _taskManager.Initialize(); // Load config. _configurationManager.LoadFromFile(PathHelpers.ExecutableRelativeFile("client_config.toml")); if (Mode == DisplayMode.OpenGL) { _displayManagerOpenGL = IoCManager.Resolve <IDisplayManagerOpenGL>(); } // Init resources. // Doesn't do anything right now because TODO Godot asset management is a bit ad-hoc. _resourceCache.LoadBaseResources(); _resourceCache.LoadLocalResources(); // Bring display up as soon as resources are mounted. _displayManager.Initialize(); _displayManager.SetWindowTitle("Space Station 14"); if (Mode == DisplayMode.OpenGL) { _fontManager = IoCManager.Resolve <IFontManagerInternal>(); _fontManager.Initialize(); } //identical code for server in baseserver if (!AssemblyLoader.TryLoadAssembly <GameShared>(_resourceManager, $"Content.Shared")) { Logger.Warning($"[ENG] Could not load any Shared DLL."); } if (!AssemblyLoader.TryLoadAssembly <GameClient>(_resourceManager, $"Content.Client")) { Logger.Warning($"[ENG] Could not load any Client DLL."); } // Call Init in game assemblies. AssemblyLoader.BroadcastRunLevel(AssemblyLoader.RunLevel.Init); _eyeManager.Initialize(); _serializer.Initialize(); _userInterfaceManager.Initialize(); _networkManager.Initialize(false); _inputManager.Initialize(); _console.Initialize(); _prototypeManager.LoadDirectory(new ResourcePath(@"/Prototypes/")); _prototypeManager.Resync(); _tileDefinitionManager.Initialize(); _mapManager.Initialize(); _placementManager.Initialize(); _lightManager.Initialize(); _entityManager.Initialize(); _gameStateManager.Initialize(); _overlayManager.Initialize(); _viewVariablesManager.Initialize(); _client.Initialize(); AssemblyLoader.BroadcastRunLevel(AssemblyLoader.RunLevel.PostInit); _stateManager.RequestStateChange <MainScreen>(); if (_displayManagerOpenGL != null) { _displayManagerOpenGL.Ready(); } var args = GetCommandLineArgs(); if (args.Contains("--connect")) { _client.ConnectToServer("127.0.0.1", 1212); } }
/// <summary> /// Handles saving of an avatar archive. /// </summary> /// <param name="scene">Scene.</param> /// <param name="cmdparams">Cmdparams.</param> protected void HandleSaveAvatarArchive(IScene scene, string[] cmdparams) { string userName; string fileName; string foldername; UUID snapshotUUID = UUID.Zero; bool isPublic = true; // check for switch options var parms = new List <string>(); for (int i = 3; i < cmdparams.Length;) { if (cmdparams [i].StartsWith("--private")) { isPublic = false; i++; } else if (cmdparams [i].StartsWith("--snapshot")) { snapshotUUID = UUID.Parse(cmdparams [i + 1]); i += 2; } else if (cmdparams [i].StartsWith("--")) { MainConsole.Instance.WarnFormat("Unknown parameter: " + cmdparams [i]); i++; } else { parms.Add(cmdparams [i]); i++; } } if (parms.Count == 0) { userName = MainConsole.Instance.Prompt(" Avatar appearence to save (<first> <last>)"); if (userName == "") { return; } } else if (parms.Count > 1) { userName = parms [0] + " " + parms [1]; } else { MainConsole.Instance.Info("Error in command format."); return; } UserAccount account = userAccountService.GetUserAccount(null, userName); if (account == null) { MainConsole.Instance.Error("[AvatarArchive]: User '" + userName + "' not found!"); return; } if (parms.Count > 2) { fileName = parms [2]; } else { fileName = userName.Replace(" ", ""); fileName = MainConsole.Instance.Prompt(" Avatar archive filename)", fileName); if (fileName == "") { return; } } //some file sanity checks fileName = PathHelpers.VerifyWriteFile(fileName, ".aa", m_storeDirectory, true); if (fileName == "") { return; } // check options foldername = (Path.GetFileNameWithoutExtension(fileName)); // use the filename as the default folder if (parms.Count > 3) { foldername = OSD.FromString(cmdparams[3]); } foldername = foldername.Replace(' ', '_'); SaveAvatarArchive(fileName, account.PrincipalID, foldername, snapshotUUID, isPublic); }
public void Test_InvalidInputPathNull() { Assert.IsFalse(PathHelpers.IsValidAbsoluteFilePath(null)); IFilePath filePath = PathHelpers.ToAbsoluteFilePath(null); }
public AvatarArchive LoadAvatarArchive(string fileName, UUID principalID) { AvatarArchive archive = new AvatarArchive(); UserAccount account = userAccountService.GetUserAccount(null, principalID); if (account == null) { MainConsole.Instance.Error("[AvatarArchive]: User not found!"); return(null); } // need to be smart here... fileName = PathHelpers.VerifyReadFile(fileName, ".aa", m_storeDirectory); if (!File.Exists(fileName)) { MainConsole.Instance.Error("[AvatarArchive]: Unable to load from file: file does not exist!"); return(null); } MainConsole.Instance.Info("[AvatarArchive]: Loading archive from " + fileName); archive.FromOSD((OSDMap)OSDParser.DeserializeLLSDXml(File.ReadAllText(fileName))); AvatarAppearance appearance = ConvertXMLToAvatarAppearance(archive.BodyMap); appearance.Owner = principalID; InventoryFolderBase AppearanceFolder = inventoryService.GetFolderForType(account.PrincipalID, InventoryType.Wearable, AssetType.Clothing); if (AppearanceFolder == null) { AppearanceFolder = new InventoryFolderBase(); // does not exist so... AppearanceFolder.Owner = account.PrincipalID; AppearanceFolder.ID = UUID.Random(); AppearanceFolder.Type = (short)InventoryType.Wearable; } List <InventoryItemBase> items; InventoryFolderBase folderForAppearance = new InventoryFolderBase( UUID.Random(), archive.FolderName, account.PrincipalID, -1, AppearanceFolder.ID, 1); inventoryService.AddFolder(folderForAppearance); folderForAppearance = inventoryService.GetFolder(folderForAppearance); try { LoadAssets(archive.AssetsMap); appearance = CopyWearablesAndAttachments(account.PrincipalID, UUID.Zero, appearance, folderForAppearance, account.PrincipalID, archive.ItemsMap, out items); } catch (Exception ex) { MainConsole.Instance.Warn("[AvatarArchiver]: Error loading assets and items, " + ex); } MainConsole.Instance.Info("[AvatarArchive]: Loaded archive from " + fileName); archive.Appearance = appearance; return(archive); }
/// <inheritdoc /> public bool Start(Func <ILogHandler>?logHandlerFactory = null) { // Sets up the configMgr // If a config file path was passed, use it literally. // This ensures it's working-directory relative // (for people passing config file through the terminal or something). // Otherwise use the one next to the executable. if (_commandLineArgs?.ConfigFile != null) { _config.LoadFromFile(_commandLineArgs.ConfigFile); } else { var path = PathHelpers.ExecutableRelativeFile("server_config.toml"); if (File.Exists(path)) { _config.LoadFromFile(path); } else { _config.SetSaveFile(path); } } _config.OverrideConVars(EnvironmentVariables.GetEnvironmentCVars()); if (_commandLineArgs != null) { _config.OverrideConVars(_commandLineArgs.CVars); } //Sets up Logging _config.RegisterCVar("log.enabled", true, CVar.ARCHIVE); _config.RegisterCVar("log.path", "logs", CVar.ARCHIVE); _config.RegisterCVar("log.format", "log_%(date)s-T%(time)s.txt", CVar.ARCHIVE); _config.RegisterCVar("log.level", LogLevel.Info, CVar.ARCHIVE); _logHandlerFactory = logHandlerFactory; var logHandler = logHandlerFactory?.Invoke() ?? null; var logEnabled = _config.GetCVar <bool>("log.enabled"); if (logEnabled && logHandler == null) { var logPath = _config.GetCVar <string>("log.path"); var logFormat = _config.GetCVar <string>("log.format"); var logFilename = logFormat.Replace("%(date)s", DateTime.Now.ToString("yyyy-MM-dd")) .Replace("%(time)s", DateTime.Now.ToString("hh-mm-ss")); var fullPath = Path.Combine(logPath, logFilename); if (!Path.IsPathRooted(fullPath)) { logPath = PathHelpers.ExecutableRelativeFile(fullPath); } logHandler = new FileLogHandler(logPath); } _log.RootSawmill.Level = _config.GetCVar <LogLevel>("log.level"); if (logEnabled && logHandler != null) { _logHandler = logHandler; _log.RootSawmill.AddHandler(_logHandler !); } SelfLog.Enable(s => { System.Console.WriteLine("SERILOG ERROR: {0}", s); }); if (!SetupLoki()) { return(true); } // Has to be done early because this guy's in charge of the main thread Synchronization Context. _taskManager.Initialize(); LoadSettings(); // Load metrics really early so that we can profile startup times in the future maybe. _metricsManager.Initialize(); var netMan = IoCManager.Resolve <IServerNetManager>(); try { netMan.Initialize(true); netMan.StartServer(); netMan.RegisterNetMessage <MsgSetTickRate>(MsgSetTickRate.NAME); } catch (Exception e) { var port = netMan.Port; Logger.Fatal( "Unable to setup networking manager. Check port {0} is not already in use and that all binding addresses are correct!\n{1}", port, e); return(true); } var dataDir = _commandLineArgs?.DataDir ?? PathHelpers.ExecutableRelativeFile("data"); // Set up the VFS _resources.Initialize(dataDir); #if FULL_RELEASE _resources.MountContentDirectory(@"./Resources/"); #else // Load from the resources dir in the repo root instead. // It's a debug build so this is fine. var contentRootDir = ProgramShared.FindContentRootDir(); _resources.MountContentDirectory($@"{contentRootDir}RobustToolbox/Resources/"); _resources.MountContentDirectory($@"{contentRootDir}bin/Content.Server/", new ResourcePath("/Assemblies/")); _resources.MountContentDirectory($@"{contentRootDir}Resources/"); #endif _modLoader.SetUseLoadContext(!DisableLoadContext); //identical code in game controller for client if (!_modLoader.TryLoadAssembly <GameShared>(_resources, $"Content.Shared")) { Logger.FatalS("eng", "Could not load any Shared DLL."); return(true); } if (!_modLoader.TryLoadAssembly <GameServer>(_resources, $"Content.Server")) { Logger.FatalS("eng", "Could not load any Server DLL."); return(true); } _modLoader.BroadcastRunLevel(ModRunLevel.PreInit); // HAS to happen after content gets loaded. // Else the content types won't be included. // TODO: solve this properly. _serializer.Initialize(); //IoCManager.Resolve<IMapLoader>().LoadedMapData += // IoCManager.Resolve<IRobustMappedStringSerializer>().AddStrings; IoCManager.Resolve <IPrototypeManager>().LoadedData += IoCManager.Resolve <IRobustMappedStringSerializer>().AddStrings; // Initialize Tier 2 services IoCManager.Resolve <IGameTiming>().InSimulation = true; _stateManager.Initialize(); IoCManager.Resolve <IPlayerManager>().Initialize(MaxPlayers); _mapManager.Initialize(); _mapManager.Startup(); IoCManager.Resolve <IPlacementManager>().Initialize(); IoCManager.Resolve <IViewVariablesHost>().Initialize(); IoCManager.Resolve <IDebugDrawingManager>().Initialize(); // Call Init in game assemblies. _modLoader.BroadcastRunLevel(ModRunLevel.Init); _entities.Initialize(); // because of 'reasons' this has to be called after the last assembly is loaded // otherwise the prototypes will be cleared var prototypeManager = IoCManager.Resolve <IPrototypeManager>(); prototypeManager.LoadDirectory(new ResourcePath(@"/Prototypes")); prototypeManager.Resync(); IoCManager.Resolve <IConsoleShell>().Initialize(); IoCManager.Resolve <IConGroupController>().Initialize(); _entities.Startup(); _scriptHost.Initialize(); _modLoader.BroadcastRunLevel(ModRunLevel.PostInit); IoCManager.Resolve <IStatusHost>().Start(); AppDomain.CurrentDomain.ProcessExit += ProcessExiting; _watchdogApi.Initialize(); return(false); }
public override void Handle(Arguments args, DotvvmProjectMetadata dotvvmProjectMetadata) { // make sure the test directory exists if (string.IsNullOrEmpty(dotvvmProjectMetadata.UITestProjectPath)) { dotvvmProjectMetadata.UITestProjectPath = ConsoleHelpers.AskForValue($"Enter the path to the test project\n(relative to DotVVM project directory, e.g. '..\\{dotvvmProjectMetadata.ProjectName}.Tests'): "); } var testProjectDirectory = dotvvmProjectMetadata.GetUITestProjectFullPath(); if (!Directory.Exists(testProjectDirectory)) { throw new Exception($"The directory {testProjectDirectory} doesn't exist!"); } // make sure we know the test project namespace if (string.IsNullOrEmpty(dotvvmProjectMetadata.UITestProjectRootNamespace)) { var csprojService = new CSharpProjectService(); var csproj = csprojService.FindCsprojInDirectory(testProjectDirectory); if (csproj != null) { csprojService.Load(csproj); dotvvmProjectMetadata.UITestProjectRootNamespace = csprojService.GetRootNamespace(); } else { dotvvmProjectMetadata.UITestProjectRootNamespace = ConsoleHelpers.AskForValue("Enter the test project root namespace: "); if (string.IsNullOrEmpty(dotvvmProjectMetadata.UITestProjectRootNamespace)) { throw new Exception("The test project root namespace must not be empty!"); } } } // generate the test stubs var name = args[0]; var files = ExpandFileNames(name); foreach (var file in files) { Console.WriteLine($"Generating stub for {file}..."); // determine full type name and target file var relativePath = PathHelpers.GetDothtmlFileRelativePath(dotvvmProjectMetadata, file); var relativeTypeName = PathHelpers.TrimFileExtension(relativePath) + "Helper"; var fullTypeName = dotvvmProjectMetadata.UITestProjectRootNamespace + "." + PathHelpers.CreateTypeNameFromPath(relativeTypeName); var targetFileName = Path.Combine(dotvvmProjectMetadata.UITestProjectPath, "Helpers", relativeTypeName + ".cs"); // generate the file //var generator = new SeleniumHelperGenerator(); //var config = new SeleniumGeneratorConfiguration() //{ // TargetNamespace = PathHelpers.GetNamespaceFromFullType(fullTypeName), // HelperName = PathHelpers.GetTypeNameFromFullType(fullTypeName), // HelperFileFullPath = targetFileName, // ViewFullPath = file //}; //generator.ProcessMarkupFile(DotvvmConfiguration.CreateDefault(), config); } }
/// <summary> /// Returns the full path of the find result. /// </summary> public string ToFullPath() => PathHelpers.CombineNoChecks(Directory, FileName);
public void Run() { Logger.Debug("Initializing GameController."); _configurationManager.LoadFromFile(PathHelpers.ExecutableRelativeFile("client_config.toml")); _resourceCache.LoadBaseResources(); ShowSplashScreen(); _resourceCache.LoadLocalResources(); LoadContentAssembly <GameShared>("Shared"); LoadContentAssembly <GameClient>("Client"); //Setup Cluwne first, as the rest depends on it. SetupCluwne(); CleanupSplashScreen(); //Initialization of private members _tileDefinitionManager.InitializeResources(); _serializer.Initialize(); var prototypeManager = IoCManager.Resolve <IPrototypeManager>(); prototypeManager.LoadDirectory(PathHelpers.ExecutableRelativeFile("Resources/Prototypes")); prototypeManager.Resync(); _networkManager.Initialize(false); _netGrapher.Initialize(); _userInterfaceManager.Initialize(); _stateManager.RequestStateChange <MainScreen>(); #region GameLoop // maximum number of ticks to queue before the loop slows down. const int maxTicks = 5; _time.ResetRealTime(); var maxTime = TimeSpan.FromTicks(_time.TickPeriod.Ticks * maxTicks); while (CluwneLib.IsRunning) { var accumulator = _time.RealTime - _lastTick; // If the game can't keep up, limit time. if (accumulator > maxTime) { // limit accumulator to max time. accumulator = maxTime; // pull lastTick up to the current realTime // This will slow down the simulation, but if we are behind from a // lag spike hopefully it will be able to catch up. _lastTick = _time.RealTime - maxTime; // announce we are falling behind if ((_time.RealTime - _lastKeepUpAnnounce).TotalSeconds >= 15.0) { Logger.Warning("[SRV] MainLoop: Cannot keep up!"); _lastKeepUpAnnounce = _time.RealTime; } } _time.StartFrame(); var realFrameEvent = new FrameEventArgs((float)_time.RealFrameTime.TotalSeconds); // process Net/KB/Mouse input Process(realFrameEvent); _time.InSimulation = true; // run the simulation for every accumulated tick while (accumulator >= _time.TickPeriod) { accumulator -= _time.TickPeriod; _lastTick += _time.TickPeriod; // only run the sim if unpaused, but still use up the accumulated time if (!_time.Paused) { // update the simulation var simFrameEvent = new FrameEventArgs((float)_time.FrameTime.TotalSeconds); Update(simFrameEvent); _time.CurTick++; } } // if not paused, save how close to the next tick we are so interpolation works if (!_time.Paused) { _time.TickRemainder = accumulator; } _time.InSimulation = false; // render the simulation Render(realFrameEvent); } #endregion _networkManager.ClientDisconnect("Client disconnected from game."); CluwneLib.Terminate(); Logger.Info("GameController terminated."); IoCManager.Resolve <IConfigurationManager>().SaveToFile(); }
/// <summary> /// Returns the full path for find results, based on the initially provided path. /// </summary> public string ToSpecifiedFullPath() => PathHelpers.CombineNoChecks(OriginalRootDirectory, Directory.Slice(RootDirectory.Length), FileName);
public void EndsWithExtensionReturnsFalse(string path, string extension) { Assert.False(PathHelpers.EndsWithExtension(path, extension)); }
public void PathHelpers_RelativeDirectory_UpADirectoryTesting() { Assert.AreEqual(@"..\Second\thing.xml", PathHelpers.GenerateRelativePath(@"C:\Test\First", @"C:\Test\Second\thing.xml")); }
internal static WebPageMatch MatchRequest(string pathValue, string[] supportedExtensions, Func <string, bool> virtualPathExists, HttpContextBase context, DisplayModeProvider displayModes) { string currentLevel = String.Empty; string currentPathInfo = pathValue; // We can skip the file exists check and normal lookup for empty paths, but we still need to look for default pages if (!String.IsNullOrEmpty(pathValue)) { // If the file exists and its not a supported extension, let the request go through if (FileExists(pathValue, virtualPathExists)) { // TODO: Look into switching to RawURL to eliminate the need for this issue bool foundSupportedExtension = false; for (int i = 0; i < supportedExtensions.Length; i++) { string supportedExtension = supportedExtensions[i]; if (PathHelpers.EndsWithExtension(pathValue, supportedExtension)) { foundSupportedExtension = true; break; } } if (!foundSupportedExtension) { return(null); } } // For each trimmed part of the path try to add a known extension and // check if it matches a file in the application. currentLevel = pathValue; currentPathInfo = String.Empty; while (true) { // Does the current route level patch any supported extension? string routeLevelMatch = GetRouteLevelMatch(currentLevel, supportedExtensions, virtualPathExists, context, displayModes); if (routeLevelMatch != null) { return(new WebPageMatch(routeLevelMatch, currentPathInfo)); } // Try to remove the last path segment (e.g. go from /foo/bar to /foo) int indexOfLastSlash = currentLevel.LastIndexOf('/'); if (indexOfLastSlash == -1) { // If there are no more slashes, we're done break; } else { // Chop off the last path segment to get to the next one currentLevel = currentLevel.Substring(0, indexOfLastSlash); // And save the path info in case there is a match currentPathInfo = pathValue.Substring(indexOfLastSlash + 1); } } } return(MatchDefaultFiles(pathValue, supportedExtensions, virtualPathExists, context, displayModes, currentLevel)); }
/// <summary> /// Get default file paths (including filename) for possible NLog config files. /// </summary> public IEnumerable <string> GetDefaultCandidateConfigFilePaths(string filename = null) { // NLog.config from application directory string nlogConfigFile = filename ?? "NLog.config"; string baseDirectory = PathHelpers.TrimDirectorySeparators(_appEnvironment.AppDomainBaseDirectory); if (!string.IsNullOrEmpty(baseDirectory)) { yield return(Path.Combine(baseDirectory, nlogConfigFile)); } string nLogConfigFileLowerCase = nlogConfigFile.ToLower(); bool platformFileSystemCaseInsensitive = nlogConfigFile == nLogConfigFileLowerCase || PlatformDetector.IsWin32; if (!platformFileSystemCaseInsensitive && !string.IsNullOrEmpty(baseDirectory)) { yield return(Path.Combine(baseDirectory, nLogConfigFileLowerCase)); } #if !SILVERLIGHT && !NETSTANDARD1_3 string entryAssemblyLocation = PathHelpers.TrimDirectorySeparators(_appEnvironment.EntryAssemblyLocation); #else string entryAssemblyLocation = string.Empty; #endif if (!string.IsNullOrEmpty(entryAssemblyLocation) && !string.Equals(entryAssemblyLocation, baseDirectory, StringComparison.OrdinalIgnoreCase)) { yield return(Path.Combine(entryAssemblyLocation, nlogConfigFile)); if (!platformFileSystemCaseInsensitive) { yield return(Path.Combine(entryAssemblyLocation, nLogConfigFileLowerCase)); } } if (string.IsNullOrEmpty(baseDirectory)) { yield return(nlogConfigFile); if (!platformFileSystemCaseInsensitive) { yield return(nLogConfigFileLowerCase); } } if (filename == null) { // Scan for process specific nlog-files foreach (var filePath in GetAppSpecificNLogLocations(entryAssemblyLocation)) { yield return(filePath); } } foreach (var filePath in GetPrivateBinPathNLogLocations(baseDirectory, nlogConfigFile, platformFileSystemCaseInsensitive ? nLogConfigFileLowerCase : string.Empty)) { yield return(filePath); } string nlogAssemblyLocation = filename != null ? null : LookupNLogAssemblyLocation(); if (nlogAssemblyLocation != null) { yield return(nlogAssemblyLocation + ".nlog"); } }
/// <summary> /// Loads a material library. /// </summary> /// <param name="mtlFile"> /// The material file name. /// </param> private void LoadMaterialLib(string mtlFile) { string path = PathHelpers.GetFullPath(this.TexturePath, mtlFile); if (!File.Exists(path)) { return; } using (var materialReader = new StreamReader(path)) { MaterialDefinition currentMaterial = null; while (!materialReader.EndOfStream) { var line = materialReader.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.StartsWith("#") || line.Length == 0) { continue; } string keyword, value; SplitLine(line, out keyword, out value); switch (keyword.ToLower()) { case "newmtl": if (value != null) { if (this.Materials.ContainsKey(value)) { currentMaterial = null; } else { currentMaterial = new MaterialDefinition(value); this.Materials.Add(value, currentMaterial); } } break; case "ka": if (currentMaterial != null && value != null) { currentMaterial.Ambient = ColorParse(value); } break; case "kd": if (currentMaterial != null && value != null) { currentMaterial.Diffuse = ColorParse(value); } break; case "ks": if (currentMaterial != null && value != null) { currentMaterial.Specular = ColorParse(value); } break; case "ns": if (currentMaterial != null && value != null) { currentMaterial.SpecularCoefficient = DoubleParse(value); } break; case "d": if (currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "tr": if (!this.SkipTransparencyValues && currentMaterial != null && value != null) { currentMaterial.Dissolved = DoubleParse(value); } break; case "illum": if (currentMaterial != null && value != null) { currentMaterial.Illumination = int.Parse(value); } break; case "map_ka": if (currentMaterial != null) { currentMaterial.AmbientMap = value; } break; case "map_kd": if (currentMaterial != null) { currentMaterial.DiffuseMap = value; } break; case "map_ks": if (currentMaterial != null) { currentMaterial.SpecularMap = value; } break; case "map_d": if (currentMaterial != null) { currentMaterial.AlphaMap = value; } break; case "map_bump": case "bump": if (currentMaterial != null) { currentMaterial.BumpMap = value; } break; } } } }