#region Apache Notice /***************************************************************************** * $Revision$ * $LastChangedDate$ * $LastChangedBy$ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Using using System; using System.Collections.Specialized; using System.Data; using System.Reflection; using System.Xml; using System.Xml.Serialization; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Utilities.Objects; using IBatisNet.DataMapper.Configuration.Serializers; using IBatisNet.DataMapper.DataExchange; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.Scope; using IBatisNet.Common.Utilities; #endregion namespace IBatisNet.DataMapper.Configuration.ResultMapping { /// /// Main implementation of ResultMap interface /// [Serializable] [XmlRoot("resultMap", Namespace="http://ibatis.apache.org/mapping")] public class ResultMap : IResultMap { /// /// Token for xml path to argument constructor elements. /// public static BindingFlags ANY_VISIBILITY_INSTANCE = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; /// /// Token for xml path to result elements. /// private const string XML_RESULT = "result"; /// /// Token for xml path to result elements. /// private const string XML_CONSTRUCTOR_ARGUMENT = "constructor/argument"; /// /// Token for xml path to discriminator elements. /// private const string XML_DISCRIMNATOR = "discriminator"; /// /// Token for xml path to subMap elements. /// private const string XML_SUBMAP = "subMap"; private static IResultMap _nullResultMap = null; #region Fields [NonSerialized] private bool _isInitalized = true; [NonSerialized] private string _id = string.Empty; [NonSerialized] private string _className = string.Empty; [NonSerialized] private string _extendMap = string.Empty; [NonSerialized] private Type _class = null; [NonSerialized] private StringCollection _groupByPropertyNames = new StringCollection(); [NonSerialized] private ResultPropertyCollection _properties = new ResultPropertyCollection(); [NonSerialized] private ResultPropertyCollection _groupByProperties = new ResultPropertyCollection(); [NonSerialized] private ResultPropertyCollection _parameters = new ResultPropertyCollection(); [NonSerialized] private Discriminator _discriminator = null; [NonSerialized] private string _sqlMapNameSpace = string.Empty; [NonSerialized] private IFactory _objectFactory = null; [NonSerialized] private DataExchangeFactory _dataExchangeFactory = null; [NonSerialized] private IDataExchange _dataExchange = null; #endregion #region Properties /// /// The GroupBy Properties. /// [XmlIgnore] public StringCollection GroupByPropertyNames { get { return _groupByPropertyNames; } } /// /// Gets or sets a value indicating whether this instance is initalized. /// /// /// true if this instance is initalized; otherwise, false. /// public bool IsInitalized { get { return true; } set { _isInitalized = value; } } /// /// The discriminator used to choose the good SubMap /// [XmlIgnore] public Discriminator Discriminator { get { return _discriminator; } set { _discriminator = value; } } /// /// The collection of ResultProperty. /// [XmlIgnore] public ResultPropertyCollection Properties { get { return _properties; } } /// /// The GroupBy Properties. /// [XmlIgnore] public ResultPropertyCollection GroupByProperties { get { return _groupByProperties; } } /// /// The collection of constructor parameters. /// [XmlIgnore] public ResultPropertyCollection Parameters { get { return _parameters; } } /// /// Identifier used to identify the resultMap amongst the others. /// /// GetProduct [XmlAttribute("id")] public string Id { get { return _id; } } /// /// Extend ResultMap attribute /// [XmlAttribute("extends")] public string ExtendMap { get { return _extendMap; } set { _extendMap = value; } } /// /// The output type class of the resultMap. /// [XmlIgnore] public Type Class { get { return _class; } } /// /// Sets the IDataExchange /// [XmlIgnore] public IDataExchange DataExchange { set { _dataExchange = value; } } #endregion #region Constructor (s) / Destructor /// /// Initializes a new instance of the class. /// /// The config scope. /// The output class name of the resultMap. /// The extend result map bame. /// Identifier used to identify the resultMap amongst the others. /// The groupBy properties public ResultMap(ConfigurationScope configScope, string id, string className, string extendMap, string groupBy) { _nullResultMap = new NullResultMap(); _dataExchangeFactory = configScope.DataExchangeFactory; _sqlMapNameSpace = configScope.SqlMapNamespace; if ((id == null) || (id.Length < 1)) { throw new ArgumentNullException("The id attribute is mandatory in a ResultMap tag."); } _id = configScope.ApplyNamespace(id); if ((className == null) || (className.Length < 1)) { throw new ArgumentNullException("The class attribute is mandatory in the ResultMap tag id:"+_id); } _className = className; _extendMap = extendMap; if (groupBy != null && groupBy.Length>0) { string[] groupByProperties = groupBy.Split(','); for (int i = 0; i < groupByProperties.Length; i++) { string memberName = groupByProperties[i].Trim(); _groupByPropertyNames.Add(memberName); } } } #endregion #region Methods #region Configuration /// /// Initialize the resultMap from an xmlNode.. /// /// public void Initialize( ConfigurationScope configScope ) { try { _class = configScope.SqlMapper.TypeHandlerFactory.GetType(_className); _dataExchange = _dataExchangeFactory.GetDataExchangeForClass(_class); // Load the child node GetChildNode(configScope); // Verify that that each groupBy element correspond to a class member // of one of result property for (int i = 0; i < _groupByProperties.Count; i++) { string memberName = GroupByPropertyNames[i]; if (!_properties.Contains(memberName)) { throw new ConfigurationException( string.Format( "Could not configure ResultMap named \"{0}\". Check the groupBy attribute. Cause: there's no result property named \"{1}\".", _id, memberName)); } } } catch(Exception e) { throw new ConfigurationException( string.Format("Could not configure ResultMap named \"{0}\", Cause: {1}", _id, e.Message) , e); } } /// /// Initializes the groupBy properties. /// public void InitializeGroupByProperties() { for (int i = 0; i < GroupByPropertyNames.Count; i++) { ResultProperty resultProperty = Properties.FindByPropertyName(this.GroupByPropertyNames[i]); this.GroupByProperties.Add(resultProperty); } } /// /// Get the result properties and the subMap properties. /// /// private void GetChildNode(ConfigurationScope configScope) { ResultProperty mapping = null; SubMap subMap = null; #region Load the parameters constructor XmlNodeList nodeList = configScope.NodeContext.SelectNodes( DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_CONSTRUCTOR_ARGUMENT), configScope.XmlNamespaceManager); if (nodeList.Count>0) { Type[] parametersType= new Type[nodeList.Count]; string[] parametersName = new string[nodeList.Count]; for( int i =0; i0 && this.Discriminator==null) { throw new ConfigurationException("The discriminator is null, but somehow a subMap was reached. This is a bug."); } foreach ( XmlNode resultNode in configScope.NodeContext.SelectNodes(DomSqlMapBuilder.ApplyMappingNamespacePrefix(XML_SUBMAP), configScope.XmlNamespaceManager) ) { configScope.ErrorContext.MoreInfo = "initialize subMap"; subMap = SubMapDeSerializer.Deserialize(resultNode, configScope); this.Discriminator.Add( subMap ); } #endregion } /// /// Sets the object factory. /// public void SetObjectFactory(ConfigurationScope configScope) { Type[] parametersType = new Type[_parameters.Count]; for (int i = 0; i < _parameters.Count; i++) { ArgumentProperty argumentMapping = (ArgumentProperty)_parameters[i]; parametersType[i] = argumentMapping.MemberType; } // Init the object factory _objectFactory = configScope.SqlMapper.ObjectFactory.CreateFactory(_class, parametersType); } /// /// Finds the constructor that takes the parameters. /// /// The to find the constructor in. /// The parameters name to use to find the appropriate constructor. /// /// An that can be used to create the type with /// the specified parameters. /// /// /// Thrown when no constructor with the correct signature can be found. /// private ConstructorInfo GetConstructor(Type type, string[] parametersName ) { ConstructorInfo[] candidates = type.GetConstructors(ANY_VISIBILITY_INSTANCE); foreach( ConstructorInfo constructor in candidates ) { ParameterInfo[] parameters = constructor.GetParameters(); if( parameters.Length == parametersName.Length ) { bool found = true; for( int j = 0; j < parameters.Length; j++ ) { bool ok = (parameters[ j ].Name == parametersName[ j ]); if( !ok ) { found = false; break; } } if( found ) { return constructor; } } } throw new DataMapperException( "Cannot find an appropriate constructor which map parameters in class: "+ type.Name ); } #endregion /// /// Create an instance Of result. /// /// /// An array of values that matches the number, order and type /// of the parameters for this constructor. /// /// An object. public object CreateInstanceOfResult(object[] parameters) { TypeCode typeCode = Type.GetTypeCode(_class); if (typeCode == TypeCode.Object) { return _objectFactory.CreateInstance(parameters); } else { return TypeUtils.InstantiatePrimitiveType(typeCode); } } /// /// Set the value of an object property. /// /// The object to set the property. /// The result property to use. /// The database value to set. public void SetValueOfProperty( ref object target, ResultProperty property, object dataBaseValue ) { _dataExchange.SetData(ref target, property, dataBaseValue); } /// /// /// /// /// public IResultMap ResolveSubMap(IDataReader dataReader) { IResultMap subMap = this; if (_discriminator != null) { ResultProperty mapping = _discriminator.ResultProperty; object dataBaseValue = mapping.GetDataBaseValue( dataReader ); if (dataBaseValue!=null) { subMap = _discriminator.GetSubMap( dataBaseValue.ToString() ); if (subMap == null) { subMap = this; } else if (subMap != this) { subMap = subMap.ResolveSubMap(dataReader); } } else { subMap = _nullResultMap; } } return subMap; } #endregion } }