Example #1
0
    private void LogPropertyDef(PropertyDef propertyDef)
    {
      Debug.WriteLine("Name: " + propertyDef.Name);
      Debug.WriteLine("ContentType: " + propertyDef.ContentType);
      Debug.WriteLine("ObjectType: " + propertyDef.ObjectType);
      Debug.WriteLine("DependencyPD: " + propertyDef.DependencyPD);
      Debug.WriteLine("DependencyRelation: " + propertyDef.DependencyRelation);
      Debug.WriteLine("ValueList: " + propertyDef.ValueList);
      Debug.WriteLine("StaticFilter: " + propertyDef.StaticFilter.Count);

      foreach (SearchCondition condition in propertyDef.StaticFilter)
        Debug.WriteLine("condition.ConditionType: " + condition.ConditionType);
      Debug.WriteLine("");
    }
Example #2
0
    //private int GetValueListItemId(int valueListId, string value, Vault vault, SearchConditions searchConditions)
    private int GetValueListItemId(PropertyDef propertyDef, string value, Vault vault)
    {
      int valueListItemId = -1;

      System.Collections.IEnumerable items = null;

      bool useSearch = false;

      /* search fails for MFExpressionTypePropertyValue */
      foreach (SearchCondition searchCondition in propertyDef.StaticFilter)
      {
        Debug.WriteLine("searchCondition: " + searchCondition.Expression.Type.ToString() + " " +
                        "condition: " + searchCondition.ConditionType + " " +
                        "typedValue: " + searchCondition.TypedValue.DisplayValue);
        useSearch = searchCondition.Expression.Type == MFExpressionType.MFExpressionTypeTypedValue;
      }

      /* use the search trim down elements (value list items are capped at 5000) */
      if (useSearch)
        items = vault.ValueListItemOperations.SearchForValueListItemsEx(propertyDef.ValueList, propertyDef.StaticFilter);
      else
        items = vault.ValueListItemOperations.GetValueListItems(propertyDef.ValueList);

      //int index = 0;
      foreach (ValueListItem valueListItem in items)
      {
        if (valueListItem.Name == value)
        {
          valueListItemId = valueListItem.ID;
          break;
        }
        //index++;
      }

      //Debug.WriteLine(index);

      Debug.WriteLine(string.Format("valueListId={0}, value={1} => valueListItemId={2}", propertyDef.ValueList, value, valueListItemId));
      return valueListItemId;
    }
Example #3
0
        void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, PropertyDef property)
        {
            if (IsVisibleOutside(context, parameters, property.DeclaringType) &&
                (property.IsFamily() || property.IsFamilyOrAssembly() || property.IsPublic()) &&
                IsVisibleOutside(context, parameters, property))
            {
                service.SetCanRename(property, false);
            }

            else if (property.IsRuntimeSpecialName)
            {
                service.SetCanRename(property, false);
            }

            else if (parameters.GetParameter(context, property, "forceRen", false))
            {
                return;
            }

            else if (property.DeclaringType.Implements("System.ComponentModel.INotifyPropertyChanged"))
            {
                service.SetCanRename(property, false);
            }

            else if (property.DeclaringType.Name.String.Contains("AnonymousType"))
            {
                service.SetCanRename(property, false);
            }
        }
Example #4
0
        public void Analyze(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
        {
            var module = def as ModuleDefMD;

            if (module == null)
            {
                return;
            }

            MDTable table;
            uint    len;

            // MemberRef
            table = module.TablesStream.Get(Table.Method);
            len   = table.Rows;
            IEnumerable <MethodDef> methods = module.GetTypes().SelectMany(type => type.Methods);

            foreach (MethodDef method in methods)
            {
                foreach (MethodOverride methodImpl in method.Overrides)
                {
                    if (methodImpl.MethodBody is MemberRef)
                    {
                        AnalyzeMemberRef(context, service, (MemberRef)methodImpl.MethodBody);
                    }
                    if (methodImpl.MethodDeclaration is MemberRef)
                    {
                        AnalyzeMemberRef(context, service, (MemberRef)methodImpl.MethodDeclaration);
                    }
                }
                if (!method.HasBody)
                {
                    continue;
                }
                foreach (Instruction instr in method.Body.Instructions)
                {
                    if (instr.Operand is MemberRef)
                    {
                        AnalyzeMemberRef(context, service, (MemberRef)instr.Operand);
                    }
                    else if (instr.Operand is MethodSpec)
                    {
                        var spec = (MethodSpec)instr.Operand;
                        if (spec.Method is MemberRef)
                        {
                            AnalyzeMemberRef(context, service, (MemberRef)spec.Method);
                        }
                    }
                }
            }


            // CustomAttribute
            table = module.TablesStream.Get(Table.CustomAttribute);
            len   = table.Rows;
            var attrs = Enumerable.Range(1, (int)len)
                        .Select(rid => {
                if (module.TablesStream.TryReadCustomAttributeRow((uint)rid, out var row))
                {
                    return(module.ResolveHasCustomAttribute(row.Parent));
                }
                return(null);
            })
                        .Where(a => a != null)
                        .Distinct()
                        .SelectMany(owner => owner.CustomAttributes);

            foreach (CustomAttribute attr in attrs)
            {
                if (attr.Constructor is MemberRef)
                {
                    AnalyzeMemberRef(context, service, (MemberRef)attr.Constructor);
                }

                foreach (CAArgument arg in attr.ConstructorArguments)
                {
                    AnalyzeCAArgument(context, service, arg);
                }

                foreach (CANamedArgument arg in attr.Fields)
                {
                    AnalyzeCAArgument(context, service, arg.Argument);
                }

                foreach (CANamedArgument arg in attr.Properties)
                {
                    AnalyzeCAArgument(context, service, arg.Argument);
                }

                TypeDef attrType = attr.AttributeType.ResolveTypeDefThrow();
                if (!context.Modules.Contains((ModuleDefMD)attrType.Module))
                {
                    continue;
                }

                foreach (CANamedArgument fieldArg in attr.Fields)
                {
                    FieldDef field = attrType.FindField(fieldArg.Name, new FieldSig(fieldArg.Type));
                    if (field == null)
                    {
                        context.Logger.WarnFormat("Failed to resolve CA field '{0}::{1} : {2}'.", attrType, fieldArg.Name, fieldArg.Type);
                    }
                    else
                    {
                        service.AddReference(field, new CAMemberReference(fieldArg, field));
                    }
                }
                foreach (CANamedArgument propertyArg in attr.Properties)
                {
                    PropertyDef property = attrType.FindProperty(propertyArg.Name, new PropertySig(true, propertyArg.Type));
                    if (property == null)
                    {
                        context.Logger.WarnFormat("Failed to resolve CA property '{0}::{1} : {2}'.", attrType, propertyArg.Name, propertyArg.Type);
                    }
                    else
                    {
                        service.AddReference(property, new CAMemberReference(propertyArg, property));
                    }
                }
            }
        }
Example #5
0
    private object ConvertPropertyValue(PropertyDef propertyDef, string value, Vault vault)
    {
      object ret;
      switch (propertyDef.DataType)
      {
        case MFDataType.MFDatatypeText:
          ret = value;
          break;

        case MFDataType.MFDatatypeDate:
          DateTime dt;
          if (DateTime.TryParse(value, out dt))
            ret = dt;
          else
            throw new ArgumentException(string.Format("failed to convert '{0}' to a valid date", value));
          break;

        case MFDataType.MFDatatypeLookup:
          /* we need to retrieve the id of the lookup */
          {
            LogPropertyDef(propertyDef);

            //Debug.WriteLine("based on valueList: " + propertyDef.BasedOnValueList + " " + 
            //  propertyDef.StaticFilter.);
            //int valueListItemId = GetValueListItemId(propertyDef.ValueList, value, vault, propertyDef.StaticFilter);
            int valueListItemId = GetValueListItemId(propertyDef, value, vault);
            ret = valueListItemId;
            if (valueListItemId == -1)
              throw new ArgumentException(string.Format("failed to find valuelist entry '{0}' for property '{1}'", value, propertyDef.Name));
          }
          break;

        case MFDataType.MFDatatypeMultiSelectLookup:
          {
            /* split into multiple values */
            string[] values = value.Split(Constants.MultiSelectDelimiter);
            int[] valueListItemIds = new int[values.Length];
            for (int i = 0; i < values.Length; i++)
            {
              //valueListItemIds[i] = GetValueListItemId(propertyDef.ValueList, value, vault, propertyDef.StaticFilter);
              valueListItemIds[i] = GetValueListItemId(propertyDef, value, vault);
              if (valueListItemIds[i] == -1)
                throw new ArgumentException(string.Format("failed to find valuelist entry '{0}' for property '{1}'", value, propertyDef.Name));
            }
            ret = valueListItemIds;
          }
          break;

        case MFDataType.MFDatatypeBoolean:
          if (value.ToLower() == "yes" ||
              value.ToLower() == "ja")
            ret = true;
          else
            ret = false;
          break;

        case MFDataType.MFDatatypeInteger:
          {
            int i;
            if (Int32.TryParse(value, out i))
              ret = i;
            else
              throw new ArgumentException(string.Format("failed to convert value '{0}' to an integer for property '{1}'", value, propertyDef.Name));
          }
          break;

        default:
          LogPropertyDef(propertyDef);
          throw new NotImplementedException(string.Format("converting to '{0}' is not implemented.", propertyDef.DataType));
      }

      return ret;
    }
Example #6
0
 public MPropertyDef find(PropertyDef pr)
 {
     return properties.find(pr);
 }
		/// <inheritdoc/>
		public override uint GetRid(PropertyDef pd) {
			uint rid;
			if (propertyDefInfos.TryGetRid(pd, out rid))
				return rid;
			if (pd == null)
				Error("Property is null");
			else
				Error("Property {0} ({1:X8}) is not defined in this module ({2}). A property was removed that is still referenced by this module.", pd, pd.MDToken.Raw, module);
			return 0;
		}
Example #8
0
        public virtual bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null) {
            bool bReset = false;

            foreach(Attachments.Attachment attach in this.Attachments) {
                bReset |= attach.ResetMembers(check, agentType, clear, method, property);
            }

            foreach(Node child in this.GetChildNodes()) {
                bReset |= child.ResetMembers(check, agentType, clear, method, property);
            }

            return bReset;
        }
Example #9
0
        public static bool CanShow(PropertyDef property)
        {
            var accessor = property.GetMethod ?? property.SetMethod;

            return(!(accessor is null) && accessor.IsVirtual && !(accessor.DeclaringType.BaseType is null));
        }
Example #10
0
        public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null) {
            bool bReset = false;

            if (this.Method != null) {
                if (method != null && this.Method.Name == method.OldName &&
                    (clear || this.Method.ShouldBeCleared(agentType))) {
                    bReset = true;

                    if (!check)
                    { this.Method = null; }

                } else {
                    bReset |= this.Method.ResetMembers(check, agentType, clear, method, property);
                }
            }

            if (this.ResultFunctor != null) {
                if (method != null && this.ResultFunctor.Name == method.OldName &&
                    (clear || this.Method.ShouldBeCleared(agentType))) {
                    bReset = true;

                    if (!check)
                    { this.ResultFunctor = null; }

                } else {
                    bReset |= this.ResultFunctor.ResetMembers(check, agentType, clear, method, property);
                }
            }

            bReset |= base.ResetMembers(check, agentType, clear, method, property);

            return bReset;
        }
Example #11
0
 public IPropertyNode Create(PropertyDef property)
 {
     return(Context.FileTreeView.Create(property));
 }
Example #12
0
        public static string GenerateCode(DefaultObject defaultObj, Behaviac.Design.MethodDef method, StringWriter stream, string indent, string typename, string var, string caller)
        {
            Debug.Check(!string.IsNullOrEmpty(var) || !string.IsNullOrEmpty(caller));

            string allParams  = string.Empty;
            string paramsName = getParamsName(var, caller);

            for (int i = 0; i < method.Params.Count; ++i)
            {
                string nativeType = DataCsExporter.GetGeneratedNativeType(method.Params[i].NativeType);
                string param      = string.Empty;

                if (method.IsPublic)
                {
                    param = getParamName(var, caller, i);
                }
                else
                {
                    param = string.Format("{0}[{1}]", paramsName, i);
                }

                if (method.Params[i].IsProperty || method.Params[i].IsLocalVar) // property
                {
                    if ((method.Params[i].Property != null && method.Params[i].Property.IsCustomized) || method.Params[i].IsLocalVar)
                    {
                        ParameterCsExporter.GenerateCode(defaultObj, method.Params[i], stream, indent, method.IsPublic ? nativeType : "", param, caller);
                    }
                    else
                    {
                        if (method.IsPublic)
                        {
                            param = ParameterCsExporter.GenerateCode(defaultObj, method.Params[i], stream, indent, nativeType, "", param);
                        }
                        else
                        {
                            ParameterCsExporter.GenerateCode(defaultObj, method.Params[i], stream, indent, "", param, caller);
                        }
                    }

                    VariableDef v = method.Params[i].Value as VariableDef;

                    if (v != null && v.ArrayIndexElement != null)
                    {
                        PropertyDef prop = method.Params[i].Property;

                        if (prop != null && prop.IsArrayElement)
                        {
                            ParameterCsExporter.GenerateCode(defaultObj, v.ArrayIndexElement, stream, indent, "int", param + "_index", param + caller);

                            if (string.IsNullOrEmpty(param))
                            {
                                string property = PropertyCsExporter.GetProperty(defaultObj, prop, v.ArrayIndexElement, stream, indent, param, caller);
                                param = string.Format("({0})[{1}_index]", property, param);
                            }
                            else
                            {
                                param = string.Format("{0}[{0}_index]", param);
                            }
                        }
                    }
                }
                else // const value
                {
                    object obj = method.Params[i].Value;

                    if (obj != null)
                    {
                        Type type = obj.GetType();

                        if (Plugin.IsCustomClassType(type) && !DesignerStruct.IsPureConstDatum(obj, method, method.Params[i].Name))
                        {
                            string paramName = getParamName(var, caller, i);
                            string paramType = DataCsExporter.GetGeneratedNativeType(method.Params[i].NativeType);

                            StructCsExporter.GenerateCode(obj, defaultObj, stream, indent, paramName, paramType, method, method.Params[i].Name);

                            if (!method.IsPublic)
                            {
                                stream.WriteLine("{0}{1} = {2};", indent, param, paramName);
                            }
                        }
                    }
                }

                if (i > 0)
                {
                    allParams += ", ";
                }

                if (method.Params[i].IsRef)
                {
                    param = "ref " + param;
                }
                else if (method.Params[i].IsOut)
                {
                    param = "out " + param;
                }

                allParams += param;
            }

            string agentName = "pAgent";

            if (method.Owner != Behaviac.Design.VariableDef.kSelf && (!method.IsPublic || !method.IsStatic))
            {
                string instanceName = method.Owner.Replace("::", ".");
                agentName = "pAgent_" + caller;

                bool        isGlobal      = Plugin.IsInstanceName(instanceName, null);
                PropertyDef ownerProperty = null;

                if (!isGlobal)
                {
                    Debug.Check(defaultObj != null && defaultObj.Behavior != null && defaultObj.Behavior.AgentType != null);
                    if (defaultObj != null && defaultObj.Behavior != null && defaultObj.Behavior.AgentType != null)
                    {
                        ownerProperty = defaultObj.Behavior.AgentType.GetPropertyByName(instanceName);
                    }
                }

                if (isGlobal || ownerProperty == null || ownerProperty.IsCustomized || ownerProperty.IsPar) // global or customized instance
                {
                    stream.WriteLine("{0}behaviac.Agent {1} = behaviac.Utils.GetParentAgent(pAgent, \"{2}\");", indent, agentName, instanceName);
                }
                else // member instance
                {
                    string prop = "";

                    if (ownerProperty.IsPublic)
                    {
                        string className = ownerProperty.ClassName.Replace("::", ".");

                        if (ownerProperty.IsStatic)
                        {
                            prop = string.Format("{0}.{1}", className, instanceName);
                        }
                        else
                        {
                            prop = string.Format("(({0})pAgent).{1}", className, instanceName);
                        }
                    }
                    else
                    {
                        string nativeType = DataCsExporter.GetGeneratedNativeType(ownerProperty.NativeType);
                        prop = string.Format("({0})AgentMetaVisitor.GetProperty(pAgent, \"{1}\")", nativeType, instanceName);
                    }

                    stream.WriteLine("{0}behaviac.Agent {1} = {2};", indent, agentName, prop);
                }

                stream.WriteLine("{0}Debug.Check(!System.Object.ReferenceEquals({1}, null) || Utils.IsStaticClass(\"{2}\"));", indent, agentName, instanceName);
            }

            string retStr = string.Empty;

            if (method.IsPublic)
            {
                string className = method.ClassName.Replace("::", ".");

                if (method.IsStatic)
                {
                    retStr = string.Format("{0}.{1}({2})", className, method.BasicName, allParams);
                }
                else
                {
                    retStr = string.Format("(({0}){1}).{2}({3})", className, agentName, method.BasicName, allParams);
                }
            }
            else
            {
                retStr = string.Format("AgentMetaVisitor.ExecuteMethod({0}, \"{1}\", {2})", agentName, method.BasicName, paramsName);
            }

            if (!string.IsNullOrEmpty(var))
            {
                string nativeReturnType = DataCsExporter.GetGeneratedNativeType(method.NativeReturnType);
                string typeConvertStr   = (nativeReturnType == "void") ? string.Empty : "(" + nativeReturnType + ")";

                stream.WriteLine("{0}{1} {2} = {3}{4};", indent, nativeReturnType, var, typeConvertStr, retStr);
            }

            return(retStr);
        }
Example #13
0
        private void ExportCustomizedTypes(string agentFolder)
        {
            if (CustomizedTypeManager.Instance.Enums.Count > 0 || CustomizedTypeManager.Instance.Structs.Count > 0)
            {
                string   filename    = Path.Combine(agentFolder, "customizedtypes.cs");
                Encoding utf8WithBom = new UTF8Encoding(true);

                using (StreamWriter file = new StreamWriter(filename, false, utf8WithBom))
                {
                    // write comments
                    file.WriteLine("// ---------------------------------------------------------------------");
                    file.WriteLine("// This file is auto-generated by behaviac designer, so please don't modify it by yourself!");
                    file.WriteLine("// ---------------------------------------------------------------------\n");

                    file.WriteLine("using System.Collections;");
                    file.WriteLine("using System.Collections.Generic;");
                    file.WriteLine();

                    //file.WriteLine("namespace behaviac");
                    //file.WriteLine("{");

                    file.WriteLine("// -------------------");
                    file.WriteLine("// Customized enums");
                    file.WriteLine("// -------------------\n");

                    for (int e = 0; e < CustomizedTypeManager.Instance.Enums.Count; ++e)
                    {
                        if (e > 0)
                        {
                            file.WriteLine();
                        }

                        CustomizedEnum customizedEnum = CustomizedTypeManager.Instance.Enums[e];
                        file.WriteLine("[behaviac.TypeMetaInfo(\"{0}\", \"{1}\")]", customizedEnum.DisplayName, customizedEnum.Description);

                        file.WriteLine("public enum {0}", customizedEnum.Name);
                        file.WriteLine("{");

                        for (int m = 0; m < customizedEnum.Members.Count; ++m)
                        {
                            if (m > 0)
                            {
                                file.WriteLine();
                            }

                            CustomizedEnum.CustomizedEnumMember member = customizedEnum.Members[m];
                            if (member.DisplayName != member.Name || !string.IsNullOrEmpty(member.Description))
                            {
                                file.WriteLine("\t[behaviac.MemberMetaInfo(\"{0}\", \"{1}\")]", member.DisplayName, member.Description);
                            }

                            if (member.Value >= 0)
                            {
                                file.WriteLine("\t{0} = {1},", member.Name, member.Value);
                            }
                            else
                            {
                                file.WriteLine("\t{0},", member.Name);
                            }
                        }

                        file.WriteLine("}");
                    }

                    if (CustomizedTypeManager.Instance.Enums.Count > 0)
                    {
                        file.WriteLine();
                    }

                    file.WriteLine("// -------------------");
                    file.WriteLine("// Customized structs");
                    file.WriteLine("// -------------------\n");

                    for (int s = 0; s < CustomizedTypeManager.Instance.Structs.Count; s++)
                    {
                        if (s > 0)
                        {
                            file.WriteLine();
                        }

                        CustomizedStruct customizedStruct = CustomizedTypeManager.Instance.Structs[s];
                        file.WriteLine("[behaviac.TypeMetaInfo(\"{0}\", \"{1}\")]", customizedStruct.DisplayName, customizedStruct.Description);

                        file.WriteLine("public struct {0}", customizedStruct.Name);
                        file.WriteLine("{");

                        for (int m = 0; m < customizedStruct.Properties.Count; ++m)
                        {
                            if (m > 0)
                            {
                                file.WriteLine();
                            }

                            PropertyDef member = customizedStruct.Properties[m];
                            if (member.DisplayName != member.Name || !string.IsNullOrEmpty(member.BasicDescription))
                            {
                                file.WriteLine("\t[behaviac.MemberMetaInfo(\"{0}\", \"{1}\")]", member.DisplayName, member.BasicDescription);
                            }

                            file.WriteLine("\tpublic {0} {1};", DataCsExporter.GetGeneratedNativeType(member.NativeType), member.BasicName);
                        }

                        file.WriteLine("}");
                    }

                    //file.WriteLine("}");
                }
            }
        }
Example #14
0
 public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null) {
     // This function should be empty here, so don't remove it.
     return false;
 }
Example #15
0
        public bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method, PropertyDef property)
        {
            bool bReset = false;

            if (this.Opl != null)
            {
                bReset |= this.Opl.ResetMembers(check, agentType, clear, method, property);
            }

            if (this.Opr1 != null)
            {
                bReset |= this.Opr1.ResetMembers(check, agentType, clear, method, property);
            }

            if (this.Opr2 != null)
            {
                bReset |= this.Opr2.ResetMembers(check, agentType, clear, method, property);
            }

            return bReset;
        }
Example #16
0
        public static bool CanShow(PropertyDef property)
        {
            var accessor = property.GetMethod ?? property.SetMethod;

            return(accessor != null && accessor.IsVirtual && !accessor.IsFinal && !accessor.DeclaringType.IsInterface);
        }
Example #17
0
 /// <summary>
 ///   <c>true</c> if <see cref="MethodAttributes.FamORAssem" /> is set.
 /// </summary>
 /// <param name="property">The property.</param>
 /// <returns>
 ///   <c>true</c> if [is family or assembly] [the specified property]; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsFamilyOrAssembly(this PropertyDef property)
 {
     return(property.AllMethods().Any(method => method.IsFamilyOrAssembly));
 }
Example #18
0
        public override bool ResetMembers(MetaOperations metaOperation, AgentType agentType, BaseType baseType, MethodDef method, PropertyDef property)
        {
            bool bReset = false;

            if (this._time != null)
            {
                bReset |= this._time.ResetMembers(metaOperation, agentType, baseType, method, property);
            }

            bReset |= base.ResetMembers(metaOperation, agentType, baseType, method, property);

            return(bReset);
        }
Example #19
0
 /// <summary>
 /// Determines whether this instance has private flags for all prop methods.
 /// </summary>
 /// <param name="property">The property.</param>
 /// <returns>
 ///   <c>true</c> if the specified property is family; otherwise, <c>false</c>.
 /// </returns>
 public static bool HasAllPrivateFlags(this PropertyDef property)
 {
     return(property.AllMethods().All(method => method.HasPrivateFlags()));
 }
Example #20
0
		public MPropertyDef Create(PropertyDef newProp) {
			if (FindAny(newProp) != null)
				throw new ApplicationException("Can't add a property when it's already been added");

			var propDef = new MPropertyDef(newProp, this, properties.Count);
			Add(propDef);
			TypeDef.Properties.Add(newProp);
			return propDef;
		}
Example #21
0
 /// <summary>
 ///     Determines whether the specified property is static.
 /// </summary>
 /// <param name="property">The property.</param>
 /// <returns><c>true</c> if the specified property is static; otherwise, <c>false</c>.</returns>
 public static bool IsStatic(this PropertyDef property)
 {
     return(property.AllMethods().Any(method => method.IsStatic));
 }
        private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_valueWasAssigned || comboBox.SelectedIndex < 0 || comboBox.SelectedIndex >= _properties.Count)
                return;

            PropertyDef selectedProperty = _properties[comboBox.SelectedIndex];
            selectedProperty = new PropertyDef(selectedProperty);
            selectedProperty.Owner = !string.IsNullOrEmpty(_globalType) ? _globalType : VariableDef.kSelf;

            if (_property.Property != null)
            {
                object propertyMember = _property.Property.GetValue(_object, null);
                VariableDef var = propertyMember as VariableDef;
                DesignerRightValueEnum rvPropertyEnum = _property.Attribute as DesignerRightValueEnum;
                if (rvPropertyEnum == null)
                {
                    if (var == null)
                        var = new VariableDef(selectedProperty, VariableDef.kSelf);
                    else
                        var.SetProperty(selectedProperty, var.ValueClass);

                    _property.Property.SetValue(_object, var, null);
                }
                else if (propertyMember != null)
                {
                    RightValueDef varRV = propertyMember as RightValueDef;

                    if (varRV == null)
                    {
                        Debug.Check(false);
                        //varRV = new RightValueDef(selectedProperty, VariableDef.kSelf);
                    }
                    else
                    {
                        if (varRV.IsMethod)
                        {
                            Debug.Check(false);
                        }
                        else
                        {
                            if (varRV.Var != null)
                            {
                                varRV.Var.SetProperty(selectedProperty, varRV.ValueClassReal);
                            }
                            else
                            {
                                var = new VariableDef(selectedProperty, varRV.ValueClassReal);
                                varRV = new RightValueDef(var);
                            }
                        }
                    }

                    _property.Property.SetValue(_object, varRV, null);
                }
            }
            else if (_param != null)
            {
                string valueType = !string.IsNullOrEmpty(_globalType) ? _globalType : VariableDef.kSelf;
                _param.Value = new VariableDef(selectedProperty, valueType);
            }

            OnValueChanged(_property);

            this.RereshProperty(false, _property);
        }
Example #23
0
        public object Deserialize(string fileName)
        {
            var serializer = new XmlSerializer(typeof(game));
            directory = new FileInfo(fileName).Directory.FullName;
            game g = null;
            var fileHash = "";
            using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                g = (game)serializer.Deserialize(fs);
                if (g == null)
                {
                    return null;
                }
                using (MD5 md5 = new MD5CryptoServiceProvider())
                {
                    fs.Seek(0, SeekOrigin.Begin);
                    byte[] retVal = md5.ComputeHash(fs);
                    fileHash = BitConverter.ToString(retVal).Replace("-", ""); // hex string
                }
            }
            var ret = new Game()
                          {
                              Id = new Guid(g.id),
                              Name = g.name,
							  CardSizes = new Dictionary<string, CardSize>(),
                              GameBoards = new Dictionary<string, GameBoard>(),
                              Version = Version.Parse(g.version),
                              CustomProperties = new List<PropertyDef>(),
                              DeckSections = new Dictionary<string, DeckSection>(),
                              SharedDeckSections = new Dictionary<string, DeckSection>(),
                              GlobalVariables = new List<GlobalVariable>(),
                              Authors = g.authors.Split(',').ToList(),
                              Description = g.description,
                              Filename = fileName,
                              ChatFont = new Font(),
                              ContextFont = new Font(),
                              NoteFont = new Font(),
                              DeckEditorFont = new Font(),
                              GameUrl = g.gameurl,
                              IconUrl = g.iconurl,
                              Tags = g.tags.Split(' ').ToList(),
                              OctgnVersion = Version.Parse(g.octgnVersion),
                              Variables = new List<Variable>(),
                              MarkerSize = g.markersize,
                              Documents = new List<Document>(),
                              Sounds = new Dictionary<string, GameSound>(),
                              FileHash = fileHash,
                              Events = new Dictionary<string, GameEvent[]>(),
                              InstallPath = directory,
                              UseTwoSidedTable = g.usetwosidedtable == boolean.True ? true : false,
                              NoteBackgroundColor = g.noteBackgroundColor,
                              NoteForegroundColor = g.noteForegroundColor,
                              ScriptVersion = Version.Parse(g.scriptVersion),
                              Scripts = new List<string>(),
							  Modes = new List<GameMode>(),
                          };
            var defSize = new CardSize();
            defSize.Name = "Default";
			defSize.Back = String.IsNullOrWhiteSpace(g.card.back) ? "pack://application:,,,/Resources/Back.jpg" : Path.Combine(directory, g.card.back);
			defSize.Front = String.IsNullOrWhiteSpace(g.card.front) ? "pack://application:,,,/Resources/Front.jpg" : Path.Combine(directory, g.card.front);
            defSize.Height = int.Parse(g.card.height);
            defSize.Width = int.Parse(g.card.width);
			defSize.CornerRadius = int.Parse(g.card.cornerRadius);
            defSize.BackHeight = int.Parse(g.card.backHeight);
            defSize.BackWidth = int.Parse(g.card.backWidth);
			defSize.BackCornerRadius = int.Parse(g.card.backCornerRadius);
            if (defSize.BackHeight < 0)
                defSize.BackHeight = defSize.Height;
            if (defSize.BackWidth < 0)
                defSize.BackWidth = defSize.Width;
            if (defSize.BackCornerRadius < 0)
                defSize.BackCornerRadius = defSize.CornerRadius;
			ret.CardSizes.Add("Default", defSize);
            ret.CardSize = ret.CardSizes["Default"];

            #region variables
            if (g.variables != null)
            {
                foreach (var item in g.variables)
                {
                    ret.Variables.Add(new Variable
                                          {
                                              Name = item.name,
                                              Global = bool.Parse(item.global.ToString()),
                                              Reset = bool.Parse(item.reset.ToString()),
                                              Default = int.Parse(item.@default)
                                          });
                }
            }
            #endregion variables
            #region table
            ret.Table = this.DeserialiseGroup(g.table, 0);
            #endregion table
            #region gameBoards
            if (g.gameboards == null)
            {
                var defBoard = new GameBoard();
                defBoard.Name = "Default";
                defBoard.Source = g.table.board == null ? null : Path.Combine(directory, g.table.board);
                defBoard.XPos = g.table.boardPosition == null ? 0 : double.Parse(g.table.boardPosition.Split(',')[0]);
                defBoard.YPos = g.table.boardPosition == null ? 0 : double.Parse(g.table.boardPosition.Split(',')[1]);
                defBoard.Width = g.table.boardPosition == null ? 0 : double.Parse(g.table.boardPosition.Split(',')[2]);
                defBoard.Height = g.table.boardPosition == null ? 0 : double.Parse(g.table.boardPosition.Split(',')[3]);
                ret.GameBoards.Add("Default", defBoard);
            }
            else
            {
                var defBoard = new GameBoard();
                defBoard.Name = "Default";
                defBoard.Source = Path.Combine(directory, g.gameboards.src);
                defBoard.XPos = int.Parse(g.gameboards.x);
                defBoard.YPos = int.Parse(g.gameboards.y);
                defBoard.Width = int.Parse(g.gameboards.width);
                defBoard.Height = int.Parse(g.gameboards.height);
                ret.GameBoards.Add("Default", defBoard);
                foreach (var board in g.gameboards.gameboard)
                {
                    var b = new GameBoard();
                    b.Name = board.name;
                    b.XPos = int.Parse(board.x);
                    b.YPos = int.Parse(board.y);
                    b.Width = int.Parse(board.width);
                    b.Height = int.Parse(board.height);
                    b.Source = Path.Combine(directory, board.src);
                    ret.GameBoards.Add(board.name, b);
                   }
             }
            #endregion gameBoards
            #region shared
            if (g.shared != null)
            {
                var player = new GlobalPlayer
                                   { 
                                     Counters = new List<Counter>(), 
                                     Groups = new List<Group>(),
                                     IndicatorsFormat = g.shared.summary
                                   };

                var curCounter = 1;
                var curGroup = 2;
                if (g.shared.counter != null)
                {
                    foreach (var i in g.shared.counter)
                    {
                        (player.Counters as List<Counter>).Add(
                            new Counter
                                {
                                    Id = (byte)curCounter,
                                    Name = i.name,
                                    Icon = Path.Combine(directory, i.icon ?? ""),
                                    Reset = bool.Parse(i.reset.ToString()),
                                    Start = int.Parse(i.@default)
                                });
                        curCounter++;
                    }
                }
                if (g.shared.group != null)
                {
                    foreach (var i in g.shared.group)
                    {
                        (player.Groups as List<Group>).Add(this.DeserialiseGroup(i, curGroup));
                        curGroup++;
                    }
                }
                ret.GlobalPlayer = player;
            }
            #endregion shared
            #region Player
            if (g.player != null)
            {
                var player = new Player
                                 {
                                     Groups = new List<Group>(),
                                     GlobalVariables = new List<GlobalVariable>(),
                                     Counters = new List<Counter>(),
                                     IndicatorsFormat = g.player.summary
                                 };
                var curCounter = 1;
                var curGroup = 2;
                foreach (var item in g.player.Items)
                {
                    if (item is counter)
                    {
                        var i = item as counter;
                        (player.Counters as List<Counter>)
                            .Add(new Counter
                                     {
                                         Id = (byte)curCounter,
                                         Name = i.name,
                                         Icon = Path.Combine(directory, i.icon ?? ""),
                                         Reset = bool.Parse(i.reset.ToString()),
                                         Start = int.Parse(i.@default)
                                     });
                        curCounter++;
                    }
                    else if (item is gamePlayerGlobalvariable)
                    {
                        var i = item as gamePlayerGlobalvariable;
                        var to = new GlobalVariable { Name = i.name, Value = i.value, DefaultValue = i.value };
                        (player.GlobalVariables as List<GlobalVariable>).Add(to);
                    }
                    else if (item is hand)
                    {
                        player.Hand = this.DeserialiseGroup(item as hand, 1);
                    }
                    else if (item is group)
                    {
                        var i = item as group;
                        (player.Groups as List<Group>).Add(this.DeserialiseGroup(i, curGroup));
                        curGroup++;
                    }
                }
                ret.Player = player;
            }
            #endregion Player

            #region documents
            if (g.documents != null)
            {
                foreach (var doc in g.documents)
                {
                    var d = new Document();
                    d.Icon = Path.Combine(directory, doc.icon);
                    d.Name = doc.name;
                    d.Source = Path.Combine(directory, doc.src);
                    ret.Documents.Add(d);
                }
            }
            #endregion documents
            #region sounds
            if (g.sounds != null)
            {
                foreach (var sound in g.sounds)
                {
                    var s = new GameSound();
                    s.Gameid = ret.Id;
                    s.Name = sound.name;
                    s.Src = Path.Combine(directory, sound.src);
                    ret.Sounds.Add(s.Name.ToLowerInvariant(), s);
                }
            }
            #endregion sounds
            #region deck
            if (g.deck != null)
            {
                foreach (var ds in g.deck)
                {
                    ret.DeckSections.Add(ds.name, new DeckSection { Group = ds.group, Name = ds.name, Shared = false });
                }
            }
            if (g.sharedDeck != null)
            {
                foreach (var s in g.sharedDeck)
                {
                    ret.SharedDeckSections.Add(s.name, new DeckSection { Group = s.group, Name = s.name, Shared = true });
                }
            }
            #endregion deck
            #region card
            if (g.card != null)
            {
                if (g.card.property != null)
                {
                    foreach (var prop in g.card.property)
                    {
                        var pd = new PropertyDef();
                        pd.Name = prop.name;
                        switch (prop.textKind)
                        {
                            case propertyDefTextKind.Free:
                                pd.TextKind = PropertyTextKind.FreeText;
                                break;
                            case propertyDefTextKind.Enum:
                                pd.TextKind = PropertyTextKind.Enumeration;
                                break;
                            case propertyDefTextKind.Tokens:
                                pd.TextKind = PropertyTextKind.Tokens;
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                        pd.Type = (PropertyType) Enum.Parse(typeof (PropertyType), prop.type.ToString());
                        pd.IgnoreText = bool.Parse(prop.ignoreText.ToString());
                        pd.Hidden = bool.Parse(prop.hidden);
                        ret.CustomProperties.Add(pd);
                    }
                }
                if (g.card.size != null)
                {
                    foreach (var size in g.card.size)
                    {
                        var cs = new CardSize();
                        cs.Name = size.name;
                        cs.Width = int.Parse(size.width);
                        cs.Height = int.Parse(size.height);
                        cs.CornerRadius = int.Parse(size.cornerRadius);
                        cs.BackWidth = int.Parse(size.backWidth);
                        cs.BackHeight = int.Parse(size.backHeight);
                        cs.BackCornerRadius = int.Parse(size.backCornerRadius);
                        if (cs.BackHeight < 0)
                            cs.BackHeight = ret.CardSize.Height;
                        if (cs.BackWidth < 0)
                            cs.BackWidth = ret.CardSize.Width;
                        if (cs.BackCornerRadius < 0)
                            cs.BackCornerRadius = ret.CardSize.CornerRadius;
                        cs.Front = String.IsNullOrWhiteSpace(size.front) ? "pack://application:,,,/Resources/Front.jpg" : Path.Combine(directory, size.front);
                        cs.Back = String.IsNullOrWhiteSpace(size.back) ? "pack://application:,,,/Resources/Back.jpg" : Path.Combine(directory, size.back);
						ret.CardSizes.Add(cs.Name,cs);
                    }
                }
            }
            var namepd = new PropertyDef();
            namepd.Name = "Name";
            namepd.TextKind = PropertyTextKind.FreeText;
            namepd.Type = PropertyType.String;
            ret.CustomProperties.Add(namepd);
            #endregion card
            #region fonts
            if (g.fonts != null)
            {
                foreach (gameFont font in g.fonts)
                {
                    Font f = new Font();
                    f.Src = Path.Combine(directory, font.src ?? "").Replace("/", "\\");
                    f.Size = (int)font.size;
                    switch (font.target)
                    {
                        case fonttarget.chat:
                            ret.ChatFont = f;
                            break;
                        case fonttarget.context:
                            ret.ContextFont = f;
                            break;
                        case fonttarget.deckeditor:
                            ret.DeckEditorFont = f;
                            break;
                        case fonttarget.notes:
                            ret.NoteFont = f;
                            break;
                    }
                }
            }
            #endregion fonts
            #region scripts
            if (g.scripts != null)
            {
                foreach (var s in g.scripts)
                {
                    ret.Scripts.Add(s.src);
                    var coll = Def.Config
                        .DefineCollection<GameScript>("Scripts")
                        .OverrideRoot(x => x.Directory("GameDatabase"))
                        .SetPart(x => x.Directory(ret.Id.ToString()));
                    var pathParts = s.src.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    for (var index = 0; index < pathParts.Length; index++)
                    {
                        var i = index;
                        if (i == pathParts.Length - 1) coll.SetPart(x => x.File(pathParts[i]));
                        else coll.SetPart(x => x.Directory(pathParts[i]));
                    }
                    coll.SetSerializer(new GameScriptSerializer(ret.Id));
                }
            }
            #endregion scripts

            #region events

            if (g.events != null)
            {
                foreach (var e in g.events)
                {
                    var eve = new GameEvent()
                      {
                          Name = e.name.Clone() as string,
                          PythonFunction =
                              e.action.Clone() as string
                      };
                    if (ret.Events.ContainsKey(e.name))
                    {
                        var narr = ret.Events[e.name];
                        Array.Resize(ref narr, narr.Length + 1);
                        narr[narr.Length - 1] = eve;
                        ret.Events[e.name] = narr;
                    }
                    else
                    {
                        ret.Events.Add(e.name, new GameEvent[1] { eve });
                    }
                }
            }
            #endregion Events
            #region proxygen
            if (g.proxygen != null && g.proxygen.definitionsrc != null)
            {
                ret.ProxyGenSource = g.proxygen.definitionsrc;
                var coll =
                    Def.Config.DefineCollection<ProxyDefinition>("Proxies")
                       .OverrideRoot(x => x.Directory("GameDatabase"))
                       .SetPart(x => x.Directory(ret.Id.ToString()));
                //.SetPart(x => x.Property(y => y.Key));
                var pathParts = g.proxygen.definitionsrc.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                for (var index = 0; index < pathParts.Length; index++)
                {
                    var i = index;
                    if (i == pathParts.Length - 1) coll.SetPart(x => x.File(pathParts[i]));
                    else coll.SetPart(x => x.Directory(pathParts[i]));
                }
                coll.SetSerializer(new ProxyGeneratorSerializer(ret.Id, g.proxygen));
            }
            #endregion proxygen
            #region globalvariables
            if (g.globalvariables != null)
            {
                foreach (var item in g.globalvariables)
                {
                    ret.GlobalVariables.Add(new GlobalVariable { Name = item.name, Value = item.value, DefaultValue = item.value });
                }
            }
            #endregion globalvariables
            #region hash
            #endregion hash
            #region GameModes

            if (g.gameModes != null)
            {
                foreach (var mode in g.gameModes)
                {
                    var m = new GameMode();
                    m.Name = mode.name;
                    m.PlayerCount = mode.playerCount;
                    m.ShortDescription = mode.shortDescription;
                    m.Image = Path.Combine(directory, mode.image);
                    m.UseTwoSidedTable = mode.usetwosidedtable;
                    ret.Modes.Add(m);
                }
            }

            if (ret.Modes.Count == 0)
            {
                var gm = new GameMode();
                gm.Name = "Default";
                gm.PlayerCount = 2;
                gm.ShortDescription = "Default Game Mode";
                ret.Modes.Add(gm);
            }

            #endregion GameModes
            return ret;
        }
Example #24
0
 public virtual bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null) {
     return false;
 }
Example #25
0
        void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, PropertyDef property)
        {
            bool setRename = service.CanRename(property.SetMethod);
            bool getRename = service.CanRename(property.GetMethod);

            if ((!setRename || !getRename) &&
                parameters.GetParameter(context, property, "dontRenImpls", false))
            {
                service.SetCanRename(property, false);
            }

            else if (IsVisibleOutside(context, parameters, property.DeclaringType) &&
                     property.IsPublic() &&
                     IsVisibleOutside(context, parameters, property))
            {
                service.SetCanRename(property, false);
            }

            else if (property.IsRuntimeSpecialName)
            {
                service.SetCanRename(property, false);
            }

            else if (parameters.GetParameter(context, property, "forceRen", false))
            {
                return;
            }

            else if (property.DeclaringType.Implements("System.ComponentModel.INotifyPropertyChanged"))
            {
                service.SetCanRename(property, false);
            }

            else if (property.DeclaringType.Name.String.Contains("AnonymousType"))
            {
                service.SetCanRename(property, false);
            }
        }
Example #26
0
 /// <summary>
 ///     Determines whether the specified property is an explictly implemented interface member.
 /// </summary>
 /// <param name="property">The method.</param>
 /// <returns><c>true</c> if the specified property is an explictly implemented interface member; otherwise, <c>false</c>.</returns>
 public static bool IsExplicitlyImplementedInterfaceMember(this PropertyDef property)
 {
     return(property.AllMethods().Any(IsExplicitlyImplementedInterfaceMember));
 }
Example #27
0
 public PropertyInfo(PropertyDef propertyDef)
     : base(propertyDef)
 {
 }
Example #28
0
 public PropertyInfo prop(PropertyDef prop)
 {
     return allPropertyInfos[prop];
 }
Example #29
0
 private static IEnumerable <MethodDef> AllMethods(this PropertyDef property)
 {
     return(new[] { property.GetMethod, property.SetMethod }
            .Concat(property.OtherMethods)
            .Where(m => m != null));
 }
Example #30
0
 public PropertyNode Create(PropertyDef property) =>
 (PropertyNode)TreeView.Create(new PropertyNodeImpl(DocumentTreeNodeGroups.GetGroup(DocumentTreeNodeGroupType.PropertyTreeNodeGroupType), property)).Data;
Example #31
0
 public PropertyInfo prop(PropertyDef prop)
 {
     return memberInfos.prop(prop);
 }
Example #32
0
 public static string GetGeneratedPropertyDefaultValue(PropertyDef prop, string typename)
 {
     return((prop != null) ? GetGeneratedDefaultValue(prop.Type, typename, prop.DefaultValue) : null);
 }
Example #33
0
        void prepareRenameProperty(PropertyDef propDef)
        {
            if (propDef.isVirtual())
                throw new ApplicationException("Can't rename virtual props here");
            var propInfo = prop(propDef);
            if (propInfo.renamed)
                return;

            string propName = propInfo.oldName;
            if (!NameChecker.isValidPropertyName(propName))
                propName = propInfo.suggestedName;
            if (!NameChecker.isValidPropertyName(propName))
                propName = variableNameState.getNewPropertyName(propDef.PropertyDefinition);
            variableNameState.addPropertyName(propName);
            propInfo.rename(propName);

            renameSpecialMethod(propDef.GetMethod, "get_" + propName);
            renameSpecialMethod(propDef.SetMethod, "set_" + propName);
        }
 public override DocumentTreeNodeFilterResult GetResult(PropertyDef prop) => new DocumentTreeNodeFilterResult(FilterType.Visible, false);
Example #35
0
 public PropertyOverridesNode(PropertyDef analyzedProperty) => this.analyzedProperty = analyzedProperty ?? throw new ArgumentNullException(nameof(analyzedProperty));
        void Analyze(NameService service, ConfuserContext context, ProtectionParameters parameters, PropertyDef property)
        {
            if (IsVisibleOutside(context, parameters, property.DeclaringType) &&
                IsVisibleOutside(context, parameters, property))
            {
                service.SetCanRename(property, false);
            }

            else if (property.IsRuntimeSpecialName)
            {
                service.SetCanRename(property, false);
            }

            else if (parameters.GetParameter(context, property, "forceRen", false))
            {
                return;
            }

            /*
             * System.Xml.Serialization.XmlSerializer
             *
             * XmlSerializer by default serializes fields marked with [NonSerialized]
             * This is a work-around that causes all fields in a class marked [Serializable]
             * to _not_ be renamed, unless marked with [XmlIgnoreAttribute]
             *
             * If we have a way to detect which serializer method the code is going to use
             * for the class, or if Microsoft makes XmlSerializer respond to [NonSerialized]
             * we'll have a more accurate way to achieve this.
             */
            else if (property.DeclaringType.IsSerializable) // && !field.IsNotSerialized)
            {
                service.SetCanRename(property, false);
            }

            else if (property.IsExplicitlyImplementedInterfaceMember())
            {
                service.SetCanRename(property, false);
            }

            else if (property.DeclaringType.IsSerializable && (property.CustomAttributes.IsDefined("XmlIgnore") ||
                                                               property.CustomAttributes.IsDefined("XmlIgnoreAttribute") ||
                                                               property.CustomAttributes.IsDefined("System.Xml.Serialization.XmlIgnore") ||
                                                               property.CustomAttributes.IsDefined("System.Xml.Serialization.XmlIgnoreAttribute") ||
                                                               property.CustomAttributes.IsDefined("T:System.Xml.Serialization.XmlIgnoreAttribute"))) // Can't seem to detect CustomAttribute
            {
                service.SetCanRename(property, true);
            }

            /*
             * End of XmlSerializer work-around
             */

            else if (property.DeclaringType.Implements("System.ComponentModel.INotifyPropertyChanged"))
            {
                service.SetCanRename(property, false);
            }

            else if (property.DeclaringType.Name.String.Contains("AnonymousType"))
            {
                service.SetCanRename(property, false);
            }
        }
Example #37
0
 public virtual DocumentTreeNodeFilterResult GetResult(PropertyDef prop) => new DocumentTreeNodeFilterResult(FilterType.Hide, false);
		/// <inheritdoc/>
		public override uint GetRid(PropertyDef pd) {
			uint rid;
			if (propertyDefInfos.TryGetRid(pd, out rid))
				return rid;
			if (pd == null)
				Error("Property is null");
			else
				Error("Property {0} ({1:X8}) is not defined in this module ({2})", pd, pd.MDToken.Raw, module);
			return 0;
		}
 public virtual FileTreeNodeFilterResult GetResult(PropertyDef prop) => this.filter.GetResult(prop);
Example #40
0
		public MPropertyDef FindAny(PropertyDef pr) {
			return properties.FindAny(pr);
		}
Example #41
0
 public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null)
 {
     // This function should be empty here, so don't remove it.
     return(false);
 }
Example #42
0
        public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null) {
            bool bReset = false;

            if (!this._isVisiting) {
                this._isVisiting = true;

                bReset = base.ResetMembers(check, agentType, clear, method, property);

                this._isVisiting = false;
            }

            return bReset;
        }
Example #43
0
        public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null)
        {
            bool bReset = false;

            if (this._task != null && method != null && this._task.Name == method.OldName)
            {
                if (method != null && this._task.Name == method.OldName &&
                    (clear || this._task.ShouldBeCleared(agentType)))
                {
                    bReset = true;

                    if (!check)
                    {
                        this._task = null;
                    }
                }
                else
                {
                    bReset |= this._task.ResetMembers(check, agentType, clear, method, property);
                }
            }

            bReset |= base.ResetMembers(check, agentType, clear, method, property);

            return(bReset);
        }
Example #44
0
        public object Deserialize(string fileName)
        {
            var serializer = new XmlSerializer(typeof(game));
            directory = new FileInfo(fileName).Directory.FullName;
            game g = null;
            var fileHash = "";
            using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                g = (game)serializer.Deserialize(fs);
                if (g == null)
                {
                    return null;
                }
                using (MD5 md5 = new MD5CryptoServiceProvider())
                {
                    fs.Seek(0, SeekOrigin.Begin);
                    byte[] retVal = md5.ComputeHash(fs);
                    fileHash = BitConverter.ToString(retVal).Replace("-", ""); // hex string
                }
            }
            var ret = new Game()
                          {
                              Id = new Guid(g.id),
                              Name = g.name,
                              CardBack = String.IsNullOrWhiteSpace(g.card.back) ? "pack://application:,,,/Resources/Back.jpg" : Path.Combine(directory, g.card.back),
                              CardFront = String.IsNullOrWhiteSpace(g.card.front) ? "pack://application:,,,/Resources/Front.jpg" : Path.Combine(directory, g.card.front),
                              CardHeight = int.Parse(g.card.height),
                              CardWidth = int.Parse(g.card.width),
                              CardCornerRadius = int.Parse(g.card.cornerRadius),
                              Version = Version.Parse(g.version),
                              CustomProperties = new List<PropertyDef>(),
                              DeckSections = new Dictionary<string, DeckSection>(),
                              SharedDeckSections = new Dictionary<string, DeckSection>(),
                              GlobalVariables = new List<GlobalVariable>(),
                              Authors = g.authors.Split(',').ToList(),
                              Description = g.description,
                              Filename = fileName,
                              Fonts = new List<Font>(),
                              GameUrl = g.gameurl,
                              IconUrl = g.iconurl,
                              Tags = g.tags.Split(' ').ToList(),
                              OctgnVersion = Version.Parse(g.octgnVersion),
                              Variables = new List<Variable>(),
                              MarkerSize = g.markersize,
                              Documents = new List<Document>(),
                              Sounds = new Dictionary<string,GameSound>(),
                              FileHash=fileHash
                          };
            #region variables
            if (g.variables != null)
            {
                foreach (var item in g.variables)
                {
                    ret.Variables.Add(new Variable
                                          {
                                              Name = item.name,
                                              Global = bool.Parse(item.global.ToString()),
                                              Reset = bool.Parse(item.reset.ToString()),
                                              Default = int.Parse(item.@default)
                                          });
                }
            }
            #endregion variables
            #region table
            ret.Table = this.DeserialiseGroup(g.table, 0);
            #endregion table
            #region shared
            if (g.shared != null)
            {
                var player = new GlobalPlayer { Counters = new List<Counter>(), Groups = new List<Group>() };
                var curCounter = 1;
                var curGroup = 1;
                if (g.shared.counter != null)
                {
                    foreach (var i in g.shared.counter)
                    {
                        (player.Counters as List<Counter>).Add(
                            new Counter
                                {
                                    Id = (byte)curCounter,
                                    Name = i.name,
                                    Icon = Path.Combine(directory, i.icon ?? ""),
                                    Reset = bool.Parse(i.reset.ToString()),
                                    Start = int.Parse(i.@default)
                                });
                        curCounter++;
                    }
                }
                if (g.shared.group != null)
                {
                    foreach (var i in g.shared.group)
                    {
                        (player.Groups as List<Group>).Add(this.DeserialiseGroup(i, curGroup));
                        curGroup++;
                    }
                }
                ret.GlobalPlayer = player;
            }
            #endregion shared
            #region Player
            if (g.player != null)
            {
                var player = new Player
                                 {
                                     Groups = new List<Group>(),
                                     GlobalVariables = new List<GlobalVariable>(),
                                     Counters = new List<Counter>(),
                                     IndicatorsFormat = g.player.summary
                                 };
                var curCounter = 1;
                var curGroup = 1;
                foreach (var item in g.player.Items)
                {
                    if (item is counter)
                    {
                        var i = item as counter;
                        (player.Counters as List<Counter>)
                            .Add(new Counter
                                     {
                                         Id = (byte)curCounter,
                                         Name = i.name,
                                         Icon = Path.Combine(directory, i.icon ?? ""),
                                         Reset = bool.Parse(i.reset.ToString()),
                                         Start = int.Parse(i.@default)
                                     });
                        curCounter++;
                    }
                    else if (item is gamePlayerGlobalvariable)
                    {
                        var i = item as gamePlayerGlobalvariable;
                        var to = new GlobalVariable { Name = i.name, Value = i.value, DefaultValue = i.value };
                        (player.GlobalVariables as List<GlobalVariable>).Add(to);
                    }
                    else if (item is hand)
                    {
                        player.Hand = this.DeserialiseGroup(item as hand, 0);
                    }
                    else if (item is group)
                    {
                        var i = item as group;
                        (player.Groups as List<Group>).Add(this.DeserialiseGroup(i, curGroup));
                        curGroup++;
                    }
                }
                ret.Player = player;
            }
            #endregion Player

            #region documents
            if (g.documents != null)
            {
                foreach (var doc in g.documents)
                {
                    var d = new Document();
                    d.Icon = Path.Combine(directory, doc.icon);
                    d.Name = doc.name;
                    d.Source = Path.Combine(directory, doc.src);
                    ret.Documents.Add(d);
                }
            }
            #endregion documents
            #region sounds
            if (g.sounds != null)
            {
                foreach (var sound in g.sounds)
                {
                    var s = new GameSound();
                    s.Gameid = ret.Id;
                    s.Name = sound.name;
                    s.Src = Path.Combine(directory, sound.src);
                    ret.Sounds.Add(s.Name.ToLowerInvariant(),s);
                }
            }
            #endregion sounds
            #region deck
            if (g.deck != null)
            {
                foreach (var ds in g.deck)
                {
                    ret.DeckSections.Add(ds.name, new DeckSection { Group = ds.group, Name = ds.name });
                }
            }
            if (g.sharedDeck != null)
            {
                foreach (var s in g.sharedDeck)
                {
                    ret.SharedDeckSections.Add(s.name, new DeckSection { Group = s.group, Name = s.name });
                }
            }
            #endregion deck
            #region card
            if (g.card != null && g.card.property != null)
            {
                foreach (var prop in g.card.property)
                {
                    var pd = new PropertyDef();
                    pd.Name = prop.name;
                    switch (prop.textKind)
                    {
                        case propertyDefTextKind.Free:
                            pd.TextKind = PropertyTextKind.FreeText;
                            break;
                        case propertyDefTextKind.Enum:
                            pd.TextKind = PropertyTextKind.Enumeration;
                            break;
                        case propertyDefTextKind.Tokens:
                            pd.TextKind = PropertyTextKind.Tokens;
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                    pd.Type = (PropertyType)Enum.Parse(typeof(PropertyType), prop.type.ToString());
                    pd.IgnoreText = bool.Parse(prop.ignoreText.ToString());
                    pd.Hidden = bool.Parse(prop.hidden);
                    ret.CustomProperties.Add(pd);
                }
            }
            var namepd = new PropertyDef();
            namepd.Name = "Name";
            namepd.TextKind = PropertyTextKind.FreeText;
            namepd.Type = PropertyType.String;
            ret.CustomProperties.Add(namepd);
            #endregion card
            #region fonts
            if (g.fonts != null)
            {
                foreach (gameFont font in g.fonts)
                {
                    Font f = new Font();
                    f.Src = Path.Combine(directory, font.src ?? "");
                    f.Size = (int)font.size;
                    switch (font.target)
                    {
                        case fonttarget.chat:
                            f.Target = Enum.Parse(typeof(fonttarget), "chat").ToString();
                            break;
                        case fonttarget.context:
                            f.Target = Enum.Parse(typeof(fonttarget), "context").ToString();
                            break;
                        case fonttarget.deckeditor:
                            f.Target = Enum.Parse(typeof(fonttarget), "deckeditor").ToString();
                            break;
                    }
                    ret.Fonts.Add(f);
                }
            }
            #endregion fonts
            #region scripts
            if (g.scripts != null)
            {
                foreach (var s in g.scripts)
                {
                    var coll = Def.Config
                        .DefineCollection<GameScript>("Scripts")
                        .OverrideRoot(x => x.Directory("GameDatabase"))
                        .SetPart(x => x.Directory(ret.Id.ToString()));
                    var pathParts = s.src.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                    for (var index = 0; index < pathParts.Length; index++)
                    {
                        var i = index;
                        if (i == pathParts.Length - 1) coll.SetPart(x => x.File(pathParts[i]));
                        else coll.SetPart(x => x.Directory(pathParts[i]));
                    }
                    coll.SetSerializer(new GameScriptSerializer(ret.Id));
                }
            }
            #endregion scripts
            #region proxygen
            if (g.proxygen != null)
            {
                var coll =
                    Def.Config.DefineCollection<ProxyDefinition>("Proxies")
                       .OverrideRoot(x => x.Directory("GameDatabase"))
                       .SetPart(x => x.Directory(ret.Id.ToString()));
                //.SetPart(x => x.Property(y => y.Key));
                var pathParts = g.proxygen.definitionsrc.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                for (var index = 0; index < pathParts.Length; index++)
                {
                    var i = index;
                    if (i == pathParts.Length - 1) coll.SetPart(x => x.File(pathParts[i]));
                    else coll.SetPart(x => x.Directory(pathParts[i]));
                }
                coll.SetSerializer(new ProxyGeneratorSerializer(ret.Id, g.proxygen));
            }
            #endregion proxygen
            #region globalvariables
            if (g.globalvariables != null)
            {
                foreach (var item in g.globalvariables)
                {
                    ret.GlobalVariables.Add(new GlobalVariable { Name = item.name, Value = item.value, DefaultValue = item.value });
                }
            }
            #endregion globalvariables
            #region hash
            #endregion hash
            return ret;
        }
Example #45
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="property">Property</param>
 protected PropertyNode(PropertyDef property) => PropertyDef = property ?? throw new ArgumentNullException(nameof(property));
Example #46
0
 void Add(PropertyDef pd)
 {
     if (pd == null || propertyDefs.ContainsKey(pd))
         return;
     if (pd.DeclaringType != null && pd.DeclaringType.Module != validModule)
         return;
     propertyDefs[pd] = true;
     Add(pd.Type);
     Add(pd.CustomAttributes);
     Add(pd.GetMethod);
     Add(pd.SetMethod);
     Add(pd.OtherMethods);
     Add(pd.DeclaringType);
 }
        private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!_valueWasAssigned || comboBox.SelectedIndex < 0 || comboBox.SelectedIndex >= _properties.Count)
            {
                return;
            }

            PropertyDef selectedProperty = _properties[comboBox.SelectedIndex];

            selectedProperty       = selectedProperty.Clone();
            selectedProperty.Owner = _valueOwner;

            bool isArrayElement = selectedProperty.IsArrayElement;
            bool bForceFresh    = false;

            if (_property.Property != null)
            {
                object                 propertyMember = _property.Property.GetValue(_object, null);
                VariableDef            var            = propertyMember as VariableDef;
                DesignerRightValueEnum rvPropertyEnum = _property.Attribute as DesignerRightValueEnum;

                if (rvPropertyEnum == null)
                {
                    if (var == null)
                    {
                        var = new VariableDef(selectedProperty, VariableDef.kSelf);
                    }

                    else
                    {
                        var.SetProperty(selectedProperty, var.ValueClass);
                    }

                    if (isArrayElement && var.ArrayIndexElement == null)
                    {
                        var.ArrayIndexElement = new MethodDef.Param("ArrayIndex", typeof(int), "int", "ArrayIndex", "ArrayIndex");
                        var.ArrayIndexElement.IsArrayIndex = true;
                        bForceFresh = true;
                    }
                    else if (!isArrayElement && var.ArrayIndexElement != null)
                    {
                        var.ArrayIndexElement = null;
                        bForceFresh           = true;
                    }

                    _property.Property.SetValue(_object, var, null);
                }
                else if (propertyMember != null)
                {
                    RightValueDef varRV = propertyMember as RightValueDef;

                    if (varRV == null)
                    {
                        Debug.Check(false);
                        //varRV = new RightValueDef(selectedProperty, VariableDef.kSelf);
                    }
                    else
                    {
                        if (varRV.IsMethod)
                        {
                            Debug.Check(false);
                        }
                        else
                        {
                            if (varRV.Var != null)
                            {
                                varRV.Var.SetProperty(selectedProperty, varRV.ValueClassReal);
                            }
                            else
                            {
                                var   = new VariableDef(selectedProperty, varRV.ValueClassReal);
                                varRV = new RightValueDef(var);
                            }
                        }
                    }

                    if (varRV != null && varRV.Var != null)
                    {
                        if (isArrayElement && varRV.Var.ArrayIndexElement == null)
                        {
                            varRV.Var.ArrayIndexElement = new MethodDef.Param("ArrayIndex", typeof(int), "int", "ArrayIndex", "ArrayIndex");
                            varRV.Var.ArrayIndexElement.IsArrayIndex = true;

                            bForceFresh = true;
                        }
                        else if (!isArrayElement && varRV.Var.ArrayIndexElement != null)
                        {
                            varRV.Var.ArrayIndexElement = null;
                            bForceFresh = true;
                        }
                    }

                    _property.Property.SetValue(_object, varRV, null);
                }
            }
            else if (_param != null)
            {
                string valueType       = _valueOwner;
                bool   bOldArrayElment = false;

                if (_param.Value != null && _param.Value is VariableDef)
                {
                    VariableDef paramV = _param.Value as VariableDef;

                    if (paramV.ArrayIndexElement != null)
                    {
                        bOldArrayElment = true;
                    }
                }

                VariableDef paramValue = new VariableDef(selectedProperty, valueType);
                _param.Value = paramValue;

                if (isArrayElement && paramValue.ArrayIndexElement == null)
                {
                    paramValue.ArrayIndexElement = new MethodDef.Param("ArrayIndex", typeof(int), "int", "ArrayIndex", "ArrayIndex");
                    paramValue.ArrayIndexElement.IsArrayIndex = true;

                    bForceFresh = true;
                }
                else if (!isArrayElement && bOldArrayElment)
                {
                    paramValue.ArrayIndexElement = null;
                    bForceFresh = true;
                }
            }

            this.RereshProperty(bForceFresh, _property);

            OnValueChanged(_property);
        }
Example #48
0
		public void RemovePropertyDef(PropertyDef pd) {
			if (!PropertyDefs.Remove(pd))
				throw new ApplicationException(string.Format("Could not remove PropertyDef: {0}", pd));
		}
Example #49
0
        void AnalyzeMethod(ConfuserContext context, INameService service, MethodDef method)
        {
            var dpRegInstrs        = new List <Tuple <bool, Instruction> >();
            var routedEvtRegInstrs = new List <Instruction>();

            for (int i = 0; i < method.Body.Instructions.Count; i++)
            {
                Instruction instr = method.Body.Instructions[i];
                if ((instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt))
                {
                    var regMethod = (IMethod)instr.Operand;

                    if (regMethod.DeclaringType.FullName == "System.Windows.DependencyProperty" &&
                        regMethod.Name.String.StartsWith("Register"))
                    {
                        dpRegInstrs.Add(Tuple.Create(regMethod.Name.String.StartsWith("RegisterAttached"), instr));
                    }
                    else if (regMethod.DeclaringType.FullName == "System.Windows.EventManager" &&
                             regMethod.Name.String == "RegisterRoutedEvent")
                    {
                        routedEvtRegInstrs.Add(instr);
                    }
                }
                else if (instr.OpCode.Code == Code.Newobj)
                {
                    var methodRef = (IMethod)instr.Operand;

                    if (methodRef.DeclaringType.FullName == "System.Windows.Data.PropertyGroupDescription" &&
                        methodRef.Name == ".ctor" && i - 1 >= 0 && method.Body.Instructions[i - 1].OpCode.Code == Code.Ldstr)
                    {
                        foreach (var property in analyzer.LookupProperty((string)method.Body.Instructions[i - 1].Operand))
                        {
                            service.SetCanRename(property, false);
                        }
                    }
                }
                else if (instr.OpCode == OpCodes.Ldstr)
                {
                    var operand = ((string)instr.Operand).ToUpperInvariant();
                    if (operand.EndsWith(".BAML") || operand.EndsWith(".XAML"))
                    {
                        var match = UriPattern.Match(operand);
                        if (match.Success)
                        {
                            var resourceAssemblyName = match.Groups[1].Success ? match.Groups[1].Value : string.Empty;
                            // Check if the expression contains a resource name (group 1)
                            // If it does, check if it is this assembly.
                            if (!string.IsNullOrWhiteSpace(resourceAssemblyName) &&
                                !resourceAssemblyName.Equals(method.Module.Assembly.Name.String, StringComparison.OrdinalIgnoreCase))
                            {
                                // This resource points to another assembly.
                                // Leave it alone!
                                return;
                            }
                            operand = match.Groups[2].Value;
                        }
                        else if (operand.Contains("/"))
                        {
                            context.Logger.WarnFormat("Fail to extract XAML name from '{0}'.", instr.Operand);
                        }

                        var reference = new BAMLStringReference(instr);
                        operand = WebUtility.UrlDecode(operand.TrimStart('/'));
                        var baml = operand.Substring(0, operand.Length - 5) + ".BAML";
                        var xaml = operand.Substring(0, operand.Length - 5) + ".XAML";
                        bamlRefs.AddListEntry(baml, reference);
                        bamlRefs.AddListEntry(xaml, reference);
                    }
                }
            }

            if (dpRegInstrs.Count == 0)
            {
                return;
            }

            var         traceSrv = context.Registry.GetService <ITraceService>();
            MethodTrace trace    = traceSrv.Trace(method);

            bool erred = false;

            foreach (var instrInfo in dpRegInstrs)
            {
                int[] args = trace.TraceArguments(instrInfo.Item2);
                if (args == null)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract dependency property name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }
                Instruction ldstr = method.Body.Instructions[args[0]];
                if (ldstr.OpCode.Code != Code.Ldstr)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract dependency property name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }

                var     name     = (string)ldstr.Operand;
                TypeDef declType = method.DeclaringType;
                bool    found    = false;
                if (instrInfo.Item1)                 // Attached DP
                {
                    MethodDef accessor;
                    if ((accessor = declType.FindMethod("Get" + name)) != null && accessor.IsStatic)
                    {
                        service.SetCanRename(accessor, false);
                        found = true;
                    }
                    if ((accessor = declType.FindMethod("Set" + name)) != null && accessor.IsStatic)
                    {
                        service.SetCanRename(accessor, false);
                        found = true;
                    }
                }

                // Normal DP
                // Find CLR property for attached DP as well, because it seems attached DP can be use as normal DP as well.
                PropertyDef property = null;
                if ((property = declType.FindProperty(name)) != null)
                {
                    service.SetCanRename(property, false);

                    found = true;
                    if (property.GetMethod != null)
                    {
                        service.SetCanRename(property.GetMethod, false);
                    }

                    if (property.SetMethod != null)
                    {
                        service.SetCanRename(property.SetMethod, false);
                    }

                    if (property.HasOtherMethods)
                    {
                        foreach (MethodDef accessor in property.OtherMethods)
                        {
                            service.SetCanRename(accessor, false);
                        }
                    }
                }
                if (!found)
                {
                    if (instrInfo.Item1)
                    {
                        context.Logger.WarnFormat("Failed to find the accessors of attached dependency property '{0}' in type '{1}'.",
                                                  name, declType.FullName);
                    }
                    else
                    {
                        context.Logger.WarnFormat("Failed to find the CLR property of normal dependency property '{0}' in type '{1}'.",
                                                  name, declType.FullName);
                    }
                }
            }

            erred = false;
            foreach (Instruction instr in routedEvtRegInstrs)
            {
                int[] args = trace.TraceArguments(instr);
                if (args == null)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract routed event name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }
                Instruction ldstr = method.Body.Instructions[args[0]];
                if (ldstr.OpCode.Code != Code.Ldstr)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract routed event name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }

                var     name     = (string)ldstr.Operand;
                TypeDef declType = method.DeclaringType;

                EventDef eventDef = null;
                if ((eventDef = declType.FindEvent(name)) == null)
                {
                    context.Logger.WarnFormat("Failed to find the CLR event of routed event '{0}' in type '{1}'.",
                                              name, declType.FullName);
                    continue;
                }
                service.SetCanRename(eventDef, false);

                if (eventDef.AddMethod != null)
                {
                    service.SetCanRename(eventDef.AddMethod, false);
                }

                if (eventDef.RemoveMethod != null)
                {
                    service.SetCanRename(eventDef.RemoveMethod, false);
                }

                if (eventDef.InvokeMethod != null)
                {
                    service.SetCanRename(eventDef.InvokeMethod, false);
                }

                if (eventDef.HasOtherMethods)
                {
                    foreach (MethodDef accessor in eventDef.OtherMethods)
                    {
                        service.SetCanRename(accessor, false);
                    }
                }
            }
        }
Example #50
0
 private string GetCardPropertyValue(ObservableMultiCard card, PropertyDef def)
 {
     if (!card.PropertySet().ContainsKey(def)) return null;
     return card.PropertySet()[def] as String;
 }
 public override TreeViewNodeFilterResult GetFilterResult(PropertyDef prop)
 {
     return(new TreeViewNodeFilterResult(FilterResult.Match, false));
 }
Example #52
0
        private void AnalyzeMethod(ConfuserContext context, INameService service, MethodDef method)
        {
            var dpRegInstrs        = new List <Tuple <bool, Instruction> >();
            var routedEvtRegInstrs = new List <Instruction>();

            foreach (Instruction instr in method.Body.Instructions)
            {
                if ((instr.OpCode.Code == Code.Call || instr.OpCode.Code == Code.Callvirt))
                {
                    var regMethod = (IMethod)instr.Operand;

                    if (regMethod.DeclaringType.FullName == "System.Windows.DependencyProperty" &&
                        regMethod.Name.String.StartsWith("Register"))
                    {
                        dpRegInstrs.Add(Tuple.Create(regMethod.Name.String.StartsWith("RegisterAttached"), instr));
                    }
                    else if (regMethod.DeclaringType.FullName == "System.Windows.EventManager" &&
                             regMethod.Name.String == "RegisterRoutedEvent")
                    {
                        routedEvtRegInstrs.Add(instr);
                    }
                }
            }

            if (dpRegInstrs.Count == 0)
            {
                return;
            }

            var         traceSrv = context.Registry.GetService <ITraceService>();
            MethodTrace trace    = traceSrv.Trace(method);

            bool erred = false;

            foreach (var instrInfo in dpRegInstrs)
            {
                int[] args = trace.TraceArguments(instrInfo.Item2);
                if (args == null)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract dependency property name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }
                Instruction ldstr = method.Body.Instructions[args[0]];
                if (ldstr.OpCode.Code != Code.Ldstr)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract dependency property name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }

                var     name     = (string)ldstr.Operand;
                TypeDef declType = method.DeclaringType;
                bool    found    = false;
                if (instrInfo.Item1)                 // Attached DP
                {
                    MethodDef accessor;
                    if ((accessor = declType.FindMethod("Get" + name)) != null && accessor.IsStatic)
                    {
                        service.SetCanRename(accessor, false);
                        found = true;
                    }
                    if ((accessor = declType.FindMethod("Set" + name)) != null && accessor.IsStatic)
                    {
                        service.SetCanRename(accessor, false);
                        found = true;
                    }
                }

                // Normal DP
                // Find CLR property for attached DP as well, because it seems attached DP can be use as normal DP as well.
                PropertyDef property = null;
                if ((property = declType.FindProperty(name)) != null)
                {
                    found = true;
                    if (property.GetMethod != null)
                    {
                        service.SetCanRename(property.GetMethod, false);
                    }

                    if (property.SetMethod != null)
                    {
                        service.SetCanRename(property.SetMethod, false);
                    }

                    if (property.HasOtherMethods)
                    {
                        foreach (MethodDef accessor in property.OtherMethods)
                        {
                            service.SetCanRename(accessor, false);
                        }
                    }
                }
                if (!found)
                {
                    if (instrInfo.Item1)
                    {
                        context.Logger.WarnFormat("Failed to find the accessors of attached dependency property '{0}' in type '{1}'.",
                                                  name, declType.FullName);
                    }
                    else
                    {
                        context.Logger.WarnFormat("Failed to find the CLR property of normal dependency property '{0}' in type '{1}'.",
                                                  name, declType.FullName);
                    }
                }
            }

            erred = false;
            foreach (Instruction instr in routedEvtRegInstrs)
            {
                int[] args = trace.TraceArguments(instr);
                if (args == null)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract routed event name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }
                Instruction ldstr = method.Body.Instructions[args[0]];
                if (ldstr.OpCode.Code != Code.Ldstr)
                {
                    if (!erred)
                    {
                        context.Logger.WarnFormat("Failed to extract routed event name in '{0}'.", method.FullName);
                    }
                    erred = true;
                    continue;
                }

                var     name     = (string)ldstr.Operand;
                TypeDef declType = method.DeclaringType;

                EventDef eventDef = null;
                if ((eventDef = declType.FindEvent(name)) == null)
                {
                    context.Logger.WarnFormat("Failed to find the CLR event of routed event '{0}' in type '{1}'.",
                                              name, declType.FullName);
                    continue;
                }
                if (eventDef.AddMethod != null)
                {
                    service.SetCanRename(eventDef.AddMethod, false);
                }

                if (eventDef.RemoveMethod != null)
                {
                    service.SetCanRename(eventDef.RemoveMethod, false);
                }

                if (eventDef.InvokeMethod != null)
                {
                    service.SetCanRename(eventDef.InvokeMethod, false);
                }

                if (eventDef.HasOtherMethods)
                {
                    foreach (MethodDef accessor in eventDef.OtherMethods)
                    {
                        service.SetCanRename(accessor, false);
                    }
                }
            }
        }
Example #53
0
        public override bool ResetMembers(bool check, AgentType agentType, bool clear, MethodDef method = null, PropertyDef property = null)
        {
            bool bReset = false;

            if (this._frames != null)
            {
                bReset |= this._frames.ResetMembers(check, agentType, clear, method, property);
            }

            bReset |= base.ResetMembers(check, agentType, clear, method, property);

            return(bReset);
        }
Example #54
0
        public object Deserialize(string fileName)
        {
            //var timer = new Stopwatch();
            //timer.Start();
            var ret = new Set();
            var directory = new FileInfo(fileName).Directory.FullName;
            using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var settings = new XmlReaderSettings();
                settings.Schemas.Add(SetSchema);
                var doc = XDocument.Load(fs);
                doc.Validate(settings.Schemas, (a, b) =>
                    {
                        Console.WriteLine(b.Exception);
                    });
                ret.Cards = new List<Card>();
                var root = doc.Element("set");
                ret.Id = new Guid(root.Attribute("id").Value);
                ret.Name = root.Attribute("name").Value;
                ret.Filename = fileName;
                ret.GameId = new Guid(root.Attribute("gameId").Value);
                ret.Cards = new List<Card>();
                ret.GameVersion = new Version(root.Attribute("gameVersion").Value);
                ret.Markers = new List<Marker>();
                ret.Packs = new List<Pack>();
                ret.Version = new Version(root.Attribute("version").Value);
                ret.PackageName = "";
                ret.InstallPath = directory;
                ret.DeckPath = Path.Combine(ret.InstallPath, "Decks");
                ret.PackUri = Path.Combine(ret.InstallPath, "Cards");
                var gameImageInstallPath = Path.Combine(Config.Instance.Paths.ImageDatabasePath, ret.GameId.ToString());
                ret.ImageInstallPath = Path.Combine(gameImageInstallPath, "Sets", ret.Id.ToString());
                ret.ImagePackUri = Path.Combine(ret.ImageInstallPath, "Cards");
                ret.ProxyPackUri = Path.Combine(ret.ImagePackUri, "Proxies");

                if (!Directory.Exists(ret.PackUri)) Directory.CreateDirectory(ret.PackUri);
                if (!Directory.Exists(ret.ImagePackUri)) Directory.CreateDirectory(ret.ImagePackUri);
                if (!Directory.Exists(ret.ProxyPackUri)) Directory.CreateDirectory(ret.ProxyPackUri);
                var game = DbContext.Get().Games.First(x => x.Id == ret.GameId);
                foreach (var c in doc.Document.Descendants("card"))
                {
					var card = new Card(new Guid(c.Attribute("id").Value), ret.Id, c.Attribute("name").Value,c.Attribute("id").Value, "",game.CardSizes["Default"],new Dictionary<string, CardPropertySet>());
                    //var card = new Card
                    //               {
                    //                   Id = new Guid(c.Attribute("id").Value),
                    //                   Name = c.Attribute("name").Value,
                    //                   SetId = ret.Id,
                    //                   Properties = new Dictionary<string, CardPropertySet>(),
                    //                   ImageUri = c.Attribute("id").Value,
                    //                   Alternate = "",
                    //                   Size = game.CardSizes["Default"]
                    //               };

                    var cs = c.Attribute("size");
                    if (cs != null)
                    {
						if(game.CardSizes.ContainsKey(cs.Value) == false)
                            throw new UserMessageException(Octgn.Library.Localization.L.D.Exception__BrokenGameContactDev_Format, game.Name);

                        card.Size = game.CardSizes[cs.Value];
                    }

                    var defaultProperties = new CardPropertySet();
                    defaultProperties.Type = "";
                    defaultProperties.Properties = new Dictionary<PropertyDef, object>();
                    foreach (var p in c.Descendants("property").Where(x => x.Parent.Name == "card"))
                    {
                        var pd = game.CustomProperties.FirstOrDefault(x => x.Name == p.Attribute("name").Value);
                        if (pd == null)
                        {
                            throw new UserMessageException(Octgn.Library.Localization.L.D.Exception__BrokenGameContactDev_Format, game.Name);
                        }
                        var newpd = pd.Clone() as PropertyDef;
                        defaultProperties.Properties.Add(newpd, p.Attribute("value").Value);
                    }
                    foreach (var cp in game.CustomProperties)
                    {
                        if (!defaultProperties.Properties.ContainsKey(cp))
                        {
                            var cpnew = cp.Clone() as PropertyDef;
                            cpnew.IsUndefined = true;
                            defaultProperties.Properties.Add(cpnew, "");
                        }
                    }
                    var np = new PropertyDef()
                                 {
                                     Hidden = false,
                                     Name = "Name",
                                     Type = PropertyType.String,
                                     TextKind = PropertyTextKind.FreeText,
                                     IgnoreText = false,
                                     IsUndefined = false
                                 };
                    if (defaultProperties.Properties.ContainsKey(np))
                        defaultProperties.Properties.Remove(np);
                    defaultProperties.Properties.Add(np, card.Name);
                    card.Properties.Add("", defaultProperties);

                    // Add all of the other property sets
                    foreach (var a in c.Descendants("alternate"))
                    {
                        var propset = new CardPropertySet();
                        propset.Properties = new Dictionary<PropertyDef, object>();
                        propset.Type = a.Attribute("type").Value;
                        var thisName = a.Attribute("name").Value;
                        foreach (var p in a.Descendants("property"))
                        {
                            var pd = game.CustomProperties.First(x => x.Name.Equals(p.Attribute("name").Value, StringComparison.InvariantCultureIgnoreCase));
                            var newprop = pd.Clone() as PropertyDef;
                            var val = p.Attribute("value").Value;
                            propset.Properties.Add(newprop, val);
                        }
                        foreach (var cp in game.CustomProperties)
                        {
                            if (!propset.Properties.ContainsKey(cp))
                            {
                                var cpnew = cp.Clone() as PropertyDef;
                                cpnew.IsUndefined = true;
                                propset.Properties.Add(cpnew, "");
                            }
                        }
                        var np2 = new PropertyDef()
                        {
                            Hidden = false,
                            Name = "Name",
                            Type = PropertyType.String,
                            TextKind = PropertyTextKind.FreeText,
                            IgnoreText = false,
                            IsUndefined = false
                        };
                        if (propset.Properties.ContainsKey(np2))
                            propset.Properties.Remove(np2);
                        propset.Properties.Add(np2, thisName);
                        card.Properties.Add(propset.Type, propset);
                    }

                    (ret.Cards as List<Card>).Add(card);
                }
                foreach (var p in doc.Document.Descendants("pack"))
                {
                    var pack = new Pack();
                    pack.Id = new Guid(p.Attribute("id").Value);
                    pack.Name = p.Attribute("name").Value;
                    pack.Definition = DeserializePack(p.Elements());
                    pack.SetId = ret.Id;
                    (ret.Packs as List<Pack>).Add(pack);
                }
                foreach (var m in doc.Document.Descendants("marker"))
                {
                    var marker = new Marker();
                    marker.Id = new Guid(m.Attribute("id").Value);
                    marker.Name = m.Attribute("name").Value;
                    var mpathd = new DirectoryInfo(Path.Combine(directory, "Markers"));
                    var mpath = mpathd.Exists == false ? null : mpathd.GetFiles(marker.Id.ToString() + ".*", SearchOption.TopDirectoryOnly).First();
                    marker.IconUri = mpath == null ? null : Path.Combine(directory, "Markers", mpath.FullName);
                    (ret.Markers as List<Marker>).Add(marker);
                }
            }

            if (ret.Cards == null) ret.Cards = new Card[0];
            if (ret.Markers == null) ret.Markers = new Marker[0];
            if (ret.Packs == null) ret.Packs = new Pack[0];
            //Console.WriteLine(timer.ElapsedMilliseconds);
            return ret;
        }
Example #55
0
        public override bool ResetMembers(MetaOperations metaOperation, AgentType agentType, BaseType baseType, MethodDef method, PropertyDef property)
        {
            bool bReset = false;

            if (this._task != null)
            {
                if (metaOperation == MetaOperations.ChangeAgentType || metaOperation == MetaOperations.RemoveAgentType)
                {
                    if (this._task.ShouldBeCleared(agentType))
                    {
                        this._task = null;

                        bReset = true;
                    }
                }
                else if (metaOperation == MetaOperations.RemoveMethod)
                {
                    if (method != null && method.OldName == this._task.Name)
                    {
                        this._task = null;

                        bReset = true;
                    }
                }
                else
                {
                    bReset |= this._task.ResetMembers(metaOperation, agentType, baseType, method, property);
                }
            }

            bReset |= base.ResetMembers(metaOperation, agentType, baseType, method, property);

            return(bReset);
        }
Example #56
0
		public MPropertyDef(PropertyDef propertyDef, MTypeDef owner, int index)
			: base(propertyDef, owner, index) {
		}
Example #57
0
 public void add(PropertyDef prop)
 {
     allPropertyInfos[prop] = new PropertyInfo(prop);
 }