internal override void Initialize(ConfigurationScope configurationScope)
 {
     if (this.PropertyName.Length > 0)
     {
         IMappedStatement mappedStatement = configurationScope.SqlMapper.GetMappedStatement(base.Id);
         Type             parameterClass  = mappedStatement.Statement.ParameterClass;
         if ((parameterClass != null) && !ObjectProbe.IsSimpleType(parameterClass))
         {
             configurationScope.ErrorContext.MoreInfo = string.Format("Looking for settable property named '{0}' on type '{1}' for selectKey node of statement id '{2}'.", this.PropertyName, mappedStatement.Statement.ParameterClass.Name, base.Id);
             ReflectionInfo.GetInstance(mappedStatement.Statement.ParameterClass).GetSetter(this.PropertyName);
         }
     }
     base.Initialize(configurationScope);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Create a ISetAccessor instance for a field
        /// </summary>
        /// <param name="targetType">Target object type.</param>
        /// <param name="fieldName">Field name.</param>
        /// <returns>null if the generation fail</returns>
        private ISetAccessor CreateFieldAccessor(Type targetType, string fieldName)
        {
            ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
            FieldInfo      fieldInfo       = (FieldInfo)reflectionCache.GetSetter(fieldName);

            if (fieldInfo.IsPublic)
            {
                return(new EmitFieldSetAccessor(targetType, fieldName, _assemblyBuilder, _moduleBuilder));
            }
            else
            {
                return(new ReflectionFieldSetAccessor(targetType, fieldName));
            }
        }
Exemplo n.º 3
0
 static ReflectionInfo GetSectionInfo(Type t)
 {
     lock (_sLock)
     {
         ReflectionInfo info;
         if (sectionclasses.TryGetValue(t, out info))
         {
             return(info);
         }
         info = new ReflectionInfo()
         {
             Type = t
         };
         foreach (var field in t.GetFields(F_CLASSMEMBERS))
         {
             var attrs = field.GetCustomAttributes <EntryAttribute>();
             foreach (var a in attrs)
             {
                 info.Fields.Add(new ReflectionField()
                 {
                     Attr = a, Field = field
                 });
                 if (a.Required)
                 {
                     info.RequiredFields |= (1ul << (info.Fields.Count - 1));
                 }
             }
         }
         //This should never be tripped
         if (info.Fields.Count > 64)
         {
             throw new Exception("Too many fields!! Edit bitmask code & raise limit");
         }
         info.FieldHashes = new uint[info.Fields.Count];
         for (int i = 0; i < info.Fields.Count; i++)
         {
             info.FieldHashes[i] = HashLC(info.Fields[i].Attr.Name);
         }
         foreach (var mthd in t.GetMethods(F_CLASSMEMBERS))
         {
             if (mthd.Name == "HandleEntry")
             {
                 info.HandleEntry = mthd;
                 break;
             }
         }
         sectionclasses.Add(t, info);
         return(info);
     }
 }
Exemplo n.º 4
0
        private IGetAccessor CreateDynamicPropertyGetAccessor(Type targetType, string propertyName)
        {
            PropertyInfo getter = (PropertyInfo)ReflectionInfo.GetInstance(targetType).GetGetter(propertyName);

            if (!getter.CanRead)
            {
                throw new NotSupportedException(string.Format("Property \"{0}\" on type {1} cannot be get.", getter.Name, targetType));
            }
            if (getter.GetGetMethod() != null)
            {
                return(new DelegatePropertyGetAccessor(targetType, propertyName));
            }
            return(new ReflectionPropertyGetAccessor(targetType, propertyName));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create a Dynamic ISetAccessor instance for a field
        /// </summary>
        /// <param name="targetType">Target object type.</param>
        /// <param name="fieldName">field name.</param>
        /// <returns>null if the generation fail</returns>
        private ISetAccessor CreateDynamicFieldSetAccessor(Type targetType, string fieldName)
        {
            ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
            FieldInfo      fieldInfo       = (FieldInfo)reflectionCache.GetSetter(fieldName);

            if (fieldInfo.IsPublic)
            {
                return(new DelegateFieldSetAccessor(targetType, fieldName));
            }
            else
            {
                return(new ReflectionFieldSetAccessor(targetType, fieldName));
            }
        }
Exemplo n.º 6
0
        private ISetAccessor CreatePropertyAccessor(Type targetType, string propertyName)
        {
            PropertyInfo setter = (PropertyInfo)ReflectionInfo.GetInstance(targetType).GetSetter(propertyName);

            if (!setter.CanWrite)
            {
                throw new NotSupportedException(string.Format("Property \"{0}\" on type {1} cannot be set.", setter.Name, targetType));
            }
            if (setter.GetSetMethod() != null)
            {
                return(new EmitPropertySetAccessor(targetType, propertyName, this._assemblyBuilder, this._moduleBuilder));
            }
            return(new ReflectionPropertySetAccessor(targetType, propertyName));
        }
Exemplo n.º 7
0
 /// <summary>
 /// Произвести печать PDF
 /// </summary>
 private IResultCollection <IFileDataSourceServer> StampContainerCreatePdf(IStampContainer stampContainer, IDocumentLibrary documentLibrary,
                                                                           IFilePath filePath, IConvertingSettings convertingSettings,
                                                                           ConvertingModeType convertingModeType, ColorPrintType colorPrintType) =>
 stampContainer.
 Void(_ => _messagingService.ShowMessage("Вставка подписей...")).
 Map(_ => stampContainer.InsertSignatures().ToResultCollectionFromApplication()).
 ResultVoidOk(signatures => _loggerService.LogByObjects(LoggerLevel.Debug, LoggerAction.Operation, ReflectionInfo.GetMethodBase(this),
                                                        signatures.Select(signature => signature.SignatureLibrary.PersonInformation.FullName))).
 ResultValueOkBind(signatures => StampContainerPrinting(stampContainer.GetStampsToPrint().ToResultCollectionFromApplication(),
                                                        documentLibrary, filePath, convertingSettings, convertingModeType, colorPrintType).
                   Void(_ => _messagingService.ShowMessage("Удаление подписей...")).
                   Void(_ => stampContainer.DeleteSignatures(signatures)).
                   Void(_ => _loggerService.LogByObject(LoggerLevel.Debug, LoggerAction.Operation,
                                                        ReflectionInfo.GetMethodBase(this), nameof(stampContainer.DeleteSignatures)))).
 ToResultCollection();
        private void DrawField(ReflectionInfo info, SerializedProperty property)
        {
            if (!info.IsVisible)
            {
                return;
            }

            var result = info.CheckValidate(target, property);

            if (!result)
            {
                ValidatorWindow.GetInstance().RegisterValidation(result, target);
                GUILayout.BeginVertical(EditorStyles.helpBox);
            }

            if (!property.isArray || property.type == "string")
            {
                // Somehow check if this type can be drawn other way
                // Is it defined with attribute?
                EditorGUILayout.PropertyField(property, true);
            }
            else
            {
                Pair <bool, ReorderableList> list = ReorderableDrawer.GetList(property);

                if (property.arrayElementType.Equals(typeof(GenericParameter).Name) &&
                    list.First)
                {
                    list.Second.drawElementCallback      += GenericParameterDrawer;
                    list.Second.onAddDropdownCallback    += GenericParameterAdd;
                    list.Second.getElementHeightCallback += (e, i) => 16;
                }

                list.Second.DoLayoutList();
            }

            if (!result)
            {
                GUILayout.BeginVertical();
                using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox))
                {
                    GUILayout.Box(SpaceEditorStyles.GetValidationIcon(result.Status), GUIStyle.none, GUILayout.Width(24));
                    GUILayout.Label(result.Message, EditorStyles.wordWrappedMiniLabel);
                }
                GUILayout.EndVertical();
                GUILayout.EndVertical();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Добавить файлы
        /// </summary>
        public void AddFiles(IEnumerable <IFileData> filesData)
        {
            var filesDataToAdd = filesData?.Where(CanFileDataBeAddedToList).ToList();

            if (filesDataToAdd == null || filesDataToAdd.Count == 0)
            {
                return;
            }

            _filesData.AddRange(filesDataToAdd);
            _loggerService.LogByObjects(LoggerLevel.Info, LoggerAction.Add, ReflectionInfo.GetMethodBase(this), filesDataToAdd);

            bool isStatusProcessingProjectChanged = SetStatusProcessingProject(StatusProcessingProject.NeedToStartConverting);

            UpdateFileData(new FilesChange(_filesData, filesDataToAdd, ActionType.Add, isStatusProcessingProjectChanged));
        }
Exemplo n.º 10
0
        public ISetAccessor CreateSetAccessor(Type targetType, string name)
        {
            string key = new StringBuilder(targetType.FullName).Append(".").Append(name).ToString();

            if (_cachedISetAccessor.Contains(key))
            {
                return((ISetAccessor)_cachedISetAccessor[key]);
            }
            else
            {
                ISetAccessor setAccessor = null;
                lock (_syncObject)
                {
                    if (!_cachedISetAccessor.Contains(key))
                    {
                        // Property
                        ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
                        MemberInfo     memberInfo      = reflectionCache.GetSetter(name);

                        if (memberInfo != null)
                        {
                            if (memberInfo is PropertyInfo)
                            {
                                setAccessor = _createPropertySetAccessor(targetType, name);
                                _cachedISetAccessor[key] = setAccessor;
                            }
                            else
                            {
                                setAccessor = _createFieldSetAccessor(targetType, name);
                                _cachedISetAccessor[key] = setAccessor;
                            }
                        }
                        else
                        {
                            throw new ProbeException(
                                      string.Format("No property or field named \"{0}\" exists for type "
                                                    + "{1}.", name, targetType));
                        }
                    }
                    else
                    {
                        setAccessor = (ISetAccessor)_cachedISetAccessor[key];
                    }
                }
                return(setAccessor);
            }
        }
Exemplo n.º 11
0
 // static constructor
 static StringMethod()
 {
     __contains = ReflectionInfo.Method((string s, string value) => s.Contains(value));
     __endsWith = ReflectionInfo.Method((string s, string value) => s.EndsWith(value));
     __endsWithWithComparisonType       = ReflectionInfo.Method((string s, string value, StringComparison comparisonType) => s.EndsWith(value, comparisonType));
     __endsWithWithIgnoreCaseAndCulture = ReflectionInfo.Method((string s, string value, bool ignoreCase, CultureInfo culture) => s.EndsWith(value, ignoreCase, culture));
     __getChars   = ReflectionInfo.Method((string s, int index) => s[index]);
     __indexOfAny = ReflectionInfo.Method((string s, char[] anyOf) => s.IndexOfAny(anyOf));
     __indexOfAnyWithStartIndex                   = ReflectionInfo.Method((string s, char[] anyOf, int startIndex) => s.IndexOfAny(anyOf, startIndex));
     __indexOfAnyWithStartIndexAndCount           = ReflectionInfo.Method((string s, char[] anyOf, int startIndex, int count) => s.IndexOfAny(anyOf, startIndex, count));
     __indexOfBytesWithValue                      = ReflectionInfo.Method((string s, string value) => s.IndexOfBytes(value));
     __indexOfBytesWithValueAndStartIndex         = ReflectionInfo.Method((string s, string value, int startIndex) => s.IndexOfBytes(value, startIndex));
     __indexOfBytesWithValueAndStartIndexAndCount = ReflectionInfo.Method((string s, string value, int startIndex, int count) => s.IndexOfBytes(value, startIndex, count));
     __indexOfWithChar = ReflectionInfo.Method((string s, char value) => s.IndexOf(value));
     __indexOfWithCharAndStartIndex         = ReflectionInfo.Method((string s, char value, int startIndex) => s.IndexOf(value, startIndex));
     __indexOfWithCharAndStartIndexAndCount = ReflectionInfo.Method((string s, char value, int startIndex, int count) => s.IndexOf(value, startIndex, count));
     __indexOfWithString = ReflectionInfo.Method((string s, string value) => s.IndexOf(value));
     __indexOfWithStringAndStartIndex                          = ReflectionInfo.Method((string s, string value, int startIndex) => s.IndexOf(value, startIndex));
     __indexOfWithStringAndStartIndexAndCount                  = ReflectionInfo.Method((string s, string value, int startIndex, int count) => s.IndexOf(value, startIndex, count));
     __indexOfWithStringAndComparisonType                      = ReflectionInfo.Method((string s, string value, StringComparison comparisonType) => s.IndexOf(value, comparisonType));
     __indexOfWithStringAndStartIndexAndComparisonType         = ReflectionInfo.Method((string s, string value, int startIndex, StringComparison comparisonType) => s.IndexOf(value, startIndex, comparisonType));
     __indexOfWithStringAndStartIndexAndCountAndComparisonType = ReflectionInfo.Method((string s, string value, int startIndex, int count, StringComparison comparisonType) => s.IndexOf(value, startIndex, count, comparisonType));
     __isNullOrEmpty                      = ReflectionInfo.Method((string value) => string.IsNullOrEmpty(value));
     __splitWithChars                     = ReflectionInfo.Method((string s, char[] separator) => s.Split(separator));
     __splitWithCharsAndCount             = ReflectionInfo.Method((string s, char[] separator, int count) => s.Split(separator, count));
     __splitWithCharsAndCountAndOptions   = ReflectionInfo.Method((string s, char[] separator, int count, StringSplitOptions options) => s.Split(separator, count, options));
     __splitWithCharsAndOptions           = ReflectionInfo.Method((string s, char[] separator, StringSplitOptions options) => s.Split(separator, options));
     __splitWithStringsAndCountAndOptions = ReflectionInfo.Method((string s, string[] separator, int count, StringSplitOptions options) => s.Split(separator, count, options));
     __splitWithStringsAndOptions         = ReflectionInfo.Method((string s, string[] separator, StringSplitOptions options) => s.Split(separator, options));
     __startsWith = ReflectionInfo.Method((string s, string value) => s.StartsWith(value));
     __startsWithWithComparisonType       = ReflectionInfo.Method((string s, string value, StringComparison comparisonType) => s.StartsWith(value, comparisonType));
     __startsWithWithIgnoreCaseAndCulture = ReflectionInfo.Method((string s, string value, bool ignoreCase, CultureInfo culture) => s.StartsWith(value, ignoreCase, culture));
     __strLenBytes         = ReflectionInfo.Method((string s) => s.StrLenBytes());
     __substrBytes         = ReflectionInfo.Method((string s, int startIndex, int length) => s.SubstrBytes(startIndex, length));
     __substring           = ReflectionInfo.Method((string s, int startIndex) => s.Substring(startIndex));
     __substringWithLength = ReflectionInfo.Method((string s, int startIndex, int length) => s.Substring(startIndex, length));
     __toLower             = ReflectionInfo.Method((string s) => s.ToLower());
     __toLowerInvariant    = ReflectionInfo.Method((string s) => s.ToLowerInvariant());
     __toLowerWithCulture  = ReflectionInfo.Method((string s, CultureInfo culture) => s.ToLower(culture));
     __toUpper             = ReflectionInfo.Method((string s) => s.ToUpper());
     __toUpperInvariant    = ReflectionInfo.Method((string s) => s.ToUpperInvariant());
     __toUpperWithCulture  = ReflectionInfo.Method((string s, CultureInfo culture) => s.ToUpper(culture));
     __trim          = ReflectionInfo.Method((string s) => s.Trim());
     __trimEnd       = ReflectionInfo.Method((string s, char[] trimChars) => s.TrimEnd(trimChars));
     __trimStart     = ReflectionInfo.Method((string s, char[] trimChars) => s.TrimStart(trimChars));
     __trimWithChars = ReflectionInfo.Method((string s, char[] trimChars) => s.Trim(trimChars));
 }
Exemplo n.º 12
0
        /// <summary>
        /// Удалить файлы
        /// </summary>
        public void RemoveFiles(IEnumerable <IFileData> filesData)
        {
            var filesDataCollection = filesData?.ToList();

            if (filesDataCollection == null || filesDataCollection.Count == 0)
            {
                return;
            }

            _filesData.RemoveAll(filesDataCollection.Contains);
            _loggerService.LogByObjects(LoggerLevel.Info, LoggerAction.Remove, ReflectionInfo.GetMethodBase(this), filesDataCollection);

            bool isStatusProcessingProjectChanged = (_filesData == null || _filesData.Count == 0)
                                                    ? SetStatusProcessingProject(StatusProcessingProject.NeedToLoadFiles)
                                                    : SetStatusProcessingProject(StatusProcessingProject.NeedToStartConverting);

            UpdateFileData(new FilesChange(_filesData, filesDataCollection, ActionType.Remove, isStatusProcessingProjectChanged));
        }
        /// <summary>
        /// Reads data for this dependency cache from disk
        /// </summary>
        private void Read()
        {
            try
            {
                using (BinaryArchiveReader Reader = new BinaryArchiveReader(Location))
                {
                    int Version = Reader.ReadInt();
                    if (Version != CurrentVersion)
                    {
                        Log.TraceLog("Unable to read dependency cache from {0}; version {1} vs current {2}", Location, Version, CurrentVersion);
                        return;
                    }

                    int FileToFirstIncludeCount = Reader.ReadInt();
                    for (int Idx = 0; Idx < FileToFirstIncludeCount; Idx++)
                    {
                        FileItem File = Reader.ReadCompactFileItem();

                        IncludeInfo IncludeInfo = new IncludeInfo();
                        IncludeInfo.LastWriteTimeUtc = Reader.ReadLong();
                        IncludeInfo.IncludeText      = Reader.ReadString();

                        FileToIncludeInfo[File] = IncludeInfo;
                    }

                    int FileToMarkupFlagCount = Reader.ReadInt();
                    for (int Idx = 0; Idx < FileToMarkupFlagCount; Idx++)
                    {
                        FileItem File = Reader.ReadCompactFileItem();

                        ReflectionInfo ReflectionInfo = new ReflectionInfo();
                        ReflectionInfo.LastWriteTimeUtc = Reader.ReadLong();
                        ReflectionInfo.bContainsMarkup  = Reader.ReadBool();

                        FileToReflectionInfo[File] = ReflectionInfo;
                    }
                }
            }
            catch (Exception Ex)
            {
                Log.TraceWarning("Unable to read {0}. See log for additional information.", Location);
                Log.TraceLog("{0}", ExceptionUtils.FormatExceptionDetails(Ex));
            }
        }
Exemplo n.º 14
0
    public void ReflectionInfo_ConstructorParam2_Exception()
    {
        // Arrange
        var actual = false;
        var param  = typeof(Test).GetConstructor(Type.EmptyTypes);

        // Act
        try
        {
            var unused = new ReflectionInfo(param, null, null, null);
        }
        catch (ArgumentNullException)
        {
            actual = true;
        }

        // Assert
        Assert.IsTrue(actual);
    }
Exemplo n.º 15
0
    public void ReflectionInfo_ConstructorParam1_Exception()
    {
        // Arrange
        var actual        = false;
        var methodsParams = typeof(Test).GetMethods();

        // Act
        try
        {
            var unused = new ReflectionInfo(null, new List <Type>(), null, null);
        }
        catch (ArgumentNullException)
        {
            actual = true;
        }

        // Assert
        Assert.IsTrue(actual);
    }
Exemplo n.º 16
0
 private static ReflectionInfo _InitializeInstanceCache(Type type)
 {
     if (!_instanceCache.TryGetValue(type, out ReflectionInfo info))
     {
         var read = _GetInstanceProperties(type).Where(p => !p.SetMethod?.IsPublic ?? true)
                    .Where(p => p.GetMethod?.IsPublic ?? false)
                    .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any())
                    .Select(_BuildSerializationInfo);
         var readWrite = _GetInstanceProperties(type).Where(p => p.SetMethod?.IsPublic ?? false)
                         .Where(p => p.GetMethod?.IsPublic ?? false)
                         .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any())
                         .Select(_BuildSerializationInfo);
         var fields = _GetInstanceFields(type).Where(p => !p.IsInitOnly)
                      .Where(p => !p.GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Any())
                      .Select(_BuildSerializationInfo);
         _instanceCache[type] = info = new ReflectionInfo(read, readWrite, fields);
     }
     return(info);
 }
Exemplo n.º 17
0
        private ReflectionInfo GenerateReflectionInfoForType(Type type)
        {
            var properties    = GetExceptionPropertiesForDestructuring(type);
            var propertyInfos = properties.Select(p => new ReflectionPropertyInfo()
            {
                Name          = p.Name,
                DeclaringType = p.DeclaringType,
                Getter        = GenerateFastGetterForProperty(type, p)
            }).ToArray();

            var propertyInfosExceptBaseOnes = propertyInfos.Where(p => _exceptionProperties.All(b => b.Name != p.Name)).ToArray();

            var reflectInfo = new ReflectionInfo {
                Properties = propertyInfos,
                PropertiesExceptBaseOnes = propertyInfosExceptBaseOnes
            };

            return(reflectInfo);
        }
 /// <summary>
 /// Determines whether the given file contains reflection markup
 /// </summary>
 /// <param name="SourceFile">The source file to parse</param>
 /// <returns>True if the file contains reflection markup</returns>
 public bool ContainsReflectionMarkup(FileItem SourceFile)
 {
     if (Parent != null && !SourceFile.Location.IsUnderDirectory(BaseDirectory))
     {
         return(Parent.ContainsReflectionMarkup(SourceFile));
     }
     else
     {
         ReflectionInfo ReflectionInfo;
         if (!FileToReflectionInfo.TryGetValue(SourceFile, out ReflectionInfo) || SourceFile.LastWriteTimeUtc.Ticks > ReflectionInfo.LastWriteTimeUtc)
         {
             ReflectionInfo = new ReflectionInfo();
             ReflectionInfo.LastWriteTimeUtc  = SourceFile.LastWriteTimeUtc.Ticks;
             ReflectionInfo.bContainsMarkup   = ReflectionMarkupRegex.IsMatch(FileReference.ReadAllText(SourceFile.Location));
             FileToReflectionInfo[SourceFile] = ReflectionInfo;
             bModified = true;
         }
         return(ReflectionInfo.bContainsMarkup);
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Create a Dynamic IGetAccessor instance for a property
        /// </summary>
        /// <param name="targetType">Target object type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <returns>null if the generation fail</returns>
        private static IGetAccessor CreateDynamicPropertyGetAccessor(Type targetType, string propertyName)
        {
            ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
            PropertyInfo   propertyInfo    = (PropertyInfo)reflectionCache.GetGetter(propertyName);

            if (propertyInfo.CanRead)
            {
                MethodInfo methodInfo = null;
                methodInfo = propertyInfo.GetGetMethod();

                if (methodInfo != null)// == visibilty public
                {
                    return(new DelegatePropertyGetAccessor(targetType, propertyName));
                }
                return(new ReflectionPropertyGetAccessor(targetType, propertyName));
            }
            throw new NotSupportedException(
                      string.Format("Property \"{0}\" on type "
                                    + "{1} cannot be get.", propertyInfo.Name, targetType));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Create a ISetAccessor instance for a property
        /// </summary>
        /// <param name="targetType">Target object type.</param>
        /// <param name="propertyName">Property name.</param>
        /// <returns>null if the generation fail</returns>
        private ISetAccessor CreatePropertyAccessor(Type targetType, string propertyName)
        {
            ReflectionInfo reflectionCache = ReflectionInfo.GetInstance(targetType);
            PropertyInfo   propertyInfo    = (PropertyInfo)reflectionCache.GetSetter(propertyName);

            if (propertyInfo.CanWrite)
            {
                MethodInfo methodInfo = null;
                methodInfo = propertyInfo.GetSetMethod();

                if (methodInfo != null)// == visibilty public
                {
                    return(new EmitPropertySetAccessor(targetType, propertyName, _assemblyBuilder, _moduleBuilder));
                }
                return(new ReflectionPropertySetAccessor(targetType, propertyName));
            }
            throw new NotSupportedException(
                      string.Format("Property \"{0}\" on type "
                                    + "{1} cannot be set.", propertyInfo.Name, targetType));
        }
        private ReflectionInfo GenerateReflectionInfoForType(Type valueType)
        {
            var properties    = GetExceptionPropertiesForDestructuring(valueType);
            var propertyInfos = properties.Select(p => new ReflectionPropertyInfo()
            {
                Name   = p.Name,
                Getter = GenerateFastGetterForProperty(valueType, p),
            }).ToArray();
            var propertiesInfosExceptBaseOnes = propertyInfos
                                                .Where(p => this.baseExceptionPropertiesForDestructuring.All(bp => bp.Name != p.Name))
                                                .ToArray();

            var reflectionInfo = new ReflectionInfo()
            {
                Properties = propertyInfos,
                PropertiesExceptBaseOnes = propertiesInfosExceptBaseOnes
            };

            return(reflectionInfo);
        }
Exemplo n.º 22
0
        private void DrawField(ReflectionInfo info, SerializedProperty property)
        {
            if (!info.IsVisible)
            {
                return;
            }

            var result = info.CheckValidate(target, property);

            if (!result)
            {
                ValidatorWindow.GetInstance().RegisterValidation(result, target);
                GUILayout.BeginVertical(EditorStyles.helpBox);
            }

            if (!property.isArray || property.type == "string")
            {
                // Somehow check if this type can be drawn other way
                // Is it defined with attribute?
                EditorGUILayout.PropertyField(property, true);
            }
            else
            {
                ReorderableList list = ReorderableDrawer.GetList(property);
                list.DoLayoutList();
            }

            if (!result)
            {
                GUILayout.BeginVertical();
                using (new EditorGUILayout.HorizontalScope(EditorStyles.helpBox))
                {
                    GUILayout.Box(SpaceEditorStyles.GetValidationIcon(result.Status), GUIStyle.none, GUILayout.Width(24));
                    GUILayout.Label(result.Message, EditorStyles.wordWrappedMiniLabel);
                }
                GUILayout.EndVertical();
                GUILayout.EndVertical();
            }
        }
Exemplo n.º 23
0
        public override object Execute(ProtoCore.Runtime.Context c, Interpreter dsi, List <StackValue> s)
        {
            if (s == null)
            {
                s = dsi.runtime.rmem.Stack;
            }

            FFIObjectMarshaler marshaller = Module.GetMarshaler(dsi.runtime.RuntimeCore);

            var thisObject = marshaller.UnMarshal(s.Last(), c, dsi, ReflectionInfo.DeclaringType);

            //Notify marshler for dispose.
            marshaller.OnDispose(s.Last(), c, dsi);

            Object retVal = null;

            if (ReflectionInfo.IsWrapperOf(CLRModuleType.DisposeMethod))
            {
                // For those FFI objects that are disposable but don't provide
                // Dispose() method in their classes, they will share a same
                // Dispose() method from CLRModuleType.DisposeMethod. We need
                // to manually dispose them.

                if (thisObject != null && thisObject is IDisposable)
                {
                    var disposable = thisObject as IDisposable;
                    disposable.Dispose();
                }
            }
            else
            {
                retVal = InvokeFunctionPointerNoThrow(c, dsi, thisObject, null);
            }

            return(retVal);
        }
        public void TestGetIntegerPerformance()
        {
            const int TEST_ITERATIONS = 1000000;
            Property  prop            = new Property();
            int       test            = -1;
            Timer     timer           = new Timer();

            #region Direct access (fastest)
            GC.Collect();
            GC.WaitForPendingFinalizers();

            timer.Start();
            for (int i = 0; i < TEST_ITERATIONS; i++)
            {
                test = -1;
                test = prop.Int;
                Assert.AreEqual(int.MinValue, test);
            }
            timer.Stop();
            double directAccessDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS);
            #endregion

            #region IL Property accessor
            GC.Collect();
            GC.WaitForPendingFinalizers();

            IGetAccessorFactory factory          = new GetAccessorFactory(true);
            IGetAccessor        propertyAccessor = factory.CreateGetAccessor(typeof(Property), "Int");
            timer.Start();
            for (int i = 0; i < TEST_ITERATIONS; i++)
            {
                test = -1;
                test = (int)propertyAccessor.Get(prop);
                Assert.AreEqual(int.MinValue, test);
            }
            timer.Stop();
            double propertyAccessorDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS);
            double propertyAccessorRatio    = propertyAccessorDuration / directAccessDuration;
            #endregion

            #region SqlBatis.DataMapper.Utilities.Object.ReflectionInfo
            GC.Collect();
            GC.WaitForPendingFinalizers();

            ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(prop.GetType());
            timer.Start();
            for (int i = 0; i < TEST_ITERATIONS; i++)
            {
                test = -1;
                PropertyInfo propertyInfo = (PropertyInfo)reflectionInfo.GetGetter("Int");
                test = (int)propertyInfo.GetValue(prop, null);
                Assert.AreEqual(int.MinValue, test);
            }
            timer.Stop();
            double reflectionInfoDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS);
            double reflectionInfoRatio    = (float)reflectionInfoDuration / directAccessDuration;
            #endregion

            #region Reflection
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Type type = prop.GetType();
            timer.Start();
            for (int i = 0; i < TEST_ITERATIONS; i++)
            {
                test = -1;
                PropertyInfo propertyInfo = type.GetProperty("Int", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);
                test = (int)propertyInfo.GetValue(prop, null);
                Assert.AreEqual(int.MinValue, test);
            }
            timer.Stop();
            double reflectionDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS);
            double reflectionRatio    = reflectionDuration / directAccessDuration;
            #endregion

            #region ReflectionInvokeMember (slowest)
            GC.Collect();
            GC.WaitForPendingFinalizers();

            timer.Start();
            for (int i = 0; i < TEST_ITERATIONS; i++)
            {
                test = -1;
                test = (int)type.InvokeMember("Int",
                                              BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance,
                                              null, prop, null);
                Assert.AreEqual(int.MinValue, test);
            }
            timer.Stop();
            double reflectionInvokeMemberDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS);
            double reflectionInvokeMemberRatio    = reflectionInvokeMemberDuration / directAccessDuration;
            #endregion

            // Print results
            Console.WriteLine("{0} property gets on integer...", TEST_ITERATIONS);
            Console.WriteLine("Direct access: \t\t{0} ", directAccessDuration.ToString("F3"));
            Console.WriteLine("IMemberAccessor: \t\t{0} Ratio: {1}", propertyAccessorDuration.ToString("F3"), propertyAccessorRatio.ToString("F3"));
            Console.WriteLine("IBatisNet ReflectionInfo: \t{0} Ratio: {1}", reflectionInfoDuration.ToString("F3"), reflectionInfoRatio.ToString("F3"));
            Console.WriteLine("ReflectionInvokeMember: \t{0} Ratio: {1}", reflectionInvokeMemberDuration.ToString("F3"), reflectionInvokeMemberRatio.ToString("F3"));
            Console.WriteLine("Reflection: \t\t\t{0} Ratio: {1}", reflectionDuration.ToString("F3"), reflectionRatio.ToString("F3"));
        }
Exemplo n.º 25
0
        private bool TryParseModExpr(string script, Type vistType)
        {
            int start = 0;

            List <ReflectionInfo> rootReflection = null;
            ReflectionInfo        currReflection = null;

            while (start < raw.Length)
            {
                var matched = Regex.Match(raw.Substring(start), @"^[A-Za-z_]+\.*");
                if (!matched.Success)
                {
                    return(false);
                }

                var matchedValue = matched.Value.TrimEnd('.');

                if (start == 0)
                {
                    if (!dictReflect.ContainsKey(matchedValue))
                    {
                        if (vistType == Type.WRITE)
                        {
                            return(false);
                        }

                        if (matched.Length != raw.Length)
                        {
                            return(false);
                        }

                        if (matched.Value == "true")
                        {
                            FuncSetStaticValue(true);
                        }
                        else if (matched.Value == "false")
                        {
                            FuncSetStaticValue(false);
                        }
                        else
                        {
                            FuncSetStaticValue(matchedValue);
                        }

                        return(true);
                    }

                    rootReflection = dictReflect[matchedValue];
                    innerName      = matchedValue;
                }
                else
                {
                    if (currReflection == null)
                    {
                        currReflection = rootReflection.Single(x => x.element.Name == matchedValue);
                    }
                    else
                    {
                        currReflection = currReflection.subs.Single(x => x.element.Name == matchedValue);
                    }

                    if ((vistType == Type.READ && !currReflection.element.canRead) ||
                        (vistType == Type.WRITE && !currReflection.element.canWrite))
                    {
                        return(false);
                    }

                    refElements.Add(currReflection.element);
                }

                start += matched.Length;
            }

            return(true);
        }
Exemplo n.º 26
0
        public void TestReflectionInfo()
        {
            ReflectionInfo info = ReflectionInfo.GetInstance(typeof(Document));

            Type type = info.GetGetterType("PageNumber");
        }
Exemplo n.º 27
0
 public void SetDefaultValue(object defaultConstruct)
 {
     DefaultValue = ReflectionInfo.GetValue(defaultConstruct);
 }
 public IResultValue <IDocumentLibrary> OpenDocument(string filePath) =>
 IsDocumentValid(filePath).
 ResultValueOkBind(GetActiveLibraryByExtension).
 ResultValueOkTry(activeLibrary => activeLibrary.OpenDocument(filePath).ToResultValueFromApplication(),
                  new ErrorCommon(ErrorConvertingType.FileNotOpen, $"Ошибка открытия файла {filePath}")).
 ResultVoidOk(_ => _loggerService.LogByObject(LoggerLevel.Debug, LoggerAction.Operation, ReflectionInfo.GetMethodBase(this), filePath));
Exemplo n.º 29
0
        static object GetFromSection(Section s, ReflectionInfo type)
        {
            var   obj          = Activator.CreateInstance(type.Type);
            ulong bitmask      = 0;
            ulong requiredBits = type.RequiredFields;

            foreach (var e in s)
            {
                //Find entry
                int idx = -1;
                for (int i = 0; i < type.Fields.Count; i++)
                {
                    if (type.Fields[i].Attr.Name.Equals(e.Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        idx = i;
                        break;
                    }
                }
                //Special Handling
                if (idx == -1)
                {
                    bool handled = false;
                    if (type.HandleEntry != null)
                    {
                        handled = (bool)type.HandleEntry.Invoke(obj, new object[] { e });
                    }
                    if (!handled)
                    {
                        FLLog.Warning("Ini", "Unknown entry " + e.Name + FormatLine(e.File, e.Line, s.Name));
                    }
                    continue;
                }

                var field = type.Fields[idx];
                //Warning for duplicates
                if (!field.Attr.Multiline)
                {
                    if ((bitmask & (1ul << idx)) != 0)
                    {
                        FLLog.Warning("Ini", "Duplicate of " + field.Attr.Name + FormatLine(e.File, e.Line, s.Name));
                    }
                    bitmask |= 1ul << idx;
                }
                requiredBits &= ~(1ul << idx);
                var  ftype = field.Field.FieldType;
                Type nType;
                if ((nType = Nullable.GetUnderlyingType(ftype)) != null)
                {
                    ftype = nType;
                }
                //Fill
                if (ftype == typeof(string))
                {
                    if (ComponentCheck(1, s, e))
                    {
                        field.Field.SetValue(obj, e[0].ToString());
                    }
                }
                else if (ftype == typeof(float))
                {
                    if (ComponentCheck(1, s, e))
                    {
                        field.Field.SetValue(obj, e[0].ToSingle());
                    }
                }
                else if (ftype == typeof(int))
                {
                    if (ComponentCheck(1, s, e))
                    {
                        field.Field.SetValue(obj, e[0].ToInt32());
                    }
                }
                else if (ftype == typeof(long))
                {
                    if (ComponentCheck(1, s, e))
                    {
                        field.Field.SetValue(obj, e[0].ToInt64());
                    }
                }
                else if (ftype == typeof(bool))
                {
                    if (field.Attr.Presence)
                    {
                        field.Field.SetValue(obj, true);
                    }
                    else if (ComponentCheck(1, s, e))
                    {
                        field.Field.SetValue(obj, e[0].ToBoolean());
                    }
                }
                else if (ftype == typeof(Vector3))
                {
                    if (ComponentCheck(3, s, e))
                    {
                        field.Field.SetValue(obj, new Vector3(e[0].ToSingle(), e[1].ToSingle(), e[2].ToSingle()));
                    }
                }
                else if (ftype == typeof(Quaternion))
                {
                    if (ComponentCheck(4, s, e))
                    {
                        field.Field.SetValue(obj, new Quaternion(e[1].ToSingle(), e[2].ToSingle(), e[3].ToSingle(), e[0].ToSingle()));
                    }
                }
                else if (ftype == typeof(Vector2))
                {
                    if (e.Count == 1 && field.Attr.MinMax)
                    {
                        field.Field.SetValue(obj, new Vector2(-1, e[0].ToSingle()));
                    }
                    else if (ComponentCheck(2, s, e))
                    {
                        field.Field.SetValue(obj, new Vector2(e[0].ToSingle(), e[1].ToSingle()));
                    }
                }
                else if (ftype == typeof(Color4))
                {
                    if (ComponentCheck(4, s, e, 3))
                    {
                        Color4 col;
                        if (e.Count == 3)
                        {
                            col = new Color4(e[0].ToInt32() / 255f, e[1].ToInt32() / 255f, e[2].ToInt32() / 255f, 1f);
                        }
                        else
                        {
                            col = new Color4(e[0].ToInt32() / 255f, e[1].ToInt32() / 255f, e[2].ToInt32() / 255f, e[3].ToInt32() / 255f);
                        }
                        field.Field.SetValue(obj, col);
                    }
                }
                else if (ftype == typeof(Color3f))
                {
                    if (ComponentCheck(3, s, e))
                    {
                        field.Field.SetValue(obj, new Color3f(e[0].ToSingle(), e[1].ToSingle(), e[2].ToSingle()));
                    }
                }
                else if (ftype == typeof(List <string>))
                {
                    if (field.Attr.Multiline)
                    {
                        bitmask &= ~(1ul << idx); //Avoid duplicate warnings
                        if (ComponentCheck(1, s, e))
                        {
                            var v = (List <string>)field.Field.GetValue(obj);
                            v.Add(e[0].ToString());
                        }
                    }
                    else if (ComponentCheck(int.MaxValue, s, e, 1))
                    {
                        field.Field.SetValue(obj, e.Select((x) => x.ToString()).ToList());
                    }
                }
                else if (ftype == typeof(float[]))
                {
                    if (ComponentCheck(int.MaxValue, s, e, 1))
                    {
                        var floats = new float[e.Count];
                        for (int i = 0; i < e.Count; i++)
                        {
                            floats[i] = e[i].ToSingle();
                        }
                        field.Field.SetValue(obj, floats);
                    }
                }
                else if (ftype == typeof(string[]))
                {
                    if (ComponentCheck(int.MaxValue, s, e, 1))
                    {
                        var strings = new string[e.Count];
                        for (int i = 0; i < e.Count; i++)
                        {
                            strings[i] = e[i].ToString();
                        }
                        field.Field.SetValue(obj, strings);
                    }
                }
                else if (ftype.IsEnum)
                {
                    if (ComponentCheck(1, s, e))
                    {
                        //TryParse requires generics, wrap in exception handler
                        try
                        {
                            field.Field.SetValue(obj, Enum.Parse(field.Field.FieldType, e[0].ToString(), true));
                        }
                        catch (Exception)
                        {
                            FLLog.Error("Ini", "Invalid value for enum " + e[0].ToString() + FormatLine(e.File, e.Line, s.Name));
                        }
                    }
                }
            }
            if (requiredBits != 0)
            {
                //These sections crash the game if they don't have required fields
                //So don't let them be added to lists
                for (int i = 0; i < 64; i++)
                {
                    if ((requiredBits & (1ul << i)) != 0)
                    {
                        FLLog.Error("Ini", string.Format("Missing required field {0}{1}", type.Fields[i].Attr.Name, FormatLine(s.File, s.Line, s.Name)));
                    }
                }
                return(null);
            }
            else
            {
                return(obj);
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>.
        /// </summary>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory,
                                                     IDataReader reader,
                                                     ref object resultObject)
        {
            Type targetType = resultObject.GetType();
            ResultPropertyCollection properties = new ResultPropertyCollection();

            try
            {
                // Get all PropertyInfo from the resultObject properties
                ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(targetType);
                string[]       membersName    = reflectionInfo.GetWriteableMemberNames();

                IDictionary <string, ISetAccessor> propertyMap = new Dictionary <string, ISetAccessor>();
                int length = membersName.Length;
                for (int i = 0; i < length; i++)
                {
                    ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory;
                    ISetAccessor        setAccessor        = setAccessorFactory.CreateSetAccessor(targetType, membersName[i]);
                    propertyMap.Add(membersName[i], setAccessor);
                }

                // Get all column Name from the reader
                // and build a resultMap from with the help of the PropertyInfo[].
                DataTable dataColumn = reader.GetSchemaTable();
                int       count      = dataColumn.Rows.Count;
                for (int i = 0; i < count; i++)
                {
                    string propertyName = string.Empty;
                    string columnName   = dataColumn.Rows[i][0].ToString();

                    ISetAccessor matchedSetAccessor = null;
                    propertyMap.TryGetValue(columnName, out matchedSetAccessor);

                    int columnIndex = i;

                    if (resultObject is Hashtable)
                    {
                        propertyName = columnName;

                        ResultProperty property = new ResultProperty(
                            propertyName,
                            columnName,
                            columnIndex,
                            string.Empty,
                            string.Empty,
                            string.Empty,
                            false,
                            string.Empty,
                            null,
                            string.Empty,
                            targetType,
                            dataExchangeFactory,
                            null);
                        properties.Add(property);
                    }

                    Type propertyType = null;

                    if (matchedSetAccessor == null)
                    {
                        try
                        {
                            propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName);
                        }
                        catch
                        {
                            _logger.Error("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject + "]");
                        }
                    }
                    else
                    {
                        propertyType = matchedSetAccessor.MemberType;
                    }

                    if (propertyType != null || matchedSetAccessor != null)
                    {
                        propertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName);
                        ITypeHandler typeHandler = null;

                        if (matchedSetAccessor != null)
                        {
                            //property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor);
                            typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(matchedSetAccessor.MemberType);
                        }
                        else
                        {
                            typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType);
                        }

                        //property.PropertyStrategy = PropertyStrategyFactory.Get(property);

                        ResultProperty property = new ResultProperty(
                            propertyName,
                            columnName,
                            columnIndex,
                            string.Empty,
                            string.Empty,
                            string.Empty,
                            false,
                            string.Empty,
                            null,
                            string.Empty,
                            targetType,
                            dataExchangeFactory,
                            typeHandler);

                        properties.Add(property);
                    }
                }
            }
            catch (Exception e)
            {
                throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e);
            }

            return(properties);
        }