private void DrawFieldListValueLabel(Element element, object obj, ITypeHandler handler)
        {
            string valueText;

            if (element.type == Element.Type.ValueRow)
            {
                valueText = obj == null ? "null" : EscapeNewlines(handler.GetStringValue(obj));
            }
            else
            {
                valueText = "";
            }
            GUILayout.Label(valueText, FieldListValueLabelStyle);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Performs processing on a value before it is used to set
 /// the parameter of a IDbCommand.
 /// </summary>
 /// <param name="dataParameter"></param>
 /// <param name="parameterValue">The value to be set</param>
 /// <param name="dbType">Data base type</param>
 public override void SetParameter(IDataParameter dataParameter, object parameterValue, string dbType)
 {
     if (parameterValue != null)
     {
         ITypeHandler handler = _factory.GetTypeHandler(parameterValue.GetType(), dbType);
         handler.SetParameter(dataParameter, parameterValue, dbType);
     }
     else
     {
         // When sending a null parameter value to the server,
         // the user must specify DBNull, not null.
         dataParameter.Value = System.DBNull.Value;
     }
 }
Ejemplo n.º 3
0
 public object Read(Format format, FormatReader reader)
 {
     if (format.IsArrayFamily)
     {
         floatHandler = floatHandler ?? context.TypeHandlers.Get <float>();
         Vector4 vector = new Vector4();
         vector.x = (float)floatHandler.Read(reader.ReadFormat(), reader);
         vector.y = (float)floatHandler.Read(reader.ReadFormat(), reader);
         vector.z = (float)floatHandler.Read(reader.ReadFormat(), reader);
         vector.w = (float)floatHandler.Read(reader.ReadFormat(), reader);
         return(vector);
     }
     throw new FormatException(this, format, reader);
 }
        private IList <Element> GetChildren(object parent, ITypeHandler parentHandler)
        {
            if (!childrenCached)
            {
                var enumerator = parentHandler.GetChildren(parent, displayOptions);
                while (enumerator.MoveNext())
                {
                    childrenCache.Add(enumerator.Current);
                }
                childrenCached = true;
            }

            return(childrenCache);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool IsSimpleType(Type type)
        {
            bool result = false;

            if (type != null)
            {
                ITypeHandler handler = this.GetTypeHandler(type, null);
                if (handler != null)
                {
                    result = handler.IsSimpleType;
                }
            }
            return(result);
        }
Ejemplo n.º 6
0
        public void Register(TypeHandler typeHandlerConfig)
        {
            ITypeHandler typeHandler = null;

            if (typeHandlerConfig.HandlerType.IsGenericType)
            {
                var genericArgs = typeHandlerConfig.HandlerType.GetGenericArguments();
                switch (genericArgs.Length)
                {
                case 2:
                {
                    typeHandler = _typeHandlerBuilder.Build(typeHandlerConfig.HandlerType
                                                            , typeHandlerConfig.PropertyType, typeHandlerConfig.FieldType, typeHandlerConfig.Properties);
                    break;
                }

                case 1:
                {
                    if (typeHandlerConfig.PropertyType != null)
                    {
                        typeHandler = _typeHandlerBuilder.Build(typeHandlerConfig.HandlerType, typeHandlerConfig.PropertyType, typeHandlerConfig.Properties);
                    }
                    if (typeHandlerConfig.FieldType != null)
                    {
                        typeHandler = _typeHandlerBuilder.Build(typeHandlerConfig.HandlerType, typeHandlerConfig.FieldType, typeHandlerConfig.Properties);
                    }
                    break;
                }

                default:
                {
                    throw new SmartSqlException($"Wrong TypeHandlerConfig.Type:{typeHandlerConfig.HandlerType.FullName}.");
                }
                }
            }
            else
            {
                typeHandler = _typeHandlerBuilder.Build(typeHandlerConfig.HandlerType, typeHandlerConfig.Properties);
            }

            if (!String.IsNullOrEmpty(typeHandlerConfig.Name))
            {
                Register(typeHandlerConfig.Name, typeHandler);
            }
            else
            {
                Register(typeHandler);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Builds the type handlers.
        /// </summary>
        /// <param name="store">The store.</param>
        private void BuildTypeHandlers(IConfigurationStore store)
        {
            for (int i = 0; i < store.TypeHandlers.Length; i++)
            {
                IConfiguration handlerConfig = store.TypeHandlers[i];
                try
                {
                    //_configScope.ErrorContext.Activity = "loading typeHandler";
                    TypeHandler handler = TypeHandlerDeSerializer.Deserialize(handlerConfig);

                    //configScope.ErrorContext.MoreInfo = "Check the callback attribute '" + handler.CallBackName + "' (must be a classname).";
                    ITypeHandler typeHandler = null;
                    Type         type        = modelStore.DataExchangeFactory.TypeHandlerFactory.GetType(handler.Callback);

                    object impl = Activator.CreateInstance(type);
                    if (impl is ITypeHandlerCallback)
                    {
                        typeHandler = new CustomTypeHandler((ITypeHandlerCallback)impl);
                    }
                    else if (impl is ITypeHandler)
                    {
                        typeHandler = (ITypeHandler)impl;
                    }
                    else
                    {
                        throw new ConfigurationException("The callBack type is not a valid implementation of ITypeHandler or ITypeHandlerCallback");
                    }

                    //configScope.ErrorContext.MoreInfo = "Check the type attribute '" + handler.ClassName + "' (must be a class name) or the dbType '" + handler.DbType + "' (must be a DbType type name).";
                    if (handler.DbType != null && handler.DbType.Length > 0)
                    {
                        modelStore.DataExchangeFactory.TypeHandlerFactory.Register(handler.Type, handler.DbType, typeHandler);
                    }
                    else
                    {
                        modelStore.DataExchangeFactory.TypeHandlerFactory.Register(handler.Type, typeHandler);
                    }
                }
                catch (Exception e)
                {
                    throw new ConfigurationException(
                              String.Format("Error registering TypeHandler class \"{0}\" for handling .Net type \"{1}\" and dbType \"{2}\". Cause: {3}",
                                            handlerConfig.GetAttributeValue("callback"),
                                            handlerConfig.GetAttributeValue("type"),
                                            handlerConfig.GetAttributeValue("dbType"),
                                            e.Message), e);
                }
            }
        }
Ejemplo n.º 8
0
        string GenTypeCode(Type type, ITypeHandler typeHandler)
        {
            var fileds = FilterFields(type.GetFields(bindingAttr));

            IFiledHandler[] Handlers = typeHandler.GetFiledHandlers();
            List <string>   sbfs     = new List <string>();

            foreach (var Handler in Handlers)
            {
                var sbf = GetFiledInfo(fileds, Handler);
                sbfs.Add(sbf);
            }

            return(typeHandler.DealType(type, sbfs));
        }
Ejemplo n.º 9
0
        public void Write(object obj, FormatWriter writer)
        {
            switch (context.EnumOptions.PackingFormat)
            {
            case EnumPackingFormat.Integer:
                intHandler = intHandler ?? context.TypeHandlers.Get <int>();
                intHandler.Write(obj, writer);
                break;

            case EnumPackingFormat.String:
                stringHandler = stringHandler ?? context.TypeHandlers.Get <string>();
                stringHandler.Write(obj.ToString(), writer);
                break;
            }
        }
Ejemplo n.º 10
0
        private void BuildDbParameters(AbstractRequestContext reqConetxt)
        {
            if (reqConetxt.CommandType == CommandType.StoredProcedure)
            {
                foreach (var sqlParameter in reqConetxt.Parameters.Values)
                {
                    if (sqlParameter.SourceParameter != null)
                    {
                        sqlParameter.OnSetSourceParameter.Invoke(sqlParameter);
                        continue;
                    }

                    var sourceParam = _dbProviderFactory.CreateParameter();
                    InitSourceDbParameter(sourceParam, sqlParameter);
                    sourceParam.ParameterName = sqlParameter.Name;
                    sourceParam.Value         = sqlParameter.Value;
                    sqlParameter.TypeHandler?.SetParameter(sourceParam, sqlParameter.Value);
                    sqlParameter.SourceParameter = sourceParam;
                }
            }
            else
            {
                reqConetxt.RealSql = _sqlParamAnalyzer.Replace(reqConetxt.RealSql, (paramName, nameWithPrefix) =>
                {
                    if (!reqConetxt.Parameters.TryGetValue(paramName, out var sqlParameter))
                    {
                        return(nameWithPrefix);
                    }

                    ITypeHandler typeHandler =
                        (reqConetxt.ParameterMap?.GetParameter(paramName)?.Handler ?? sqlParameter.TypeHandler) ??
                        _typeHandlerFactory.GetTypeHandler(sqlParameter.ParameterType);

                    var sourceParam = _dbProviderFactory.CreateParameter();
                    InitSourceDbParameter(sourceParam, sqlParameter);
                    sourceParam.ParameterName = sqlParameter.Name;
                    typeHandler.SetParameter(sourceParam, sqlParameter.Value);
                    sqlParameter.SourceParameter = sourceParam;
                    if (sqlParameter.Name != paramName)
                    {
                        return
                        ($"{reqConetxt.ExecutionContext.SmartSqlConfig.Database.DbProvider.ParameterPrefix}{sqlParameter.Name}");
                    }

                    return(nameWithPrefix);
                });
            }
        }
Ejemplo n.º 11
0
        private void BuildDbParameters(AbstractRequestContext reqConetxt)
        {
            var dbParameterNames = _sqlParamAnalyzer.Analyse(reqConetxt.RealSql);

            if (reqConetxt.CommandType == CommandType.StoredProcedure)
            {
                foreach (var sqlParameter in reqConetxt.Parameters.Values)
                {
                    var sourceParam = _dbProviderFactory.CreateParameter();
                    sourceParam.ParameterName    = sqlParameter.Name;
                    sourceParam.Value            = sqlParameter.Value;
                    sqlParameter.SourceParameter = sourceParam;
                    InitSourceDbParameter(sourceParam, sqlParameter);
                }
            }
            else
            {
                foreach (var paramName in dbParameterNames)
                {
                    var          parameter    = reqConetxt.ParameterMap?.GetParameter(paramName);
                    var          propertyName = paramName;
                    ITypeHandler typeHandler  = null;
                    if (parameter != null)
                    {
                        propertyName = parameter.Property;
                        typeHandler  = parameter.Handler;
                    }

                    if (!reqConetxt.Parameters.TryGetValue(propertyName, out var sqlParameter))
                    {
                        continue;
                    }

                    var sourceParam = _dbProviderFactory.CreateParameter();
                    sourceParam.ParameterName = paramName;

                    if (typeHandler == null)
                    {
                        typeHandler = sqlParameter.TypeHandler ??
                                      _typeHandlerFactory.GetTypeHandler(sqlParameter.ParameterType);
                    }

                    typeHandler.SetParameter(sourceParam, sqlParameter.Value);
                    sqlParameter.SourceParameter = sourceParam;
                    InitSourceDbParameter(sourceParam, sqlParameter);
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Processes the specified <see cref="IDataReader"/>
        /// when a ResultClass is specified on the statement and
        /// the ResultClass is a SimpleType.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        public object Process(RequestScope request, ref IDataReader reader, object resultObject)
        {
            object        outObject = resultObject;
            AutoResultMap resultMap = (AutoResultMap)request.CurrentResultMap;

            if (outObject == null)
            {
                outObject = resultMap.CreateInstanceOfResult(null);
            }

            if (!resultMap.IsInitalized)
            {
                lock (resultMap)
                {
                    if (!resultMap.IsInitalized)
                    {
                        // Create a ResultProperty
                        const string propertyName = "value";
                        const int    columnIndex  = 0;
                        ITypeHandler typeHandler  = request.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(outObject.GetType());

                        ResultProperty property = new ResultProperty(
                            propertyName,
                            string.Empty,
                            columnIndex,
                            string.Empty,
                            string.Empty,
                            string.Empty,
                            false,
                            string.Empty,
                            null,
                            string.Empty,
                            null,
                            null,
                            typeHandler);
                        //property.PropertyStrategy = PropertyStrategyFactory.Get(property);

                        resultMap.Properties.Add(property);
                        resultMap.DataExchange = request.DataExchangeFactory.GetDataExchangeForClass(typeof(int));// set the PrimitiveDataExchange
                        resultMap.IsInitalized = true;
                    }
                }
            }
            //为outObject类的属性property赋值
            resultMap.Properties[0].PropertyStrategy.Set(request, resultMap, resultMap.Properties[0], ref outObject, reader, null);

            return(outObject);
        }
Ejemplo n.º 13
0
        //--------------------------------------------------------------------------------
        // Lookup
        //--------------------------------------------------------------------------------

        private bool LookupTypeHandler(Type type, out ITypeHandler handler)
        {
            type = Nullable.GetUnderlyingType(type) ?? type;
            if (typeHandlers.TryGetValue(type, out handler))
            {
                return(true);
            }

            if (type.IsEnum && typeHandlers.TryGetValue(Enum.GetUnderlyingType(type), out handler))
            {
                return(true);
            }

            handler = null;
            return(false);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Processes the specified <see cref="IDataReader"/>
        /// when a 'resultClass' attribute is specified on the statement and
        /// the 'resultClass' attribute is a <see cref="IDictionary"/>.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="reader">The reader.</param>
        /// <param name="resultObject">The result object.</param>
        public object Process(RequestScope request, ref IDataReader reader, object resultObject)
        {
            object outObject = resultObject;

            //AutoResultMap resultMap = request.CurrentResultMap as AutoResultMap;

            if (outObject == null)
            {
                outObject = request.CurrentResultMap.CreateInstanceOfResult(null);
            }
            //将reader当前行中的所有字段加入到IDictionary对象中
            int         count      = reader.FieldCount;
            IDictionary dictionary = (IDictionary)outObject;

            for (int i = 0; i < count; i++)
            {
                //ResultProperty property = new ResultProperty();
                //property.PropertyName = "value";
                //property.ColumnIndex = i;
                //property.TypeHandler = request.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(reader.GetFieldType(i));

                const string propertyName = "value";
                int          columnIndex  = i;
                ITypeHandler typeHandler  = request.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(reader.GetFieldType(i));

                ResultProperty property = new ResultProperty(
                    propertyName,
                    string.Empty,
                    columnIndex,
                    string.Empty,
                    string.Empty,
                    string.Empty,
                    false,
                    string.Empty,
                    null,
                    string.Empty,
                    typeof(IDictionary),
                    request.DataExchangeFactory,
                    typeHandler);

                dictionary.Add(
                    reader.GetName(i),
                    property.GetDataBaseValue(reader));
            }

            return(outObject);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Register (add) a type handler for a type and dbType
        /// </summary>
        /// <param name="type">the type</param>
        /// <param name="dbType">the dbType (optional, if dbType is null the handler will be used for all dbTypes)</param>
        /// <param name="handler">the handler instance</param>
        public void Register(Type type, string dbType, ITypeHandler handler)
        {
            IDictionary <string, ITypeHandler> map = null;

            typeHandlerMap.TryGetValue(type, out map);
            if (map == null)
            {
                map = new Dictionary <string, ITypeHandler>();
                typeHandlerMap.Add(type, map);
            }
            if (dbType == null)
            {
                if (logger.IsInfoEnabled)
                {
                    // notify the user that they are no longer using one of the built-in type handlers
                    ITypeHandler oldTypeHandler = null;
                    map.TryGetValue(NULL, out oldTypeHandler);

                    if (oldTypeHandler != null)
                    {
                        // the replacement will always(?) be a CustomTypeHandler
                        CustomTypeHandler customTypeHandler = handler as CustomTypeHandler;

                        string replacement = string.Empty;

                        if (customTypeHandler != null)
                        {
                            // report the underlying type
                            replacement = customTypeHandler.Callback.ToString();
                        }
                        else
                        {
                            replacement = handler.ToString();
                        }

                        // should oldTypeHandler be checked if its a CustomTypeHandler and if so report the Callback property ???
                        logger.Info("Replacing type handler [" + oldTypeHandler + "] with [" + replacement + "].");
                    }
                }

                map[NULL] = handler;
            }
            else
            {
                map.Add(dbType, handler);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Set parameter value, replace the null value if any.
        /// </summary>
        /// <param name="mapping"></param>
        /// <param name="dataParameter"></param>
        /// <param name="parameterValue"></param>
        public void SetParameter(ParameterProperty mapping, IDataParameter dataParameter, object parameterValue)
        {
            object value = dataExchange.GetData(mapping, parameterValue);

            ITypeHandler typeHandler = mapping.TypeHandler;

            // Apply Null Value
            if (mapping.HasNullValue)
            {
                if (typeHandler.Equals(value, mapping.NullValue))
                {
                    value = null;
                }
            }

            typeHandler.SetParameter(dataParameter, value, mapping.DbType);
        }
Ejemplo n.º 17
0
        public void AddTypeHandler(Type type, ITypeHandler typeHandler)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (typeHandler == null)
            {
                throw new ArgumentNullException("typeHandler");
            }

            if (typeHandlerMap == null)
            {
                typeHandlerMap = new Dictionary <Type, ITypeHandler>();
            }
            typeHandlerMap[type] = typeHandler;
        }
Ejemplo n.º 18
0
        public void HandleRead(TypeHandlingContext context)
        {
            IDeclaredType valueType = context.Type.GetScalarType();

            if (valueType == null)
            {
                throw new NotSupportedException();
            }

            ITypeHandler valueHandler = TypeHandlers.All.SingleOrDefault(h => h.CanHandle(context.WithType(valueType)));

            if (valueHandler == null)
            {
                throw new NotSupportedException();
            }

            var indexName  = context.Variables.Declare(Index);
            var lengthName = context.Variables.Declare(Length);
            var exists     = context.Variables.Declare(VariableKeys.NotNull);

            TypeHandlers.Boolean.HandleRead(new TypeHandlingContext(context)
            {
                TypeOwnerName = String.Format("var {0}", exists)
            });
            context.Builder.AppendFormat("if({0})", exists);
            context.Builder.Append("{");
            context.Builder.AppendFormat("var {0} = BitConverter.ToInt32(bytes, index);", lengthName);
            context.Builder.Append("index += sizeof(Int32);");
            context.Builder.AppendFormat("{0} = new {1}[{2}];", context.TypeOwnerName, valueType.GetPresentableName(context.PresentationLanguage), lengthName);
            context.Builder.AppendFormat("if({0} > 0)", lengthName);
            context.Builder.Append("{");
            context.Builder.AppendFormat("for(Int32 {0} = 0; {0} < {1}; {0}++)", indexName, lengthName);
            context.Builder.Append("{");
            valueHandler.HandleRead(new TypeHandlingContext(context)
            {
                TypeOwnerName = String.Format("{0}[{1}]", context.TypeOwnerName, indexName),
                Type          = valueType,
                TypeName      = valueType.GetPresentableName(context.PresentationLanguage),
                TypeOwner     = context.TypeOwner
            });
            context.Builder.Append("}}}");

            context.Variables.Dispose(Index);
            context.Variables.Dispose(Length);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Register (add) a type handler for a type and dbType
        /// </summary>
        /// <param name="type">the type</param>
        /// <param name="dbType">the dbType (optional, if dbType is null the handler will be used for all dbTypes)</param>
        /// <param name="handler">the handler instance</param>
        public void Register(Type type, string dbType, ITypeHandler handler)
        {
            HybridDictionary map = (HybridDictionary)_typeHandlerMap[type];

            if (map == null)
            {
                map = new HybridDictionary();
                _typeHandlerMap.Add(type, map);
            }
            if (dbType == null)
            {
                if (_logger.IsDebugEnabled)
                {
                    // notify the user that they are no longer using one of the built-in type handlers
                    ITypeHandler oldTypeHandler = (ITypeHandler)map[NULL];

                    if (oldTypeHandler != null)
                    {
                        // the replacement will always(?) be a CustomTypeHandler
                        CustomTypeHandler customTypeHandler = handler as CustomTypeHandler;

                        string replacement = string.Empty;

                        if (customTypeHandler != null)
                        {
                            // report the underlying type
                            replacement = customTypeHandler.Callback.ToString();
                        }
                        else
                        {
                            replacement = handler.ToString();
                        }

                        // should oldTypeHandler be checked if its a CustomTypeHandler and if so report the Callback property ???
                        _logger.Debug("Replacing type handler [" + oldTypeHandler.ToString() + "] with [" + replacement + "].");
                    }
                }

                map[NULL] = handler;
            }
            else
            {
                map.Add(dbType, handler);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Register (add) a type handler for a type and dbType
        /// </summary>
        /// <param name="type">the type</param>
        /// <param name="dbType">the dbType (optional, if dbType is null the handler will be used for all dbTypes)</param>
        /// <param name="handler">the handler instance</param>
        public void Register(Type type, string dbType, ITypeHandler handler)
        {
            HybridDictionary map = (HybridDictionary)_typeHandlerMap[type];

            if (map == null)
            {
                map = new HybridDictionary();
                _typeHandlerMap.Add(type, map);
            }
            if (dbType == null)
            {
                map[NULL] = handler;
            }
            else
            {
                map.Add(dbType, handler);
            }
        }
Ejemplo n.º 21
0
 public object Read(Format format, FormatReader reader)
 {
     if (format.IsIntFamily)
     {
         intHandler = intHandler ?? context.TypeHandlers.Get <int>();
         return(Enum.ToObject(type, intHandler.Read(format, reader)));
     }
     if (format.IsStringFamily)
     {
         stringHandler = stringHandler ?? context.TypeHandlers.Get <string>();
         return(Enum.Parse(type, (string)stringHandler.Read(format, reader), true));
     }
     if (format.IsNil)
     {
         return(Enum.ToObject(type, 0));
     }
     throw new FormatException(this, format, reader);
 }
Ejemplo n.º 22
0
        public void HandleWrite(TypeHandlingContext context)
        {
            IDeclaredType valueType = context.Type.GetScalarType();

            if (valueType == null)
            {
                throw new NotSupportedException();
            }

            ITypeHandler valueHandler = TypeHandlers.All.SingleOrDefault(h => h.CanHandle(context.WithType(valueType)));

            if (valueHandler == null)
            {
                throw new NotSupportedException();
            }

            String indexName = context.Variables.Declare(Index);

            var exists = context.Variables.Declare(VariableKeys.NotNull);

            context.Builder.AppendFormat("var {0} = {1} != null;", exists, context.TypeOwnerName);
            TypeHandlers.Boolean.HandleWrite(new TypeHandlingContext(context)
            {
                TypeOwnerName = exists
            });
            context.Builder.AppendFormat("if({0})", exists);
            context.Builder.Append("{");
            TypeHandlers.Int32.HandleWrite(new TypeHandlingContext(context)
            {
                TypeName      = TypeHandlers.Int32.TypeName,
                TypeOwnerName = String.Format("{0}.Length", context.TypeOwnerName)
            });
            context.Builder.AppendFormat("if({0}.Length > 0)", context.TypeOwnerName);
            context.Builder.Append("{");
            context.Builder.AppendFormat("for(Int32 {0} = 0; {0} < {1}.Length; {0}++)", indexName, context.TypeOwnerName);
            context.Builder.Append("{");
            valueHandler.HandleWrite(new TypeHandlingContext(context)
            {
                TypeName      = valueType.GetPresentableName(context.PresentationLanguage),
                TypeOwnerName = String.Format("{0}[{1}]", context.TypeOwnerName, indexName)
            });
            context.Builder.Append("}}}");
            context.Variables.Dispose(Index);
        }
        public ITypeHandler ResolveTypeHandler(ConfigurationScope configScope, Type argumenType, string clrType, string dbType)
        {
            ITypeHandler typeHandler = null;

            if (argumenType == null)
            {
                return(configScope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler());
            }
            if (typeof(IDictionary).IsAssignableFrom(argumenType))
            {
                if ((clrType == null) || (clrType.Length == 0))
                {
                    return(configScope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler());
                }
                try
                {
                    Type type = TypeUtils.ResolveType(clrType);
                    return(configScope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, dbType));
                }
                catch (Exception exception)
                {
                    throw new ConfigurationErrorsException("Error. Could not set TypeHandler.  Cause: " + exception.Message, exception);
                }
            }
            if (configScope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(argumenType, dbType) != null)
            {
                return(configScope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(argumenType, dbType));
            }
            if ((clrType == null) || (clrType.Length == 0))
            {
                return(configScope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler());
            }
            try
            {
                Type type2 = TypeUtils.ResolveType(clrType);
                typeHandler = configScope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type2, dbType);
            }
            catch (Exception exception2)
            {
                throw new ConfigurationErrorsException("Error. Could not set TypeHandler.  Cause: " + exception2.Message, exception2);
            }
            return(typeHandler);
        }
Ejemplo n.º 24
0
        public static void Build(DbCommand cmd, string name, DbType dbType, ITypeHandler handler, object value)
        {
            var p = cmd.CreateParameter();

            p.ParameterName = name;
            if (value is null)
            {
                p.Value = DBNull.Value;
            }
            else if (handler is null)
            {
                p.DbType = dbType;
                p.Value  = value;
            }
            else
            {
                handler.Build(p, value);
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool IsSimpleType(Type type)
        {
            bool result = false;

            if (!simpleTypes.TryGetValue(type, out result))
            {
                if (type != null)
                {
                    ITypeHandler handler = GetTypeHandler(type, null);
                    if (handler != null)
                    {
                        result = handler.IsSimpleType;
                    }
                    simpleTypes[type] = result;
                }
            }

            return(result);
        }
Ejemplo n.º 26
0
        public ComponentInfo(Type componentType, ITypeHandler typeHandler)
        {
            if (componentType == null) throw new ArgumentNullException("componentType");
            if (typeHandler == null) throw new ArgumentNullException("typeHandler");

            ComponentType = componentType;
            this.typeHandler = typeHandler;

            properties = typeHandler.GetProperties(componentType);
            if (properties.Length == 0)
            {
                propertyNames = emptyPropertyNames;
            }
            else
            {
                propertyNames = new string[properties.Length];
                for (int i = 0; i < properties.Length; i++)
                    propertyNames[i] = properties[i].Name;
            }
        }
Ejemplo n.º 27
0
        public void Register(ITypeHandler typeHandler)
        {
            if (!_typeHandlerMap.TryGetValue(typeHandler.PropertyType, out var fieldTypeHandlerMap))
            {
                fieldTypeHandlerMap = new Dictionary <Type, ITypeHandler>();
                _typeHandlerMap.Add(typeHandler.PropertyType, fieldTypeHandlerMap);
            }

            if (fieldTypeHandlerMap.ContainsKey(typeHandler.FieldType))
            {
                fieldTypeHandlerMap[typeHandler.FieldType] = typeHandler;
            }
            else
            {
                fieldTypeHandlerMap.Add(typeHandler.FieldType, typeHandler);
            }

            TypeHandlerCacheType.SetHandler(typeHandler);
            PropertyTypeHandlerCacheType.SetHandler(typeHandler);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Resolve TypeHandler
        /// </summary>
        /// <param name="parameterClassType"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyType"></param>
        /// <param name="dbType"></param>
        /// <param name="typeHandlerFactory"></param>
        /// <returns></returns>
        private ITypeHandler ResolveTypeHandler(TypeHandlerFactory typeHandlerFactory,
                                                Type parameterClassType, string propertyName,
                                                string propertyType, string dbType)
        {
            ITypeHandler handler = null;

            if (parameterClassType == null)
            {
                handler = typeHandlerFactory.GetUnkownTypeHandler();
            }
            else if (typeof(IDictionary).IsAssignableFrom(parameterClassType))
            {
                if (propertyType == null || propertyType.Length == 0)
                {
                    handler = typeHandlerFactory.GetUnkownTypeHandler();
                }
                else
                {
                    try
                    {
                        Type typeClass = TypeUtils.ResolveType(propertyType);
                        handler = typeHandlerFactory.GetTypeHandler(typeClass, dbType);
                    }
                    catch (Exception e)
                    {
                        throw new ConfigurationException("Error. Could not set TypeHandler.  Cause: " + e.Message, e);
                    }
                }
            }
            else if (typeHandlerFactory.GetTypeHandler(parameterClassType, dbType) != null)
            {
                handler = typeHandlerFactory.GetTypeHandler(parameterClassType, dbType);
            }
            else
            {
                Type typeClass = ObjectProbe.GetMemberTypeForGetter(parameterClassType, propertyName);
                handler = typeHandlerFactory.GetTypeHandler(typeClass, dbType);
            }

            return(handler);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Deserialize a TypeHandler object
        /// </summary>
        /// <param name="node"></param>
        /// <param name="configScope"></param>
        /// <returns></returns>
        public static void Deserialize(XmlNode node, ConfigurationScope configScope)
        {
            TypeHandler handler = new TypeHandler();

            NameValueCollection prop = NodeUtils.ParseAttributes(node, configScope.Properties);

            handler.CallBackName = NodeUtils.GetStringAttribute(prop, "callback");
            handler.ClassName    = NodeUtils.GetStringAttribute(prop, "type");
            handler.DbType       = NodeUtils.GetStringAttribute(prop, "dbType");

            handler.Initialize();

            configScope.ErrorContext.MoreInfo = "Check the callback attribute '" + handler.CallBackName + "' (must be a classname).";
            ITypeHandler typeHandler = null;
            Type         type        = configScope.SqlMapper.TypeHandlerFactory.GetType(handler.CallBackName);
            object       impl        = Activator.CreateInstance(type);

            if (impl is ITypeHandlerCallback)
            {
                typeHandler = new CustomTypeHandler((ITypeHandlerCallback)impl);
            }
            else if (impl is ITypeHandler)
            {
                typeHandler = (ITypeHandler)impl;
            }
            else
            {
                throw new ConfigurationErrorsException("The callBack type is not a valid implementation of ITypeHandler or ITypeHandlerCallback");
            }

            //
            configScope.ErrorContext.MoreInfo = "Check the type attribute '" + handler.ClassName + "' (must be a class name) or the dbType '" + handler.DbType + "' (must be a DbType type name).";
            if (handler.DbType != null && handler.DbType.Length > 0)
            {
                configScope.DataExchangeFactory.TypeHandlerFactory.Register(TypeUtils.ResolveType(handler.ClassName), handler.DbType, typeHandler);
            }
            else
            {
                configScope.DataExchangeFactory.TypeHandlerFactory.Register(TypeUtils.ResolveType(handler.ClassName), typeHandler);
            }
        }
Ejemplo n.º 30
0
        public string GenTypeCode(ITypeHandler typeHandler, params Type[] types)
        {
            this.typeHandler = typeHandler;
            foreach (var t in types)
            {
                AddType(t);
            }


            var           type = GetNextType();
            StringBuilder sb   = new StringBuilder();

            while (type != null)
            {
                var typeStr = GenTypeCode(type, typeHandler);
                sb.AppendLine(typeStr);
                type = GetNextType();
            }

            return(sb.ToString());
        }
        private void DrawFieldListButton(Element element, object obj, ITypeHandler handler)
        {
            var buttonText = element.text;

            if (element.type == Element.Type.ValueRow)
            {
                GUI.enabled = !handler.IsLeaf(obj);
                if (GUILayout.Button(buttonText, FieldListButtonStyle, FieldListButtonLayout))
                {
                    action = () => SelectChild(element);
                }
                GUI.enabled = true;
            }
            else if (element.type == Element.Type.Header)
            {
                var color = GUI.color;
                GUI.color = element.textColor;
                GUILayout.Label(element.text, FieldListHeaderLabelStyle);
                GUI.color = color;
            }
        }
Ejemplo n.º 32
0
		/// <summary>
		/// Initialize the PropertyInfo of the result property.
		/// </summary>
		/// <param name="resultClass"></param>
		/// <param name="configScope"></param>
		public void Initialize( ConfigurationScope configScope, Type resultClass )
		{
			if ( _propertyName.Length>0 && 
				 _propertyName != "value" && 
				!typeof(IDictionary).IsAssignableFrom(resultClass) )
			{
				if (!_isComplexMemberName)
				{
                    _setAccessor = configScope.DataExchangeFactory.AccessorFactory.SetAccessorFactory.CreateSetAccessor(resultClass, _propertyName);
				}
				else // complex member name FavouriteLineItem.Id
				{
					MemberInfo propertyInfo = ObjectProbe.GetMemberInfoForSetter(resultClass, _propertyName);
					string memberName = _propertyName.Substring( _propertyName.LastIndexOf('.')+1);
                    _setAccessor = configScope.DataExchangeFactory.AccessorFactory.SetAccessorFactory.CreateSetAccessor(propertyInfo.ReflectedType, memberName);
				}

                _isGenericIList = TypeUtils.IsImplementGenericIListInterface(this.MemberType);
                _isIList = typeof(IList).IsAssignableFrom(this.MemberType);
			    
			    // set the list factory
			    if (_isGenericIList)
			    {
			        if (this.MemberType.IsArray)
			        {
                        _listFactory = _arrayListFactory;
			        }
			        else
			        {
                        Type[] typeArgs = this.MemberType.GetGenericArguments();

                        if (typeArgs.Length == 0)// Custom collection which derive from List<T>
			            {
                            _listFactory = configScope.DataExchangeFactory.ObjectFactory.CreateFactory(this.MemberType, Type.EmptyTypes);
			            }
			            else
			            {
                            Type genericIList = typeof(IList<>);
                            Type interfaceListType = genericIList.MakeGenericType(typeArgs);

                            Type genericList = typeof(List<>);
                            Type listType = genericList.MakeGenericType(typeArgs);

                            if ((interfaceListType == this.MemberType) || (listType == this.MemberType))
                            {
                                Type constructedType = genericList.MakeGenericType(typeArgs);
                                _listFactory = configScope.DataExchangeFactory.ObjectFactory.CreateFactory(
                                    constructedType,
                                    Type.EmptyTypes);
                            }
                            else // Custom collection which derive from List<T>
                            {
                                _listFactory = configScope.DataExchangeFactory.ObjectFactory.CreateFactory(this.MemberType, Type.EmptyTypes);
                            }  
			            }			            
			        }
			    }
			    else if (_isIList)
			    {
                    if (this.MemberType.IsArray)
                    {
                        _listFactory = _arrayListFactory;
                    }
			        else
                    {
                        if (this.MemberType == typeof(IList))
                        {
                            _listFactory = _arrayListFactory;
                        }
                        else // custom collection
                        {
                            _listFactory = configScope.DataExchangeFactory.ObjectFactory.CreateFactory(this.MemberType,                                                                                                   Type.EmptyTypes);
                        }                        
                    }
			    }
			}

			if (this.CallBackName!=null && this.CallBackName.Length >0)
			{
				configScope.ErrorContext.MoreInfo = "Result property '"+_propertyName+"' check the typeHandler attribute '" + this.CallBackName + "' (must be a ITypeHandlerCallback implementation).";
				try 
				{
					Type type = configScope.SqlMapper.TypeHandlerFactory.GetType(this.CallBackName);
					ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback) Activator.CreateInstance( type );
					_typeHandler = new CustomTypeHandler(typeHandlerCallback);
				}
				catch (Exception e) 
				{
					throw new ConfigurationException("Error occurred during custom type handler configuration.  Cause: " + e.Message, e);
				}
			}
			else
			{
				configScope.ErrorContext.MoreInfo = "Result property '"+_propertyName+"' set the typeHandler attribute.";
				_typeHandler = configScope.ResolveTypeHandler( resultClass, _propertyName, _clrType, _dbType, true);
			}

            if (this.IsLazyLoad)
            {
                _lazyFactory = new LazyFactoryBuilder().GetLazyFactory(_setAccessor.MemberType);
            }
		}
Ejemplo n.º 33
0
        /// <summary>
        /// Constructor
        /// </summary>
        public TypeHandlerFactory()
        {
            ITypeHandler handler = null;

            handler = new DBNullTypeHandler();
            this.Register(typeof(DBNull), handler);

            handler = new BooleanTypeHandler();
            this.Register(typeof(bool), handler); // key= "System.Boolean"

            handler = new ByteTypeHandler();
            this.Register(typeof(Byte), handler);

            handler = new CharTypeHandler();
            this.Register(typeof(Char), handler);

            handler = new DateTimeTypeHandler();
            this.Register(typeof(DateTime), handler);

            handler = new DecimalTypeHandler();
            this.Register(typeof(Decimal), handler);

            handler = new DoubleTypeHandler();
            this.Register(typeof(Double), handler);

            handler = new Int16TypeHandler();
            this.Register(typeof(Int16), handler);

            handler = new Int32TypeHandler();
            this.Register(typeof(Int32), handler);

            handler = new Int64TypeHandler();
            this.Register(typeof(Int64), handler);

            handler = new SingleTypeHandler();
            this.Register(typeof(Single), handler);

            handler = new StringTypeHandler();
            this.Register(typeof(String), handler);

            handler = new GuidTypeHandler();
            this.Register(typeof(Guid), handler);

            handler = new TimeSpanTypeHandler();
            this.Register(typeof(TimeSpan), handler);

            handler = new ByteArrayTypeHandler();
            this.Register(typeof(Byte[]), handler);

            handler = new ObjectTypeHandler();
            this.Register(typeof(object), handler);

            handler = new EnumTypeHandler();
            this.Register(typeof(System.Enum), handler);

            handler = new UInt16TypeHandler();
            this.Register(typeof(UInt16), handler);

            handler = new UInt32TypeHandler();
            this.Register(typeof(UInt32), handler);

            handler = new UInt64TypeHandler();
            this.Register(typeof(UInt64), handler);

            handler = new SByteTypeHandler();
            this.Register(typeof(SByte), handler);

            handler = new NullableBooleanTypeHandler();
            this.Register(typeof(bool?), handler);

            handler = new NullableByteTypeHandler();
            this.Register(typeof(byte?), handler);

            handler = new NullableCharTypeHandler();
            this.Register(typeof(char?), handler);

            handler = new NullableDateTimeTypeHandler();
            this.Register(typeof(DateTime?), handler);

            handler = new NullableDecimalTypeHandler();
            this.Register(typeof(decimal?), handler);

            handler = new NullableDoubleTypeHandler();
            this.Register(typeof(double?), handler);

            handler = new NullableGuidTypeHandler();
            this.Register(typeof(Guid?), handler);

            handler = new NullableInt16TypeHandler();
            this.Register(typeof(Int16?), handler);

            handler = new NullableInt32TypeHandler();
            this.Register(typeof(Int32?), handler);

            handler = new NullableInt64TypeHandler();
            this.Register(typeof(Int64?), handler);

            handler = new NullableSingleTypeHandler();
            this.Register(typeof(Single?), handler);

            handler = new NullableUInt16TypeHandler();
            this.Register(typeof(UInt16?), handler);

            handler = new NullableUInt32TypeHandler();
            this.Register(typeof(UInt32?), handler);

            handler = new NullableUInt64TypeHandler();
            this.Register(typeof(UInt64?), handler);

            handler = new NullableSByteTypeHandler();
            this.Register(typeof(SByte?), handler);

            handler = new NullableTimeSpanTypeHandler();
            this.Register(typeof(TimeSpan?), handler);

            _unknownTypeHandler = new UnknownTypeHandler(this);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Register (add) a type handler for a type and dbType
        /// </summary>
        /// <param name="type">the type</param>
        /// <param name="dbType">the dbType (optional, if dbType is null the handler will be used for all dbTypes)</param>
        /// <param name="handler">the handler instance</param>
        public void Register(Type type, string dbType, ITypeHandler handler)
        {
            HybridDictionary map = (HybridDictionary)_typeHandlerMap[type];
            if (map == null)
            {
                map = new HybridDictionary();
                _typeHandlerMap.Add(type, map);
            }
            if (dbType == null)
            {
                if (_logger.IsInfoEnabled)
                {
                    // notify the user that they are no longer using one of the built-in type handlers
                    ITypeHandler oldTypeHandler = (ITypeHandler)map[NULL];

                    if (oldTypeHandler != null)
                    {
                        // the replacement will always(?) be a CustomTypeHandler
                        CustomTypeHandler customTypeHandler = handler as CustomTypeHandler;

                        string replacement = string.Empty;

                        if (customTypeHandler != null)
                        {
                            // report the underlying type
                            replacement = customTypeHandler.Callback.ToString();
                        }
                        else
                        {
                            replacement = handler.ToString();
                        }

                        // should oldTypeHandler be checked if its a CustomTypeHandler and if so report the Callback property ???
                        _logger.Info("Replacing type handler [" + oldTypeHandler.ToString() + "] with [" + replacement + "].");
                    }
                }

                map[NULL] = handler;
            }
            else
            {
                map.Add(dbType, handler);
            }
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Register (add) a type handler for a type
 /// </summary>
 /// <param name="type">the type</param>
 /// <param name="handler">the handler instance</param>
 public void Register(Type type, ITypeHandler handler)
 {
     this.Register(type, null, handler);
 }
Ejemplo n.º 36
0
 public IEnumerable<ITypeHandler> Handlers(ITypeHandler rootHandler)
     => _variableTypes._customHandlers.Select(h => h(rootHandler));
Ejemplo n.º 37
0
        /// <summary>
        /// Initializes the parameter property
        /// </summary>
        /// <param name="scope">The scope.</param>
        /// <param name="parameterClass">The parameter class.</param>
        public void Initialize(IScope scope, Type parameterClass)
        {
            if(_directionAttribute.Length >0)
            {
                _direction = (ParameterDirection)Enum.Parse( typeof(ParameterDirection), _directionAttribute, true );
            }

            if (!typeof(IDictionary).IsAssignableFrom(parameterClass) // Hashtable parameter map
                && parameterClass !=null // value property
                && !scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(parameterClass) ) // value property
            {
                if (!_isComplexMemberName)
                {
                    IGetAccessorFactory getAccessorFactory = scope.DataExchangeFactory.AccessorFactory.GetAccessorFactory;
                    _getAccessor = getAccessorFactory.CreateGetAccessor(parameterClass, _propertyName);
                }
                else // complex member name FavouriteLineItem.Id
                {
                    string memberName = _propertyName.Substring( _propertyName.LastIndexOf('.')+1);
                    string parentName = _propertyName.Substring(0,_propertyName.LastIndexOf('.'));
                    Type parentType = ObjectProbe.GetMemberTypeForGetter(parameterClass, parentName);

                    IGetAccessorFactory getAccessorFactory = scope.DataExchangeFactory.AccessorFactory.GetAccessorFactory;
                    _getAccessor = getAccessorFactory.CreateGetAccessor(parentType, memberName);
                }
            }

            scope.ErrorContext.MoreInfo = "Check the parameter mapping typeHandler attribute '" + this.CallBackName + "' (must be a ITypeHandlerCallback implementation).";
            if (this.CallBackName.Length >0)
            {
                try
                {
                    Type type = scope.DataExchangeFactory.TypeHandlerFactory.GetType(this.CallBackName);
                    ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback) Activator.CreateInstance( type );
                    _typeHandler = new CustomTypeHandler(typeHandlerCallback);
                }
                catch (Exception e)
                {
                    throw new ConfigurationException("Error occurred during custom type handler configuration.  Cause: " + e.Message, e);
                }
            }
            else
            {
                if (this.CLRType.Length == 0 )  // Unknown
                {
                    if (_getAccessor!= null &&
                        scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(_getAccessor.MemberType))
                    {
                        // Primitive
                        _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(_getAccessor.MemberType, _dbType);
                    }
                    else
                    {
                        _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
                    }
                }
                else // If we specify a CLR type, use it
                {
                    Type type = TypeUtils.ResolveType(this.CLRType);

                    if (scope.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(type))
                    {
                        // Primitive
                        _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, _dbType);
                    }
                    else
                    {
                        // .NET object
                        type = ObjectProbe.GetMemberTypeForGetter(type, this.PropertyName);
                        _typeHandler = scope.DataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, _dbType);
                    }
                }
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ResultProperty"/> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="columnIndex">Index of the column.</param>
        /// <param name="clrType">Type of the CLR.</param>
        /// <param name="callBackName">Name of the call back.</param>
        /// <param name="dbType">Type of the db.</param>
        /// <param name="isLazyLoad">if set to <c>true</c> [is lazy load].</param>
        /// <param name="nestedResultMapName">Name of the nested result map.</param>
        /// <param name="nullValue">The null value.</param>
        /// <param name="select">The select.</param>
        /// <param name="resultClass">The result class.</param>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="typeHandler">The type handler.</param>
		public ResultProperty(
            string propertyName,
            string columnName,
            int columnIndex,
            string clrType,
            string callBackName,
            string dbType,
            bool isLazyLoad,
            string nestedResultMapName,
            string nullValue,
            string select,
            Type resultClass,
            DataExchangeFactory dataExchangeFactory,
            ITypeHandler typeHandler
            )
		{
            Contract.Require.That(propertyName, Is.Not.Null & Is.Not.Empty).When("retrieving argument propertyName in ResultProperty constructor");

            this.propertyName = propertyName;

            this.columnName = columnName;
            this.callBackName = callBackName;
            this.dbType = dbType;
            this.clrType = clrType;
            this.select = select;
            this.nestedResultMapName = nestedResultMapName;
            this.isLazyLoad = isLazyLoad;
            this.nullValue = nullValue;
            this.columnIndex = columnIndex;
            this.typeHandler = typeHandler;

            #region isComplexMemberName
            if (propertyName.IndexOf('.') < 0)
            {
                isComplexMemberName = false;
            }
            else // complex member name FavouriteLineItem.Id
            {
                isComplexMemberName = true;
            } 
            #endregion			
            
            if ( propertyName.Length>0 && 
				 propertyName != "value" && 
				!typeof(IDictionary).IsAssignableFrom(resultClass)&&
                !typeof(DataRow).IsAssignableFrom(resultClass)) 
			{   
                #region SetAccessor
                if (!isComplexMemberName)
                {
                    setAccessor = dataExchangeFactory.AccessorFactory.SetAccessorFactory.CreateSetAccessor(resultClass, propertyName);
                }
                else // complex member name FavouriteLineItem.Id
                {
                    MemberInfo propertyInfo = ObjectProbe.GetMemberInfoForSetter(resultClass, propertyName);
                    string memberName = propertyName.Substring(propertyName.LastIndexOf('.') + 1);
                    setAccessor = dataExchangeFactory.AccessorFactory.SetAccessorFactory.CreateSetAccessor(propertyInfo.ReflectedType, memberName);
                }
                #endregion

                isGenericIList = TypeUtils.IsImplementGenericIListInterface(MemberType);
                isIList = typeof(IList).IsAssignableFrom(MemberType);
                    
                #region Set the list factory
                if (isGenericIList)
                {
                    if (MemberType.IsArray)
                    {
                        listFactory = arrayListFactory;
                    }
                    else
                    {
                        Type[] typeArgs = MemberType.GetGenericArguments();

                        if (typeArgs.Length == 0)// Custom collection which derive from List<T>
                        {
                            listFactory = dataExchangeFactory.ObjectFactory.CreateFactory(MemberType, Type.EmptyTypes);
                        }
                        else
                        {
                            Type genericIList = typeof(IList<>);
                            Type interfaceListType = genericIList.MakeGenericType(typeArgs);

                            Type genericList = typeof(List<>);
                            Type listType = genericList.MakeGenericType(typeArgs);

                            if ((interfaceListType == MemberType) || (listType == MemberType))
                            {
                                Type constructedType = genericList.MakeGenericType(typeArgs);
                                listFactory = dataExchangeFactory.ObjectFactory.CreateFactory(
                                    constructedType,
                                    Type.EmptyTypes);
                            }
                            else // Custom collection which derive from List<T>
                            {
                                listFactory = dataExchangeFactory.ObjectFactory.CreateFactory(MemberType, Type.EmptyTypes);
                            }
                        }
                    }
                }
                else if (isIList)
                {
                    if (MemberType.IsArray)
                    {
                        listFactory = arrayListFactory;
                    }
                    else
                    {
                        if (MemberType == typeof(IList))
                        {
                            listFactory = arrayListFactory;
                        }
                        else // custom collection
                        {
                            listFactory = dataExchangeFactory.ObjectFactory.CreateFactory(MemberType, Type.EmptyTypes);
                        }
                    }
                } 
                #endregion
			}

            #region TypeHandler
            if (!string.IsNullOrEmpty(CallBackName))
            {
                try
                {
                    Type type = dataExchangeFactory.TypeHandlerFactory.GetType(CallBackName);
                    ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback)Activator.CreateInstance(type);
                    this.typeHandler = new CustomTypeHandler(typeHandlerCallback);
                }
                catch (Exception e)
                {
                    throw new ConfigurationException("Error occurred during custom type handler configuration.  Cause: " + e.Message, e);
                }
            }
            else
            {
                if (typeHandler == null)
                {
                    //configScope.ErrorContext.MoreInfo = "Result property '" + propertyName + "' set the typeHandler attribute.";
                    this.typeHandler = dataExchangeFactory.TypeHandlerFactory.ResolveTypeHandler(resultClass, propertyName, clrType, dbType, true);
                }
            } 
            #endregion
                
            #region LazyLoad
            if (IsLazyLoad)
            {
                lazyFactory = new LazyFactoryBuilder().GetLazyFactory(setAccessor.MemberType);
            } 
            #endregion

            if (!GetType().IsSubclassOf(typeof(ResultProperty)))
            {
                propertyStrategy = PropertyStrategyFactory.Get(this);
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ParameterProperty"/> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="callBackName">Name of the call back.</param>
        /// <param name="clrType">Type of the CLR.</param>
        /// <param name="dbType">Type of the db.</param>
        /// <param name="directionAttribute">The direction attribute.</param>
        /// <param name="nullValue">The null value.</param>
        /// <param name="precision">The precision.</param>
        /// <param name="scale">The scale.</param>
        /// <param name="size">The size.</param>
        /// <param name="parameterClass">The parameter class.</param>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        public ParameterProperty(
            string propertyName,
            string columnName,
            string callBackName,
            string clrType,
            string dbType,
            string directionAttribute,
            string nullValue,
            Byte precision,
            Byte scale,
            int size,
            Type parameterClass,
            DataExchangeFactory dataExchangeFactory 
            )
        {
            Contract.Require.That(propertyName, Is.Not.Null & Is.Not.Empty).When("retrieving argument propertyName in ParameterProperty constructor");

            this.columnName = columnName;
            this.callBackName = callBackName;
            this.clrType = clrType;
            this.dbType = dbType;
            this.nullValue = nullValue;
            this.precision = precision;
            this.scale = scale;
            this.size = size;

            #region Direction
            if (directionAttribute.Length > 0)
            {
                direction = (ParameterDirection)Enum.Parse(typeof(ParameterDirection), directionAttribute, true);
                this.directionAttribute = direction.ToString();
            }
            #endregion

            #region Property Name
            this.propertyName = propertyName;
            if (propertyName.IndexOf('.') < 0)
            {
                isComplexMemberName = false;
            }
            else // complex member name FavouriteLineItem.Id
            {
                isComplexMemberName = true;
            }
            #endregion

            #region GetAccessor
            if (!typeof(IDictionary).IsAssignableFrom(parameterClass) // Hashtable parameter map
                && parameterClass != null // value property
                && !dataExchangeFactory.TypeHandlerFactory.IsSimpleType(parameterClass)) // value property
            {
                if (!isComplexMemberName)
                {
                    IGetAccessorFactory getAccessorFactory = dataExchangeFactory.AccessorFactory.GetAccessorFactory;
                    getAccessor = getAccessorFactory.CreateGetAccessor(parameterClass, propertyName);
                }
                else // complex member name FavouriteLineItem.Id
                {
                    string memberName = propertyName.Substring(propertyName.LastIndexOf('.') + 1);
                    string parentName = propertyName.Substring(0, propertyName.LastIndexOf('.'));
                    Type parentType = ObjectProbe.GetMemberTypeForGetter(parameterClass, parentName);

                    IGetAccessorFactory getAccessorFactory = dataExchangeFactory.AccessorFactory.GetAccessorFactory;
                    getAccessor = getAccessorFactory.CreateGetAccessor(parentType, memberName);
                }
            }
            #endregion

            #region TypeHandler
            if (CallBackName.Length > 0)
            {
                try
                {
                    Type type = dataExchangeFactory.TypeHandlerFactory.GetType(CallBackName);
                    ITypeHandlerCallback typeHandlerCallback = (ITypeHandlerCallback)Activator.CreateInstance(type);
                    typeHandler = new CustomTypeHandler(typeHandlerCallback);
                }
                catch (Exception e)
                {
                    throw new ConfigurationException("Error occurred during custom type handler configuration.  Cause: " + e.Message, e);
                }
            }
            else
            {
                if (CLRType.Length == 0)  // Unknown
                {
                    if (getAccessor != null &&
                        dataExchangeFactory.TypeHandlerFactory.IsSimpleType(getAccessor.MemberType))
                    {
                        // Primitive
                        typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(getAccessor.MemberType, dbType);
                    }
                    else
                    {
                        typeHandler = dataExchangeFactory.TypeHandlerFactory.GetUnkownTypeHandler();
                    }
                }
                else // If we specify a CLR type, use it
                {
                    Type type = TypeUtils.ResolveType(CLRType);

                    if (dataExchangeFactory.TypeHandlerFactory.IsSimpleType(type))
                    {
                        // Primitive
                        typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, dbType);
                    }
                    else
                    {
                        // .NET object
                        type = ObjectProbe.GetMemberTypeForGetter(parameterClass, PropertyName);
                        typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(type, dbType);
                    }
                }
            }

            #endregion
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArgumentProperty"/> class.
        /// </summary>
        /// <param name="argumentName">Name of the argument.</param>
        /// <param name="columnName">Name of the column.</param>
        /// <param name="columnIndex">Index of the column.</param>
        /// <param name="clrType">Type of the CLR.</param>
        /// <param name="callBackName">Name of the call back.</param>
        /// <param name="dbType">Type of the db.</param>
        /// <param name="nestedResultMapName">Name of the nested result map.</param>
        /// <param name="nullValue">The null value.</param>
        /// <param name="select">The select.</param>
        /// <param name="type">The argument type.</param>
        /// <param name="resultClass">The result class.</param>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="typeHandler">The type handler.</param>
		public ArgumentProperty(
            string    argumentName,
            string    columnName,
            int       columnIndex,
            string    clrType,
            string    callBackName,
            string    dbType,
            string    nestedResultMapName,
            string    nullValue,
            string    select,
            Type      type,
            Type      resultClass,
            DataExchangeFactory dataExchangeFactory,
            ITypeHandler typeHandler
            )
            : base("value", columnName, columnIndex, clrType, callBackName, dbType, false, nestedResultMapName, nullValue, select, resultClass,
            dataExchangeFactory, typeHandler)
		{
            Contract.Require.That(argumentName, Is.Not.Null & Is.Not.Empty).When("retrieving argument argumentName in ArgumentProperty constructor");
            Contract.Require.That(type, Is.Not.Null & Is.Not.Empty).When("retrieving argument type in ArgumentProperty constructor");
            Contract.Require.That(resultClass, Is.Not.Null & Is.Not.Empty).When("retrieving argument resultClass in ArgumentProperty constructor");

            this.argumentName = argumentName;
            this.type = type;

            argumentStrategy = ArgumentStrategyFactory.Get(this);
		}
Ejemplo n.º 41
0
		/// <summary>
		/// Register (add) a type handler for a type and dbType
        /// 根据前两个参数 分两次获取数据 最后把dbType加入字典当中
		/// </summary>
		/// <param name="type">the type</param>
		/// <param name="dbType">the dbType (optional, if dbType is null the handler will be used for all dbTypes)</param>
		/// <param name="handler">the handler instance</param>
		public void Register(Type type, string dbType, ITypeHandler handler) 
		{
            IDictionary<string, ITypeHandler> map = null;
            typeHandlerMap.TryGetValue(type, out map);
			if (map == null) //如果type不存在,则加入当前对象
			{
                map = new Dictionary<string, ITypeHandler>();
				typeHandlerMap.Add(type, map)  ;
			}
			if (dbType==null)
			{
				if (logger.IsInfoEnabled)
				{
					// notify the user that they are no longer using one of the built-in type handlers
                    ITypeHandler oldTypeHandler = null;
                    map.TryGetValue(NULL, out oldTypeHandler);

					if (oldTypeHandler != null)
					{
						// the replacement will always(?) be a CustomTypeHandler
						CustomTypeHandler customTypeHandler = handler as CustomTypeHandler;
						
						string replacement = string.Empty;
						
						if (customTypeHandler != null)
						{
							// report the underlying type
							replacement = customTypeHandler.Callback.ToString();
						}
						else
						{
							replacement = handler.ToString();
						}

						// should oldTypeHandler be checked if its a CustomTypeHandler and if so report the Callback property ???
						logger.Info("Replacing type handler [" + oldTypeHandler + "] with [" + replacement + "].");
					}
				}

                map[NULL] = handler;//意味着dbType默认的null类型 对应当前
			}
			else
			{
                map.Add(dbType, handler);//最后加入字典当中ITypeHandler处理类对象
			}
		}
Ejemplo n.º 42
0
		/// <summary>
		/// Initialize a the result property
		/// for AutoMapper
		/// </summary>
        /// <param name="setAccessor">An <see cref="ISetAccessor"/>.</param>
		/// <param name="typeHandlerFactory"></param>
		internal void Initialize(TypeHandlerFactory typeHandlerFactory, ISetAccessor setAccessor )
		{
            _setAccessor = setAccessor;
            _typeHandler = typeHandlerFactory.GetTypeHandler(setAccessor.MemberType);
		}