コード例 #1
0
 public WithInterceptorTests()
 {
     beforeAssemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyWithInterceptor\bin\Debug\AssemblyWithInterceptor.dll");
     assemblyWeaver = new AssemblyWeaver(beforeAssemblyPath);
     var methodTimeLogger = assemblyWeaver.Assembly.GetType("MethodTimeLogger");
     methodBaseField = methodTimeLogger.GetField("MethodBase");
 }
コード例 #2
0
        public void run()
        {
            FieldInfo field = null;
            ClassInfo ownerClass = repository.GetClass(classInfo.Name);
            var fd = instruction.Operand as FieldDefinition;
            if(fd==null) return;

            var fieldName = fd.Name;
            var operand = instruction.Operand;

            try
            {
                field = ownerClass.GetField(fieldName);
            }
            catch (FieldNotFoundException e)
            {
                field =
                    //new FieldInfo(ownerClass, "FAKE:" + fieldName, ClrType
                    new FieldInfo(ownerClass, fieldName, ClrType.FromDescriptor(fd.FieldType.FullName), 
                        false, instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldsflda, fd.IsPrivate);
            }

            var lineNumber = instruction.Offset;
            block.label(new Label(lineNumber));
            block.addOp(new GetField(instruction.Offset, field));
        }
コード例 #3
0
ファイル: Deduction.cs プロジェクト: abakam/WaleSuper
 protected override void setupEntityInfo()
 {
     FieldInfoList["DeductionID"] = new FieldInfo(false, false, true, new DeductionEDT());
     FieldInfoList["Description"] = new FieldInfo(true, true, true, new ShortDescriptionEDT());
     FieldInfoList["DeductionType"] = new FieldInfo(true, true, true, new DeductionTypeEDT());
     FieldInfoList["Value"] = new FieldInfo(true, true, true, "Value", new AmountEDT());
 }
コード例 #4
0
ファイル: FGConsole.cs プロジェクト: hnguyen091188/BurstLine
 static FGConsole()
 {
     consoleWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ConsoleWindow");
     if (consoleWindowType != null)
     {
         consoleWindowField = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
         consoleListViewField = consoleWindowType.GetField("m_ListView", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleActiveTextField = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         consoleOnGUIMethod = consoleWindowType.GetMethod("OnGUI", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
     }
     listViewStateType = typeof(EditorWindow).Assembly.GetType("UnityEditor.ListViewState");
     if (listViewStateType != null)
     {
         listViewStateRowField = listViewStateType.GetField("row", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
     editorWindowPosField = typeof(EditorWindow).GetField("m_Pos", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     logEntriesType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntries");
     if (logEntriesType != null)
     {
         getEntryMethod = logEntriesType.GetMethod("GetEntryInternal", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         startGettingEntriesMethod = logEntriesType.GetMethod("StartGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
         endGettingEntriesMethod = logEntriesType.GetMethod("EndGettingEntries", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
     }
     logEntryType = typeof(EditorWindow).Assembly.GetType("UnityEditorInternal.LogEntry");
     if (logEntryType != null)
     {
         logEntry = System.Activator.CreateInstance(logEntryType);
         logEntryFileField = logEntryType.GetField("file", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryLineField = logEntryType.GetField("line", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
         logEntryInstanceIDField = logEntryType.GetField("instanceID", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
     }
 }
コード例 #5
0
 // Use this for initialization
 void Start()
 {
     console = FindObjectOfType<BoltConsole>();
     debugInfo = FindObjectOfType<Bolt.DebugInfo>();
     BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
     field = typeof(BoltConsole).GetField("visible", flags);
 }
コード例 #6
0
    protected override void Initialize()
    {
        base.Initialize();

        if (owner != null)
        {
            field = owner.GetType().GetField(name);
            if (field != null)
                value = field.GetValue(owner);
            else
            {
                prop = owner.GetType().GetProperty(name);
                if (prop != null)
                    value = prop.GetValue(owner, null);
            }

            if (value == null)
            {
                Debug.LogError("Orthello Action Tween variable [" + name + "] not found on " + (owner as OTObject).name + "!");
            }

        }
        else
        {
            Debug.LogError("Orthello Action Tween owner is null!");
        }


        if (getFromValue)
            fromValue = value;

    }
コード例 #7
0
    object ReadField(BinaryReader Reader, object Obj, FieldInfo Info)
    {
        //string name = Reader.ReadString();
        object value = null;

        if (Info.FieldType == typeof(System.String))
        {
            value = Reader.ReadString();
        }
        else if (Info.FieldType == typeof(System.Int16))
        {
            value = Reader.ReadInt16();
        }
        else if (Info.FieldType == typeof(System.Single))
        {
            value = Reader.ReadSingle();
        }
        else if (Info.FieldType == typeof(System.Int32))
        {
            value = Reader.ReadInt32();
        }
        else if(Info.FieldType == typeof(System.Enum) || Info.FieldType.BaseType == typeof(System.Enum))
        {
            value = Reader.ReadInt32();
        }

        return value;
    }
コード例 #8
0
    public DebugConsoleBridge()
    {
        _assembly = Assembly.GetAssembly(typeof(SceneView));

        _typeLogEntries = _assembly.GetType("UnityEditorInternal.LogEntries");

        _startGettingEntriesMethod = _typeLogEntries.GetMethod("StartGettingEntries");
        _getEntryInternalMethod = _typeLogEntries.GetMethod("GetEntryInternal");
        _endGettingEntriesMethod = _typeLogEntries.GetMethod("EndGettingEntries");
        _getCountMethod = _typeLogEntries.GetMethod("GetCount");
        _clearMethod = _typeLogEntries.GetMethod("Clear");
        _getCountsByTypeMethod = _typeLogEntries.GetMethod("GetCountsByType");
        _setConsoleFlagMethod = _typeLogEntries.GetMethod("SetConsoleFlag");
        _getConsoleFlagsMethod = _typeLogEntries.GetMethod("get_consoleFlags");
        _getStatusTextMethod = _typeLogEntries.GetMethod("GetStatusText");

        _typeLogEntry = _assembly.GetType("UnityEditorInternal.LogEntry");

        _conditionField = _typeLogEntry.GetField("condition");
        _modeField = _typeLogEntry.GetField("mode");
        _instanceIdField = _typeLogEntry.GetField("instanceID");
        _fileField = _typeLogEntry.GetField("file");
        _lineField = _typeLogEntry.GetField("line");

        Type typeStyles = typeof(EditorGUIUtility);
        if(typeStyles != null)
            _getStyleMethod = typeStyles.GetMethod("GetStyle", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField | BindingFlags.GetField | BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.Static);

        object entryPlaceholder = Activator.CreateInstance(_typeLogEntry);
          		_getEntryInternalParams = new object[2] { 0, entryPlaceholder };
    }
コード例 #9
0
ファイル: FieldDecorator.cs プロジェクト: d3x0r/Voxelarium
 public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) : base(tail)
 {
     Helpers.DebugAssert(forType != null);
     Helpers.DebugAssert(field != null);
     this.forType = forType;
     this.field = field;
 }
コード例 #10
0
        public BlockTermsWriter(TermsIndexWriterBase termsIndexWriter,
            SegmentWriteState state, PostingsWriterBase postingsWriter)
        {
            var termsFileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix,
                TERMS_EXTENSION);
            _termsIndexWriter = termsIndexWriter;
            _output = state.Directory.CreateOutput(termsFileName, state.Context);
            var success = false;

            try
            {
                FieldInfos = state.FieldInfos;
                WriteHeader(_output);
                CurrentField = null;
                PostingsWriter = postingsWriter;

                postingsWriter.Init(_output); // have consumer write its format/header
                success = true;
            }
            finally
            {
                if (!success)
                {
                    IOUtils.CloseWhileHandlingException(_output);
                }
            }
        }
コード例 #11
0
 public override TermsConsumer AddField(FieldInfo field)
 {
     Write(FIELD);
     Write(field.Name);
     Newline();
     return new SimpleTextTermsWriter(this, field);
 }
コード例 #12
0
 static void DisplayField(Object obj, FieldInfo f)
 { 
     // Display the field name, value, and attributes. 
     //
     Console.WriteLine("{0} = \"{1}\"; attributes: {2}", 
         f.Name, f.GetValue(obj), f.Attributes);
 }
コード例 #13
0
ファイル: DbField.cs プロジェクト: pveller/Sitecore.FakeDb
 protected DbField(FieldInfo fieldInfo)
 {
   this.ID = fieldInfo.Id;
   this.Name = fieldInfo.Name;
   this.Shared = fieldInfo.Shared;
   this.Type = fieldInfo.Type;
 }
コード例 #14
0
 public WithInterceptorTests()
 {
     var assemblyPath = Path.GetFullPath(@"..\..\..\AssemblyWithInterceptor\bin\Debug\AssemblyWithInterceptor.dll");
     assemblyWeaver = new AssemblyWeaver(assemblyPath);
     var methodTimeLogger = assemblyWeaver.Assembly.GetType("MethodTimeLogger");
     methodBaseField = methodTimeLogger.GetField("MethodBase");
 }
コード例 #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FieldInfoMemberDefinition"/> class.
        /// </summary>
        /// <param name="field">
        /// The field.
        /// </param>
        public FieldInfoMemberDefinition(FieldInfo field)
        {
            if (field == null)
                throw new ArgumentNullException("field");

            _field = field;
        }
コード例 #16
0
 protected override MonotonicBlockPackedReader GetAddressInstance(IndexInput data, FieldInfo field,
     BinaryEntry bytes)
 {
     data.Seek(bytes.AddressesOffset);
     return new MonotonicBlockPackedReader((IndexInput)data.Clone(), bytes.PackedIntsVersion, bytes.BlockSize, bytes.Count,
         true);
 }
コード例 #17
0
 protected override MonotonicBlockPackedReader GetOrdIndexInstance(IndexInput data, FieldInfo field,
     NumericEntry entry)
 {
     data.Seek(entry.Offset);
     return new MonotonicBlockPackedReader((IndexInput)data.Clone(), entry.PackedIntsVersion, entry.BlockSize, entry.Count,
         true);
 }
コード例 #18
0
 internal static FieldInfo GetClassLiteralField(Type type)
 {
     Debug.Assert(type != Types.Void);
     if (classLiteralType == null)
     {
     #if STATIC_COMPILER
         classLiteralType = JVM.CoreAssembly.GetType("ikvm.internal.ClassLiteral`1");
     #elif !FIRST_PASS
         classLiteralType = typeof([email protected]<>);
     #endif
     }
     #if !STATIC_COMPILER
     if (!IsTypeBuilder(type))
     {
         return classLiteralType.MakeGenericType(type).GetField("Value", BindingFlags.Public | BindingFlags.Static);
     }
     #endif
     if (classLiteralField == null)
     {
         classLiteralField = classLiteralType.GetField("Value", BindingFlags.Public | BindingFlags.Static);
     }
     #if !NOEMIT
     return TypeBuilder.GetField(classLiteralType.MakeGenericType(type), classLiteralField);
     #else
     return null;
     #endif
 }
コード例 #19
0
ファイル: SqlHelper.cs プロジェクト: uNormatov/FreboCms
        /// <summary>
        /// Create Insert statements dynamically
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="fieldinfos"></param>
        /// <returns></returns>
        public static string GenerateInsertScript(string tablename, FieldInfo[] fieldinfos)
        {
            StringBuilder parametrs = new StringBuilder();
            StringBuilder columns = new StringBuilder();
            foreach (FieldInfo info in fieldinfos)
            {
                if (FormHelper.IsComponent(info))
                    continue;

                if (info.IsPrimaryKey)
                    continue;

                if (parametrs.Length > 0)
                    parametrs.Append(",");

                if (columns.Length > 0)
                    columns.Append(",");

                columns.AppendFormat("[{0}]", info.Name);
                parametrs.AppendFormat("@{0}", info.Name);

            }

            StringBuilder insertscript = new StringBuilder();
            insertscript.AppendFormat(" INSERT INTO {0}({1}) ", tablename, columns);
            insertscript.AppendFormat("VALUES ( {0} );", parametrs);
            insertscript.Append("SELECT  @@IDENTITY; ");
            return insertscript.ToString();
        }
コード例 #20
0
 public WithInterceptorTests()
 {
     var assemblyPath = Path.GetFullPath(@"..\..\..\AssemblyToProcess\bin\DebugWithInterceptor\AssemblyToProcess.dll");
     assembly = AssemblyWeaver.Weave(assemblyPath);
     var methodTimeLogger = assembly.GetType("MethodTimeLogger");
     methodBaseField = methodTimeLogger.GetField("MethodBase");
 }
コード例 #21
0
 public void Unbind()
 {
     if (!this.isBound)
     {
         return;
     }
     this.isBound = false;
     if (this.startEventField != null)
     {
         this.unbindEvent(this.startEventField, this.startEventHandler);
         this.startEventField = null;
         this.startEventHandler = null;
     }
     if (this.stopEventField != null)
     {
         this.unbindEvent(this.stopEventField, this.stopEventHandler);
         this.stopEventField = null;
         this.stopEventHandler = null;
     }
     if (this.resetEventField != null)
     {
         this.unbindEvent(this.resetEventField, this.resetEventHandler);
         this.resetEventField = null;
         this.resetEventHandler = null;
     }
 }
コード例 #22
0
 public AMActionFieldSet(AMKey key, int frameRate, object target, FieldInfo f, object val)
     : base(key, frameRate)
 {
     mObj = target;
     mField = f;
     mVal = val;
 }
コード例 #23
0
ファイル: Ldflda.cs プロジェクト: iSalva/Cosmos
        public static void DoExecute(Cosmos.Assembler.Assembler Assembler, MethodInfo aMethod, Type aDeclaringType, FieldInfo aField, bool aDerefValue, bool aDebugEnabled)
        {
            int xExtraOffset = 0;
            var xType = aMethod.MethodBase.DeclaringType;
            bool xNeedsGC = aDeclaringType.IsClass && !aDeclaringType.IsValueType;

            if (xNeedsGC)
            {
                xExtraOffset = 12;
            }

            var xActualOffset = aField.Offset + xExtraOffset;
            var xSize = aField.Size;
            DoNullReferenceCheck(Assembler, aDebugEnabled, 0);

            if (aDerefValue && aField.IsExternalValue)
            {
                new CPUx86.Mov
                {
                    DestinationReg = CPUx86.Registers.EAX,
                    SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = (int) xActualOffset
                };
                new CPUx86.Mov {DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, SourceReg = CPUx86.Registers.EAX};
            }
            else
                new CPUx86.Add {DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, SourceValue = (uint) (xActualOffset)};
        }
コード例 #24
0
        /// <summary>
        /// Provides properties for storing and retrieving CME FIX security definition fields.
        /// </summary>
        public SecurityDefinition(FieldInfo<byte> tagInfo, FieldInfo<byte> valueInfo, Trailer trailer) 
            : base(tagInfo, valueInfo, trailer)
        {
            SecurityGroup = new FieldInfo<char>(SECURITY_GROUP_FIELD_LENGTH);
            Symbol = new FieldInfo<char>(SYMBOL_FIELD_LENGTH);
            SecurityDesc = new FieldInfo<char>(SECURITY_DESC_FIELD_LENGTH);
            SecurityID = new FieldInfo<char>(SECURITY_ID_FIELD_LENGTH);
            CFICode = new FieldInfo<char>(CFI_CODE_FIELD_LENGTH);
            SecurityExchange = new FieldInfo<char>(SECURITY_EXCHANGE_FIELD_LENGTH);
            StrikeCurrency = new FieldInfo<char>(STRIKE_CURRENCY_FIELD_LENGTH);
            Currency = new FieldInfo<char>(CURRENCY_FIELD_LENGTH);
            SettlCurrency = new FieldInfo<char>(SETTL_CURRENCY_FIELD_LENGTH);

            DataBlockEvent = new RepeatingGroupEvent[REPEATING_GROUP_ARRAY_LENGTH];
            for (int i = 0; i < REPEATING_GROUP_ARRAY_LENGTH; i++)
            {
                DataBlockEvent[i] = new RepeatingGroupEvent();
            }

            DataBlockMDFeedType = new RepeatingGroupMDFeedType[REPEATING_GROUP_ARRAY_LENGTH];
            for (int i = 0; i < REPEATING_GROUP_ARRAY_LENGTH; i++)
            {
                DataBlockMDFeedType[i] = new RepeatingGroupMDFeedType();
            }

            //throw new NotImplementedException("SecurityDefinition class not yet implemented.");
        }
コード例 #25
0
ファイル: FieldGetter.cs プロジェクト: BclEx/AdamsyncEx
 public FieldGetter(FieldInfo fieldInfo)
 {
     _fieldInfo = fieldInfo;
     _name = fieldInfo.Name;
     _memberType = fieldInfo.FieldType;
     _lateBoundFieldGet = DelegateFactory.CreateGet(fieldInfo);
 }
コード例 #26
0
 /// <summary>
 /// Called when downsizing bitsets for serialization
 /// </summary>
 /// <param name="fieldInfo">The field with sparse set bits</param>
 /// <param name="initialSet">The bits accumulated</param>
 /// <returns> null or a hopefully more densely packed, smaller bitset</returns>
 public FuzzySet Downsize(FieldInfo fieldInfo, FuzzySet initialSet)
 {
     // Aim for a bitset size that would have 10% of bits set (so 90% of searches
     // would fail-fast)
     const float targetMaxSaturation = 0.1f;
     return initialSet.Downsize(targetMaxSaturation);
 }
コード例 #27
0
ファイル: Logon.cs プロジェクト: giladbi/Observer
 /// <summary>
 /// Provides properties for storing and retrieving CME FIX logon fields.
 /// </summary>
 public Logon(FieldInfo<byte> tagInfo, FieldInfo<byte> valueInfo, Trailer trailer)
     : base(tagInfo, valueInfo, trailer)
 {
     Username = new FieldInfo<char>(USERNAME_FIELD_LENGTH);
     Password = new FieldInfo<char>(PASSWORD_FIELD_LENGTH);
     ApplID = new FieldInfo<char>(APPL_ID_FIELD_LENGTH);
 }
コード例 #28
0
		static API()
		{
			var editorAssembly = typeof(EditorWindow).Assembly;
			containerWindowType = editorAssembly.GetType("UnityEditor.ContainerWindow");
			viewType = editorAssembly.GetType("UnityEditor.View");
			dockAreaType = editorAssembly.GetType("UnityEditor.DockArea");
			parentField = typeof(EditorWindow).GetField("m_Parent", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
			if (dockAreaType != null)
			{
				panesField = dockAreaType.GetField("m_Panes", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
				addTabMethod = dockAreaType.GetMethod("AddTab", new System.Type[] { typeof(EditorWindow) });
			}
			if (containerWindowType != null)
			{
				windowsField = containerWindowType.GetProperty("windows", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic);
				mainViewField = containerWindowType.GetProperty("mainView", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic);
			}
			if (viewType != null)
				allChildrenField = viewType.GetProperty("allChildren", BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic);
				
			FieldInfo windowsReorderedField = typeof(EditorApplication).GetField("windowsReordered", BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
			windowsReordered = windowsReorderedField.GetValue(null) as EditorApplication.CallbackFunction;

			System.Type projectWindowUtilType = editorAssembly.GetType("UnityEditor.ProjectWindowUtil");
			if (projectWindowUtilType != null)
				createAssetMethod = projectWindowUtilType.GetMethod("CreateAsset", new System.Type[] { typeof(Object), typeof(string) });
		}
コード例 #29
0
 public EnumFieldGenerator(FieldInfo fld)
     : base(fld)
 {
     _enum = fld.DeclaringType.ParentConfig.ResolveName<EnumType>(
              fld.DeclaringType, ((EnumTypeRef)fld).TypeName
              );
     _generator = new EnumTypeGenerator(_enum);
 }
コード例 #30
0
 public FieldInfoOperation(FieldInfo fieldInfo)
 {
     if (fieldInfo == null)
     {
         throw new ArgumentNullException("fi");
     }
     this.fieldInfo = fieldInfo;
 }
コード例 #31
0
        void SetupPart(TypeInfo sourceType, BindingExpressionPart part)
        {
            part.Arguments  = null;
            part.LastGetter = null;
            part.LastSetter = null;

            PropertyInfo property = null;

            if (part.IsIndexer)
            {
                if (sourceType.IsArray)
                {
                    int index;
                    if (!int.TryParse(part.Content, out index))
                    {
                        Log.Warning("Binding", "{0} could not be parsed as an index for a {1}", part.Content, sourceType);
                    }
                    else
                    {
                        part.Arguments = new object[] { index }
                    };

                    part.LastGetter = sourceType.GetDeclaredMethod("Get");
                    part.LastSetter = sourceType.GetDeclaredMethod("Set");
                    part.SetterType = sourceType.GetElementType();
                }

                DefaultMemberAttribute defaultMember = sourceType.GetCustomAttributes(typeof(DefaultMemberAttribute), true).OfType <DefaultMemberAttribute>().FirstOrDefault();
                string indexerName = defaultMember != null ? defaultMember.MemberName : "Item";

                part.IndexerName = indexerName;

                property = sourceType.GetDeclaredProperty(indexerName);
                if (property == null)
                {
                    property = sourceType.BaseType.GetProperty(indexerName);
                }

                if (property != null)
                {
                    ParameterInfo parameter = property.GetIndexParameters().FirstOrDefault();
                    if (parameter != null)
                    {
                        try
                        {
                            object arg = Convert.ChangeType(part.Content, parameter.ParameterType, CultureInfo.InvariantCulture);
                            part.Arguments = new[] { arg };
                        }
                        catch (FormatException)
                        {
                        }
                        catch (InvalidCastException)
                        {
                        }
                        catch (OverflowException)
                        {
                        }
                    }
                }
            }
            else
            {
                property = sourceType.GetDeclaredProperty(part.Content) ?? sourceType.BaseType?.GetProperty(part.Content);
            }

            if (property != null)
            {
                if (property.CanRead && property.GetMethod.IsPublic && !property.GetMethod.IsStatic)
                {
                    part.LastGetter = property.GetMethod;
                }
                if (property.CanWrite && property.SetMethod.IsPublic && !property.SetMethod.IsStatic)
                {
                    part.LastSetter = property.SetMethod;
                    part.SetterType = part.LastSetter.GetParameters().Last().ParameterType;

                    if (Binding.AllowChaining)
                    {
                        FieldInfo bindablePropertyField = sourceType.GetDeclaredField(part.Content + "Property");
                        if (bindablePropertyField != null && bindablePropertyField.FieldType == typeof(BindableProperty) && sourceType.ImplementedInterfaces.Contains(typeof(IElementController)))
                        {
                            MethodInfo setValueMethod = null;
                            foreach (MethodInfo m in sourceType.AsType().GetRuntimeMethods())
                            {
                                if (m.Name.EndsWith("IElementController.SetValueFromRenderer"))
                                {
                                    ParameterInfo[] parameters = m.GetParameters();
                                    if (parameters.Length == 2 && parameters[0].ParameterType == typeof(BindableProperty))
                                    {
                                        setValueMethod = m;
                                        break;
                                    }
                                }
                            }
                            if (setValueMethod != null)
                            {
                                part.LastSetter = setValueMethod;
                                part.IsBindablePropertySetter = true;
                                part.BindablePropertyField    = bindablePropertyField.GetValue(null);
                            }
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MetadataValidatedElement"/> class for a field and a ruleset.
 /// </summary>
 /// <param name="fieldInfo">The field.</param>
 /// <param name="ruleset">The ruleset.</param>
 public MetadataValidatedElement(FieldInfo fieldInfo, string ruleset)
     : this(ruleset)
 {
     this.UpdateFlyweight(fieldInfo);
 }
コード例 #33
0
 public void EmitLoadField(FieldInfo field)
 {
     Emit(GetLoadField(field));
 }
コード例 #34
0
ファイル: FieldTracker.cs プロジェクト: xia7410/dlr
 public FieldTracker(FieldInfo field)
 {
     ContractUtils.RequiresNotNull(field, nameof(field));
     _field = field;
 }
コード例 #35
0
ファイル: Test.cs プロジェクト: awesomedotnetcore/gremit
        private IQxx BuildSwitch(ModuleBuilder module, string[] keys)
        {
            var numberOfCases = keys.Length;
            var typeBuilder   = module.DefineType("Switch" + Guid.NewGuid(), TypeAttributes.Class | TypeAttributes.Public);

            typeBuilder.AddInterfaceImplementation(typeof(IQxx));
            var fields = new FieldInfo[numberOfCases];

            for (var i = 0; i < numberOfCases; ++i)
            {
                fields[i] = typeBuilder.DefineField(keys[i], typeof(int), FieldAttributes.Public);
            }
            var tinyHashtable = Create(keys);
            var n             = tinyHashtable.Length;
            var keysField     = typeBuilder.DefineField("keys", typeof(string[]), FieldAttributes.Public);
            var constructor   = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new[] { typeof(string[]) });

            using (var il = new GroboIL(constructor))
            {
                il.Ldarg(0);
                il.Ldarg(1);
                il.Stfld(keysField);
                il.Ret();
            }

            var method = typeBuilder.DefineMethod("Set", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new[] { typeof(string), typeof(int) });

            method.DefineParameter(1, ParameterAttributes.In, "key");
            method.DefineParameter(2, ParameterAttributes.In, "value");
            using (var il = new GroboIL(method))
            {
                il.Ldarg(0);
                il.Ldfld(keysField);
                il.Ldarg(1);
                il.Call(HackHelpers.GetMethodDefinition <object>(o => o.GetHashCode()));
                il.Ldc_I4(n);
                il.Rem(true);
                var idx = il.DeclareLocal(typeof(int));
                il.Dup();
                il.Stloc(idx);
                il.Ldelem(typeof(string));
                il.Ldarg(1);
                il.Call(stringEqualityOperator);
                var doneLabel = il.DefineLabel("done");
                il.Brfalse(doneLabel);

                var labels = new GroboIL.Label[n];
                for (var i = 0; i < n; ++i)
                {
                    labels[i] = doneLabel;
                }
                foreach (var key in keys)
                {
                    var index = key.GetHashCode() % n;
                    if (index < 0)
                    {
                        index += n;
                    }
                    var label = il.DefineLabel("set_" + key);
                    labels[index] = label;
                }
                il.Ldloc(idx);
                il.Switch(labels);
                for (var i = 0; i < keys.Length; ++i)
                {
                    var index = keys[i].GetHashCode() % n;
                    if (index < 0)
                    {
                        index += n;
                    }
                    il.MarkLabel(labels[index]);
                    il.Ldarg(0);
                    il.Ldarg(2);
                    il.Stfld(fields[i]);
                    il.Br(doneLabel);
                }
                il.MarkLabel(doneLabel);
                il.Ret();
            }
            typeBuilder.DefineMethodOverride(method, typeof(IQxx).GetMethod("Set"));
            var type = typeBuilder.CreateType();

            return((IQxx)Activator.CreateInstance(type, new object[] { tinyHashtable }));
        }
コード例 #36
0
        static MembershipProviderCollectionExtensions()
        {
            var t = typeof(ProviderCollection);

            _providerCollectionReadOnlyField = t.GetField("_ReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        }
コード例 #37
0
ファイル: FieldOperations.cs プロジェクト: yuekunge/corefx
 public LoadStaticFieldInstruction(FieldInfo field)
 {
     Debug.Assert(field.IsStatic);
     _field = field;
 }
コード例 #38
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="field">is the field to use to retrieve a value from the object.</param>
 /// <param name="key">is the key to supply as parameter to the mapped property getter</param>
 /// <param name="eventAdapterService">factory for event beans and event types</param>
 public KeyedMapFieldPropertyGetter(FieldInfo field, Object key, EventAdapterService eventAdapterService)
     : base(eventAdapterService, TypeHelper.GetGenericFieldTypeMap(field, false), null)
 {
     this._key = key;
     this._field = field;
 }
コード例 #39
0
ファイル: XmlUIConstructor.cs プロジェクト: jayands/tAPI-SDK
        static object FromString(Type t, string value)
        {
            if (t.IsPointer || t.IsInterface || t.IsAbstract || t.IsArray)
            {
                return(null);
            }

            object ret = FromNode(value);

            if (ret != null)
            {
                return(ret);
            }

            ret = CheckForLiterals(value, t);
            if (ret != null)
            {
                return(ret);
            }

            if (t.IsEnum)
            {
                return(Enum.Parse(t, value, true));
            }

            if (t.IsClass || t.IsValueType)
            {
                ret = ReflectionHelper.Instantiate(t);

                List <Tuple <string, string> > fields = new List <Tuple <string, string> >();

                string[] split = value.Split(';');
                for (int i = 0; i < split.Length; i++)
                {
                    split[i] = split[i].Trim();

                    string
                        name       = split[i].Split('=')[0].Trim(),
                        fieldvalue = split[i].Split('=')[1].Trim();

                    MemberInfo mi = GetFieldOrProperty(t, name);
                    if (mi == null)
                    {
                        continue;
                    }

                    if (mi.MemberType == MemberTypes.Field)
                    {
                        FieldInfo fi = mi as FieldInfo;

                        fi.SetValue(ret, FromString(mi.ReflectedType, fieldvalue));
                    }
                    if (mi.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo pi = mi as PropertyInfo;

                        pi.SetValue(ret, FromString(mi.ReflectedType, fieldvalue), null);
                    }

                    fields.Add(new Tuple <string, string>(name, fieldvalue));
                }
            }

            return(null);
        }
コード例 #40
0
 static InterruptMusic()
 {
     _volumeLevelField = typeof(GameplayMusicController).GetField("volumeLevel", BindingFlags.NonPublic | BindingFlags.Instance);
 }
コード例 #41
0
 /// <summary>
 /// Creates the XML doc comment member reference string
 /// for a given <see cref="System.Reflection.FieldInfo"/>.
 /// </summary>
 ///
 /// <param name="field">
 /// The <see cref="System.Reflection.FieldInfo"/> to convert.
 /// </param>
 ///
 /// <returns>
 /// A string containing the requested member reference.
 /// </returns>
 public static string ToXmlDocCommentMember(FieldInfo field)
 {
     return(ToXmlDocCommentMember(field, EmptyParameterList).ToString());
 }
コード例 #42
0
        /// <summary>
        /// Raises the RenderItemImage event.
        /// </summary>
        /// <param name="e">An ToolStripItemImageRenderEventArgs containing the event data.</param>
        protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e)
        {
            // Is this a min/restore/close pendant button
            if (e.Item.GetType().ToString() == "System.Windows.Forms.MdiControlStrip+ControlBoxMenuItem")
            {
                // Get access to the owning form of the mdi control strip
                if (e.ToolStrip.Parent.TopLevelControl is Form f)
                {
                    // Get the mdi control strip instance
                    PropertyInfo piMCS = typeof(Form).GetProperty("MdiControlStrip", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                    if (piMCS != null)
                    {
                        object mcs = piMCS.GetValue(f, null);
                        if (mcs != null)
                        {
                            // Get the min/restore/close internal menu items
                            Type      mcsType = mcs.GetType();
                            FieldInfo fiM     = mcsType.GetField("minimize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            FieldInfo fiR     = mcsType.GetField("restore", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            FieldInfo fiC     = mcsType.GetField("close", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            if ((fiM != null) && (fiR != null) && (fiC != null))
                            {
                                ToolStripMenuItem m = fiM.GetValue(mcs) as ToolStripMenuItem;
                                ToolStripMenuItem r = fiR.GetValue(mcs) as ToolStripMenuItem;
                                ToolStripMenuItem c = fiC.GetValue(mcs) as ToolStripMenuItem;
                                if ((m != null) && (r != null) && (c != null))
                                {
                                    // Compare the event provided image with the internal cached ones to discover the type of pendant button we are drawing
                                    PaletteButtonSpecStyle specStyle = PaletteButtonSpecStyle.Generic;
                                    if (m.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantMin;
                                    }
                                    else if (r.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantRestore;
                                    }
                                    else if (c.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantClose;
                                    }

                                    // A match, means we have a known pendant button
                                    if (specStyle != PaletteButtonSpecStyle.Generic)
                                    {
                                        // Grab the palette pendant details needed for drawing
                                        Image paletteImage     = KCT.Palette.GetButtonSpecImage(specStyle, PaletteState.Normal);
                                        Color transparentColor = KCT.Palette.GetButtonSpecImageTransparentColor(specStyle);

                                        // Finally we actually have an image to draw!
                                        if (paletteImage != null)
                                        {
                                            using (ImageAttributes attribs = new ImageAttributes())
                                            {
                                                // Setup mapping to make required color transparent
                                                ColorMap remap = new ColorMap
                                                {
                                                    OldColor = transparentColor,
                                                    NewColor = Color.Transparent
                                                };
                                                attribs.SetRemapTable(new ColorMap[] { remap });

                                                // Phew, actually draw the darn thing
                                                e.Graphics.DrawImage(paletteImage, e.ImageRectangle,
                                                                     0, 0, e.Image.Width, e.Image.Height,
                                                                     GraphicsUnit.Pixel, attribs);

                                                // Do not let base class draw system defined image
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            base.OnRenderItemImage(e);
        }
コード例 #43
0
 public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, FieldInfo fieldInfo)
 {
     return(new TypeAccessor
     {
         PropertyType = fieldInfo.FieldType,
         GetProperty = serializer.GetParseFn(fieldInfo.FieldType),
         SetProperty = GetSetFieldMethod(typeConfig, fieldInfo),
     });
 }
コード例 #44
0
ファイル: FieldOperations.cs プロジェクト: yuekunge/corefx
 public StoreStaticFieldInstruction(FieldInfo field)
 {
     Assert.NotNull(field);
     _field = field;
 }
コード例 #45
0
ファイル: FieldOperations.cs プロジェクト: yuekunge/corefx
 public LoadFieldInstruction(FieldInfo field)
 {
     Assert.NotNull(field);
     _field = field;
 }
コード例 #46
0
        /// <summary>
        /// Routine outputs name and value for all fields.
        /// </summary>
        /// <returns>String value.</returns>
        public string FieldsToString()
        {
            StringBuilder data = new StringBuilder();
            Type          t    = this.GetType();

            FieldInfo[] finfos = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.FlattenHierarchy);
            bool        typeHasFieldsToStringMethod = false;

            data.Append("\r\nClass fields for ");
            data.Append(t.FullName);
            data.Append("\r\n");

            int inx    = 0;
            int maxInx = finfos.Length - 1;

            for (inx = 0; inx <= maxInx; inx++)
            {
                FieldInfo fld = finfos[inx];
                object    val = fld.GetValue(this);
                if (fld.IsPublic)
                {
                    data.Append(" public ");
                }
                if (fld.IsPrivate)
                {
                    data.Append(" private ");
                }
                if (!fld.IsPublic && !fld.IsPrivate)
                {
                    data.Append(" internal ");
                }
                if (fld.IsStatic)
                {
                    data.Append(" static ");
                }
                data.Append(" ");
                data.Append(fld.FieldType.FullName);
                data.Append(" ");
                data.Append(fld.Name);
                data.Append(": ");
                typeHasFieldsToStringMethod = UseFieldsToString(fld.FieldType);
                if (val != null)
                {
                    if (typeHasFieldsToStringMethod)
                    {
                        data.Append(GetFieldValues(val));
                    }
                    else
                    {
                        data.Append(val.ToString());
                    }
                }
                else
                {
                    data.Append("<null value>");
                }
                data.Append("  ");

                if (fld.FieldType.IsArray)
                //if (fld.Name == "TestStringArray" || "_testStringArray")
                {
                    System.Collections.IList valueList = (System.Collections.IList)fld.GetValue(this);
                    for (int i = 0; i < valueList.Count; i++)
                    {
                        data.Append("Index ");
                        data.Append(i.ToString("#,##0"));
                        data.Append(": ");
                        data.Append(valueList[i].ToString());
                        data.Append("  ");
                    }
                }

                data.Append("\r\n");
            }

            return(data.ToString());
        }
コード例 #47
0
ファイル: CustomMarshaler.cs プロジェクト: dengliyan/XUtils
 public virtual void ReadFromStream(BinaryReader reader)
 {
     FieldInfo[] fields = base.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
     FieldInfo[] array  = fields;
     for (int i = 0; i < array.Length; i++)
     {
         FieldInfo  fieldInfo  = array[i];
         MethodInfo methodInfo = (MethodInfo)MarshallingMethods.ReadMethods[fieldInfo.FieldType];
         if (fieldInfo.FieldType.IsArray)
         {
             Type elementType = fieldInfo.FieldType.GetElementType();
             if (elementType.IsValueType && elementType.IsPrimitive)
             {
                 if (elementType == typeof(char) || elementType == typeof(byte))
                 {
                     fieldInfo.SetValue(this, methodInfo.Invoke(reader, new object[]
                     {
                         this.GetFieldSize(fieldInfo)
                     }));
                 }
                 else
                 {
                     fieldInfo.SetValue(this, methodInfo.Invoke(null, new object[]
                     {
                         reader,
                         this.GetFieldSize(fieldInfo)
                     }));
                 }
             }
             else
             {
                 int fieldSize = this.GetFieldSize(fieldInfo);
                 methodInfo = (MethodInfo)MarshallingMethods.ReadMethods[typeof(CustomMarshaler)];
                 Array array2 = Array.CreateInstance(elementType, fieldSize);
                 for (int j = 0; j < fieldSize; j++)
                 {
                     array2.SetValue(Activator.CreateInstance(elementType), j);
                     methodInfo.Invoke(array2.GetValue(j), new object[]
                     {
                         reader
                     });
                 }
                 fieldInfo.SetValue(this, array2);
             }
         }
         else
         {
             if (fieldInfo.FieldType == typeof(string))
             {
                 fieldInfo.SetValue(this, methodInfo.Invoke(null, new object[]
                 {
                     reader,
                     this.GetFieldSize(fieldInfo)
                 }));
             }
             else
             {
                 if (fieldInfo.FieldType.IsValueType && fieldInfo.FieldType.IsPrimitive)
                 {
                     fieldInfo.SetValue(this, methodInfo.Invoke(reader, null));
                 }
                 else
                 {
                     CustomMarshaler customMarshaler = (CustomMarshaler)Activator.CreateInstance(fieldInfo.FieldType);
                     customMarshaler.ReadFromStream(reader);
                 }
             }
         }
     }
 }
コード例 #48
0
        private static ExcelWorksheet BuildSheetHeader(ExcelPackage package, FieldInfo item, object att)
        {
            ExcelConfigAttribute excelAtt  = att as ExcelConfigAttribute;
            ExcelWorksheet       workSheet = package.Workbook.Worksheets[excelAtt.SheetName];

            if (workSheet == null)
            {
                var type = item.FieldType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary <,>))
                {
                    var pkmRef = package.Workbook.Worksheets["Pokemons"];

                    workSheet = package.Workbook.Worksheets.Add(excelAtt.SheetName, pkmRef);
                    Type keyType   = type.GetGenericArguments()[0];
                    Type valueType = type.GetGenericArguments()[1];
                    int  pos       = 1;

                    workSheet.Cells[1, 1].Value = excelAtt.SheetName;
                    workSheet.Cells[2, 1].Value = excelAtt.Description;

                    foreach (var vtp in valueType.GetProperties())
                    {
                        var att1     = vtp.GetCustomAttributes <ExcelConfigAttribute>(true).FirstOrDefault();
                        int colIndex = (att1 == null ? pos : att1.Position) + COL_OFFSET;
                        workSheet.Column(colIndex).AutoFit();
                        workSheet.Cells[4, colIndex].Value = att1 == null ? vtp.Name : att1.Key;
                        if (att1 != null)
                        {
                            workSheet.Cells[4, colIndex].AddComment(att1.Description, "necrobot2");
                            AddValidationForType(workSheet, vtp, $"{GetCol(colIndex)}5:{GetCol(colIndex)}155");
                        }
                        pos++;
                    }
                    workSheet.Cells[$"A1:{GetCol(COL_OFFSET + pos)}1"].Merge           = true;
                    workSheet.Cells[$"A2:{GetCol(COL_OFFSET + pos)}2"].Merge           = true;
                    workSheet.Cells[$"A1:{GetCol(COL_OFFSET + pos)}1"].Style.Font.Size = 16;
                }
                else
                {
                    workSheet = package.Workbook.Worksheets.Add(excelAtt.SheetName);
                    workSheet.Cells[1, 1].Value = excelAtt.SheetName;
                    workSheet.Cells[2, 1].Value = excelAtt.Description;

                    workSheet.Cells[$"A1:C1"].Merge = true;
                    workSheet.Cells[$"A2:C2"].Merge = true;


                    workSheet.Cells["A1:C1"].Style.Font.Size = 16;
                    workSheet.Row(1).CustomHeight            = true;
                    workSheet.Row(1).Height = 30;

                    workSheet.Cells["A1:C1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    workSheet.Cells["A1:C1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Justify;

                    workSheet.Cells[4, 1].Value = "Key";
                    workSheet.Cells[4, 2].Value = "Value";
                    workSheet.Cells[4, 3].Value = "Description";
                }

                workSheet.Row(4).Style.Font.Bold = true;
            }

            return(workSheet);
        }
コード例 #49
0
 void LocalizeListView(string formName, string formClassName, ListView lv)
 {
     if (null == formName || null == lv || string.IsNullOrEmpty(lv.Name))
     {
         return;
     }
     if (lv.Columns.Count < 1)
     {
         return;
     }
     for (int i = 0; i < 2; i++)
     {
         // First look at this control, in case this is a derived class, then get list view parent so we have a place to look for ControlHeader variables
         Control ctrl = i < 1 ? lv : lv.Parent;
         if (null != ctrl)
         {
             // Get list of fields (variables) that the ctrl class includes
             FieldInfo[] fields = ctrl.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
             {
                 // Find all the ColumnHeader fields in the ctrl class and build a dictionary of the field value and its field name
                 var header_fields = new Dictionary <ColumnHeader, string>();
                 for (int j = 0, length = fields.Length; j < length; j++)
                 {
                     FieldInfo fi = fields[j];
                     if (null != fi)
                     {
                         var ch = fi.GetValue(ctrl) as ColumnHeader;
                         if (null != ch)
                         {
                             header_fields.Add(ch, fi.Name);
                         }
                     }
                 }
                 if (header_fields.Count > 0)
                 {
                     // Iterate column header list
                     for (int j = 0, count = lv.Columns.Count; j < count; j++)
                     {
                         ColumnHeader header = lv.Columns[j];
                         // If this header item is not null and the text is not empty and the header object is in the control dictionary
                         string control_field_name;
                         if (null != header && !string.IsNullOrEmpty(header.Text) && header_fields.TryGetValue(header, out control_field_name) && !string.IsNullOrEmpty(control_field_name))
                         {
                             // Look up the localized string for this column header item
                             string key = formName + "::" + control_field_name + "::Text";
                             string value;
                             if (m_dialog_list.TryGetValue(key, out value))
                             {
                                 header.Text = value;
                             }
                             else if (!string.IsNullOrEmpty(formClassName))
                             {
                                 key = formName + "::" + formClassName + "::" + control_field_name + "::Text";
                                 if (m_dialog_list.TryGetValue(key, out value))
                                 {
                                     header.Text = value;
                                 }
                                 else
                                 {
                                     key = formClassName + "::" + control_field_name + "::Text";
                                     if (m_dialog_list.TryGetValue(key, out value))
                                     {
                                         header.Text = value;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
コード例 #50
0
        private static void WriteOnePropertyToSheet(ExcelWorksheet workSheet, object configProp, FieldInfo cfg)
        {
            var att2 = cfg.GetCustomAttributes(typeof(ExcelConfigAttribute), true).FirstOrDefault();

            if (att2 != null)
            {
                var    exAtt     = att2 as ExcelConfigAttribute;
                string configKey = string.IsNullOrEmpty(exAtt.Key) ? cfg.Name : exAtt.Key;
                var    propValue = cfg.GetValue(configProp);
                workSheet.Cells[exAtt.Position + OFFSET_START, 1].Value                     = configKey;
                workSheet.Cells[exAtt.Position + OFFSET_START, 2].Value                     = propValue;
                workSheet.Cells[exAtt.Position + OFFSET_START, 2].Style.Locked              = false;
                workSheet.Cells[exAtt.Position + OFFSET_START, 2].Style.Font.Bold           = true;
                workSheet.Cells[exAtt.Position + OFFSET_START, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                workSheet.Cells[exAtt.Position + OFFSET_START, 3].Value                     = exAtt.Description;
                workSheet.Cells[exAtt.Position + OFFSET_START, 3].Style.Locked              = false;
                workSheet.Cells[exAtt.Position + OFFSET_START, 1].AutoFitColumns();
                workSheet.Cells[exAtt.Position + OFFSET_START, 2].AutoFitColumns();
                workSheet.Cells[exAtt.Position + OFFSET_START, 3].AutoFitColumns();
                //AddValidationForType(workSheet, cfg, $"B{exAtt.Position + OFFSET_START}");
                if (propValue is Boolean)
                {
                    var validation = workSheet.DataValidations.AddListValidation($"B{exAtt.Position + OFFSET_START}");
                    validation.ShowErrorMessage = true;
                    validation.ErrorStyle       = ExcelDataValidationWarningStyle.stop;
                    validation.Error            = "Please select from list";
                    validation.ErrorTitle       = $"{configKey} Validation";
                    validation.Formula.Values.Add("TRUE");
                    validation.Formula.Values.Add("FALSE");
                    validation.PromptTitle      = "Boolean only";
                    validation.Prompt           = "Only TRUE or FALSE are accepted";
                    validation.ShowInputMessage = true;
                    //data validation
                }

                if (propValue is int || propValue is double)
                {
                    var validation = workSheet.DataValidations.AddIntegerValidation($"B{exAtt.Position + OFFSET_START}");
                    validation.ShowErrorMessage = true;
                    validation.Error            = "Please enter a valid number";
                    validation.ErrorTitle       = $"{configKey} Validation";
                    validation.ErrorStyle       = ExcelDataValidationWarningStyle.stop;
                    validation.PromptTitle      = "Enter a integer value here";
                    validation.Prompt           = "Please enter a negative number here";
                    validation.ShowInputMessage = true;
                    validation.ShowErrorMessage = true;
                    validation.Operator         = ExcelDataValidationOperator.between;
                    validation.Formula.Value    = 0;
                    validation.Formula2.Value   = int.MaxValue;
                    var range = cfg.GetCustomAttributes(typeof(RangeAttribute), true)
                                .Cast <RangeAttribute>()
                                .FirstOrDefault();
                    if (range != null)
                    {
                        validation.Formula.Value  = (int)range.Minimum;
                        validation.Formula2.Value = (int)range.Maximum;
                        validation.Prompt         = $"Please enter a valid number from {validation.Formula.Value} to {validation.Formula2.Value}";
                        validation.Error          = $"Please enter a valid number from {validation.Formula.Value} to {validation.Formula2.Value}";
                    }
                }
                if (propValue is string)
                {
                    var maxLength = cfg.GetCustomAttributes(typeof(MaxLengthAttribute), true)
                                    .Cast <MaxLengthAttribute>()
                                    .FirstOrDefault();
                    var minLength = cfg.GetCustomAttributes(typeof(MinLengthAttribute), true)
                                    .Cast <MinLengthAttribute>()
                                    .FirstOrDefault();
                    if (maxLength != null && minLength != null)
                    {
                        var validation = workSheet.DataValidations.AddTextLengthValidation($"B{exAtt.Position + OFFSET_START}");
                        validation.ErrorTitle       = $"{configKey} Validation";
                        validation.ErrorStyle       = ExcelDataValidationWarningStyle.stop;
                        validation.PromptTitle      = "String Validation";
                        validation.ShowInputMessage = true;
                        validation.ShowErrorMessage = true;

                        validation.Error  = $"Please enter a string from {minLength.Length} to {maxLength.Length} characters";
                        validation.Prompt = $"Please enter a string from {minLength.Length} to {maxLength.Length} characters";

                        validation.Operator       = ExcelDataValidationOperator.between;
                        validation.Formula.Value  = minLength.Length;
                        validation.Formula2.Value = maxLength.Length;
                    }
                    else
                    {
                        if (minLength != null)
                        {
                            var validation = workSheet.DataValidations.AddTextLengthValidation($"B{exAtt.Position + OFFSET_START}");
                            validation.ErrorTitle       = $"{configKey} Validation";
                            validation.ErrorStyle       = ExcelDataValidationWarningStyle.stop;
                            validation.PromptTitle      = "String Validation";
                            validation.ShowInputMessage = true;
                            validation.ShowErrorMessage = true;

                            validation.Error  = $"Please enter a string atleast {minLength.Length} characters";
                            validation.Prompt = $"Please enter a string atleast {minLength.Length} characters";

                            validation.Operator      = ExcelDataValidationOperator.greaterThan;
                            validation.Formula.Value = minLength.Length;
                        }
                    }
                }
                var enumDataType = cfg.GetCustomAttributes(typeof(EnumDataTypeAttribute), true)
                                   .Cast <EnumDataTypeAttribute>()
                                   .FirstOrDefault();
                if (enumDataType != null)
                {
                    var validation = workSheet.DataValidations.AddListValidation($"B{exAtt.Position + OFFSET_START}");
                    validation.ErrorTitle       = $"{configKey} Validation";
                    validation.ErrorStyle       = ExcelDataValidationWarningStyle.stop;
                    validation.PromptTitle      = $"{configKey} Validation";
                    validation.ShowInputMessage = true;
                    validation.ShowErrorMessage = true;

                    List <string> values = new List <string>();
                    foreach (var v in Enum.GetValues(enumDataType.EnumType))
                    {
                        validation.Formula.Values.Add(v.ToString());
                        values.Add(v.ToString());
                    }
                    string value = String.Join(",", values);
                    validation.Error  = $"Please select data from a list: {value}";
                    validation.Prompt = $"Please select data from a list: {value}";
                }
            }
        }
コード例 #51
0
		public GetFieldEmitter(FieldInfo field) : base(field.DeclaringType, field.Name)
		{
			_field = field;
		}
コード例 #52
0
ファイル: LuaMisc.cs プロジェクト: yolokbe/StriveGame
        public static Delegate GetEventHandler(object obj, Type t, string eventName)
        {
            FieldInfo eventField = t.GetField(eventName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            return((Delegate)eventField.GetValue(obj));
        }
        /// <summary>
        /// Updates the flyweight for a field.
        /// </summary>
        /// <param name="fieldInfo">The field.</param>
        public void UpdateFlyweight(FieldInfo fieldInfo)
        {
            if (fieldInfo == null) throw new ArgumentNullException("fieldInfo");

            this.UpdateFlyweight(fieldInfo, fieldInfo.FieldType);
        }
コード例 #54
0
 /// <summary>
 /// Determines whether the specified field is an alias.
 /// </summary>
 /// <param name="fieldInfo">The field to check.</param>
 /// <returns>
 ///   <c>true</c> if the specified field is an alias; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsAliasField(this FieldInfo fieldInfo)
 {
     return(fieldInfo is MemberAliasFieldInfo);
 }
コード例 #55
0
 public static IEnumerable <TAttrib> GetFieldAttributes <TAttrib>(this FieldInfo field)
     where TAttrib : Attribute
 {
     return(field.GetCustomAttributes <TAttrib>(true));
 }
コード例 #56
0
 protected override IAspectWeaver CreateWeaver(IAspectWeavingSettings aspectWeavingSettings, FieldInfo weavedType)
 {
     return(new BindingAddEventInterceptionAspectWeaver(aspectDefinition, aspectWeavingSettings, weavedType));
 }
コード例 #57
0
        /// <summary>
        /// Creates a function that gets the value of the specified field. The parameter of the
        /// resulting function takes the object whose field value is to be accessed. If the
        /// specified field is static, the parameter of the resulting function is ignored.
        /// </summary>
        /// <typeparam name="TDeclaringType">
        /// The type of the parameter of the resulting function. This type must be compatible
        /// with the <see cref="MemberInfo.DeclaringType"/> of the <paramref name="field"/>
        /// parameter.
        /// </typeparam>
        /// <typeparam name="TFieldType">
        /// The return type of the resulting function. This type must be compatible with the
        /// <see cref="FieldInfo.FieldType"/> of the <paramref name="field"/> parameter.
        /// </typeparam>
        /// <param name="field">The field to create the getter function for.</param>
        /// <returns>A function that gets the field value.</returns>
        public static Func <TDeclaringType, TFieldType> CreateGetter <TDeclaringType, TFieldType>(this FieldInfo field)
        {
            if (field is null || field.DeclaringType is null)
            {
                throw new ArgumentNullException(nameof(field));
            }
            if (!field.DeclaringType.IsAssignableFrom(typeof(TDeclaringType)))
            {
                throw new ArgumentException("field.DeclaringType must be assignable from TDeclaringType", nameof(field));
            }
            if (!typeof(TFieldType).IsAssignableFrom(field.FieldType))
            {
                throw new ArgumentException("TFieldType must be assignable from field.FieldType", nameof(field));
            }

            var getter = new FieldGetter <TDeclaringType, TFieldType>(field);

            QueueUserWorkItem(getter, g => g.SetOptimizedFunc());
            return(getter.GetValue);
        }
コード例 #58
0
 public static object FastGetValue(this FieldInfo fieldInfo, object instance)
 {
     return(FastReflectionCaches.FieldAccessorCache.Get(fieldInfo).GetValue(instance));
 }
コード例 #59
0
ファイル: Reflector.cs プロジェクト: Metibor/ualbion
 static object GetFieldSafe(FieldInfo x, object o)
 {
     try { return(x.GetValue(o)); }
     catch (Exception e) { return(e); }
 }
コード例 #60
0
 internal static SetPropertyDelegate GetSetFieldMethod(Type type, FieldInfo fieldInfo)
 {
     return(PclExport.Instance.GetSetFieldMethod(fieldInfo));
 }