public static bool Validate(CustomActions sourceCustomActions, CustomActions targetCustomActions, TokenParser tokenParser) { Console.WriteLine("Custom Action validation started..."); bool isSiteCustomActionsMatch = false; bool isWebCustomActionsMatch = false; if (sourceCustomActions.SiteCustomActions.Count > 0) { isSiteCustomActionsMatch = ValidateCustomActions(sourceCustomActions.SiteCustomActions, targetCustomActions.SiteCustomActions, tokenParser); Console.WriteLine("Site Custom Actions validation " + isSiteCustomActionsMatch); } if (sourceCustomActions.WebCustomActions.Count > 0) { isWebCustomActionsMatch = ValidateCustomActions(sourceCustomActions.WebCustomActions, targetCustomActions.WebCustomActions, tokenParser); Console.WriteLine("Web Custom Actions validation " + isWebCustomActionsMatch); } if (!isSiteCustomActionsMatch || !isWebCustomActionsMatch) { return(false); } else { return(true); } }
static public void AddCustomAction() { string webUrl = Shared.GetAppSettingValue("webUrl"); string userName = Shared.GetAppSettingValue("webClientUsername"); SecureString securePassword = new SecureString(); foreach (var c in Shared.GetAppSettingValue("webClientSecurePassword")) { securePassword.AppendChar(c); } using (var context = new ClientContext(webUrl)) { context.Credentials = new SharePointOnlineCredentials(userName, securePassword); context.Load(context.Web); Web web = context.Web; var lessonslearned = web.Lists.GetByTitle(LessonsLearnedLists.LESSONSLEARNEDLISTTITLE); context.Load(lessonslearned); context.ExecuteQuery(); CustomActions.AddCustomAction(lessonslearned, Shared.GetAppSettingValue("ActionUrl")); } }
public static bool Validate(CustomActions sourceCustomActions, CustomActions targetCustomActions, TokenParser tokenParser, Web web) { if (web.IsNoScriptSite()) { Console.WriteLine("Skipping validation of custom actions due to noscript site."); return(true); } Console.WriteLine("Custom Action validation started..."); bool isSiteCustomActionsMatch = false; bool isWebCustomActionsMatch = false; if (sourceCustomActions.SiteCustomActions.Count > 0) { isSiteCustomActionsMatch = ValidateCustomActions(sourceCustomActions.SiteCustomActions, targetCustomActions.SiteCustomActions, tokenParser, web); Console.WriteLine("Site Custom Actions validation " + isSiteCustomActionsMatch); } if (sourceCustomActions.WebCustomActions.Count > 0) { isWebCustomActionsMatch = ValidateCustomActions(sourceCustomActions.WebCustomActions, targetCustomActions.WebCustomActions, tokenParser, web); Console.WriteLine("Web Custom Actions validation " + isWebCustomActionsMatch); } if (!isSiteCustomActionsMatch || !isWebCustomActionsMatch) { return(false); } else { return(true); } }
public void TestSupportedLanguageOnly() { CultureInfo culture = CultureInfo.GetCultureInfo("de"); string match = CustomActions.GetDefaultLanguageCode(culture); Assert.AreEqual("de-DE", match); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { var context = web.Context as ClientContext; bool isSubSite = web.IsSubSite(); var webCustomActions = web.GetCustomActions(); var siteCustomActions = context.Site.GetCustomActions(); var customActions = new CustomActions(); foreach (var customAction in webCustomActions) { customActions.WebCustomActions.Add(CopyUserCustomAction(customAction)); } // if this is a sub site then we're not creating entities for site collection scoped custom actions if (!isSubSite) { foreach (var customAction in siteCustomActions) { customActions.SiteCustomActions.Add(CopyUserCustomAction(customAction)); } } template.CustomActions = customActions; // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate, isSubSite); } return(template); }
public void TestSupportedLanguageAndCountry() { CultureInfo culture = CultureInfo.GetCultureInfo("da-DK"); string match = CustomActions.GetDefaultLanguageCode(culture); Assert.AreEqual("da-DK", match); }
static void Main(string[] args) { bool netFramework = CustomActions.DetectNetFramework40(); bool xnaFramework = CustomActions.DetectXnaFramework40(); CustomActions.UninstallClickOnceKodu(); }
public void TestSupportedLanguageAndUnsupportedCountryWithDefaults() { CultureInfo culture = CultureInfo.GetCultureInfo("en-FK"); string match = CustomActions.GetDefaultLanguageCode(culture); // Default to English UK Assert.AreEqual("en-GB", match); }
public void TestUnsupportedLanguageOnly() { CultureInfo culture = CultureInfo.GetCultureInfo("vo-001"); string match = CustomActions.GetDefaultLanguageCode(culture); // If not supported at all, default to uk english Assert.AreEqual("en-GB", match); }
public void TestSupportedLanguageAndUnsupportedCountry() { CultureInfo culture = CultureInfo.GetCultureInfo("da-GL"); string match = CustomActions.GetDefaultLanguageCode(culture); // Default to matching language, if not country Assert.True(match.Contains("da")); }
public void AddCustomAction(string handle, string actionText) { CustomActions.Add( new CustomAction() { Handle = handle, ActionText = actionText }); }
private bool ValidateCustomActions(CustomActions srcCustomActions, CustomActions targetCustomActions, TokenParser sParser, TokenParser tParser, bool rootSite) { List <Localization> sCustomActions = LoadCustomActions(srcCustomActions, rootSite); List <Localization> tCustomActions = LoadCustomActions(targetCustomActions, rootSite); if (sCustomActions.Count > 0) { if (!Validatelocalization(sCustomActions, tCustomActions, sParser, tParser)) { return(false); } } return(true); }
public void TestMethod1() { var session = Mock.Of <ISessionWrapper>(); Mock.Get(session).Setup(s => s.Get("TransientProperties0")).Returns("CUSTOMER_NAME;GROUP_NAME;CONFIG_FILE_URL;MONITORING_SERVICE_TEMPLATE_URL;CONNECTION_STRING"); Mock.Get(session).Setup(s => s.Get("INSTALL_LOCATION")).Returns(@"d:\DEV\Cegeka.Updater\Setup\Assemblies\"); Mock.Get(session).Setup(s => s.Get("CUSTOMER_NAME")).Returns("My customer"); Mock.Get(session).Setup(s => s.Get("GROUP_NAME")).Returns("Development"); Mock.Get(session).Setup(s => s.Get("CONFIG_FILE_URL")).Returns("http://example.com/file.xml"); Mock.Get(session).Setup(s => s.Get("MONITORING_SERVICE_TEMPLATE_URL")).Returns("https://mon.cegeka.be/remote_maintenance/?token=token&reason=reason&hostname={0}&action=action"); Mock.Get(session).Setup(s => s.Get("CONNECTION_STRING")).Returns("constr"); CustomActions.ExecuteDumpPropertiesToCustomActiondata(session); CustomActions.ExecuteModifyConfigurationFile(session); }
/// <summary> /// Registers hot keys /// </summary> public static void RegisterHotKeys() { mActionHooks = new Dictionary <int, Action>(); mKeyboardHookWindow = new KeyboardHookWindow(); int hotKeyId = HK_CUP_BASE; List <string> keysToRemove = new List <string>(); foreach (KeyValuePair <string, string> hotKeyData in Preferences.HotKeys) { try { Action action = Action.GetAction(CustomActions.ContainsKey(hotKeyData.Key) ? ActionType.CustomAction : ActionType.BuiltInAction, hotKeyData.Key, true); HotKey hotKey = HotKey.Parse(hotKeyData.Value); if (hotKey != HotKey.Nil) { if (mKeyboardHookWindow.RegisterHotKey(hotKeyId, hotKey)) { mActionHooks.Add(hotKeyId++, action); Logger.WriteLine(LogLevel.Informational, "registered hotkey 0x{0:X2}: {1}, {2}", hotKeyId, hotKeyData.Key, hotKey); } else { Logger.WriteLine(LogLevel.Warning, "unable to register hotkey 0x{0:X2} - ignoring", hotKeyId); } } } catch { // may be an invalid key value pair - remove kebab Logger.WriteLine(LogLevel.Warning, "invalid hot key detected - removing"); keysToRemove.Add(hotKeyData.Key); } } foreach (string key in keysToRemove) { Preferences.HotKeys.Remove(key); } if (keysToRemove.Count > 0) { Preferences.Save(); } mKeyboardHookWindow.OnKeyboardHookTriggered += OnKeyboardHookTriggered; }
private List <Localization> LoadCustomActions(CustomActions customActions, bool rootSite) { List <Localization> locCustomActions = new List <Localization>(); if (rootSite) { foreach (CustomAction action in customActions.SiteCustomActions) { locCustomActions.Add(new Localization(action.Name, action.Title, action.Description)); } } foreach (CustomAction action in customActions.WebCustomActions) { locCustomActions.Add(new Localization(action.Name, action.Title, action.Description)); } return(locCustomActions); }
public void SetCurrentPMS_OpenDental() { // Arrange var repository = new Repository(); // Act CustomActions.Setup("OpenDental", "c:\\", "True"); // Assert var path = repository.GetSettingValue <string>(Settings.PMS.PathKey); Assert.AreEqual("C:\\Program Files (x86)\\Open Dental", path); var type = repository.GetSettingValue <Settings.PMS.Types>(Settings.PMS.TypeKey); Assert.AreEqual(Settings.PMS.Types.OpenDental, type); var isClient = repository.GetSettingValue <bool>(Settings.IsClient); Assert.IsTrue(isClient); }
public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { using (var scope = new PnPMonitoredScope(this.Name)) { var context = web.Context as ClientContext; bool isSubSite = web.IsSubSite(); var webCustomActions = web.GetCustomActions(); var siteCustomActions = context.Site.GetCustomActions(); var customActions = new CustomActions(); foreach (var customAction in webCustomActions) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_CustomActions_Adding_web_scoped_custom_action___0___to_template, customAction.Name); customActions.WebCustomActions.Add(CopyUserCustomAction(customAction)); } // if this is a sub site then we're not creating entities for site collection scoped custom actions if (!isSubSite) { foreach (var customAction in siteCustomActions) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_CustomActions_Adding_site_scoped_custom_action___0___to_template, customAction.Name); customActions.SiteCustomActions.Add(CopyUserCustomAction(customAction)); } } template.CustomActions = customActions; // If a base template is specified then use that one to "cleanup" the generated template model if (creationInfo.BaseTemplate != null) { template = CleanupEntities(template, creationInfo.BaseTemplate, isSubSite, scope); } } return(template); }
public Mapper(CustomActions <T> actions) { customActions = actions; mapper = new Default <T>(); }
public void RegisterToEndRound(CustomActions action) { EndRound.Add(action); }
public Hook(CustomActions <T> customActions) { CustomHooks = customActions; Format = "DD-MM-YYYY"; }
public void RegisterToStartRound(CustomActions action) { StartRound.Add(action); }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName)) { JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName); return; } // Parse the needs-electric-charge here. if (!string.IsNullOrEmpty(needsElectricCharge)) { switch (needsElectricCharge.ToLowerInvariant().Trim()) { case "true": case "yes": case "1": needsElectricChargeValue = true; break; case "false": case "no": case "0": needsElectricChargeValue = false; break; } } // Now parse consumeOnToggle and consumeWhileActive... if (!string.IsNullOrEmpty(consumeOnToggle)) { string[] tokens = consumeOnToggle.Split(','); if (tokens.Length == 3) { consumeOnToggleName = tokens[0].Trim(); if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null && float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out consumeOnToggleAmount))) { JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle); } switch (tokens[2].Trim().ToLower()) { case "on": consumingOnToggleUp = true; break; case "off": consumingOnToggleDown = true; break; case "both": consumingOnToggleUp = true; consumingOnToggleDown = true; break; default: JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle); break; } } } if (!string.IsNullOrEmpty(consumeWhileActive)) { string[] tokens = consumeWhileActive.Split(','); if (tokens.Length == 2) { consumeWhileActiveName = tokens[0].Trim(); if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null && float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out consumeWhileActiveAmount))) { JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive); } else { consumingWhileActive = true; JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName, internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount); } } } if (groupList.ContainsKey(actionName)) { kspAction = groupList[actionName]; currentState = vessel.ActionGroups[kspAction]; // action group switches may not belong to a radio group switchGroupIdentifier = -1; } else { isCustomAction = true; switch (actionName) { case "intlight": persistentVarName = internalLightName; if (!string.IsNullOrEmpty(internalLightName)) { Light[] availableLights = internalModel.FindModelComponents <Light>(); if (availableLights != null && availableLights.Length > 0) { List <Light> lights = new List <Light>(availableLights); for (int i = lights.Count - 1; i >= 0; --i) { if (lights[i].name != internalLightName) { lights.RemoveAt(i); } } if (lights.Count > 0) { lightObjects = lights.ToArray(); needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue; } else { actionName = "dummy"; } } } else { actionName = "dummy"; } break; case "plugin": persistentVarName = string.Empty; comp.UpdateDataRefreshRate(refreshRate); foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION")) { if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim(); actionHandler = (Action <bool>)comp.GetMethod(action, internalProp, typeof(Action <bool>)); if (actionHandler == null) { JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", action); } else { if (pluginConfig.HasValue("stateMethod")) { string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim(); stateVariable = "PLUGIN_" + state; } else if (pluginConfig.HasValue("stateVariable")) { stateVariable = pluginConfig.GetValue("stateVariable").Trim(); } isPluginAction = true; break; } } } } } if (actionHandler == null) { actionName = "dummy"; JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode."); } break; case "transfer": persistentVarName = string.Empty; comp.UpdateDataRefreshRate(refreshRate); foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("TRANSFERACTION")) { if ((pluginConfig.HasValue("name") || pluginConfig.HasValue("getVariable")) && pluginConfig.HasValue("perPodPersistenceName")) { transferPersistentName = pluginConfig.GetValue("perPodPersistenceName").Trim(); if (pluginConfig.HasValue("stateMethod")) { string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim(); stateVariable = "PLUGIN_" + state; } else if (pluginConfig.HasValue("stateVariable")) { stateVariable = pluginConfig.GetValue("stateVariable").Trim(); } if (pluginConfig.HasValue("setMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("setMethod").Trim(); transferSetter = (Action <double>)comp.GetMethod(action, internalProp, typeof(Action <double>)); if (transferSetter == null) { JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name")); } else { //JUtil.LogMessage(this, "Got setter {0}", action); break; } } else if (pluginConfig.HasValue("getMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("getMethod").Trim(); var getter = (Func <double>)comp.GetMethod(action, internalProp, typeof(Func <double>)); if (getter == null) { JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name")); } else { transferGetter = "PLUGIN_" + action; //JUtil.LogMessage(this, "Got getter {0}", action); break; } } else if (pluginConfig.HasValue("getVariable")) { transferGetter = pluginConfig.GetValue("getVariable").Trim(); } } } } } if (string.IsNullOrEmpty(transferGetter) && transferSetter == null) { actionName = "dummy"; stateVariable = string.Empty; JUtil.LogMessage(this, "Transfer handlers did not start, reverting to dummy mode."); } break; default: persistentVarName = "switch" + internalProp.propID + "_" + moduleID; break; } if (!string.IsNullOrEmpty(perPodPersistenceName)) { persistentVarName = perPodPersistenceName; } else { // If there's no persistence name, there's no valid group id for this switch switchGroupIdentifier = -1; } } if (customGroupList.ContainsKey(actionName)) { customAction = customGroupList[actionName]; } if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName) || !string.IsNullOrEmpty(transferGetter) || transferSetter != null) { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateDataRefreshRate(refreshRate); if (!string.IsNullOrEmpty(masterVariableName)) { string[] range = masterVariableRange.Split(','); if (range.Length == 2) { masterVariable = new VariableOrNumberRange(masterVariableName, range[0], range[1]); } else { masterVariable = null; } } } // set up the toggle switch if (!string.IsNullOrEmpty(switchTransform)) { if (momentarySwitch) { SmarterButton.CreateButton(internalProp, switchTransform, Click, Click); } else { SmarterButton.CreateButton(internalProp, switchTransform, Click); } } if (isCustomAction) { if (isPluginAction && !string.IsNullOrEmpty(stateVariable)) { try { currentState = (comp.ProcessVariable(stateVariable, -1).MassageToInt()) > 0; } catch { // no-op } } else { if (rpmComp != null && !string.IsNullOrEmpty(persistentVarName)) { if (switchGroupIdentifier >= 0) { int activeSwitch = rpmComp.GetVar(persistentVarName, 0); currentState = customGroupState = (switchGroupIdentifier == activeSwitch); } else { currentState = customGroupState = rpmComp.GetBool(persistentVarName, initialState); } if (customAction == CustomActions.IntLight) { // We have to restore lighting after reading the // persistent variable. SetInternalLights(customGroupState); } } } } if (rpmComp != null && !rpmComp.HasVar(persistentVarName)) { if (switchGroupIdentifier >= 0) { if (currentState) { rpmComp.SetVar(persistentVarName, switchGroupIdentifier); } } else { rpmComp.SetVar(persistentVarName, currentState); } } if (!string.IsNullOrEmpty(animationName)) { // Set up the animation Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName); if (animators.Length > 0) { anim = animators[0]; } else { JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"", animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop"); return; } anim[animationName].wrapMode = WrapMode.Once; if (currentState ^ reverse) { anim[animationName].speed = float.MaxValue; anim[animationName].normalizedTime = 0; } else { anim[animationName].speed = float.MinValue; anim[animationName].normalizedTime = 1; } anim.Play(animationName); } else if (!string.IsNullOrEmpty(coloredObject)) { // Set up the color shift. Renderer colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject); disabledColorValue = ConfigNode.ParseColor32(disabledColor); enabledColorValue = ConfigNode.ParseColor32(enabledColor); colorShiftMaterial = colorShiftRenderer.material; colorShiftMaterial.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue)); } else { JUtil.LogMessage(this, "Warning, neither color nor animation are defined in prop {0} #{1} (this may be okay).", internalProp.propName, internalProp.propID); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); if (!string.IsNullOrEmpty(loopingSound) && loopingSoundVolume > 0.0f) { loopingOutput = JUtil.SetupIVASound(internalProp, loopingSound, loopingSoundVolume, true); } startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
public void RegisterToInitRound(CustomActions action) { InitRound.Add(action); }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName)) { JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName); return; } // Parse the needs-electric-charge here. if (!string.IsNullOrEmpty(needsElectricCharge)) { switch (needsElectricCharge.ToLowerInvariant().Trim()) { case "true": case "yes": case "1": needsElectricChargeValue = true; break; case "false": case "no": case "0": needsElectricChargeValue = false; break; } } // Now parse consumeOnToggle and consumeWhileActive... if (!string.IsNullOrEmpty(consumeOnToggle)) { string[] tokens = consumeOnToggle.Split(','); if (tokens.Length == 3) { consumeOnToggleName = tokens[0].Trim(); if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null && float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out consumeOnToggleAmount))) { JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle); } switch (tokens[2].Trim().ToLower()) { case "on": consumingOnToggleUp = true; break; case "off": consumingOnToggleDown = true; break; case "both": consumingOnToggleUp = true; consumingOnToggleDown = true; break; default: JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle); break; } } } if (!string.IsNullOrEmpty(consumeWhileActive)) { string[] tokens = consumeWhileActive.Split(','); if (tokens.Length == 2) { consumeWhileActiveName = tokens[0].Trim(); if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null && float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out consumeWhileActiveAmount))) { JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive); } else { consumingWhileActive = true; JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName, internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount); } } } if (groupList.ContainsKey(actionName)) { kspAction = groupList[actionName]; currentState = vessel.ActionGroups[kspAction]; // action group switches may not belong to a radio group switchGroupIdentifier = -1; } else { isCustomAction = true; switch (actionName) { case "intlight": persistentVarName = internalLightName; lightObjects = internalModel.FindModelComponents<Light>(); needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue; break; case "plugin": persistentVarName = string.Empty; comp.UpdateDataRefreshRate(refreshRate); foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION")) { if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim(); actionHandler = (Action<bool>)comp.GetMethod(action, internalProp, typeof(Action<bool>)); if (actionHandler == null) { JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", action); } else { if (pluginConfig.HasValue("stateMethod")) { string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim(); stateVariable = "PLUGIN_" + state; } else if(pluginConfig.HasValue("stateVariable")) { stateVariable = pluginConfig.GetValue("stateVariable").Trim(); } isPluginAction = true; break; } } } } } if (actionHandler == null) { actionName = "dummy"; JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode."); } break; case "transfer": persistentVarName = string.Empty; comp.UpdateDataRefreshRate(refreshRate); foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP")) { if (node.GetValue("name") == internalProp.propName) { foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("TRANSFERACTION")) { if (pluginConfig.HasValue("name") && pluginConfig.HasValue("perPodPersistenceName")) { transferPersistentName = pluginConfig.GetValue("perPodPersistenceName").Trim(); if (pluginConfig.HasValue("stateMethod")) { string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim(); stateVariable = "PLUGIN_" + state; } else if (pluginConfig.HasValue("stateVariable")) { stateVariable = pluginConfig.GetValue("stateVariable").Trim(); } if (pluginConfig.HasValue("setMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("setMethod").Trim(); transferSetter = (Action<double>)comp.GetMethod(action, internalProp, typeof(Action<double>)); if (transferSetter == null) { JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name")); } else { //JUtil.LogMessage(this, "Got setter {0}", action); break; } } else if (pluginConfig.HasValue("getMethod")) { string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("getMethod").Trim(); transferGetter = (Func<double>)comp.GetMethod(action, internalProp, typeof(Func<double>)); if (transferGetter == null) { JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name")); } else { //JUtil.LogMessage(this, "Got getter {0}", action); break; } } } } } } if (transferGetter == null && transferSetter == null) { actionName = "dummy"; stateVariable = string.Empty; JUtil.LogMessage(this, "Transfer handlers did not start, reverting to dummy mode."); } break; default: persistentVarName = "switch" + internalProp.propID + "_" + moduleID; break; } if (!string.IsNullOrEmpty(perPodPersistenceName)) { persistentVarName = perPodPersistenceName; } else { // If there's no persistence name, there's no valid group id for this switch switchGroupIdentifier = -1; } } if (customGroupList.ContainsKey(actionName)) { customAction = customGroupList[actionName]; } if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName) || transferGetter != null || transferSetter != null) { rpmComp = RasterPropMonitorComputer.Instantiate(internalProp); comp.UpdateDataRefreshRate(refreshRate); if (!string.IsNullOrEmpty(masterVariableName)) { string[] range = masterVariableRange.Split(','); if (range.Length == 2) { masterVariable = new VariableOrNumberRange(masterVariableName, range[0], range[1]); } else { masterVariable = null; } } } // set up the toggle switch if (!string.IsNullOrEmpty(switchTransform)) { SmarterButton.CreateButton(internalProp, switchTransform, Click); } if (isCustomAction) { if (isPluginAction && !string.IsNullOrEmpty(stateVariable)) { try { currentState = ((int)comp.ProcessVariable(stateVariable, -1)) > 0; } catch { // no-op } } else { if (rpmComp != null && !string.IsNullOrEmpty(persistentVarName)) { if (switchGroupIdentifier >= 0) { int activeSwitch = rpmComp.GetVar(persistentVarName, 0); currentState = customGroupState = (switchGroupIdentifier == activeSwitch); } else { currentState = customGroupState = rpmComp.GetBool(persistentVarName, initialState); } if (customAction == CustomActions.IntLight) { // We have to restore lighting after reading the // persistent variable. SetInternalLights(customGroupState); } } } } if (rpmComp != null && !rpmComp.HasVar(persistentVarName)) { if (switchGroupIdentifier >= 0) { if (currentState) { rpmComp.SetVar(persistentVarName, switchGroupIdentifier); } } else { rpmComp.SetVar(persistentVarName, currentState); } } if (!string.IsNullOrEmpty(animationName)) { // Set up the animation Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName); if (animators.Length > 0) { anim = animators[0]; } else { JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"", animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop"); return; } anim[animationName].wrapMode = WrapMode.Once; if (currentState ^ reverse) { anim[animationName].speed = float.MaxValue; anim[animationName].normalizedTime = 0; } else { anim[animationName].speed = float.MinValue; anim[animationName].normalizedTime = 1; } anim.Play(animationName); } else if (!string.IsNullOrEmpty(coloredObject)) { // Set up the color shift. colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject); disabledColorValue = ConfigNode.ParseColor32(disabledColor); enabledColorValue = ConfigNode.ParseColor32(enabledColor); colorShiftRenderer.material.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue)); } else { JUtil.LogMessage(this, "Warning, neither color nor animation are defined in prop {0} #{1} (this may be okay).", internalProp.propName, internalProp.propID); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
/// <summary> /// Watches the action directory for changes and performs the pertinent tasks /// </summary> private static void WatchActionDirectory() { FileSystemWatcher watcher = new FileSystemWatcher(Path.Combine(AppDirectory, "Actions")) { IncludeSubdirectories = true, EnableRaisingEvents = true, NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size }; watcher.Deleted += delegate(object sender, FileSystemEventArgs args) { string key = Path.GetFileNameWithoutExtension(args.Name); Logger.WriteLine(LogLevel.Verbose, "action has been deleted: {0}", key); if (CustomActions.ContainsKey(key)) { CustomActions.Remove(key); } if (Preferences.ActionType == ActionType.CustomAction && Preferences.ActionName == key) { Preferences tempPreferences = new Preferences(); Preferences.ActionType = tempPreferences.ActionType; Preferences.ActionName = tempPreferences.ActionName; UnregisterHotKeys(); RegisterHotKeys(); Preferences.Save(); } UpdatePreferencesDialog(); }; watcher.Changed += delegate(object sender, FileSystemEventArgs args) { string key = Path.GetFileNameWithoutExtension(args.Name); Logger.WriteLine(LogLevel.Verbose, "action has been updated: {0}", key); if (CustomActions.ContainsKey(key)) { CustomActions.Remove(key); } CustomAction action = DeserializeAction(args.FullPath); if (action != null) { CustomActions[key] = action; } UpdatePreferencesDialog(); }; watcher.Renamed += delegate(object sender, RenamedEventArgs args) { string key = Path.GetFileNameWithoutExtension(args.Name), oldKey = Path.GetFileNameWithoutExtension(args.OldName); Logger.WriteLine(LogLevel.Verbose, "action has been renamed: {0} -> {1}", oldKey, key); if (CustomActions.ContainsKey(oldKey)) { CustomActions.Add(key, CustomActions[oldKey]); CustomActions.Remove(oldKey); } if (Preferences.ActionType == ActionType.CustomAction && Preferences.ActionName == oldKey) { Preferences.ActionName = key; Logger.WriteLine(LogLevel.Informational, "new user action set: {0} -> {1}", oldKey, key); Preferences.Save(); } UpdatePreferencesDialog(); }; watcher.Created += delegate(object sender, FileSystemEventArgs args) { string key = Path.GetFileNameWithoutExtension(args.Name); Logger.WriteLine(LogLevel.Verbose, "created action: {0}", key); if (!CustomActions.ContainsKey(key)) { Logger.WriteLine(LogLevel.Verbose, "unregistering previous conflicting action"); CustomAction action = DeserializeAction(args.FullPath); if (action != null) { CustomActions[key] = action; } UpdatePreferencesDialog(); } ; }; new Thread(new ThreadStart(() => { try { watcher.WaitForChanged(WatcherChangeTypes.All); Logger.WriteLine(LogLevel.Verbose, "watching action directory"); } catch { Logger.WriteLine(LogLevel.Warning, "failed to watch action directory"); } })).Start(); }
public void AddAction(CustomAction customAction) { CustomActions.Add(customAction); }