using System; using System.Collections.Generic; using dnlib.DotNet; namespace Confuser.Core { using ProtectionParams = Dictionary; /// /// Parameters of . /// public class ProtectionParameters { static readonly object ParametersKey = new object(); /// /// A empty instance of . /// public static readonly ProtectionParameters Empty = new ProtectionParameters(null, new IDnlibDef[0]); readonly ConfuserComponent comp; /// /// Initializes a new instance of the class. /// /// The component that this parameters applied to. /// The protection targets. internal ProtectionParameters(ConfuserComponent component, IList targets) { comp = component; Targets = targets; } /// /// Gets the targets of protection. /// Possible targets are module, types, methods, fields, events, properties. /// /// A list of protection targets. public IList Targets { get; private set; } /// /// Obtains the value of a parameter of the specified target. /// /// The type of the parameter value. /// The working context. /// The protection target. /// The name of the parameter. /// Default value if the parameter does not exist. /// The value of the parameter. public T GetParameter(ConfuserContext context, IDnlibDef target, string name, T defValue = default(T)) { Dictionary parameters; if (comp == null) return defValue; if (comp is Packer && target == null) { // Packer parameters are stored in modules target = context.Modules[0]; } var objParams = context.Annotations.Get(target, ParametersKey); if (objParams == null) return defValue; if (!objParams.TryGetValue(comp, out parameters)) return defValue; string ret; if (parameters.TryGetValue(name, out ret)) { Type paramType = typeof(T); Type nullable = Nullable.GetUnderlyingType(paramType); if (nullable != null) paramType = nullable; if (paramType.IsEnum) return (T)Enum.Parse(paramType, ret, true); return (T)Convert.ChangeType(ret, paramType); } return defValue; } /// /// Sets the protection parameters of the specified target. /// /// The context. /// The protection target. /// The parameters. public static void SetParameters( ConfuserContext context, IDnlibDef target, ProtectionSettings parameters) { context.Annotations.Set(target, ParametersKey, parameters); } /// /// Gets the protection parameters of the specified target. /// /// The context. /// The protection target. /// The parameters. public static ProtectionSettings GetParameters( ConfuserContext context, IDnlibDef target) { return context.Annotations.Get(target, ParametersKey); } } }