/// <summary> /// 添加模块数据 /// </summary> /// <param name="moduleData"></param> public void addModuleData(ModuleData moduleData) { if (_moduleDataDict.ContainsKey(moduleData.moduleId)) { return; } _moduleDataDict.Add(moduleData.moduleId, moduleData); }
/// <summary> /// load data from xml Node /// </summary> /// <param name="node"></param> /// <returns></returns> public static ModuleData LoadFromXml(XmlNode node) { if (null == node) return null; ModuleData mData = new ModuleData(); mData.m_strModuleName = XmlLoaderBase.getInnerTextByPath(node, "./name"); mData.m_strModuleVersion = XmlLoaderBase.getInnerTextByPath(node, "./version"); mData.m_strModuleBase = XmlLoaderBase.getInnerTextByPath(node, "./base"); if (null == mData.m_strModuleBase || 0 == mData.m_strModuleBase.Length) return null; mData.m_nModuleBase = Convert.ToInt32(mData.m_strModuleBase, 16); mData.m_strModuleSize = XmlLoaderBase.getInnerTextByPath(node, "./size"); if (null == mData.m_strModuleSize || 0 == mData.m_strModuleSize.Length) return null; mData.m_nModuleSize = Convert.ToInt32(mData.m_strModuleSize, 16); return mData; }
public void LoadData(CLIFile pFile) { int token = 0; if (pFile.ModuleTable.Length > ResolutionScopeTypeMax16BitRows || pFile.ModuleRefTable.Length > ResolutionScopeTypeMax16BitRows || pFile.AssemblyRefTable.Length > ResolutionScopeTypeMax16BitRows || pFile.TypeRefTable.Length > ResolutionScopeTypeMax16BitRows) token = pFile.ReadInt32(); else token = pFile.ReadUInt16(); Type = (ResolutionScopeType)(token & ResolutionScopeTypeMask); token = (token >> ResolutionScopeTypeBits) - 1; if (token >= 0) { switch (Type) { case ResolutionScopeType.Module: Module = pFile.ModuleTable[token]; break; case ResolutionScopeType.ModuleRef: ModuleRef = pFile.ModuleRefTable[token]; break; case ResolutionScopeType.AssemblyRef: AssemblyRef = pFile.AssemblyRefTable[token]; break; case ResolutionScopeType.TypeRef: TypeRef = pFile.TypeRefTable[token]; break; default: throw new BadImageFormatException("ResolutionScope Type"); } } }
/// <summary> /// Loads a module from a zip file. /// </summary> /// <param name="zipFile">The path to the zip file.</param> /// <param name="startImmediately">True if execution should be started immediately after configuring the module, false if module should be configured but not started.</param> private static void LoadZipAndConfigure(string zipFile, bool startImmediately) { string tempPath = null; int i = 0; while (Directory.Exists(tempPath = Path.Combine(Path.Combine(Path.GetTempPath(), "TaskManager"), Path.GetRandomFileName()))) { i++; if (i == 10) { throw new Exception("Failed to create a new temporary folder."); } } if (!tempPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { tempPath += Path.DirectorySeparatorChar; } string overridePath = Path.Combine(Path.GetDirectoryName(zipFile), Path.GetFileNameWithoutExtension(zipFile)) + Path.DirectorySeparatorChar; string loaderDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll"); string tempLoaderDll = Path.Combine(tempPath, "TaskManager.Loader.dll"); string commonDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Common.dll"); string tempCommonDll = Path.Combine(tempPath, "TaskManager.Common.dll"); List <string> dependencies = new List <string>(); DirectoryInfo directoryInfo = Directory.CreateDirectory(tempPath); try { using (Stream fileStream = File.Open(zipFile, FileMode.Open, FileAccess.Read)) { using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Read)) { var directory = zip.Entries; foreach (var compressedFile in directory) { string destinationFile = Path.Combine(tempPath, compressedFile.FullName); string overrideFile = Path.Combine(overridePath, compressedFile.FullName); dependencies.Add(overrideFile); compressedFile.ExtractToFile(destinationFile, true); } } } if (Directory.Exists(overridePath)) { foreach (string overrideFile in Directory.GetFiles(overridePath, "*.*", SearchOption.AllDirectories)) { if (!dependencies.Contains(overrideFile)) { dependencies.Add(overrideFile); } dependencies.Add(Path.Combine(overridePath, overrideFile.Replace(tempPath, string.Empty))); string relativeName = overrideFile.Replace(overridePath, string.Empty); string destination = Path.Combine(tempPath, relativeName); string destinationPath = Path.GetDirectoryName(destination); if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } File.Copy(overrideFile, destination, true); } } List <string> possibleFiles = new List <string>(); foreach (string moduleFile in Directory.GetFiles(tempPath, "*" + ModuleFileDefaultExtension, SearchOption.AllDirectories)) { string xmlFile = Path.ChangeExtension(moduleFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { possibleFiles.Add(moduleFile); } } File.Copy(loaderDll, tempLoaderDll, true); File.Copy(commonDll, tempCommonDll, true); foreach (string dllFile in possibleFiles) { string xmlFile = Path.ChangeExtension(dllFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { if (!xmlFile.IsValidConfigurationFile()) { continue; } string modulePath = Path.GetDirectoryName(dllFile); string[] files = Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories); AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ShadowCopyFiles = "true"; domainSetup.ApplicationBase = tempPath; domainSetup.ConfigurationFile = dllFile + ".config"; AppDomain domain = AppDomain.CreateDomain(dllFile, null, domainSetup); TaskWrapper[] tasks = new TaskWrapper[0]; try { TaskManagerService.Logger.Log(string.Format("Module found: '{0}', configuration file: '{1}', scanning assembly for tasks...", dllFile, xmlFile)); AssemblyName loaderAssemblyName = AssemblyName.GetAssemblyName(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll")); Loader loader = (Loader)domain.CreateInstanceAndUnwrap(loaderAssemblyName.ToString(), "TaskManager.Loader"); tasks = loader.LoadAndConfigure(dllFile, xmlFile, TaskManagerService.Logger, AppDomain.CurrentDomain.BaseDirectory); ModuleData newModule = new ModuleData(); newModule.BasePath = overridePath; newModule.Tasks = tasks; newModule.DllFile = dllFile; newModule.XmlFile = xmlFile; newModule.ZipFile = zipFile; newModule.ZipDirectory = tempPath; newModule.Files = new List <string>(files); newModule.Files.AddRange(dependencies); newModule.Files.Add(zipFile); newModule.Domain = domain; if (startImmediately) { foreach (TaskWrapper task in newModule.Tasks) { TaskSupervisor.ScheduleTask(task); } } _moduleList.Add(newModule); } catch (Exception ex) { foreach (TaskWrapper task in tasks) { try { TaskSupervisor.RemoveTask(task); } catch { } } AppDomain.Unload(domain); TaskManagerService.Logger.Log(string.Format("Unable to load module '{0}' from zipped file '{1}'.", dllFile, zipFile), ex); } } } foreach (ModuleData module in _moduleList) { if (module.ZipFile == zipFile) { return; } } throw new Exception(string.Format("Unable to find tasks in zipped file '{0}'.", zipFile)); } catch { try { Directory.Delete(tempPath, true); } catch (Exception ex) { TaskManagerService.Logger.Log(string.Format("Unable to remove temporary directory '{0}'.", tempPath), ex); } throw; } }
private EcmaModule AddModule(string filePath, string expectedSimpleName, bool useForBinding) { MemoryMappedViewAccessor mappedViewAccessor = null; PdbSymbolReader pdbReader = null; try { PEReader peReader = OpenPEFile(filePath, out mappedViewAccessor); pdbReader = OpenAssociatedSymbolFile(filePath, peReader); EcmaModule module = EcmaModule.Create(this, peReader, pdbReader); MetadataReader metadataReader = module.MetadataReader; string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name); if (expectedSimpleName != null && !simpleName.Equals(expectedSimpleName, StringComparison.OrdinalIgnoreCase)) { throw new FileNotFoundException("Assembly name does not match filename " + filePath); } ModuleData moduleData = new ModuleData() { SimpleName = simpleName, FilePath = filePath, Module = module, MappedViewAccessor = mappedViewAccessor }; lock (this) { if (useForBinding) { ModuleData actualModuleData = _simpleNameHashtable.AddOrGetExisting(moduleData); if (actualModuleData != moduleData) { if (actualModuleData.FilePath != filePath) { throw new FileNotFoundException("Module with same simple name already exists " + filePath); } return(actualModuleData.Module); } } mappedViewAccessor = null; // Ownership has been transfered pdbReader = null; // Ownership has been transferred _moduleHashtable.AddOrGetExisting(moduleData); } return(module); } finally { if (mappedViewAccessor != null) { mappedViewAccessor.Dispose(); } if (pdbReader != null) { pdbReader.Dispose(); } } }
// Binary file format, all data is little-endian: // // [Magic string] # XATM // [Format version] # 32-bit integer, 4 bytes // [Module UUID] # 16 bytes // [Entry count] # unsigned 32-bit integer, 4 bytes // [Duplicate count] # unsigned 32-bit integer, 4 bytes (might be 0) // [Java type name width] # unsigned 32-bit integer, 4 bytes // [Assembly name size] # unsigned 32-bit integer, 4 bytes // [Assembly name] # Non-null terminated assembly name // [Java-to-managed map] # Format described below, [Entry count] entries // [Managed-to-java map] # Format described below, [Entry count] entries // [Managed-to-java duplicates map] # Map of unique managed IDs which point to the same Java type name (might be empty) // // Java-to-managed map format: // // [Java type name]<NUL>[Managed type token ID] // // Each name is padded with <NUL> to the width specified in the [Java type name width] field above. // Names are written without the size prefix, instead they are always terminated with a nul character // to make it easier and faster to handle by the native runtime. // // Each token ID is an unsigned 32-bit integer, 4 bytes // // // Managed-to-java map format: // // [Managed type token ID][Java type name table index] // // Both fields are unsigned 32-bit integers, to a total of 8 bytes per entry. Index points into the // [Java-to-managed map] table above. // // Managed-to-java duplicates map format: // // Format is identical to [Managed-to-java] above. // void OutputModule(BinaryWriter bw, byte[] moduleUUID, ModuleData moduleData) { bw.Write(moduleMagicString); bw.Write(TypeMapFormatVersion); bw.Write(moduleUUID); var javaNames = new Dictionary <string, uint> (StringComparer.Ordinal); var managedTypes = new Dictionary <uint, uint> (); int maxJavaNameLength = 0; foreach (TypeMapEntry entry in moduleData.Types) { javaNames.Add(entry.JavaName, entry.Token); if (entry.JavaNameLength > maxJavaNameLength) { maxJavaNameLength = entry.JavaNameLength; } managedTypes.Add(entry.Token, 0); } var javaNameList = javaNames.Keys.ToList(); foreach (TypeMapEntry entry in moduleData.Types) { var javaIndex = (uint)javaNameList.IndexOf(entry.JavaName); managedTypes[entry.Token] = javaIndex; } bw.Write(javaNames.Count); bw.Write(moduleData.DuplicateTypes.Count); bw.Write(maxJavaNameLength + 1); string assemblyName = moduleData.Assembly.Name.Name; bw.Write(assemblyName.Length); bw.Write(outputEncoding.GetBytes(assemblyName)); var sortedJavaNames = javaNames.Keys.ToArray(); Array.Sort(sortedJavaNames, StringComparer.Ordinal); foreach (string typeName in sortedJavaNames) { byte[] bytes = outputEncoding.GetBytes(typeName); bw.Write(bytes); PadField(bw, bytes.Length, maxJavaNameLength + 1); bw.Write(javaNames[typeName]); } WriteManagedTypes(managedTypes); if (moduleData.DuplicateTypes.Count == 0) { return; } var managedDuplicates = new Dictionary <uint, uint> (); foreach (var kvp in moduleData.DuplicateTypes) { uint javaIndex = kvp.Key; uint typeId = kvp.Value.Token; managedDuplicates.Add(javaIndex, typeId); } WriteManagedTypes(managedDuplicates); void WriteManagedTypes(IDictionary <uint, uint> types) { var sortedTokens = types.Keys.ToArray(); Array.Sort(sortedTokens); foreach (uint token in sortedTokens) { bw.Write(token); bw.Write(types[token]); } } }
internal override void PopulateData(ModuleData moduleData) { _data = new ModulePhysicsSettingsData((ModulePhysicsSettingsData)moduleData); ApplyData(); }
internal abstract void PopulateData(ModuleData moduleData);
/// <summary> /// Injects our monitor into the assembly. /// </summary> /// <param name="module">The module to inject.</param> public void Inject(ModuleData module) { }
internal AssemblyData(ModuleData moduleData) { ModuleData = moduleData; Assembly = null; }
int WalkTree(Module module, Dictionary<Module, ModuleData> map, int depth = 0) { int maxChildSources = 0; int childDepth = 0; foreach (var source in module.SourceModules) { int d = WalkTree(source, map, depth + 1); if (d > childDepth) childDepth = d; maxChildSources += map[source].MaxSources; } var nc = new NoiseControl() { Module = module, }; map[module] = new ModuleData() { MaxSources = Math.Max(maxChildSources, 1), Depth = depth, Control = nc, }; m_controls.Add(nc); return childDepth + 1; }
private void Start() { Instance = this; transform.Find("Prefabs").gameObject.SetActive(false); twitchGame = GetComponentInChildren <TwitchGame>(true); twitchGame.twitchBombPrefab = GetComponentInChildren <TwitchBomb>(true); twitchGame.twitchModulePrefab = GetComponentInChildren <TwitchModule>(true); twitchGame.moduleCamerasPrefab = GetComponentInChildren <ModuleCameras>(true); TwitchGame.Instance = twitchGame; GameRoom.InitializeSecondaryCamera(); _gameInfo = GetComponent <KMGameInfo>(); _gameInfo.OnStateChange += OnStateChange; CoroutineQueue = GetComponent <CoroutineQueue>(); Leaderboard.Instance.LoadDataFromFile(); LeaderboardController.Install(); ModuleData.LoadDataFromFile(); ModuleData.WriteDataToFile(); AuditLog.SetupLog(); MainThreadQueue.Initialize(); TwitchPlaySettings.LoadDataFromFile(); MusicPlayer.LoadMusic(); IRCConnection.Instance.OnMessageReceived.AddListener(OnMessageReceived); twitchGame.ParentService = this; TwitchPlaysAPI.Setup(); GameObject infoObject = new GameObject("TwitchPlays_Info"); infoObject.transform.parent = gameObject.transform; _publicProperties = infoObject.AddComponent <TwitchPlaysProperties>(); _publicProperties.TwitchPlaysService = this; // TODO: Useless variable? if (TwitchPlaySettings.data.SkipModManagerInstructionScreen || IRCConnection.Instance.State == IRCConnectionState.Connected) { ModManagerManualInstructionScreen.HasShownOnce = true; } UpdateUiHue(); if (TwitchPlaySettings.data.DarkMode) { HeaderBackground.color = new Color32(0x0E, 0x0E, 0x10, 0xFF); HeaderText.color = new Color32(0xEF, 0xEF, 0xEC, 0xFF); MessagesBackground.color = new Color32(0x3A, 0x3A, 0x3D, 0xFF); } else { HeaderBackground.color = new Color32(0xEE, 0xEE, 0xEE, 0xFF); HeaderText.color = new Color32(0x4F, 0x4F, 0x4F, 0xFF); MessagesBackground.color = new Color32(0xD8, 0xD8, 0xD8, 0xFF); } SetupChatSimulator(); // Delete the steam_appid.txt since it was created for a one-time steam boot. // Steam will have initialized before this. if (File.Exists("steam_appid.txt")) { File.Delete("steam_appid.txt"); } }
// public static void GetVidPid(string str, ref int vid, ref int pid) // { // var matches = Regex.Matches(str, @"VID_(\w{4})&PID_(\w{4})"); // if (matches.Count <= 0 || matches[0].Groups.Count <= 1) return; // vid = Convert.ToInt32(matches[0].Groups[1].Value, 16); // pid = Convert.ToInt32(matches[0].Groups[2].Value, 16); // } public void start() { // var stroke = new ManagedWrapper.Stroke(); // stroke.key.code = (ushort)Keys.J; // stroke.key.state = (ushort)ManagedWrapper.KeyState.Down; // int devId = 1; // ManagedWrapper.Send(_deviceContext, devId, ref stroke, 1); //use this code to determine keys // ManagedWrapper.SetFilter(deviceContext, ManagedWrapper.IsKeyboard, ManagedWrapper.Filter.All); // var stroke = new ManagedWrapper.Stroke(); // int device = 0; // while (ManagedWrapper.Receive(deviceContext, device = ManagedWrapper.Wait(deviceContext), ref stroke, 1) > 0) // { // if(ManagedWrapper.IsKeyboard(device) > 0) { // Console.WriteLine(stroke.key.code); // if(stroke.key.code == 1) // break; // } // } // ManagedWrapper.SetFilter(deviceContext, ManagedWrapper.IsKeyboard, ManagedWrapper.Filter.None); // var ret = new List<DeviceInfo>(); for (var i = 1; i < 21; i++) { var handle = ManagedWrapper.GetHardwareStr(deviceContext, i, 1000); if (handle == "") { continue; } // int foundVid = 0, foundPid = 0; // GetVidPid(handle, ref foundVid, ref foundPid); //if (foundVid == 0 || foundPid == 0) continue; // Console.WriteLine(i + " " + handle); // ret.Add(new DeviceInfo {Id = i, IsMouse = i > 10, Handle = handle}); } // foreach (var device in ret) // { // Console.WriteLine(device); // } var controllers = new[] { new Controller(), new Controller(UserIndex.One), new Controller(UserIndex.Two), new Controller(UserIndex.Three), new Controller(UserIndex.Four) }; // Get 1st controller available Controller controller = controllers[0]; foreach (var selectControler in controllers) { // Console.WriteLine(selectControler); if (selectControler.IsConnected) { controller = selectControler; break; } } if (controller == null) { Console.WriteLine("No XInput controller installed"); } else { Console.WriteLine("KeyMapper loaded"); // Console.WriteLine("Found a XInput controller available"); // Console.WriteLine("Press buttons on the controller to display events or escape key to exit... "); // Poll events from joystick SharpDX.XInput.State previousControllerState = controller.GetState(); Dictionary <Button, bool> lastSimpleGamepadState = determineSimpleButtonState(previousControllerState); StateTransition lastState = null; while (!ModuleData.getInstance().cancellationToken.IsCancellationRequested) { if (controller.IsConnected) { SharpDX.XInput.State controllerState = controller.GetState(); if (previousControllerState.PacketNumber != controllerState.PacketNumber) { // Console.WriteLine(controllerState.Gamepad); Dictionary <Button, bool> simpleGamepadState = determineSimpleButtonState(controllerState); Dictionary <Button, Settings.Action> changedState = determineStateDifferences(lastSimpleGamepadState, simpleGamepadState); printStateChanges(changedState); // Console.WriteLine(GetActiveWindowTitle()); //determine if we are transitioning to a new 'state' // this is based on the current state, the game state and the keys pressed/not pressed // NOTE: the first state wins, for speed StateTransition newState = getNewState(simpleGamepadState, ModuleData.getInstance().companionSettings.stateTransitions); if (newState == null && lastState == null) { //nothing to do } else if (newState != null && lastState == null) { activateState(newState); } else if (newState == null && lastState != null) { deactivateState(lastState); } else if (newState != null && lastState != null && !newState.transitionName.Equals(lastState.transitionName)) { deactivateState(lastState); activateState(newState); } //now that we have the state name determined, load the correct mappings StateControllerMapping stateControllerMappings = findStateControllerMappings(newState, ModuleData.getInstance().companionSettings.stateMappings); //apply button presses and such foreach (Button key in changedState.Keys) { Settings.Action action = changedState[key]; foreach (ControllerMapping controllerMapping in stateControllerMappings.controllerMappings) { if (controllerMapping.button.button == key && action == controllerMapping.button.action) { handleCommand(controllerMapping); } } } lastState = newState; lastSimpleGamepadState = simpleGamepadState; } Thread.Sleep(10); previousControllerState = controllerState; } } } }
private void OnStateChange(KMGameInfo.State state) { CurrentState = state; if (!transform.gameObject.activeInHierarchy) { return; } Votes.OnStateChange(); CheckSupport.Cleanup(); if (state != KMGameInfo.State.PostGame && _leaderboardDisplay != null) { DestroyObject(_leaderboardDisplay); _leaderboardDisplay = null; } twitchGame?.gameObject.SetActive(state == KMGameInfo.State.Gameplay); OtherModes.RefreshModes(state); // Automatically check for updates after a round is finished or when entering the setup state but never more than once per hour. bool hourPassed = DateTime.Now.Subtract(Updater.LastCheck).TotalHours >= 1; if ((state == KMGameInfo.State.PostGame || state == KMGameInfo.State.Setup) && hourPassed && !Updater.UpdateAvailable) { _coroutinesToStart.Enqueue(Updater.CheckForUpdates().Yield(() => { if (Updater.UpdateAvailable) { IRCConnection.SendMessage("There is a new update to Twitch Plays!"); } })); } switch (state) { case KMGameInfo.State.Gameplay: DefaultCamera(); LeaderboardController.DisableLeaderboards(); break; case KMGameInfo.State.Setup: DefaultCamera(); _coroutinesToStart.Enqueue(VanillaRuleModifier.Refresh()); _coroutinesToStart.Enqueue(MultipleBombs.Refresh()); _coroutinesToStart.Enqueue(FactoryRoomAPI.Refresh()); if (!initialLoad) { initialLoad = true; _coroutinesToStart.Enqueue(ComponentSolverFactory.LoadDefaultInformation(true)); _coroutinesToStart.Enqueue(Repository.LoadData()); if (TwitchPlaySettings.data.TestModuleCompatibility && !TwitchPlaySettings.data.TwitchPlaysDebugEnabled) { _coroutinesToStart.Enqueue(CheckSupport.FindSupportedModules()); } } // Clear out the retry reward if we return to the setup room since the retry button doesn't return to setup. // A post game run command would set the retry bonus and then return to the setup room to start the mission, so we don't want to clear that. if (TwitchPlaySettings.GetRewardBonus() == 0) { TwitchPlaySettings.ClearRetryReward(); } break; case KMGameInfo.State.PostGame: DefaultCamera(); if (_leaderboardDisplay == null) { _leaderboardDisplay = Instantiate(TwitchLeaderboardPrefab); } Leaderboard.Instance.SaveDataToFile(); break; case KMGameInfo.State.Transitioning: ModuleData.LoadDataFromFile(); TwitchPlaySettings.LoadDataFromFile(); var pageManager = SceneManager.Instance?.SetupState?.Room.GetComponent <SetupRoom>().BombBinder.MissionTableOfContentsPageManager; if (pageManager != null) { var tableOfContentsList = pageManager.GetValue <List <Assets.Scripts.BombBinder.MissionTableOfContents> >("tableOfContentsList"); if (tableOfContentsList[SetupState.LastBombBinderTOCIndex].ToCID == "toc_tp_search") { SetupState.LastBombBinderTOCIndex = 0; SetupState.LastBombBinderTOCPage = 0; } } break; } StopEveryCoroutine(); }
protected override bool ValidateData(FixedContainer context, ModuleData data, [NotNullWhen(false)] out string?error) { // We could potentially validate that it contains non-control-character ASCII... error = null; return(true); }
public override void Reset(FixedContainer context, ModuleData data) => TrySetText(context, data, new string(' ', Length));
private void InitializeSymbolReader(ModuleData moduleData) { if (_pdbSymbolProvider == null) _pdbSymbolProvider = new PdbSymbolProvider(); moduleData.PdbReader = _pdbSymbolProvider.GetSymbolReaderForFile(moduleData.Path); }
public virtual IEnumerable <Site> AllSitesInModule(string moduleName) { return(ModuleData.GetSitesInModule(moduleName).Select(it => new Site(it).AsActual()).Where(it => it != null)); }
/// <summary> /// Loads a module. /// </summary> /// <param name="dllFile">The path to the module DLL file.</param> /// <param name="xmlFile">The path to the module XML configuration file.</param> /// <param name="startImmediately">True if execution should be started immediately after configuring the module, false if module should be configured but not started.</param> private static void LoadAndConfigure(string dllFile, string xmlFile, bool startImmediately) { string modulePath = Path.GetDirectoryName(dllFile); if (!modulePath.EndsWith(Path.DirectorySeparatorChar.ToString())) { modulePath += Path.DirectorySeparatorChar; } string[] files = Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories); AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ShadowCopyFiles = "true"; domainSetup.ApplicationBase = modulePath; domainSetup.ConfigurationFile = dllFile + ".config"; AppDomain domain = AppDomain.CreateDomain(dllFile, null, domainSetup); TaskManagerService.Logger.Log(string.Format("Module found: '{0}', configuration file: '{1}', scanning assembly for tasks...", dllFile, xmlFile)); if (modulePath != AppDomain.CurrentDomain.BaseDirectory) { string loaderDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll"); string tempLoaderDll = Path.Combine(modulePath, "TaskManager.Loader.dll"); string commonDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Common.dll"); string tempCommonDll = Path.Combine(modulePath, "TaskManager.Common.dll"); File.Copy(loaderDll, tempLoaderDll, true); File.Copy(commonDll, tempCommonDll, true); } AssemblyName loaderAssemblyName = AssemblyName.GetAssemblyName(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll")); Loader loader = (Loader)domain.CreateInstanceAndUnwrap(loaderAssemblyName.ToString(), "TaskManager.Loader"); TaskWrapper[] tasks = loader.LoadAndConfigure(dllFile, xmlFile, TaskManagerService.Logger, AppDomain.CurrentDomain.BaseDirectory); ModuleData newModule = new ModuleData(); newModule.BasePath = Path.GetDirectoryName(dllFile); newModule.Tasks = tasks; newModule.DllFile = dllFile; newModule.XmlFile = xmlFile; newModule.Files = new List<string>(files); newModule.Domain = domain; if (startImmediately) { foreach (TaskWrapper task in newModule.Tasks) { TaskSupervisor.ScheduleTask(task); } } _moduleList.Add(newModule); }
protected override void SetupInternal(Entity Parent, ModuleData MD) { this.Parent = (Unit)Parent; CondClass = MD.Data[0]; int.TryParse(MD.Data[1], out CondDmg); }
internal override void PopulateData(ModuleData moduleData) { _data = new ModuleLogicLinkData((ModuleLogicLinkData)moduleData); ApplyData(); }
private void LoadModuleMembers(string assemblyName) { Assembly assembly = CodeAssistTools.LoadAssembly(assemblyName); if (assembly == null) { return; } foreach (System.Reflection.Module module in assembly.GetModules()) { string moduleName = module.Name; // Remove '.dll' if (moduleName.Length > 4) { moduleName = moduleName.Substring( 0, moduleName.Length - 4); } bool isWorkspaceAssembly = false; if (assemblyName[0] == '@') { isWorkspaceAssembly = true; } else if (assemblyName[0] == '?' && moduleName.Length > 37) { // 'LoadFile' context, remove local cache signature. moduleName = moduleName.Substring(37); isWorkspaceAssembly = true; } ModuleData moduleData = new ModuleData(); moduleData.Name = moduleName; moduleData.FullName = module.FullyQualifiedName; moduleData.IsWorkspaceAssembly = isWorkspaceAssembly; moduleData.Module = module; /* * Gather all the namespaces in the module. As * always we have to do this the hard way by * looking at each type and adding each new * namespace to the list. */ try { foreach (Type type in module.GetTypes()) { if (type.IsNested) { continue; } if (_hideNonPublicMembers && type.IsNotPublic) { continue; } string namespaceName = type.Namespace; if (String.IsNullOrEmpty(namespaceName)) { continue; } if (!isWorkspaceAssembly && !_referenceManager.FullNamespaceList. Contains(namespaceName)) { continue; } if (!moduleData.NamespaceNodes. ContainsKey(namespaceName)) { moduleData.NamespaceNodes[namespaceName] = new List <TreeNode>(); } } } catch { // Just skip problematic modules. } _modules[moduleName] = moduleData; } }
public virtual bool SiteIsInModule(string moduleName, string siteName) { return(ModuleData.GetSitesInModule(moduleName).Contains(siteName, StringComparer.OrdinalIgnoreCase)); }
private void GetNamespaceTypes(TreeNode node) { node.Nodes.Clear(); // Keep track of found types so we don't add dupes. List <string> typeNames = new List <string>(); /* * Go through each assembly containing the namespace * and get the types contained within it. */ List <string> assemblyNames = new List <string>(); /* * If using namespace view add all assemblies containing the * namespace, otherwise just include the selected assembly. */ if (_showModules) { if (node.Parent != null) { /* * Add the selected assembly. */ ModuleData moduleData = node.Parent.Tag as ModuleData; if (moduleData != null) { Assembly assembly = moduleData.Module.Assembly; if (!moduleData.IsWorkspaceAssembly) { assemblyNames.Add(assembly.FullName); } else { assemblyNames.Add("?" + moduleData.FullName); } } } } else { /* * Add the assemblies that are known to cantain the namespace * and all the local ones (no way of telling if they do). */ assemblyNames.AddRange( _referenceManager.GetNamespaceAssemblies(node.Text)); if (_includeWorkspace) { assemblyNames.AddRange(_workspaceAssemblies); } } foreach (string name in assemblyNames) { Assembly assembly = CodeAssistTools.LoadAssembly(name); if (assembly == null) { continue; } try { foreach (Type type in assembly.GetTypes()) { if (typeNames.Contains(type.FullName)) { continue; } if (type.IsNested) { continue; } if (_hideNonPublicMembers && type.IsNotPublic) { continue; } // Reject types not in the namespace we're looking for. if (String.IsNullOrEmpty(type.Namespace)) { continue; } if (type.Namespace != node.Text) { continue; } string typeName = CSharpFormattingTools.GetTypeSignature(type); TreeNode typeNode = CreateTreeNode(type, typeName); node.Nodes.Add(typeNode); typeNames.Add(type.FullName); AddNestedTypes(type, typeName, node); } } catch { // Just suppress any errors from problematic assemblies. } } }
internal virtual void ResolveFields(ModuleData data, FieldContainer container) { }
public void ModuleSelect(ModuleData moduleData) { Data.StartModule(moduleData, moduleData.ModuleType); Done(); }
public bool Generate(List <TypeDefinition> javaTypes, string outputDirectory, bool generateNativeAssembly) { if (String.IsNullOrEmpty(outputDirectory)) { throw new ArgumentException("must not be null or empty", nameof(outputDirectory)); } if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } int assemblyId = 0; int maxJavaNameLength = 0; int maxModuleFileNameLength = 0; var knownAssemblies = new Dictionary <string, int> (StringComparer.Ordinal); var tempModules = new Dictionary <byte[], ModuleData> (); Dictionary <AssemblyDefinition, int> moduleCounter = null; var mvidCache = new Dictionary <Guid, byte[]> (); foreach (TypeDefinition td in javaTypes) { string assemblyName = td.Module.Assembly.FullName; if (!knownAssemblies.ContainsKey(assemblyName)) { assemblyId++; knownAssemblies.Add(assemblyName, assemblyId); } // We must NOT use Guid here! The reason is that Guid sort order is different than its corresponding // byte array representation and on the runtime we need the latter in order to be able to binary search // through the module array. byte[] moduleUUID; if (!mvidCache.TryGetValue(td.Module.Mvid, out moduleUUID)) { moduleUUID = td.Module.Mvid.ToByteArray(); mvidCache.Add(td.Module.Mvid, moduleUUID); } ModuleData moduleData; if (!tempModules.TryGetValue(moduleUUID, out moduleData)) { if (moduleCounter == null) { moduleCounter = new Dictionary <AssemblyDefinition, int> (); } moduleData = new ModuleData { Mvid = td.Module.Mvid, MvidBytes = moduleUUID, Assembly = td.Module.Assembly, AssemblyName = td.Module.Assembly.Name.Name, TypesScratch = new Dictionary <string, TypeMapEntry> (StringComparer.Ordinal), DuplicateTypes = new Dictionary <uint, TypeMapEntry> (), }; tempModules.Add(moduleUUID, moduleData); if (!generateNativeAssembly) { int moduleNum; if (!moduleCounter.TryGetValue(moduleData.Assembly, out moduleNum)) { moduleNum = 0; moduleCounter [moduleData.Assembly] = 0; } else { moduleNum++; moduleCounter [moduleData.Assembly] = moduleNum; } string fileName = $"{moduleData.Assembly.Name.Name}.{moduleNum}.typemap"; moduleData.OutputFilePath = Path.Combine(outputDirectory, fileName); if (maxModuleFileNameLength < fileName.Length) { maxModuleFileNameLength = fileName.Length; } } } string javaName = Java.Interop.Tools.TypeNameMappings.JavaNativeTypeManager.ToJniName(td); var entry = new TypeMapEntry { JavaName = javaName, JavaNameLength = outputEncoding.GetByteCount(javaName), ManagedTypeName = td.FullName, Token = td.MetadataToken.ToUInt32(), AssemblyNameIndex = knownAssemblies [assemblyName] }; if (generateNativeAssembly) { if (entry.JavaNameLength > maxJavaNameLength) { maxJavaNameLength = entry.JavaNameLength; } } if (moduleData.TypesScratch.ContainsKey(entry.JavaName)) { // This is disabled because it costs a lot of time (around 150ms per standard XF Integration app // build) and has no value for the end user. The message is left here because it may be useful to us // in our devloop at some point. //logger ($"Warning: duplicate Java type name '{entry.JavaName}' in assembly '{moduleData.AssemblyName}' (new token: {entry.Token})."); moduleData.DuplicateTypes.Add(entry.Token, entry); } else { moduleData.TypesScratch.Add(entry.JavaName, entry); } } var modules = tempModules.Values.ToArray(); Array.Sort(modules, new ModuleUUIDArrayComparer()); var typeMapEntryComparer = new TypeMapEntryArrayComparer(); foreach (ModuleData module in modules) { if (module.TypesScratch.Count == 0) { module.Types = new TypeMapEntry[0]; continue; } module.Types = module.TypesScratch.Values.ToArray(); Array.Sort(module.Types, typeMapEntryComparer); } NativeTypeMappingData data; if (!generateNativeAssembly) { string typeMapIndexPath = Path.Combine(outputDirectory, "typemap.index"); // Try to approximate the index size: // 16 bytes for the header // 16 bytes (UUID) + filename length per each entry using (var ms = new MemoryStream(16 + (modules.Length * (16 + 128)))) { using (var indexWriter = new BinaryWriter(ms)) { OutputModules(outputDirectory, modules, indexWriter, maxModuleFileNameLength + 1); indexWriter.Flush(); MonoAndroidHelper.CopyIfStreamChanged(ms, typeMapIndexPath); } } GeneratedBinaryTypeMaps.Add(typeMapIndexPath); data = new NativeTypeMappingData(logger, new ModuleData[0], 0); } else { data = new NativeTypeMappingData(logger, modules, maxJavaNameLength + 1); } NativeAssemblerTargetProvider asmTargetProvider; bool sharedBitsWritten = false; bool sharedIncludeUsesAbiPrefix; foreach (string abi in supportedAbis) { sharedIncludeUsesAbiPrefix = false; switch (abi.Trim()) { case "armeabi-v7a": asmTargetProvider = new ARMNativeAssemblerTargetProvider(is64Bit: false); sharedIncludeUsesAbiPrefix = true; // ARMv7a is "special", it uses different directive prefix // than the others and the "shared" code won't build for it break; case "arm64-v8a": asmTargetProvider = new ARMNativeAssemblerTargetProvider(is64Bit: true); break; case "x86": asmTargetProvider = new X86NativeAssemblerTargetProvider(is64Bit: false); break; case "x86_64": asmTargetProvider = new X86NativeAssemblerTargetProvider(is64Bit: true); break; default: throw new InvalidOperationException($"Unknown ABI {abi}"); } var generator = new TypeMappingNativeAssemblyGenerator(asmTargetProvider, data, Path.Combine(outputDirectory, "typemaps"), sharedBitsWritten, sharedIncludeUsesAbiPrefix); using (var sw = MemoryStreamPool.Shared.CreateStreamWriter(outputEncoding)) { generator.Write(sw); sw.Flush(); MonoAndroidHelper.CopyIfStreamChanged(sw.BaseStream, generator.MainSourceFile); if (!sharedIncludeUsesAbiPrefix) { sharedBitsWritten = true; } } } return(true); }
public ActionResult Delete(int ModuleId) { Module module = ModuleData.Fetch(ModuleId); return(PartialView("Delete", module)); }
public override void Deserialize(ModuleData data) { base.Deserialize(data); segment = data.segment; }
public ActionResult Edit(int ModuleId) { Module module = ModuleData.Fetch(ModuleId); return(PartialView("Edit", module)); }
private EcmaModule AddModule(string filePath, string expectedSimpleName, byte[] moduleDataBytes, bool useForBinding, bool throwIfNotLoadable = true) { MemoryMappedViewAccessor mappedViewAccessor = null; PdbSymbolReader pdbReader = null; try { PEReader peReader = OpenPEFile(filePath, moduleDataBytes, out mappedViewAccessor); if ((!peReader.HasMetadata) && !throwIfNotLoadable) { return(null); } pdbReader = OpenAssociatedSymbolFile(filePath, peReader); EcmaModule module = EcmaModule.Create(this, peReader, containingAssembly: null, pdbReader); MetadataReader metadataReader = module.MetadataReader; string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name); ModuleData moduleData = new ModuleData() { SimpleName = simpleName, FilePath = filePath, Module = module, MappedViewAccessor = mappedViewAccessor }; lock (this) { if (useForBinding) { ModuleData actualModuleData; if (!_simpleNameHashtable.TryGetValue(moduleData.SimpleName, out actualModuleData)) { _simpleNameHashtable.Add(moduleData.SimpleName, moduleData); actualModuleData = moduleData; } if (actualModuleData != moduleData) { if (actualModuleData.FilePath != filePath) { throw new FileNotFoundException("Module with same simple name already exists " + filePath); } return(actualModuleData.Module); } } mappedViewAccessor = null; // Ownership has been transfered pdbReader = null; // Ownership has been transferred _moduleHashtable.AddOrGetExisting(moduleData); } return(module); } catch when(!throwIfNotLoadable) { return(null); } finally { if (mappedViewAccessor != null) { mappedViewAccessor.Dispose(); } if (pdbReader != null) { pdbReader.Dispose(); } } }
public SlangStoreRoutinesVisitor(SourceCodeTable table, ModuleData module) : base(table, module) { moduleItem = table.Modules[module.Name]; }
public void LoadData(CLIFile pFile) { int token = 0; if (pFile.MethodDefTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.FieldTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.TypeRefTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.TypeDefTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.ParamTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.InterfaceImplTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.MemberRefTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.ModuleTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.DeclSecurityTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.PropertyTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.EventTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.StandAloneSigTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.ModuleRefTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.TypeSpecTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.AssemblyTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.AssemblyRefTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.FileTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.ExportedTypeTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.ManifestResourceTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.GenericParamTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.GenericParamConstraintTable.Length > HasCustomAttributeTypeMax16BitRows || pFile.MethodSpecTable.Length > HasCustomAttributeTypeMax16BitRows) token = pFile.ReadInt32(); else token = pFile.ReadUInt16(); Type = (HasCustomAttributeType)(token & HasCustomAttributeTypeMask); token = (token >> HasCustomAttributeTypeBits) - 1; if (token >= 0) { switch (Type) { case HasCustomAttributeType.MethodDef: MethodDef = pFile.MethodDefTable[token]; break; case HasCustomAttributeType.Field: Field = pFile.FieldTable[token]; break; case HasCustomAttributeType.TypeRef: TypeRef = pFile.TypeRefTable[token]; break; case HasCustomAttributeType.TypeDef: TypeDef = pFile.TypeDefTable[token]; break; case HasCustomAttributeType.Param: Param = pFile.ParamTable[token]; break; case HasCustomAttributeType.InterfaceImpl: InterfaceImpl = pFile.InterfaceImplTable[token]; break; case HasCustomAttributeType.MemberRef: MemberRef = pFile.MemberRefTable[token]; break; case HasCustomAttributeType.Module: Module = pFile.ModuleTable[token]; break; case HasCustomAttributeType.DeclSecurity: DeclSecurity = pFile.DeclSecurityTable[token]; break; case HasCustomAttributeType.Property: Property = pFile.PropertyTable[token]; break; case HasCustomAttributeType.Event: Event = pFile.EventTable[token]; break; case HasCustomAttributeType.StandAloneSig: StandAloneSig = pFile.StandAloneSigTable[token]; break; case HasCustomAttributeType.ModuleRef: ModuleRef = pFile.ModuleRefTable[token]; break; case HasCustomAttributeType.TypeSpec: TypeSpec = pFile.TypeSpecTable[token]; break; case HasCustomAttributeType.Assembly: Assembly = pFile.AssemblyTable[token]; break; case HasCustomAttributeType.AssemblyRef: AssemblyRef = pFile.AssemblyRefTable[token]; break; case HasCustomAttributeType.File: File = pFile.FileTable[token]; break; case HasCustomAttributeType.ExportedType: ExportedType = pFile.ExportedTypeTable[token]; break; case HasCustomAttributeType.ManifestResource: ManifestResource = pFile.ManifestResourceTable[token]; break; case HasCustomAttributeType.GenericParam: GenericParam = pFile.GenericParamTable[token]; break; case HasCustomAttributeType.GenericParamConstraint: GenericParamConstraint = pFile.GenericParamConstraintTable[token]; break; case HasCustomAttributeType.MethodSpec: MethodSpec = pFile.MethodSpecTable[token]; break; default: throw new BadImageFormatException("HasCustomAttribute Type"); } } }
public void Init() { Data.InitializeDirectory(ModuleData.GetRelativePath("ecoregions")); parser = new DatasetParser(); }
private void AddModule(string simpleName, string filePath, EcmaModule module) { _modules.Add(simpleName, module); ModuleData moduleData = new ModuleData() { Path = filePath }; InitializeSymbolReader(moduleData); _moduleData.Add(module, moduleData); }
static IEnumerator TestComponents(IEnumerable <BombComponent> untestedComponents, Dictionary <string, string> nameMap) { GameObject fakeModule = new GameObject(); gameObjects.Add(fakeModule); TwitchModule module = fakeModule.AddComponent <TwitchModule>(); module.enabled = false; HashSet <string> unsupportedModules = new HashSet <string>(); Dictionary <string, bool> supportStatus = new Dictionary <string, bool>(); ComponentSolverFactory.SilentMode = true; // Try to create a ComponentSolver for each module so we can see what modules are supported. foreach (BombComponent bombComponent in untestedComponents) { ComponentSolver solver = null; try { module.BombComponent = bombComponent.GetComponent <BombComponent>(); solver = ComponentSolverFactory.CreateSolver(module); module.StopAllCoroutines(); // Stop any coroutines to prevent any exceptions or from affecting the next module. } catch (Exception e) { DebugHelper.LogException(e, $"Couldn't create a component solver for \"{bombComponent.GetModuleDisplayName()}\" during startup for the following reason:"); } ModuleData.DataHasChanged |= solver != null; DebugHelper.Log(solver != null ? $"Found a solver of type \"{solver.GetType().FullName}\" for component \"{bombComponent.GetModuleDisplayName()}\". This module is {(solver.UnsupportedModule ? "not supported" : "supported")} by Twitch Plays." : $"No solver found for component \"{bombComponent.GetModuleDisplayName()}\". This module is not supported by Twitch Plays."); string moduleID = bombComponent.GetComponent <KMBombModule>()?.ModuleType ?? bombComponent.GetComponent <KMNeedyModule>()?.ModuleType; if (solver?.UnsupportedModule != false && moduleID != null) { unsupportedModules.Add(moduleID); } supportStatus[bombComponent.GetModuleDisplayName()] = !(solver?.UnsupportedModule != false && moduleID != null); yield return(null); } ComponentSolverFactory.SilentMode = false; ModuleData.WriteDataToFile(); Object.Destroy(fakeModule); // Always disable the modules from the spreadsheet var disabledSheet = new GoogleSheet("https://spreadsheets.google.com/feeds/list/1G6hZW0RibjW7n72AkXZgDTHZ-LKj0usRkbAwxSPhcqA/3/public/values?alt=json", "modulename"); yield return(disabledSheet); if (disabledSheet.Success && TwitchPlaySettings.data.AllowSheetDisabledModules) { foreach (var row in disabledSheet.GetRows()) { if (!nameMap.TryGetValue(row["modulename"], out string moduleID)) { DebugHelper.Log($"Couldn't map \"{row["modulename"]}\" to a module ID when disabling modules from the spreadsheet."); continue; } unsupportedModules.Add(moduleID); } } // Using the list of unsupported module IDs stored in unsupportedModules, make a Mod Selector profile. string profilesPath = Path.Combine(Application.persistentDataPath, "ModProfiles"); if (Directory.Exists(profilesPath)) { Dictionary <string, object> profileData = new Dictionary <string, object>() { { "DisabledList", unsupportedModules }, { "Operation", 1 } }; File.WriteAllText(Path.Combine(profilesPath, "TP_Supported.json"), SettingsConverter.Serialize(profileData)); } alertProgressBar.localScale = Vector3.one; // Send a message to chat if any modules aren't marked as having support if (supportStatus.Values.Count(status => status) > 0) { var supportedList = supportStatus.Where(pair => pair.Value).Select(pair => pair.Key).Join(", "); IRCConnection.SendMessage($"Let the Scoring Team know that the following modules have TP support: {supportedList}"); alertText.text = $"These modules have TP support: {supportedList}"; yield return(new WaitForSeconds(4)); } else { alertText.text = "Support checks passed succesfully!"; yield return(new WaitForSeconds(2)); } // Log out the full results of the testing DebugHelper.Log($"Support testing results:\n{supportStatus.OrderByDescending(pair => pair.Value).Select(pair => $"{pair.Key} - {(pair.Value ? "" : "Not ")}Supported").Join("\n")}"); }
/// <summary> /// Loads a module from a zip file. /// </summary> /// <param name="zipFile">The path to the zip file.</param> /// <param name="startImmediately">True if execution should be started immediately after configuring the module, false if module should be configured but not started.</param> private static void LoadZipAndConfigure(string zipFile, bool startImmediately) { string tempPath = null; int i = 0; while (Directory.Exists(tempPath = Path.Combine(Path.Combine(Path.GetTempPath(), "TaskManager"), Path.GetRandomFileName()))) { i++; if (i == 10) throw new Exception("Failed to create a new temporary folder."); } if (!tempPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { tempPath += Path.DirectorySeparatorChar; } string overridePath = Path.Combine(Path.GetDirectoryName(zipFile), Path.GetFileNameWithoutExtension(zipFile)) + Path.DirectorySeparatorChar; string loaderDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll"); string tempLoaderDll = Path.Combine(tempPath, "TaskManager.Loader.dll"); string commonDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Common.dll"); string tempCommonDll = Path.Combine(tempPath, "TaskManager.Common.dll"); List<string> dependencies = new List<string>(); DirectoryInfo directoryInfo = Directory.CreateDirectory(tempPath); try { using (Stream fileStream = File.Open(zipFile, FileMode.Open, FileAccess.Read)) { using (ZipArchive zip = new ZipArchive(fileStream, ZipArchiveMode.Read)) { var directory = zip.Entries; foreach (var compressedFile in directory) { string destinationFile = Path.Combine(tempPath, compressedFile.FullName); string overrideFile = Path.Combine(overridePath, compressedFile.FullName); dependencies.Add(overrideFile); compressedFile.ExtractToFile(destinationFile, true); } } } if (Directory.Exists(overridePath)) { foreach (string overrideFile in Directory.GetFiles(overridePath, "*.*", SearchOption.AllDirectories)) { if (!dependencies.Contains(overrideFile)) { dependencies.Add(overrideFile); } dependencies.Add(Path.Combine(overridePath, overrideFile.Replace(tempPath, string.Empty))); string relativeName = overrideFile.Replace(overridePath, string.Empty); string destination = Path.Combine(tempPath, relativeName); string destinationPath = Path.GetDirectoryName(destination); if (!Directory.Exists(destinationPath)) { Directory.CreateDirectory(destinationPath); } File.Copy(overrideFile, destination, true); } } List<string> possibleFiles = new List<string>(); foreach (string moduleFile in Directory.GetFiles(tempPath, "*" + ModuleFileDefaultExtension, SearchOption.AllDirectories)) { string xmlFile = Path.ChangeExtension(moduleFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { possibleFiles.Add(moduleFile); } } File.Copy(loaderDll, tempLoaderDll, true); File.Copy(commonDll, tempCommonDll, true); foreach (string dllFile in possibleFiles) { string xmlFile = Path.ChangeExtension(dllFile, ConfigFileDefaultExtension); if (File.Exists(xmlFile)) { if (!xmlFile.IsValidConfigurationFile()) { continue; } string modulePath = Path.GetDirectoryName(dllFile); string[] files = Directory.GetFiles(modulePath, "*.*", SearchOption.AllDirectories); AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ShadowCopyFiles = "true"; domainSetup.ApplicationBase = tempPath; domainSetup.ConfigurationFile = dllFile + ".config"; AppDomain domain = AppDomain.CreateDomain(dllFile, null, domainSetup); TaskWrapper[] tasks = new TaskWrapper[0]; try { TaskManagerService.Logger.Log(string.Format("Module found: '{0}', configuration file: '{1}', scanning assembly for tasks...", dllFile, xmlFile)); AssemblyName loaderAssemblyName = AssemblyName.GetAssemblyName(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TaskManager.Loader.dll")); Loader loader = (Loader)domain.CreateInstanceAndUnwrap(loaderAssemblyName.ToString(), "TaskManager.Loader"); tasks = loader.LoadAndConfigure(dllFile, xmlFile, TaskManagerService.Logger, AppDomain.CurrentDomain.BaseDirectory); ModuleData newModule = new ModuleData(); newModule.BasePath = overridePath; newModule.Tasks = tasks; newModule.DllFile = dllFile; newModule.XmlFile = xmlFile; newModule.ZipFile = zipFile; newModule.ZipDirectory = tempPath; newModule.Files = new List<string>(files); newModule.Files.AddRange(dependencies); newModule.Files.Add(zipFile); newModule.Domain = domain; if (startImmediately) { foreach (TaskWrapper task in newModule.Tasks) { TaskSupervisor.ScheduleTask(task); } } _moduleList.Add(newModule); } catch (Exception ex) { foreach (TaskWrapper task in tasks) { try { TaskSupervisor.RemoveTask(task); } catch { } } AppDomain.Unload(domain); TaskManagerService.Logger.Log(string.Format("Unable to load module '{0}' from zipped file '{1}'.", dllFile, zipFile), ex); } } } foreach (ModuleData module in _moduleList) { if (module.ZipFile == zipFile) { return; } } throw new Exception(string.Format("Unable to find tasks in zipped file '{0}'.", zipFile)); } catch { try { Directory.Delete(tempPath, true); } catch (Exception ex) { TaskManagerService.Logger.Log(string.Format("Unable to remove temporary directory '{0}'.", tempPath), ex); } throw; } }
/// <summary> /// Get a module data object for the Microsoft.PowerShell.Core pseudo-module. /// The version is given as the PowerShell version. /// </summary> /// <returns>The name, version and data of the core pseudo-module.</returns> public Tuple <string, Version, ModuleData> GetCoreModuleData() { var moduleData = new ModuleData(); IEnumerable <CommandInfo> coreCommands = _pwsh.AddCommand(GcmInfo) .AddParameter("Module", CORE_MODULE_NAME) .InvokeAndClear <CommandInfo>(); var cmdletData = new JsonCaseInsensitiveStringDictionary <CmdletData>(); var functionData = new JsonCaseInsensitiveStringDictionary <FunctionData>(); foreach (CommandInfo command in coreCommands) { switch (command) { case CmdletInfo cmdlet: cmdletData.Add(cmdlet.Name, GetSingleCmdletData(cmdlet)); continue; case FunctionInfo function: functionData.Add(function.Name, GetSingleFunctionData(function)); continue; default: throw new CompatibilityAnalysisException($"Command {command.Name} in core module is of unsupported type {command.CommandType}"); } } moduleData.Cmdlets = cmdletData; moduleData.Functions = functionData; // Get default variables and core aliases out of a fresh runspace using (SMA.PowerShell freshPwsh = SMA.PowerShell.Create(RunspaceMode.NewRunspace)) { Collection <PSObject> varsAndAliases = freshPwsh.AddCommand("Get-ChildItem") .AddParameter("Path", "variable:,alias:") .InvokeAndClear(); var variables = new List <string>(); var aliases = new JsonCaseInsensitiveStringDictionary <string>(); foreach (PSObject returnedObject in varsAndAliases) { switch (returnedObject.BaseObject) { case PSVariable variable: variables.Add(variable.Name); continue; case AliasInfo alias: aliases.Add(alias.Name, GetSingleAliasData(alias)); continue; // Skip over other objects we get back, since there's no reason to throw } } moduleData.Variables = variables.ToArray(); moduleData.Aliases = aliases; } Version psVersion = _psVersion.PreReleaseLabel != null ? new Version(_psVersion.Major, _psVersion.Minor, _psVersion.Build) : (Version)_psVersion; return(new Tuple <string, Version, ModuleData>(CORE_MODULE_NAME, psVersion, moduleData)); }
/// <summary> /// Unloads a module. /// </summary> /// <param name="moduleData">The module.</param> private static void StopModule(ModuleData moduleData) { try { for (int i = moduleData.Tasks.Length - 1; i >= 0; i--) { TaskManagerService.Logger.Log(string.Format("Stopping task '{0}'...", moduleData.Tasks[i].TaskName)); TaskSupervisor.RemoveTask(moduleData.Tasks[i]); } TaskManagerService.Logger.Log(string.Format("Unloading AppDomain '{0}'...", moduleData.Domain.FriendlyName)); AppDomain.Unload(moduleData.Domain); TaskManagerService.Logger.Log("AppDomain successfully unloaded."); if (moduleData.ZipFile != null && moduleData.ZipDirectory != null) { Directory.Delete(moduleData.ZipDirectory, true); } _moduleList.Remove(moduleData); } catch (Exception e) { TaskManagerService.Logger.Log(string.Format("Exception caught while shutting down module '{0}'", moduleData.DllFile), e); throw; } }
protected override async Task <int> InvokeAsync(InvocationContext context, IStandardStreamWriter console, DeviceController device) { var path = context.ParseResult.ValueForOption <string>("path"); var switchFieldName = context.ParseResult.ValueForOption <string>("switch"); var parametersFieldName = context.ParseResult.ValueForOption <string>("parameters"); var mfxNode = device.Schema.LogicalRoot.ResolveNode(path); var mfxContainer = mfxNode.Container; var switchField = (EnumField)mfxContainer.ResolveField(switchFieldName); var parametersField = (OverlayField)mfxContainer.ResolveField(parametersFieldName); var deviceData = ModuleData.FromLogicalRootNode(mfxNode); var deviceParametersField = (OverlayDataField)deviceData.GetDataField(parametersField); console.WriteLine($"Loading original MFX data"); await device.LoadDescendants(deviceData.LogicalRoot, null, null, default); var originalSnapshot = deviceData.CreateSnapshot(); var modelData = ModuleData.FromLogicalRootNode(mfxNode); var modelTypeField = (EnumDataField)modelData.GetDataField(switchField); var modelParametersField = (OverlayDataField)modelData.GetDataField(parametersField); try { // Set it to the max value so that we'll be resetting it. await SetDeviceMfx(switchField.Max); for (int mfxType = switchField.Min; mfxType <= switchField.Max; mfxType++) { // Make the change on the device... await SetDeviceMfx(mfxType); await device.LoadDescendants(deviceData.LogicalRoot, null, null, default); // Make the change in the model... modelTypeField.RawValue = mfxType; var modelFields = modelParametersField.CurrentFieldList; var deviceFields = deviceParametersField.CurrentFieldList; if (modelFields.Description != deviceFields.Description) { console.WriteLine($"Mismatch in description: '{modelFields.Description}' != '{deviceFields.Description}'. Skipping."); continue; } console.WriteLine($"Comparing fields for {modelFields.Description}"); foreach (var(modelField, deviceField) in AsNumericFields(modelFields.Fields).Zip(AsNumericFields(deviceFields.Fields))) { if (modelField.RawValue != deviceField.RawValue) { console.WriteLine($"{modelField.SchemaField.Name}: Device={deviceField.RawValue}; Model={modelField.RawValue}"); } } console.WriteLine(); } } finally { // Restore the original data console.WriteLine($"Restoring original kit data"); deviceData.LoadSnapshot(originalSnapshot, NullLogger.Instance); await device.SaveDescendants(deviceData.LogicalRoot, targetAddress : null, progressHandler : null, CancellationToken.None); } return(0); async Task SetDeviceMfx(int type) { var segment = new DataSegment(mfxContainer.Address + switchField.Offset, new[] { (byte)type }); await device.SaveSegment(segment, CancellationToken.None); } IEnumerable <NumericDataFieldBase> AsNumericFields(IEnumerable <IDataField> fields) { foreach (var field in fields) { switch (field) { case NumericDataFieldBase numeric: yield return(numeric); break; case TempoDataField tempo: yield return(tempo.SwitchDataField); yield return(tempo.NumericDataField); yield return(tempo.MusicalNoteDataField); break; default: throw new InvalidOperationException($"Can't convert {field.GetType()} into a numeric field"); } } } }