GetValue() public abstract method

public abstract GetValue ( Object obj ) : Object
obj Object
return Object
Esempio n. 1
2
 private void ConstructField(FieldInfo fieldInfo)
 {
     string valueStr = null;
     if (fieldInfo.FieldType.IsArray)
     {
         var arrayBuilder = new StringBuilder();
         arrayBuilder.Append("[");
         var arr = fieldInfo.GetValue(Obj) as Array;
         foreach (var element in arr)
         {
             arrayBuilder.Append(string.Format("{0}, ", ConstructValue(element)));
         }
         arrayBuilder.Remove(arrayBuilder.Length - 2, 2);
         arrayBuilder.Append("]");
         valueStr = arrayBuilder.ToString();
     }
     else
     {
         valueStr = ConstructValue(fieldInfo.GetValue(Obj));
     }
     if (valueStr == null)
     {
         throw new Exception("Unsupported data type");
     }
     builder.Append(string.Format("\"{0}\": {1},\n", fieldInfo.Name, valueStr));
 }
        public void Visit(string settingsNamesapce, string fieldPath, FieldInfo rawSettingsField, object rawSettings)
        {
            // Skip 'sealed' fields.
            if (rawSettingsField.IsDefined<SealedAttribute>()) return;

            if (rawSettingsField.FieldType == typeof(string))
            {
                var originalString = (string)rawSettingsField.GetValue(rawSettings);
                if (originalString != null)
                {
                    var expandedString = ExpandVariables(originalString, _variables);
                    rawSettingsField.SetValue(rawSettings, expandedString);
                }
            }
            else if (rawSettingsField.FieldType == typeof(string[]))
            {
                string[] arr = (string[])rawSettingsField.GetValue(rawSettings);
                for (int i = 0; i < arr.Length; i++)
                {
                    string originalString = arr[i];
                    if (originalString != null)
                    {
                        var expandedString = ExpandVariables(originalString, _variables);
                        arr[i] = expandedString;
                    }
                }
            }
        }
Esempio n. 3
0
        public void Visit(string settingsNamesapce, string fieldPath, FieldInfo refinedSettingsField, object refinedSettings, FieldInfo rawSettingsField, object rawSettings)
        {
            if (refinedSettingsField.IsDefined<RefAttribute>()) return;

            object rawValue = null;
            object refinedValue = refinedSettingsField.GetValue(refinedSettings);
            if (refinedValue != null)
            {
                Type refinedValueType = refinedValue.GetType();
                if (refinedValueType.IsSettingsType())
                {
                    rawValue = SettingsConstruction.CreateSettingsObject(refinedValue, rawSettingsField, _typeMappings);
                }
                else if (refinedValueType.IsSettingsOrObjectArrayType())
                {
                    rawValue = SettingsConstruction.CreateSettingsArray((Array)refinedValue, rawSettingsField, _typeMappings);
                }
                else if (refinedValueType != typeof(string) && rawSettingsField.FieldType == typeof(string))
                {
                    rawValue = ToString(refinedSettingsField, refinedSettings);
                }
                else
                {
                    rawValue = refinedSettingsField.GetValue(refinedSettings);
                }
                rawSettingsField.SetValue(rawSettings, rawValue);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 获取每句的描述,获取相关值,用于页面,上绑定,要继承byte,参数indexNum获取枚举的条件
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="indexNum"></param>
        /// <returns></returns>
        public static List <KeyValuePair <byte, string> > GetEnum(Type enumType, int indexFirst, int indexLast)
        {
            var names = System.Enum.GetNames(enumType);

            if (names != null && names.Length > 0)
            {
                List <KeyValuePair <byte, string> > kvList = new List <KeyValuePair <byte, string> >(names.Length);
                foreach (var item in names)
                {
                    System.Reflection.FieldInfo finfo = enumType.GetField(item);
                    if ((byte)finfo.GetValue(null) > indexFirst && (byte)finfo.GetValue(null) < indexLast)
                    {
                        object[] enumAttr = finfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true).ToArray();
                        if (enumAttr != null && enumAttr.Length > 0)
                        {
                            string description = string.Empty;

                            System.ComponentModel.DescriptionAttribute desc = enumAttr[0] as System.ComponentModel.DescriptionAttribute;
                            if (desc != null)
                            {
                                description = desc.Description;
                            }
                            kvList.Add(new KeyValuePair <byte, string>((byte)finfo.GetValue(null), description));
                        }
                    }
                }
                return(kvList);
            }
            return(null);
        }
Esempio n. 5
0
    public void UnEquip()
    {
        foreach (ElementAction action in actions)
        {
            if (action.activateOnEquip)
            {
                if (action.selectedOption == 1)
                {
                    MonoBehaviour component = (MonoBehaviour)action.activationObject.GetComponent(action.selectedComponentName);
                    System.Reflection.FieldInfo fieldInfo = component.GetType().GetField(action.selectedFieldName);

                    if (fieldInfo.GetValue(component) is int)
                    {
                        int intVal = int.Parse(action.fieldValue);
                        int oldVal = (int)fieldInfo.GetValue(component);
                        fieldInfo.SetValue(component, oldVal - intVal);
                    }
                    else if (fieldInfo.GetValue(component) is float)
                    {
                        float floatVal = float.Parse(action.fieldValue);
                        float oldVal   = (float)fieldInfo.GetValue(component);
                        fieldInfo.SetValue(component, oldVal - floatVal);
                    }
                    else if (action.cachedField.GetValue(component) is double)
                    {
                        double intVal = double.Parse(action.fieldValue);
                        double oldVal = (double)fieldInfo.GetValue(component);
                        action.cachedField.SetValue(component, oldVal - intVal);
                    }
                }
            }
        }
    }
Esempio n. 6
0
        /// <summary>
        /// 鼠标滚轮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PrintPreviewControl1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (!SystemInformation.MouseWheelPresent)
            {
                //If have no wheel
                return;
            }

            int   scrollAmount;
            float amount = Math.Abs(e.Delta) / SystemInformation.MouseWheelScrollDelta;

            amount *= SystemInformation.MouseWheelScrollLines;
            amount *= 12;                               //Row height
            amount *= (float)PrintPreviewControl1.Zoom; //Zoom Rate
            if (e.Delta < 0)
            {
                scrollAmount = (int)amount;
            }
            else
            {
                scrollAmount = -(int)amount;
            }
            Point curPos = (Point)(m_Position.GetValue(PrintPreviewControl1));

            m_SetPositionMethod.Invoke(PrintPreviewControl1, new object[] { new Point(curPos.X + 0, curPos.Y + scrollAmount) });
        }
Esempio n. 7
0
 static void push_primitive(object obj, FieldInfo field, BuffBuilder bb)
 {
     if (field.FieldType == typeof(uint))
     {
         bb.PushUint((uint)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(int))
     {
         bb.PushInt((int)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(ushort))
     {
         bb.PushUshort((ushort)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(short))
     {
         bb.PushShort((short)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(ulong))
     {
         bb.PushUlong((ulong)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(long))
     {
         bb.PushLong((long)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(byte))
     {
         bb.PushByte((byte)field.GetValue(obj));
     }
     else if (field.FieldType == typeof(float))
     {
         bb.PushFloat((float)field.GetValue(obj));
     }
 }
Esempio n. 8
0
        private string getValue(string name, string type, object clazz)
        {
            string result = "";

            Type pType = clazz.GetType();

            System.Reflection.FieldInfo field = pType.GetField(name);

            if (field != null)
            {
                try
                {
                    switch (type)
                    {
                    case "time":
                        float seconds = 0;

                        if (field.FieldType.Name.Equals("Single"))
                        {
                            seconds = (float)field.GetValue(clazz);
                        }

                        TimeSpan interval = TimeSpan.FromSeconds(seconds);
                        result = interval.ToString(@"mm\.ss\.fff");
                        break;

                    case "kmh":
                        if (field.FieldType.Name.Equals("Single"))
                        {
                            result = ((int)Math.Floor((Single)field.GetValue(clazz) * 3.6)).ToString();
                        }
                        break;

                    default:
                        if (name.Equals("gear"))
                        {
                            int gear = (int)field.GetValue(clazz) - 1;
                            if (gear < 0)
                            {
                                return("R");
                            }

                            result = (gear + 1).ToString();
                        }
                        else
                        {
                            result = field.GetValue(clazz).ToString();
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    logger.LogExceptionToFile(e);
                }
            }

            return(result);
        }
Esempio n. 9
0
        /// <summary></summary>
        public void OnEnable()
        {
            if (Application.isPlaying)
            {
                return;
            }

            // After each compilations we have to synchronize families in case of user update them inside systems.
            // Because we are here in FYFY_Inspector package we have no garanty that user use Monitoring plugin.
            // So we have to inspect types dynamically, first we try to find the Monitoring type (it will be the
            // case if user drag&drop the Monitoring libraries inside its Unity project
            Type monitoringManager_Type = Type.GetType("FYFY_plugins.Monitoring.MonitoringManager, Monitoring");

            if (monitoringManager_Type != null && !EditorApplication.isCompiling)              // could be null if user doesn't use Monitoring plugin and be sure compiling is finished before synchronize families
            // Here we found the MonitoringManager type, so we inspect it to find "Instance" field
            {
                System.Reflection.FieldInfo mmInstanceField = monitoringManager_Type.GetField("Instance");
                if (mmInstanceField != null)
                {
                    // Here we found MonitoringManager.Instance and we have to check if it is not null.
                    // It could be null if user add Monitoring plugin but don't add MonitoringManager component to the scene
                    if (mmInstanceField.GetValue(null) != null)
                    {
                        // We found the Type, we found its static field "Instance", so we can call the function to synchronize families
                        // First we have to find the "synchronizeFamilies" method defined inside MonitoringManager type
                        MethodInfo synchronizeFamilies = monitoringManager_Type.GetMethod("synchronizeFamilies", new Type[] { });
                        if (synchronizeFamilies != null)
                        {
                            // And call the method on the Instance field
                            synchronizeFamilies.Invoke(mmInstanceField.GetValue(null), new object[] { });
                        }
                        else
                        {
                            UnityEngine.Debug.LogError("Warning, inconsistent method inside FYFY_plugins.Monitoring.MonitoringManager.Instance, \"synchronizeFamilies\" method is not defined.");
                        }
                    }
                }
                else
                {
                    UnityEngine.Debug.LogError("Warning, inconsistent field inside FYFY_plugins.Monitoring.MonitoringManager, \"Instance\" field require.");
                }
            }

            // depending on script execution order, the MainLoopEditorScanner can process before MainLoop
            // in this case MainLoop.instance == null and we can't call synchronizerWrappers.
            // Then we ask MainLoop to call back this script and refresh data base
            if (MainLoop.instance != null)
            {
                if (MainLoop.instance.synchronizeWrappers())
                {
                    AssetDatabase.Refresh();
                }
            }
            else
            {
                // Notify MainLoop to call back MainLoopEditorScanner OnEnable
                MainLoop.mainLoopEditorScanner = this;
            }
        }
 static void Postfix(GameUI __instance)
 {
     colours.Clear();
     System.Reflection.FieldInfo fieldInfo = typeof(GameUI).GetField("blue", BindingFlags.NonPublic | BindingFlags.Instance);
     colours.Add("blue", (UnityEngine.Color)fieldInfo.GetValue(__instance));
     fieldInfo = typeof(GameUI).GetField("red", BindingFlags.NonPublic | BindingFlags.Instance);
     colours.Add("red", (UnityEngine.Color)fieldInfo.GetValue(__instance));
     colours.Add("white", UnityEngine.Color.white);
 }
Esempio n. 11
0
        public static bool IsAmbiguousDaylightSavingTime(this System.DateTime dte)
        {
            const UInt64 flagsMask             = 0xC000000000000000;
            const UInt64 kindLocalAmbiguousDst = 0xC000000000000000;
            ulong        dateData     = (ulong)s_dateData.GetValue(dte);
            ulong        internalKind = (dateData & flagsMask);

            return(internalKind == kindLocalAmbiguousDst);
        }
Esempio n. 12
0
 private static void SaveChangeStack()
 {
     if (changeStack != null)
     {
         Stack <bool> stack = (Stack <bool>)changeStack.GetValue(null);
         if (stack != null)
         {
             preLockStackSize = stack.Count();
         }
     }
 }
        private static object EvaluateMemberAccessField(ConstantExpression node, FieldInfo fieldAccessor)
        {
            object value;

            if (fieldAccessor.IsStatic)
                value = fieldAccessor.GetValue(null);
            else
                value = node == null ? null : fieldAccessor.GetValue(node.Value);

            return ConvertMemberAccessValue(value);
        }
            public object Read(object instance)
            {
                if (fieldInfo == null)
                {
                    InitializeField(instance.GetType());
                }
                if (fieldInfo == null)
                {
                    throw new Exception(string.Format("Couldn't find field '{0}' or '{1}'", fieldName1, fieldName2));
                }

                return(fieldInfo.GetValue(instance));
            }
Esempio n. 15
0
        public static string[] GetFieldValues(object ruleInfo, FieldInfo fieldInfo, Action<string> emitError)
        {
            var type = fieldInfo.FieldType;
            if (type == typeof(string))
                return new[] { (string)fieldInfo.GetValue(ruleInfo) };
            if (type == typeof(string[]))
                return (string[])fieldInfo.GetValue(ruleInfo);

            emitError("Bad type for reference on {0}.{1}. Supported types: string, string[]"
                .F(ruleInfo.GetType().Name, fieldInfo.Name));

            return new string[] { };
        }
Esempio n. 16
0
    /// <summary>
    /// Display EditorGUI elements to set the value of a field.
    /// </summary>
    /// <param name="fieldName">The label to show</param>
    /// <param name="field">The FieldInfo object</param>
    /// <param name="fieldOwner">The object whose field value should be set</param>
    /// <returns>true if the field was something we could display and edit, false otherwise</returns>
    public static bool LayoutFieldInfo(string fieldName, System.Reflection.FieldInfo field, object fieldOwner)
    {
        if (field.FieldType.IsEnum)
        {
            field.SetValue(fieldOwner, EditorGUILayout.EnumPopup(fieldName, (System.Enum)field.GetValue(fieldOwner)));
            return(true);
        }

        switch (field.FieldType.Name)
        {
        case "Int32":
            field.SetValue(fieldOwner, EditorGUILayout.IntField(fieldName, (int)field.GetValue(fieldOwner)));
            return(true);

        case "Single":
            field.SetValue(fieldOwner, EditorGUILayout.FloatField(fieldName, (float)field.GetValue(fieldOwner)));
            return(true);

        case "Boolean":
            field.SetValue(fieldOwner, EditorGUILayout.Toggle(fieldName, (bool)field.GetValue(fieldOwner)));
            return(true);

        case "Vector3":
            field.SetValue(fieldOwner, EditorGUILayout.Vector3Field(fieldName, (Vector3)field.GetValue(fieldOwner)));
            return(true);

        case "Color":
            field.SetValue(fieldOwner, EditorGUILayout.ColorField(new GUIContent(fieldName), (Color)field.GetValue(fieldOwner), true, true, true, null));
            return(true);

        case "String":
        {
            string value = (string)field.GetValue(fieldOwner);
            if (value == null)
            {
                value = "";
            }
            field.SetValue(fieldOwner, EditorGUILayout.TextField(fieldName, value));
        }
            return(true);

        //case "Texture2D":
        //	field.SetValue(fieldOwner, EditorGUILayout.ObjectField(fieldName, (Texture2D)field.GetValue(fieldOwner), typeof(Texture2D), true));
        //	return true;
        default:
            return(false);
        }
    }
Esempio n. 17
0
 private static void LocalizeField(Control control, ResourceManager resourceManager, FieldInfo fi, string propertyName)
 {
     MemberInfo[] mia = fi.FieldType.GetMember(propertyName);
     if (mia.GetLength(0) > 0)
     {
         try
         {
             string resourceName = control.GetType().Namespace.Replace(".", "_") + "_" + control.GetType().Name + "_" + fi.Name + "_" + propertyName;
             string localizedText = resourceManager.GetString(resourceName);
             if (localizedText == null)
             {
             }
             else if (!string.IsNullOrEmpty(localizedText))
             {
                 Object o = fi.GetValue(control);
                 if (o != null)
                 {
                     PropertyInfo pi = o.GetType().GetProperty(propertyName);
                     if (pi != null)
                     {
                         pi.SetValue(o, localizedText, null);
                     }
                 }
             }
         }
         catch (System.Resources.MissingManifestResourceException)
         {
             //just ignore
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine("Error when localizing: " + fi.Name + ":\r\n" + ex.ToString());
         }
     }
 }
Esempio n. 18
0
 /// <summary>Raised before drawing the HUD (item toolbar, clock, etc) to the screen.</summary>
 /// <param name="sender">The event sender.</param>
 /// <param name="e">The event arguments.</param>
 private void OnRendered(object sender, EventArgs e)
 {
     if (!this.hidden)
     {
         float scale = this.transparency;
         if (!Game1.eventUp && Game1.activeClickableMenu is GameMenu == false && Game1.activeClickableMenu is ShopMenu == false && Game1.activeClickableMenu is IClickableMenu == false)
         {
             scale *= 0.5f;
         }
         System.Reflection.FieldInfo matrixField = Game1.spriteBatch.GetType().GetField("_matrix", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
         object originMatrix = matrixField.GetValue(Game1.spriteBatch);
         Game1.spriteBatch.End();
         Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, Microsoft.Xna.Framework.Matrix.CreateScale(1f));
         IClickableMenu.drawTextureBoxWithIconAndText(Game1.spriteBatch, Game1.smallFont, Game1.mouseCursors, new Rectangle(0x100, 0x100, 10, 10), null, new Rectangle(0, 0, 1, 1),
                                                      this.alias, this.buttonRectangle.X, this.buttonRectangle.Y, this.buttonRectangle.Width, this.buttonRectangle.Height, Color.BurlyWood * scale, 4f,
                                                      true, false, true, false, false, false, false); // Remove bold to fix the text position issue
         Game1.spriteBatch.End();
         if (originMatrix != null)
         {
             Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null, (Matrix)originMatrix);
         }
         else
         {
             Game1.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp);
         }
     }
 }
        // Retrieves the dependency property corresponding to the passed-in property name
        private DependencyProperty getDependencyProperty(Type type, string name)
        {
            string originalName = name;

            // By convention, dependency property names end with "Property"
            if (!name.EndsWith("Property"))
            {
                name += "Property";
            }

            // Attempt to get the field for the property
            System.Reflection.FieldInfo fieldInfo = type.GetField(name, BindingFlags.Public | BindingFlags.Static);

            // If the attempt failed, append "Property" one more time and try again.  Necessary in the case where
            // the non-dependency property name already ends with property (e.g. TargetProperty)
            if (fieldInfo == null)
            {
                name     += "Property";
                fieldInfo = type.GetField(name, BindingFlags.Public | BindingFlags.Static);
            }

            if (fieldInfo != null) // return the property if found
            {
                return((DependencyProperty)fieldInfo.GetValue(null));
            }
            else if (type.BaseType != null) // look for the property on the base type if not
            {
                return(getDependencyProperty(type.BaseType, originalName));
            }
            else // return null if property not found and there is no base type
            {
                return(null);
            }
        }
Esempio n. 20
0
 private void WriteClassNameIfNeedBe(object value, FieldInfo field) {
     object fieldValue = field.GetValue(value);
     if (fieldValue == null) return;
     Type actualType = fieldValue.GetType();
     if (!field.FieldType.Equals(actualType))
         writer.WriteAttribute(Attributes.classType, actualType.AssemblyQualifiedName);
 }
Esempio n. 21
0
 private static IBaseElement GetInstancePage(object parent, FieldInfo field, Type type, Type parentType)
 {
     var instance = (IBaseElement) field.GetValue(parent) ?? (IBaseElement) Activator.CreateInstance(type);
     var pageAttribute = field.GetAttribute<PageAttribute>();
     pageAttribute?.FillPage((WebPage) instance, parentType);
     return instance;
 }
 public StepArgument(FieldInfo member, object declaringObject)
 {
     Name = member.Name;
     _get = () => member.GetValue(declaringObject);
     _set = o => member.SetValue(declaringObject, o);
     ArgumentType = member.FieldType;
 }
Esempio n. 23
0
 public ObjectMeta(FieldInfo field, object obj)
 {
     Type = field.FieldType;
     Value = field.GetValue(obj);
     Name = field.Name;
     DisplayName = GetDisplayName();
 }
Esempio n. 24
0
        private static void Postfix()
        {
            if (typeof(Database.Techs).GetField("TECH_GROUPING") == null)
            {
                Tech tech = Db.Get().Techs.TryGet(TechID);
                if (tech == null)
                {
                    return;
                }
                ICollection <string> list = (ICollection <string>)tech.GetType().GetField("unlockedItemIDs")?.GetValue(tech);
                if (list == null)
                {
                    return;
                }

                list.Add(Building.Config.LiquidBottlerConfig.ID);
                list.Add(Building.Config.LiquidBottleEmptierConfig.ID);
            }
            else
            {
                System.Reflection.FieldInfo   info = typeof(Database.Techs).GetField("TECH_GROUPING");
                Dictionary <string, string[]> dict = (Dictionary <string, string[]>)info.GetValue(null);
                dict[TechID].Append(Building.Config.LiquidBottlerConfig.ID);
                dict[TechID].Append(Building.Config.LiquidBottleEmptierConfig.ID);
                typeof(Database.Techs).GetField("TECH_GROUPING").SetValue(null, dict);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Checks to see if a field's type is an object.
        /// </summary>
        /// <param name="field"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        internal static bool IsObjectField(FieldInfo field, object obj)
        {
            var fieldValue = field.GetValue(obj);

            return fieldValue != null
                && !fieldValue.IsPrimitive();
        }
                static void Postfix()
                {
                    additionalSpellButtons.Clear();
                    GameObject buttonOriginal = GameUI.inst.witchUI.spellList.transform.GetChild(0).gameObject;

                    for (int spellIndex = 0; spellIndex < spellData.Count; spellIndex++)
                    {
                        GameObject buttonNew = GameObject.Instantiate(buttonOriginal, buttonOriginal.transform.parent);
                        buttonNew.transform.localScale    = buttonOriginal.transform.localScale;
                        buttonNew.transform.localPosition = buttonOriginal.transform.localPosition;
                        Button button = buttonNew.GetComponent <Button>();
                        button.onClick = new Button.ButtonClickedEvent();
                        int lambdaSpellIndex = spellIndex;
                        button.onClick.AddListener(() => {
                            System.Reflection.FieldInfo fieldInfo = typeof(WitchUI).GetField("witch", BindingFlags.NonPublic | BindingFlags.Instance);
                            WitchHut witchHut = (WitchHut)fieldInfo.GetValue(GameUI.inst.witchUI);
                            if (TryActivate(witchHut, spellDataOriginalCount + lambdaSpellIndex))
                            {
                                StreamerEffectCustom currentSpell = Activator.CreateInstance(spellData[lambdaSpellIndex].spellImpl) as StreamerEffectCustom;
                                currentSpell.witchUI    = GameUI.inst.witchUI;
                                currentSpell.witchHut   = witchHut;
                                currentSpell.spellData  = spellData[lambdaSpellIndex];
                                currentSpell.spellIndex = spellDataOriginalCount + lambdaSpellIndex;
                                currentSpell.Activate();
                            }
                        });
                        additionalSpellButtons.Add(buttonNew);
                    }
                }
Esempio n. 27
0
        private bool DrawSelectValueName(System.Reflection.FieldInfo filed, Rect rect, object o)
        {
            #region Select Value Name
            ValueNameSelectAttribute selectVarName = Attribute.GetCustomAttribute(filed, typeof(ValueNameSelectAttribute)) as ValueNameSelectAttribute;

            if (selectVarName != null)
            {
                //选择值
                Dialog dialog = _currentNode.GetContent() as Dialog;
                if (dialog == null)
                {
                    return(false);
                }
                string[] keys  = selectVarName.GetValueNameList(dialog);
                int      index = Array.FindIndex <string>(keys, (k) => k == (string)filed.GetValue(o));
                if (index == -1)
                {
                    index = 0;
                }
                index = EditorGUI.Popup(rect, index, keys);
                if (keys.Length > 0)
                {
                    filed.SetValue(o, keys[index]);
                }
                return(true);
            }
            return(false);

            #endregion
        }
Esempio n. 28
0
        private object GetPropertyValue(object inObj, string fieldName)
        {
            System.Type t = inObj.GetType();
            //GameObject hack
            // Due to GameObject.active is obsolete and ativeSelf is read only
            // Use a hack function to override GameObject's active status.
            if (t == typeof(GameObject) && fieldName == "m_IsActive")
            {
                return(((GameObject)inObj).activeSelf);
            }
            object ret = null;

            // Try search Field first than try property
            System.Reflection.FieldInfo fieldInfo = t.GetField(fieldName, bindingFlags);
            if (fieldInfo != null)
            {
                ret = fieldInfo.GetValue(inObj);
                return(ret);
            }
            if (t.ToString().Contains("UnityEngine."))
            {
                fieldName = ViewSystemUtilitys.ParseUnityEngineProperty(fieldName);
            }
            System.Reflection.PropertyInfo info = t.GetProperty(fieldName, bindingFlags);
            if (info != null)
            {
                ret = info.GetValue(inObj);
            }

            //ViewSystemLog.Log($"GetProperty on [{gameObject.name}] Target Object {((UnityEngine.Object)inObj).name} [{t.ToString()}] on [{fieldName}]  Value [{ret}]");
            return(ret);
        }
Esempio n. 29
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="PropertyMemberDescriptor" /> class.
        /// </summary>
        /// <param name="fi">The FieldInfo.</param>
        /// <param name="accessMode">The <see cref="InteropAccessMode" /> </param>
        public FieldMemberDescriptor(FieldInfo fi, InteropAccessMode accessMode)
        {
            if (Script.GlobalOptions.Platform.IsRunningOnAOT())
                accessMode = InteropAccessMode.Reflection;

            FieldInfo = fi;
            AccessMode = accessMode;
            Name = fi.Name;
            IsStatic = FieldInfo.IsStatic;

            if (FieldInfo.IsLiteral)
            {
                IsConst = true;
                m_ConstValue = FieldInfo.GetValue(null);
            }
            else
            {
                IsReadonly = FieldInfo.IsInitOnly;
            }

            if (AccessMode == InteropAccessMode.Preoptimized)
            {
                OptimizeGetter();
            }
        }
Esempio n. 30
0
        /// <summary>
        /// 展开或关闭Inspector中某类基类组件
        /// </summary>
        /// <param name="types">组件Editor的Type字符串列表</param>
        /// <param name="visible">是否展开</param>
        /// <param name="contraOther">是否将没有在types中的组件做相反的操作,传false保持不变</param>
        public static void SetInspectorTrackerVisible(string[] types, bool visible, bool contraOther = true)
        {
            var windowType = typeof(EditorWindow).Assembly.GetType(GetViewTypeStr(EditorViews.InspectorWindow));
            var window     = GetWindow(windowType);

            System.Reflection.FieldInfo info    = windowType.GetField("m_Tracker", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            ActiveEditorTracker         tracker = info.GetValue(window) as ActiveEditorTracker;
            var editors = tracker.activeEditors;

            for (int i = 0; i < editors.Length; i++)
            {
                bool isSame = false;
                foreach (var type in types)
                {
                    isSame = editors[i].GetType().ToString().Equals(type);
                    if (isSame)
                    {
                        tracker.SetVisible(i, isSame && visible ? 1 : 0);
                        break;
                    }
                }
                if (!isSame && contraOther)
                {
                    tracker.SetVisible(i, isSame && visible ? 1 : 0);
                }
            }
        }
Esempio n. 31
0
        public static T Copy <T>(this T obj) where T : new()
        {
            if (obj == null)
            {
                return(obj);
            }
            Object targetDeepCopyObj;
            Type   targetType = obj.GetType();

                        //值类型
                        if(targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }

                        //引用类型
                        else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);    //创建引用对象
                                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                if (propertyValue != null)
                                {
                                    myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                                }
                            }
                        }
                    }
                }
            }
            return((T)targetDeepCopyObj);
        }
Esempio n. 32
0
    // 指定名フィールドの値を取得
    public static bool getValue <T>(object obj, string name, out T objValue, T defaultValue)
    {
        if (obj == null)
        {
            objValue = defaultValue;
            return(false);
        }

        Type t = obj.GetType();

        System.Reflection.FieldInfo fi = t.GetField(name, fieldFlags);
        PropertyInfo pi = t.GetProperty(name, propertyFlags);

        if (fi != null)
        {
            objValue = (T)fi.GetValue(obj);
            return(true);
        }
        else if (pi != null)
        {
            MethodInfo getMethod = pi.GetGetMethod(true);
            objValue = (T)getMethod.Invoke(obj, null);
            return(true);
        }

        objValue = defaultValue;

        Debug.LogWarning("PTween getValue : Not found target : " + obj + " / " + name);
        return(false);
    }
Esempio n. 33
0
        public static SqlCommand GetSelectItemCommand <T>(T instance)
            where T : BusinessBase <T>
        {
            ITableSchema schema      = BusinessBase <T> .Schema;
            string       commandtext = String.Format(MakeSelectItemTemplate(schema));
            SqlCommand   cmd         = null;
            SqlCommand   tmpCmd      = null;

            try
            {
                tmpCmd             = new SqlCommand();
                tmpCmd.CommandText = commandtext;
                tmpCmd.CommandType = CommandType.Text;

                // Fill in parameter values
                foreach (ColumnAttribute key in schema.Keys.Values)
                {
                    System.Reflection.FieldInfo field = typeof(T).GetField(key.Storage, BindingFlags.NonPublic | BindingFlags.Instance);
                    tmpCmd.Parameters.AddWithValue("@" + key.Name, field.GetValue(instance));
                }

                cmd    = tmpCmd;
                tmpCmd = null;
            }
            finally
            {
                if (tmpCmd != null)
                {
                    tmpCmd.Dispose(); tmpCmd = null;
                }
            }
            return(cmd);
        }
Esempio n. 34
0
        /// <summary>
        /// Initializes a new instance of the TsEnumValue class with the specific name and value.
        /// </summary>
        /// <param name="name">The name of the enum value.</param>
        /// <param name="value">The value of the enum value.</param>
        public TsEnumValue(FieldInfo field)
        {
            this.Field = field;
            this.Name = field.Name;

            var value = field.GetValue(null);

            var valueType = Enum.GetUnderlyingType(value.GetType());
            if (valueType == typeof(byte)) {
                this.Value = ((byte)value).ToString();
            }
            if (valueType == typeof(sbyte)) {
                this.Value = ((sbyte)value).ToString();
            }
            if (valueType == typeof(short)) {
                this.Value = ((short)value).ToString();
            }
            if (valueType == typeof(ushort)) {
                this.Value = ((ushort)value).ToString();
            }
            if (valueType == typeof(int)) {
                this.Value = ((int)value).ToString();
            }
            if (valueType == typeof(uint)) {
                this.Value = ((uint)value).ToString();
            }
            if (valueType == typeof(long)) {
                this.Value = ((long)value).ToString();
            }
            if (valueType == typeof(ulong)) {
                this.Value = ((ulong)value).ToString();
            }
        }
Esempio n. 35
0
        object CanUseDoor(BasePlayer player, BaseLock codeLock)
        {
            ulong  steamID = player.userID;
            double nextpicktime;

            if (!IsAllowed(player, "ThiefAPI.can", "null"))
            {
                return(null);
            }
            //ChatMessageHandler(player, NotAllowed);
            if (Thiefs[player.userID] != null)
            {
                if (!storedData.canpick.TryGetValue(steamID, out nextpicktime))
                {
                    ChatMessageHandler(player, "UserDataCreated");
                    storedData.canpick.Add(steamID, GetTimeStamp() + Cooldown);
                    Interface.GetMod().DataFileSystem.WriteObject("ThiefAPI", storedData);
                }

                if (codeLock is CodeLock)
                {
                    List <ulong> whitelist = (List <ulong>)whitelistPlayers.GetValue(codeLock);
                    if (whitelist.Contains(player.userID))
                    {
                        ChatMessageHandler(player, "You have the code");
                        return(null);
                    }
                }

                if (GetTimeStamp() < nextpicktime)
                {
                    int nexttele = Convert.ToInt32(GetTimeStamp() - nextpicktime);
                    ChatMessageHandler(player, CooldownMessage);
                    return(null);
                }
                bool lockPickCostPass = lockPickCost(player);
                if (lockPickCostPass == true)
                {
                    string debugmessage = Convert.ToString(lockPickCostPass);
                    storedData.canpick[steamID] = GetTimeStamp() + Cooldown;
                    Interface.GetMod().DataFileSystem.WriteObject("ThiefAPI", storedData);
                    bool Pass = LPRoll();
                    if (Pass == true)
                    {
                        ChatMessageHandler(player, Success);
                        return(true);
                    }
                    else
                    {
                        ChatMessageHandler(player, Failed);
                        timer.Repeat(0.2f, DamageTicks, () =>
                        {
                            player.Hurt(DamageAmount);
                        });
                        return(false);
                    }
                }
            }
            return(null);
        }
Esempio n. 36
0
        public static SqlCommand GetSelectItemCommand <T>(string template, T instance)
            where T : BusinessBase <T>
        {
            ITableSchema schema = BusinessBase <T> .Schema;
            SqlCommand   cmd    = null;
            SqlCommand   tmpCmd = null;

            try
            {
                tmpCmd             = new SqlCommand();
                tmpCmd.CommandType = CommandType.Text;

                StringBuilder sb = new StringBuilder();
                int           nx = 0;
                foreach (ColumnAttribute key in schema.Keys.Values)
                {
                    System.Reflection.FieldInfo field = typeof(T).GetField(key.Storage, BindingFlags.NonPublic | BindingFlags.Instance);
                    tmpCmd.Parameters.AddWithValue("@" + key.Name, field.GetValue(instance));
                    sb.Append(string.Format("{0}{1}=@{1}", nx == 0 ? "" : " and ", key.Name));
                    nx++;
                }
                tmpCmd.CommandText = String.Format(template, " TOP 1", (sb.Length == 0 ? "" : " WHERE " + sb.ToString()), "");
                cmd    = tmpCmd;
                tmpCmd = null;
            }
            finally
            {
                if (tmpCmd != null)
                {
                    tmpCmd.Dispose(); tmpCmd = null;
                }
            }
            return(cmd);
        }
Esempio n. 37
0
    /**
     * Returns a list of all items in the cache that have "value"
     * in their field "prop."  Can return null, an empty list, or
     * a list of values.
     */
    public static List <T> FindAllByProperty(string prop, object value)
    {
        // Filter invalid queries.
        System.Reflection.FieldInfo field = typeof(T).GetField(prop);
        if (field == null || field.FieldType != value.GetType())
        {
            return(null);
        }

        List <T> matches = new List <T>();

        // Return the query value, if available.  If cache exists, then there is certainly at most one match.
        if (cache.ContainsKey(prop))
        {
            matches.Add(cache[prop][value]);
            return(matches);
        }

        foreach (T item in cache["id"].Values)
        {
            if (field.GetValue(item).Equals(value))
            {
                matches.Add(item);
            }
        }
        return(matches);
    }
Esempio n. 38
0
    public static object Copy(object obj)
    {
        System.Object targetDeepCopyObj;
        Type          targetType = obj.GetType();

        //值类型
        if (targetType.IsValueType == true)
        {
            targetDeepCopyObj = obj;
        }
        //引用类型
        else
        {
            targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
            System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

            foreach (System.Reflection.MemberInfo member in memberCollection)
            {
                if (member.MemberType == System.Reflection.MemberTypes.Field)
                {
                    System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                    System.Object fieldValue          = field.GetValue(obj);
                    try
                    {
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, Copy(fieldValue));
                        }
                    }
                    catch (Exception e)
                    {
                        LogMgr.UnityError(e.ToString());
                    }
                }
                else if (member.MemberType == System.Reflection.MemberTypes.Property)
                {
                    System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                    MethodInfo info = myProperty.GetSetMethod(false);
                    if (info != null)
                    {
                        object propertyValue = myProperty.GetValue(obj, null);
                        if (propertyValue is ICloneable)
                        {
                            myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                        }
                        else
                        {
                            myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);
                        }
                    }
                }
            }
        }
        return(targetDeepCopyObj);
    }
    public Specification CreateSpecificationFromBehavior(Behavior behavior, FieldInfo specificationField)
    {
      bool isIgnored = behavior.IsIgnored || specificationField.HasAttribute<IgnoreAttribute>();
      Then then = (Then) specificationField.GetValue(behavior.Instance);
      string name = specificationField.Name.ToFormat();

      return new BehaviorSpecification(name, then, isIgnored, specificationField, behavior.Context, behavior);
    }
 public void UpdateStartValue()
 {
     if (fieldInfo == null)
     {
         fieldInfo = Target.GetType().GetField(FieldName, BindingFlags.GetField | BindingFlags.SetField | BindingFlags.Instance | BindingFlags.Public);
     }
     StartValue = fieldInfo.GetValue(Target);
 }
    public Specification CreateSpecification(Context context, FieldInfo specificationField)
    {
      bool isIgnored = context.IsIgnored || specificationField.HasAttribute<IgnoreAttribute>();
      Then then = (Then) specificationField.GetValue(context.Instance);
      string name = specificationField.Name.ToFormat();

      return new Specification(name, then, isIgnored, specificationField);
    }
    public Specification CreateSpecification(Context context, FieldInfo specificationField)
    {
      bool isIgnored = context.IsIgnored || specificationField.HasAttribute<IgnoreAttribute>();
      It it = (It) specificationField.GetValue(context.Instance);
      string name = specificationField.Name.ReplaceUnderscores();

      return new Specification(name, it, isIgnored, specificationField);
    }
    public Specification CreateSpecificationFromBehavior(Behavior behavior, FieldInfo specificationField)
    {
      bool isIgnored = behavior.IsIgnored || specificationField.HasAttribute(new IgnoreAttributeFullName());
      var it = (Delegate) specificationField.GetValue(behavior.Instance);
      string name = specificationField.Name.ToFormat();

      return new BehaviorSpecification(name, specificationField.FieldType, it, isIgnored, specificationField, behavior.Context, behavior);
    }
 private ConstantModel GetConstantModel(FieldInfo fieldInfo)
 {
     if (fieldInfo.IsSpecialName)
     {
         return null;
     }
     return new ConstantModel(fieldInfo, ((IConvertible) fieldInfo.GetValue(null)).ToInt64(null));
 }
    public Specification CreateSpecificationFromBehavior(Behavior behavior, FieldInfo specificationField)
    {
      bool isIgnored = behavior.IsIgnored || specificationField.HasAttribute<IgnoreAttribute>();
      It it = (It) specificationField.GetValue(behavior.Instance);
      string name = specificationField.Name.ReplaceUnderscores();

      return new BehaviorSpecification(name, it, isIgnored, specificationField, behavior.Context, behavior);
    }
    public Specification CreateSpecification(Context context, FieldInfo specificationField)
    {
      bool isIgnored = context.IsIgnored || specificationField.HasAttribute(new IgnoreAttributeFullName());
      var it = (Delegate) specificationField.GetValue(context.Instance);
      string name = specificationField.Name.ToFormat();

      return new Specification(name, specificationField.FieldType, it, isIgnored, specificationField);
    }
Esempio n. 47
0
                static void Postfix(WitchHut.WitchHutSaveData __instance, ref WitchHut __result, WitchHut obj)
                {
                    System.Reflection.FieldInfo fieldInfo   = typeof(WitchHut).GetField("spellData", BindingFlags.NonPublic | BindingFlags.Instance);
                    ICollection spellDataCollection         = fieldInfo.GetValue(__result) as ICollection;
                    List <WitchHut.SpellData> spellDataList = new List <WitchHut.SpellData>();

                    foreach (object spellDataObject in spellDataCollection)
                    {
                        spellDataList.Add((WitchHut.SpellData)spellDataObject);
                    }

                    fieldInfo = typeof(WitchHut).GetField("currSpellCooldown", BindingFlags.NonPublic | BindingFlags.Instance);
                    ICollection cooldownCollection = fieldInfo.GetValue(__result) as ICollection;
                    List <int>  cooldownList       = new List <int>();

                    foreach (object cooldownObject in cooldownCollection)
                    {
                        cooldownList.Add((int)cooldownObject);
                    }

                    List <int> cooldownListAdjusted = new List <int>();

                    for (int cooldownIndex = 0; cooldownIndex < cooldownList.Count; cooldownIndex++)
                    {
                        if (cooldownIndex < spellDataList.Count)
                        {
                            cooldownListAdjusted.Add(cooldownList[cooldownIndex]);
                        }
                        else
                        {
                            break;
                        }
                    }

                    for (int spellIndex = 0; spellIndex < spellDataList.Count - cooldownList.Count; spellIndex++)
                    {
                        cooldownListAdjusted.Add(0);
                    }

                    int[] cooldownArray = new int[cooldownListAdjusted.Count];
                    for (int cooldownIndex = 0; cooldownIndex < cooldownListAdjusted.Count; cooldownIndex++)
                    {
                        cooldownArray[cooldownIndex] = cooldownListAdjusted[cooldownIndex];
                    }
                    fieldInfo.SetValue(__result, cooldownArray);
                }
Esempio n. 48
0
        public override object GetBoxedFieldValue(int fieldOrdinal)
        {
            System.Reflection.FieldInfo fi = GetField(fieldOrdinal);
            object rawValue = fi.GetValue(this);

            // we got raw value, it's possible that it's a sqltype, nullables are already boxed here
            return(Sooda.Utils.SqlTypesUtil.Unwrap(rawValue));
        }
Esempio n. 49
0
 public object GetValue(object obj)
 {
     if (isFast)
     {
         ((IFastGetSet)obj).FastGetValue(name);
     }
     return(fi.GetValue(obj));
 }
Esempio n. 50
0
        public static object Copy(this object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            Object targetDeepCopyObj;
            Type   targetType = obj.GetType();

            if (targetType.IsValueType == true)
            {
                targetDeepCopyObj = obj;
            }
            else
            {
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
                System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

                foreach (System.Reflection.MemberInfo member in memberCollection)
                {
                    if (member.GetType().GetProperty("Item") != null)
                    {
                        continue;
                    }
                    if (member.MemberType == System.Reflection.MemberTypes.Field)
                    {
                        System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                        Object fieldValue = field.GetValue(obj);
                        if (fieldValue is ICloneable)
                        {
                            field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                        }
                        else
                        {
                            field.SetValue(targetDeepCopyObj, fieldValue.Copy());
                        }
                    }
                    else if (member.MemberType == System.Reflection.MemberTypes.Property)
                    {
                        System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                        MethodInfo info = myProperty.GetSetMethod(false);
                        if (info != null)
                        {
                            object propertyValue = myProperty.GetValue(obj, null);
                            if (propertyValue is ICloneable)
                            {
                                myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);
                            }
                            else
                            {
                                myProperty.SetValue(targetDeepCopyObj, propertyValue.Copy(), null);
                            }
                        }
                    }
                }
            }
            return(targetDeepCopyObj);
        }
Esempio n. 51
0
        public static void Erase(NativeModuleWriter writer, ModuleDefMD module)
        {
            if (writer == null || module == null)
            {
                return;
            }

            var sects    = (IList)origSects.GetValue(writer);
            var sections = new List <Tuple <uint, uint, byte[]> >();
            var s        = new MemoryStream();

            foreach (var origSect in sects)
            {
                var oldChunk = (BinaryReaderChunk)chunk.GetValue(origSect);
                var sectHdr  = (ImageSectionHeader)peSection.GetValue(origSect);

                s.SetLength(0);
                oldChunk.WriteTo(new BinaryWriter(s));
                var buf      = s.ToArray();
                var newChunk = new BinaryReaderChunk(MemoryImageStream.Create(buf), oldChunk.GetVirtualSize());
                newChunk.SetOffset(oldChunk.FileOffset, oldChunk.RVA);

                chunk.SetValue(origSect, newChunk);

                sections.Add(Tuple.Create(
                                 sectHdr.PointerToRawData,
                                 sectHdr.PointerToRawData + sectHdr.SizeOfRawData,
                                 buf));
            }

            var md = module.MetaData;

            var row = md.TablesStream.MethodTable.Rows;

            for (uint i = 1; i <= row; i++)
            {
                var method   = md.TablesStream.ReadMethodRow(i);
                var codeType = ((MethodImplAttributes)method.ImplFlags & MethodImplAttributes.CodeTypeMask);
                if (codeType == MethodImplAttributes.IL)
                {
                    Erase(sections, (uint)md.PEImage.ToFileOffset((RVA)method.RVA));
                }
            }

            var res = md.ImageCor20Header.Resources;

            if (res.Size > 0)
            {
                Erase(sections, (uint)res.StartOffset, res.Size);
            }

            Erase(sections, md.ImageCor20Header);
            Erase(sections, md.MetaDataHeader);
            foreach (var stream in md.AllStreams)
            {
                Erase(sections, stream);
            }
        }
Esempio n. 52
0
 //public SyncItem SyncItem
 //{
 //    get { return _SyncItem; }
 //    set { _SyncItem = value; }
 //}
 public void ComputeFieldState(FieldInfo fi, ISerializableObject iso)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     FieldName = fi.Name;
     StringBuilder b = new StringBuilder();
     b.Append(fi.GetValue(iso));
     Byte[] tmp = encoding.GetBytes(b.ToString());
     HashCode = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(tmp)).Replace("-", "").ToLower();
 }
Esempio n. 53
0
		protected override string GetFieldDescription (FieldInfo field, object instance)
		{
			try {
				return string.Format ("{0}={1}", field.Name, 
						GetValue (field.GetValue(instance)));
			} catch {
				return field.Name;
			}
		}
        private static IComponent GetComponent(this IComponentSection section, FieldInfo fieldInfo)
        {
            if (fieldInfo == null)
              {
            return default(IComponent);
              }

              return (IComponent)fieldInfo.GetValue(section);
        }
Esempio n. 55
0
        public static IEnumerable<string> GetFieldValues(object ruleInfo, FieldInfo fieldInfo, Action<string> emitError)
        {
            var type = fieldInfo.FieldType;
            if (type == typeof(string))
                return new[] { (string)fieldInfo.GetValue(ruleInfo) };

            if (typeof(IEnumerable<string>).IsAssignableFrom(type))
                return fieldInfo.GetValue(ruleInfo) as IEnumerable<string>;

            if (type == typeof(BooleanExpression))
            {
                var expr = (BooleanExpression)fieldInfo.GetValue(ruleInfo);
                return expr != null ? expr.Variables : Enumerable.Empty<string>();
            }

            throw new InvalidOperationException("Bad type for reference on {0}.{1}. Supported types: string, IEnumerable<string>, BooleanExpression"
                .F(ruleInfo.GetType().Name, fieldInfo.Name));
        }
Esempio n. 56
0
        private void AssignElement(FieldInfo field, WatControl control)
        {
            var auto = field.GetValue(control) as AutoWatElement;
            if (auto == null)
                return; // This field is not marked with Auto

            var element = CreateElement(field.Name, auto, control);
            field.SetValue(control, element);
        }
 private static void InitializeField(Queue<TemplateControl> queue, TemplateControl control, FieldInfo field)
 {
     var userControl = field.GetValue(control) as UserControl;
     if (userControl != null)
     {
         TemplateClassDependencyInjector.InjectDependency(userControl);
         queue.Enqueue(userControl);
     }
 }
Esempio n. 58
0
 private static void CheckSomeBoxes(_Document doc, FieldInfo info, EnumAttribute attr, Person anketa)
 {
     var templateStr = attr.TemplateString;
     var val = Convert.ToInt32(info.GetValue(anketa)) + 1;
     for (var i = 1; i <= attr.EnumValues; i++)
     {
         object strToFindObj = templateStr + i;
         ReplaceString(doc, i == val ? "X" : EmptyBox, strToFindObj);
     }
 }
Esempio n. 59
0
 private static void CheckSomeBoxesFromBool(_Document doc, FieldInfo info, BoolAttribute attr, Person anketa)
 {
     var templateStr = attr.TemplateString;
     var val = Convert.ToBoolean(info.GetValue(anketa));
     for (var i = 0; i <= 1; i++)
     {
         object strToFindObj = templateStr + i;
         ReplaceString(doc, ((val && i == 1) || (!val && i == 0)) ? "X" : EmptyBox, strToFindObj);
     }
 }
Esempio n. 60
0
            private readonly FieldInfo fieldInfo; //internal configuration field.

            /// <summary>
            /// Creates ConfigInjection instance.
            /// </summary>
            /// <param name="updateManager">UpdateManager instance to which configuration is to be injected.</param>
            /// <param name="configuration">The configuration for injection.</param>
            public ConfigInjection(DynUpdateManager updateManager, UpdateManagerConfiguration configuration)
            {
                this.updateManager = updateManager;
                fieldInfo = updateManager.GetType()
                    .GetField("configuration", BindingFlags.NonPublic | BindingFlags.Instance);
                Assert.IsNotNull(fieldInfo);

                this.configuration = fieldInfo.GetValue(updateManager);
                fieldInfo.SetValue(updateManager, configuration);
            }