internal static void ModifyVulnerabilityAnalysis(ModTypes _mod, string currentProject, IVulnerability details) { ProjectPOCO p = GetCurrentProject(currentProject); if (ModTypes.Add == _mod) { if (!checkExists(p, details, false)) { p.Vulnerabilities.Add(details); } } else if (ModTypes.Remove == _mod) { if (checkExists(p, details, false)) { IVulnerability c = p.Vulnerabilities.FirstOrDefault(x => x.Identifier == details.Identifier); if (null != c) { p.Vulnerabilities.Remove(c); } } } else if (ModTypes.Update == _mod) { if (checkExists(p, details, true)) { IVulnerability c = p.Vulnerabilities.FirstOrDefault(x => x.Identifier == details.Identifier); if (null != c) { p.Vulnerabilities.Remove(c); } p.Vulnerabilities.Add(details); } } }
public void ModdingGetMods(Player sender, params object[] arguments) { var modsList = new List <string[]>(); var modType = ModTypes.First(x => x.Value == (string)arguments[0]).Key; var manifest = VehicleInfo.Get(sender.Vehicle); foreach (var modid in manifest.ModIds(modType)) { var price = GetModPrice(modType, modid); if (price == -1) { continue; } var m = manifest.Mod(modType, modid); bool isVip = _vipMods.ContainsKey(modType) && (_vipMods[modType] == -1 || _vipMods[modType] == modid); modsList.Add(new string[] { m.localizedName == "" ? "No Name" : (m.HasFlag("chrome") ? "CHROME - " + m.localizedName : m.localizedName), modType.ToString(), modid.ToString(), price.ToString(), isVip == true ? "true" : "false" }); } NAPI.ClientEvent.TriggerClientEvent(sender, "MODDING_FILL_MODS", NAPI.Util.ToJson(modsList.ToArray())); }
public Shrek2ModListItem(string title, ModTypes modType, bool isActive, string uuid, string description = "No description found.") { Title = title; FileName = $"{uuid}.{(modType == ModTypes.ModFile ? "dll" : "zip")}"; ModType = modType; Description = description; IsActive = isActive; UUID = uuid; }
public ModEditor() { this.InitializeComponent(); this.gridView.AutoGenerateColumns = false; this.colEnabled.DataPropertyName = "Enabled"; this.colFile.DataPropertyName = "FileName"; this.colDesc.DataPropertyName = "Description"; this.ModType = ModTypes.General; base.Disposed += new EventHandler(this.OnDisposed); }
public ModifierList(ModTypes modType) { index = 0; effects = new List <List <AbsEffect> >(); // Create list based on type passed in switch (modType) { case ModTypes.Potion: BuildPotionList(); break; case ModTypes.Prayer: BuildPrayerList(); break; case ModTypes.Aura: BuildAuraList(); break; case ModTypes.Nihil: BuildNihilList(); break; case ModTypes.Scrimshaw: BuildScrimList(); break; case ModTypes.Reaper: BuildReaperList(); break; case ModTypes.Quake: BuildQuakeList(); break; case ModTypes.StatWarh: BuildStatWarhammerList(); break; case ModTypes.Gstaff: BuildGstaffList(); break; case ModTypes.BandosBook: BuildBandosBookList(); break; default: break; } }
internal static void ModifyStaticAnalysis(ModTypes _mod, string currentProject, StaticAnalysisPOCO details) { ProjectPOCO p = GetCurrentProject(currentProject); if (ModTypes.Add == _mod) { if (!checkExists(p, details)) { p.StaticAnalysis.Add(details); } } else if (ModTypes.Remove == _mod) { if (checkExists(p, details)) { StaticAnalysisPOCO c = p.StaticAnalysis.FirstOrDefault(x => x.AnalysisDate == details.AnalysisDate); if (null != c) { p.StaticAnalysis.Remove(c); } } } }
internal static void ModifyDocumenation(ModTypes mod, string currentProject, Documentation data) { ProjectPOCO p = GetCurrentProject(currentProject); if (ModTypes.Add == mod) { if (!checkExists(p, data)) { p.DocumentationItems.Add(data); } } else if (ModTypes.Remove == mod) { if (checkExists(p, data)) { Documentation c = p.DocumentationItems.FirstOrDefault(x => x.Category == data.Category && x.DateOfIssue == data.DateOfIssue && x.Details == data.Details); if (null != c) { p.DocumentationItems.Remove(c); } } } }
internal static void ModifyPenTestAnalysis(ModTypes _mod, string currentProject, PenetrationTestPOCO details) { ProjectPOCO p = GetCurrentProject(currentProject); if (ModTypes.Add == _mod) { if (!checkExists(p, details)) { p.PenetrationTests.Add(details); } } else if (ModTypes.Remove == _mod) { if (checkExists(p, details)) { PenetrationTestPOCO c = p.PenetrationTests.FirstOrDefault(x => x.EndDate == details.EndDate && x.StartDate == details.StartDate && x.TesterName == details.TesterName); if (null != c) { p.PenetrationTests.Remove(c); } } } }
public StatMod(float parValue, string parSource, ModTypes parType) : base(parValue, parType, parSource) { }
public HealthMod(float parVal, ModTypes parModType, string parSource, HealthTypes parHealthType) : base(parVal, parModType, parSource) { this.healthType = parHealthType; }
private void API_onClientEventTrigger(Client sender, string eventName, params object[] arguments) { switch (eventName) { case "MODDING_GETMODS": { var modsList = new List <string[]>(); var modType = ModTypes.First(x => x.Value == (string)arguments[0]).Key; var manifest = VehicleInfo.Get(sender.vehicle); foreach (var modid in manifest.ModIds(modType)) { var price = GetModPrice(modType, modid); if (price == -1) { continue; } var m = manifest.Mod(modType, modid); bool isVip = _vipMods.ContainsKey(modType) && (_vipMods[modType] == -1 || _vipMods[modType] == modid); modsList.Add(new string[] { m.localizedName == "" ? "No Name" : (m.HasFlag("chrome") ? "CHROME - " + m.localizedName : m.localizedName), modType.ToString(), modid.ToString(), price.ToString(), isVip == true ? "true" : "false" }); } API.TriggerClientEvent(sender, "MODDING_FILL_MODS", API.ToJson(modsList.ToArray())); break; } case "MODDING_EXITMENU": { var vehicle = sender.vehicle; ClearVehicleMods(vehicle.handle.GetVehicle()); ApplyVehicleMods(vehicle.handle.GetVehicle()); API.SetEntityPosition(sender.vehicle, sender.getData("ModLastPos")); API.SetEntityDimension(sender.vehicle, 0); API.SetEntityDimension(sender, 0); if (sender.GetAccount().IsSpeedoOn) { API.TriggerClientEvent(sender, "TOGGLE_SPEEDO"); } break; } case "MODDONG_PURCHASE_ITEMS": { dynamic items = JsonConvert.DeserializeObject((string)arguments[0]); int allPrices = 0; int itemCount = 0; foreach (var itm in items) { var modType = int.Parse(itm[0].ToString().Trim()); int modId; int.TryParse(itm[1].ToString().Trim(), out modId); var price = GetModPrice(modType, modId); allPrices += price; itemCount++; } var prop = PropertyManager.Properties.First(x => x.Id == API.GetEntityData(sender, "MOD_ID")); if (prop.Supplies != -1 && prop.Supplies < itemCount * 5) { API.TriggerClientEvent(sender, "MODDING_ERROR", "This modshop doesn't have enough supplies."); return; } var c = sender.GetCharacter(); if (Money.GetCharacterMoney(c) < allPrices) { API.TriggerClientEvent(sender, "MODDING_ERROR", "You don't have enough money to purchase these mods. Your balance: " + Money.GetCharacterMoney(c)); return; } InventoryManager.DeleteInventoryItem <Money>(c, allPrices); InventoryManager.GiveInventoryItem(prop, new Money(), allPrices); if (prop.Supplies != -1) { prop.Supplies -= itemCount * 5; } var veh = sender.vehicle.handle.GetVehicle(); foreach (var itm in items) { var modType = int.Parse(itm[0].ToString().Trim()); AddVehicleMod(veh, modType, itm[1].ToString().Trim()); } ClearVehicleMods(veh); ApplyVehicleMods(veh); veh.Save(); API.TriggerClientEvent(sender, "MODDING_CLOSE"); API.SendChatMessageToPlayer(sender, "You have successfully purchased some vehicle mods for a total of ~g~" + allPrices.ToString("C")); API.SetEntityPosition(sender.vehicle, sender.getData("ModLastPos")); API.SetEntityDimension(sender.vehicle, 0); API.SetEntityDimension(sender, 0); if (sender.GetAccount().IsSpeedoOn) { API.TriggerClientEvent(sender, "TOGGLE_SPEEDO"); } break; } } }
public Mod(float parValue, ModTypes parType, string parSource) { this.value = parValue; this.modType = parType; this.source = parSource; }
public TempHealthMod(float parVal, ModTypes parModType, HealthTypes parHealthType, string parSource, int parDuration) : base(parVal, parModType, parSource, parHealthType) { duration = parDuration; DateSystem.NewHourEvent += TickDown; }
/// <summary> /// Load collection for ParserTargetCollection /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChildren">Whether getters on the object should get called</param> private static void LoadCollectionMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String configName = "Default", Boolean getChildren = true) { // Get the target attributes ParserTargetCollection[] targets = (ParserTargetCollection[])member.GetCustomAttributes(typeof(ParserTargetCollection), true); // Process the target attributes foreach (ParserTargetCollection target in targets) { // Figure out if this field exists and if we care Boolean isNode = node.HasNode(target.FieldName) || target.FieldName == "self"; Boolean isValue = node.HasValue(target.FieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChildren) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // Get settings data ParserOptions.Data data = ParserOptions.Options[configName]; // Log data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType + ")"); // If there was no data found for this node if (!isNode && !isValue) { if (!target.Optional && !(target.AllowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException( "Missing non-optional field: " + o.GetType() + "." + target.FieldName); } // Nothing to do, so return continue; } // If we are dealing with a generic collection if (targetType.IsGenericType) { // If the target is a generic dictionary if (typeof(IDictionary).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic dictionary requires sources to be nodes"); } // Get the target value as a dictionary IDictionary collection = targetValue as IDictionary; // Get the internal type of this collection Type genericTypeA = targetType.GetGenericArguments()[0]; Type genericTypeB = targetType.GetGenericArguments()[1]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.AllowMerge) { collection = Activator.CreateInstance(targetType) as IDictionary; targetValue = collection; } // Process the node ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName); // Check the config type RequireConfigType[] attributes = (RequireConfigType[])genericTypeA.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0) { if (attributes[0].Type == ConfigType.Node) { throw new ParserTargetTypeMismatchException( "The key value of a generic dictionary must be a Value"); } } attributes = (RequireConfigType[])genericTypeB.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0 || genericTypeB == typeof(String)) { ConfigType type = genericTypeB == typeof(String) ? ConfigType.Value : attributes[0].Type; if (type == ConfigType.Node) { // Iterate over all of the nodes in this node foreach (ConfigNode subnode in targetNode.nodes) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node collection.Add(ProcessValue(genericTypeA, subnode.name), CreateObjectFromConfigNode(genericTypeB, subnode, configName, target.GetChild)); break; case NameSignificance.Type: throw new Exception( "NameSignificance.Type isn't supported on generic dictionaries."); case NameSignificance.Key: throw new Exception( "NameSignificance.Key isn't supported on generic dictionaries"); default: throw new ArgumentOutOfRangeException(); } } } else { // Iterate over all of the values in this node foreach (ConfigNode.Value value in targetNode.values) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: collection.Add(ProcessValue(genericTypeA, value.name), ProcessValue(genericTypeB, value.value)); break; case NameSignificance.Type: throw new Exception( "NameSignificance.Type isn't supported on generic dictionaries."); case NameSignificance.Key: throw new Exception( "NameSignificance.Key isn't supported on generic dictionaries"); default: throw new ArgumentOutOfRangeException(); } } } } } // If the target is a generic collection else if (typeof(IList).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic list requires sources to be nodes"); } // Get the target value as a collection IList collection = targetValue as IList; // Get the internal type of this collection Type genericType = targetType.GetGenericArguments()[0]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.AllowMerge) { collection = Activator.CreateInstance(targetType) as IList; targetValue = collection; } // Store the objects that were already patched List <Object> patched = new List <Object>(); // Process the node ConfigNode targetNode = target.FieldName == "self" ? node : node.GetNode(target.FieldName); // Check the config type RequireConfigType[] attributes = (RequireConfigType[])genericType.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0 || genericType == typeof(String)) { ConfigType type = genericType == typeof(String) ? ConfigType.Value : attributes[0].Type; if (type == ConfigType.Node) { // Iterate over all of the nodes in this node foreach (ConfigNode subnode in targetNode.nodes) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: case NameSignificance.Key when subnode.name == target.Key: // Check if the type represents patchable data Object current = null; if (typeof(IPatchable).IsAssignableFrom(genericType) && collection.Count > 0) { for (Int32 i = 0; i < collection.Count; i++) { if (collection[i].GetType() != genericType) { continue; } if (patched.Contains(collection[i])) { continue; } IPatchable patchable = (IPatchable)collection[i]; PatchData patchData = CreateObjectFromConfigNode <PatchData>(subnode, "Internal"); if (patchData.name == patchable.name) { // Name matches, check for an index if (patchData.index == collection.IndexOf(collection[i])) { // Both values match current = collection[i]; break; } if (patchData.index > -1) { // Index doesn't match, continue continue; } // Name matches, and no index exists current = collection[i]; break; } if (patchData.name != null) { // The name doesn't match, continue the search continue; } // We found the first object that wasn't patched yet current = collection[i]; break; } } // If no object was found, check if the type implements custom constructors if (current == null) { current = Activator.CreateInstance(genericType); collection?.Add(current); } // Parse the config node into the object LoadObjectFromConfigurationNode(current, subnode, configName, target.GetChild); patched.Add(current); if (collection != null) { collection[collection.IndexOf(current)] = current; } break; case NameSignificance.Type: // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == subnode.name && !Equals(t.Assembly, typeof(HighLogic).Assembly) && genericType.IsAssignableFrom(t)); // Check if the type represents patchable data current = null; if (typeof(IPatchable).IsAssignableFrom(elementType) && collection.Count > 0) { for (Int32 i = 0; i < collection.Count; i++) { if (collection[i].GetType() != elementType) { continue; } if (patched.Contains(collection[i])) { continue; } IPatchable patchable = (IPatchable)collection[i]; PatchData patchData = CreateObjectFromConfigNode <PatchData>(subnode, "Internal"); if (patchData.name == patchable.name) { // Name matches, check for an index if (patchData.index == i) { // Both values match current = collection[i]; break; } if (patchData.index > -1) { // Index doesn't match, continue continue; } // Name matches, and no index exists current = collection[i]; break; } if (patchData.name != null) { // The name doesn't match, continue the search continue; } // We found the first object that wasn't patched yet current = collection[i]; break; } } // If no object was found, check if the type implements custom constructors if (current == null) { current = Activator.CreateInstance(elementType); collection?.Add(current); if (typeof(ICreatable).IsAssignableFrom(elementType)) { ICreatable creatable = (ICreatable)current; creatable.Create(); } } // Parse the config node into the object LoadObjectFromConfigurationNode(current, subnode, configName, target.GetChild); patched.Add(current); if (collection != null) { collection[collection.IndexOf(current)] = current; } break; default: continue; } } } else { // Iterate over all of the nodes in this node foreach (ConfigNode.Value value in targetNode.values) { // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node collection?.Add(ProcessValue(genericType, value.value)); break; case NameSignificance.Type: // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == value.name && !Equals(t.Assembly, typeof(HighLogic).Assembly) && genericType.IsAssignableFrom(t)); // Add the object to the collection collection?.Add(ProcessValue(elementType, value.value)); break; case NameSignificance.Key when value.name == target.Key: // Just processes the contents of the node collection?.Add(ProcessValue(genericType, value.value)); break; default: continue; } } } } } } // If we are dealing with a non generic collection else { // Check for invalid scenarios if (target.NameSignificance == NameSignificance.None) { throw new Exception( "Can not infer type from non generic target; can not infer type from zero name significance"); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } } }
private void addIssueButton_Click(object sender, EventArgs e) { ProjectPOCO project = projectHelper.GetCurrentProject(ddlProjects.Text); if (null == project) { ShowError("No project found."); return; } bool isUpdate = false; ModTypes t = ModTypes.Add; DateTime outCompleteDate; DateTime outDiscoveredDate; Decimal cvss = 0; IVulnerability vuln = new Vulnerability(); vuln.Identifier = Guid.NewGuid(); if (sender is Button) { Button localB = sender as Button; if (null != localB) { isUpdate = localB.Text == "Save" ? true : false; if (isUpdate) { t = ModTypes.Update; vuln.Identifier = EditGuid; } else { t = ModTypes.Add; } } } if (Decimal.TryParse(cvssDataText.Text, out cvss)) { vuln.CVSS = cvss; } else { MessageBox.Show("Value was not a decimal.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (DateTime.TryParse(completeDateInput.Text, out outCompleteDate)) { vuln.CompletedDate = outCompleteDate; } else { vuln.CompletedDate = null; } if (DateTime.TryParse(discoveredDate.Text, out outDiscoveredDate)) { vuln.DiscoveredDate = outDiscoveredDate; } else { vuln.DiscoveredDate = null; } string title = vulnTitle.Text; string status = statusInput.Text; string risklevel = riskLevelInput.Text; string details = vulnerabilityInput.Text; if (status != "Not An Issue" || status != "Fixed") { vuln.CompletedDate = null; } vuln.Title = title; vuln.VulnTypeReported = vulnTypeItems.SelectedItem.ToString(); vuln.Status = status; vuln.Risk = risklevel; vuln.Details = details; vuln.Tester = penTesterDiscover.SelectedItem.ToString(); vuln.isWeeklyReportItem = isForUpdate.Checked; Vulnerabilities.AddObject(vuln); projectHelper.ModifyVulnerabilityAnalysis(t, ddlProjects.Text, vuln); if (ModTypes.Update == t) { dataGridView1.CellContentClick += dataGridView1_CellContentClick; } bindGrid(project); ClearVulnForm(); }
public static AssingStatmod Create(float value, string source, ModTypes modTypes, StatTypes statTypes) => new AssingStatmod(new StatMod(value, source, modTypes), statTypes);
/// <summary> /// Load data for ParserTarget field or property from a configuration node /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="configName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChildren">Whether getters on the object should get called</param> private static void LoadObjectMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String configName = "Default", Boolean getChildren = true) { // Get the parser targets ParserTarget[] targets = (ParserTarget[])member.GetCustomAttributes(typeof(ParserTarget), true); // Process the targets foreach (ParserTarget target in targets) { // Figure out if this field exists and if we care Boolean isNode = node.GetNodes() .Any(n => n.name.StartsWith(target.FieldName + ":") || n.name == target.FieldName); Boolean isValue = node.HasValue(target.FieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChildren ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChildren) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // Get settings data ParserOptions.Data data = ParserOptions.Options[configName]; // Log data.LogCallback("Parsing Target " + target.FieldName + " in (" + o.GetType() + ") as (" + targetType + ")"); // If there was no data found for this node if (!isNode && !isValue) { if (!target.Optional && !(target.AllowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException( "Missing non-optional field: " + o.GetType() + "." + target.FieldName); } // Nothing to do, so DONT return! continue; } // Does this node have a required config source type (and if so, check if valid) RequireConfigType[] attributes = (RequireConfigType[])targetType.GetCustomAttributes(typeof(RequireConfigType), true); if (attributes.Length > 0) { if (attributes[0].Type == ConfigType.Node && !isNode || attributes[0].Type == ConfigType.Value && !isValue) { throw new ParserTargetTypeMismatchException( target.FieldName + " requires config value of " + attributes[0].Type); } } // If this object is a value (attempt no merge here) if (isValue) { // Process the value Object val = ProcessValue(targetType, node.GetValue(target.FieldName)); // Throw exception or print error if (val == null) { data.LogCallback("[Kopernicus]: Configuration.Parser: ParserTarget \"" + target.FieldName + "\" is a non parsable type: " + targetType); continue; } targetValue = val; } // If this object is a node (potentially merge) else { // If the target type is a ConfigNode, this works natively if (targetType == typeof(ConfigNode)) { targetValue = node.GetNode(target.FieldName); } // We need to get an instance of the object we are trying to populate // If we are not allowed to merge, or the object does not exist, make a new instance // Otherwise we can merge this value else if (targetValue == null || !target.AllowMerge) { if (!targetType.IsAbstract) { targetValue = Activator.CreateInstance(targetType); } } // Check for the name significance switch (target.NameSignificance) { case NameSignificance.None: // Just processes the contents of the node LoadObjectFromConfigurationNode(targetValue, node.GetNode(target.FieldName), configName, target.GetChild); break; case NameSignificance.Type: // Generate the type from the name ConfigNode subnode = node.GetNodes().First(n => n.name.StartsWith(target.FieldName + ":")); String[] split = subnode.name.Split(':'); Type elementType = ModTypes.FirstOrDefault(t => t.Name == split[1] && !Equals(t.Assembly, typeof(HighLogic).Assembly) && targetType.IsAssignableFrom(t)); // If no object was found, check if the type implements custom constructors targetValue = Activator.CreateInstance(elementType); if (typeof(ICreatable).IsAssignableFrom(elementType)) { ICreatable creatable = (ICreatable)targetValue; creatable.Create(); } // Parse the config node into the object LoadObjectFromConfigurationNode(targetValue, subnode, configName, target.GetChild); break; case NameSignificance.Key: throw new Exception("NameSignificance.Key is not supported on ParserTargets"); default: throw new ArgumentOutOfRangeException(); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } } }
/// <summary> /// Load collection for ParserTargetCollection /// </summary> /// <param name="member">Member to load data for</param> /// <param name="o">Instance of the object which owns member</param> /// <param name="node">Configuration node from which to load data</param> /// <param name="modName">The name of the mod that corresponds to the entry in ParserOptions</param> /// <param name="getChilds">Whether getters on the object should get called</param> public static void LoadCollectionMemberFromConfigurationNode(MemberInfo member, Object o, ConfigNode node, String modName = "Default", Boolean getChilds = true) { // Get the target attribute ParserTargetCollection target = ((ParserTargetCollection[])member.GetCustomAttributes(typeof(ParserTargetCollection), true))[0]; // Figure out if this field exists and if we care Boolean isNode = node.HasNode(target.fieldName); Boolean isValue = node.HasValue(target.fieldName); // Obtain the type the member is (can only be field or property) Type targetType; Object targetValue = null; if (member.MemberType == MemberTypes.Field) { targetType = ((FieldInfo)member).FieldType; targetValue = getChilds ? ((FieldInfo)member).GetValue(o) : null; } else { targetType = ((PropertyInfo)member).PropertyType; try { if (((PropertyInfo)member).CanRead && getChilds) { targetValue = ((PropertyInfo)member).GetValue(o, null); } } catch (Exception) { // ignored } } // If there was no data found for this node if (!isNode && !isValue) { if (!target.optional && !(target.allowMerge && targetValue != null)) { // Error - non optional field is missing throw new ParserTargetMissingException("Missing non-optional field: " + o.GetType() + "." + target.fieldName); } // Nothing to do, so return return; } // If we are dealing with a generic collection if (targetType.IsGenericType) { // If the target is a generic dictionary if (typeof(IDictionary).IsAssignableFrom(targetType)) { throw new Exception("Generic dictionaries are unsupported at this time"); } // If the target is a generic collection else if (typeof(IList).IsAssignableFrom(targetType)) { // We need a node for this decoding if (!isNode) { throw new Exception("Loading a generic list requires sources to be nodes"); } // Get the target value as a collection IList collection = targetValue as IList; // Get the internal type of this collection Type genericType = targetType.GetGenericArguments()[0]; // Create a new collection if merge is disallowed or if the collection is null if (collection == null || !target.allowMerge) { collection = Activator.CreateInstance(targetType) as IList; targetValue = collection; } // Iterate over all of the nodes in this node foreach (ConfigNode subnode in node.GetNode(target.fieldName).nodes) { // Check for the name significance if (target.nameSignificance == NameSignificance.None) { // Just processes the contents of the node collection?.Add(CreateObjectFromConfigNode(genericType, subnode, modName, target.getChild)); } // Otherwise throw an exception because we don't support named ones yet else if (target.nameSignificance == NameSignificance.Type) { // Generate the type from the name Type elementType = ModTypes.FirstOrDefault(t => t.Name == subnode.name); // Add the object to the collection collection?.Add(CreateObjectFromConfigNode(elementType, subnode, modName, target.getChild)); } } } } // If we are dealing with a non generic collection else { // Check for invalid scenarios if (target.nameSignificance == NameSignificance.None) { throw new Exception("Can not infer type from non generic target; can not infer type from zero name significance"); } } // If the member type is a field, set the value if (member.MemberType == MemberTypes.Field) { ((FieldInfo)member).SetValue(o, targetValue); } // If the member wasn't a field, it must be a property. If the property is writable, set it. else if (((PropertyInfo)member).CanWrite) { ((PropertyInfo)member).SetValue(o, targetValue, null); } }
public ModMeta(ModTypes modType, string modName) { ModType = modType; ModName = modName; }
public TempStatMod(float parValue, ModTypes parType, string parSource, int parHours) : base(parValue, parSource, parType) { duration = parHours; DateSystem.NewHourEvent += TickDown; }