You can subscribe to this list here.
2004 |
Jan
|
Feb
|
Mar
|
Apr
(248) |
May
(82) |
Jun
(90) |
Jul
(177) |
Aug
(253) |
Sep
(157) |
Oct
(151) |
Nov
(143) |
Dec
(278) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2005 |
Jan
(152) |
Feb
(107) |
Mar
(177) |
Apr
(133) |
May
(259) |
Jun
(81) |
Jul
(119) |
Aug
(306) |
Sep
(416) |
Oct
(240) |
Nov
(329) |
Dec
(206) |
2006 |
Jan
(466) |
Feb
(382) |
Mar
(153) |
Apr
(162) |
May
(133) |
Jun
(21) |
Jul
(18) |
Aug
(37) |
Sep
(97) |
Oct
(114) |
Nov
(110) |
Dec
(28) |
2007 |
Jan
(74) |
Feb
(65) |
Mar
(49) |
Apr
(76) |
May
(43) |
Jun
(15) |
Jul
(68) |
Aug
(55) |
Sep
(63) |
Oct
(59) |
Nov
(70) |
Dec
(66) |
2008 |
Jan
(71) |
Feb
(60) |
Mar
(120) |
Apr
(31) |
May
(48) |
Jun
(81) |
Jul
(107) |
Aug
(51) |
Sep
(80) |
Oct
(83) |
Nov
(83) |
Dec
(79) |
2009 |
Jan
(83) |
Feb
(110) |
Mar
(97) |
Apr
(91) |
May
(291) |
Jun
(250) |
Jul
(197) |
Aug
(58) |
Sep
(54) |
Oct
(122) |
Nov
(68) |
Dec
(34) |
2010 |
Jan
(50) |
Feb
(17) |
Mar
(63) |
Apr
(61) |
May
(84) |
Jun
(81) |
Jul
(138) |
Aug
(144) |
Sep
(78) |
Oct
(26) |
Nov
(30) |
Dec
(61) |
2011 |
Jan
(33) |
Feb
(35) |
Mar
(166) |
Apr
(221) |
May
(109) |
Jun
(76) |
Jul
(27) |
Aug
(37) |
Sep
(1) |
Oct
(4) |
Nov
(2) |
Dec
(1) |
2012 |
Jan
|
Feb
|
Mar
(2) |
Apr
(2) |
May
|
Jun
|
Jul
(1) |
Aug
|
Sep
(1) |
Oct
|
Nov
(1) |
Dec
|
2013 |
Jan
|
Feb
(1) |
Mar
|
Apr
|
May
|
Jun
|
Jul
(1) |
Aug
(1) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
(1) |
2014 |
Jan
(1) |
Feb
(1) |
Mar
(3) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <fab...@us...> - 2008-10-11 13:10:05
|
Revision: 3843 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3843&view=rev Author: fabiomaulo Date: 2008-10-11 13:09:53 +0000 (Sat, 11 Oct 2008) Log Message: ----------- forgot a possible BR is somebody are inheriting from DefaultProxyFactoryFactory Modified Paths: -------------- trunk/nhibernate/releasenotes.txt Modified: trunk/nhibernate/releasenotes.txt =================================================================== --- trunk/nhibernate/releasenotes.txt 2008-10-11 12:59:51 UTC (rev 3842) +++ trunk/nhibernate/releasenotes.txt 2008-10-11 13:09:53 UTC (rev 3843) @@ -3,6 +3,7 @@ ** BREAKING CHANGES from NH2.0.xGA to NH2.1.0 ##### Possible Breaking Changes for external frameworks ##### * ISession interface have additional methods + * DefaultProxyFactoryFactory moved to NHibernate.Bytecode.Castle ##### Initialization time ##### * The ProxyTypeValidator check for "internal virtual" (to be proxied need "protected internal virtual") This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-11 13:00:10
|
Revision: 3842 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3842&view=rev Author: fabiomaulo Date: 2008-10-11 12:59:51 +0000 (Sat, 11 Oct 2008) Log Message: ----------- - Fix NH-1515 (BREAKING CHANGE) - Minor refactoring of proxy validation stuff Modified Paths: -------------- trunk/nhibernate/releasenotes.txt trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs trunk/nhibernate/src/NHibernate/InvalidProxyTypeException.cs trunk/nhibernate/src/NHibernate/Proxy/ProxyTypeValidator.cs trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1408/DbResourceKey.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1464/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/ProxyValidator/Fixture.cs trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1515/ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1515/Fixture.cs Modified: trunk/nhibernate/releasenotes.txt =================================================================== --- trunk/nhibernate/releasenotes.txt 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/releasenotes.txt 2008-10-11 12:59:51 UTC (rev 3842) @@ -4,6 +4,10 @@ ##### Possible Breaking Changes for external frameworks ##### * ISession interface have additional methods + ##### Initialization time ##### + * The ProxyTypeValidator check for "internal virtual" (to be proxied need "protected internal virtual") + + Build 2.0.1.GA ======================== ** Bug Modified: trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -25,6 +25,7 @@ using NHibernate.Tool.hbm2ddl; using NHibernate.Type; using NHibernate.Util; +using Array=System.Array; namespace NHibernate.Cfg { @@ -77,7 +78,7 @@ protected IDictionary<string, Mappings.TableDescription> tableNameBinding; protected IDictionary<Table, Mappings.ColumnNames> columnNameBindingPerTable; - private static readonly ILog log = LogManager.GetLogger(typeof(Configuration)); + private static readonly ILog log = LogManager.GetLogger(typeof (Configuration)); protected internal SettingsFactory settingsFactory; @@ -160,8 +161,7 @@ } } - [NonSerialized] - private IMapping mapping; + [NonSerialized] private IMapping mapping; protected Configuration(SettingsFactory settingsFactory) { @@ -183,10 +183,7 @@ /// <summary> /// Create a new Configuration object. /// </summary> - public Configuration() - : this(new SettingsFactory()) - { - } + public Configuration() : this(new SettingsFactory()) {} /// <summary> /// The class mappings @@ -260,7 +257,9 @@ private static void LogAndThrow(Exception exception) { if (log.IsErrorEnabled) + { log.Error(exception.Message, exception); + } throw exception; } @@ -393,7 +392,7 @@ try { - using (MemoryStream ms = new MemoryStream()) + using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0; @@ -425,7 +424,7 @@ // selects as their prefix in the document. It is the prefix we use to // build the XPath and the nsmgr takes care of translating our prefix into // the user defined prefix... - XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.Document.NameTable); + var namespaceManager = new XmlNamespaceManager(doc.Document.NameTable); namespaceManager.AddNamespace(HbmConstants.nsPrefix, MappingSchemaXMLNS); Dialect.Dialect dialect = Dialect.Dialect.GetDialect(properties); @@ -446,26 +445,10 @@ /// </summary> public Mappings CreateMappings(Dialect.Dialect dialect) { - return new Mappings(classes, - collections, - tables, - namedQueries, - namedSqlQueries, - sqlResultSetMappings, - imports, - secondPasses, - propertyReferences, - namingStrategy, - typeDefs, - filterDefinitions, - extendsQueue, - auxiliaryDatabaseObjects, - tableNameBinding, - columnNameBindingPerTable, - defaultAssembly, - defaultNamespace, - dialect - ); + return new Mappings(classes, collections, tables, namedQueries, namedSqlQueries, sqlResultSetMappings, imports, + secondPasses, propertyReferences, namingStrategy, typeDefs, filterDefinitions, extendsQueue, + auxiliaryDatabaseObjects, tableNameBinding, columnNameBindingPerTable, defaultAssembly, + defaultNamespace, dialect); } /// <summary> @@ -555,7 +538,9 @@ finally { if (rsrc != null) + { rsrc.Close(); + } } } @@ -616,8 +601,8 @@ if (resourceNames.Count == 0) { log.Warn("No mapped documents found in assembly: " + assembly.FullName); - } - foreach (string name in resourceNames) + } + foreach (var name in resourceNames) { AddResource(name, assembly); } @@ -626,9 +611,9 @@ private static IList<string> GetAllHbmXmlResourceNames(Assembly assembly) { - List<string> result = new List<string>(); + var result = new List<string>(); - foreach (string resource in assembly.GetManifestResourceNames()) + foreach (var resource in assembly.GetManifestResourceNames()) { if (resource.EndsWith(".hbm.xml")) { @@ -646,12 +631,12 @@ /// <param name="dir">a directory</param> public Configuration AddDirectory(DirectoryInfo dir) { - foreach (DirectoryInfo subDirectory in dir.GetDirectories()) + foreach (var subDirectory in dir.GetDirectories()) { AddDirectory(subDirectory); } - foreach (FileInfo hbmXml in dir.GetFiles("*.hbm.xml")) + foreach (var hbmXml in dir.GetFiles("*.hbm.xml")) { AddFile(hbmXml); } @@ -670,7 +655,7 @@ string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); - List<string> script = new List<string>(); + var script = new List<string>(); // drop them in reverse order in case db needs it done that way... for (int i = auxiliaryDatabaseObjects.Count - 1; i >= 0; i--) @@ -684,32 +669,36 @@ if (dialect.DropConstraints) { - foreach (Table table in TableMappings) + foreach (var table in TableMappings) { if (table.IsPhysicalTable) { - foreach (ForeignKey fk in table.ForeignKeyIterator) + foreach (var fk in table.ForeignKeyIterator) { if (fk.HasPhysicalConstraint) + { script.Add(fk.SqlDropString(dialect, defaultCatalog, defaultSchema)); + } } } } } - foreach (Table table in TableMappings) + foreach (var table in TableMappings) { if (table.IsPhysicalTable) + { script.Add(table.SqlDropString(dialect, defaultCatalog, defaultSchema)); + } } IEnumerable<IPersistentIdentifierGenerator> pIDg = IterateGenerators(dialect); - foreach (IPersistentIdentifierGenerator idGen in pIDg) + foreach (var idGen in pIDg) { string[] lines = idGen.SqlDropString(dialect); if (lines != null) { - foreach (string line in lines) + foreach (var line in lines) { script.Add(line); } @@ -730,9 +719,9 @@ string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); - List<string> script = new List<string>(); + var script = new List<string>(); - foreach (Table table in TableMappings) + foreach (var table in TableMappings) { if (table.IsPhysicalTable) { @@ -741,39 +730,47 @@ } } - foreach (Table table in TableMappings) + foreach (var table in TableMappings) { if (table.IsPhysicalTable) { if (!dialect.SupportsUniqueConstraintInCreateAlterTable) { - foreach (UniqueKey uk in table.UniqueKeyIterator) + foreach (var uk in table.UniqueKeyIterator) { string constraintString = uk.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema); if (constraintString != null) + { script.Add(constraintString); + } } } - foreach (Index index in table.IndexIterator) + foreach (var index in table.IndexIterator) + { script.Add(index.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); + } if (dialect.HasAlterTable) { - foreach (ForeignKey fk in table.ForeignKeyIterator) + foreach (var fk in table.ForeignKeyIterator) { if (fk.HasPhysicalConstraint) + { script.Add(fk.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); + } } } } } IEnumerable<IPersistentIdentifierGenerator> pIDg = IterateGenerators(dialect); - foreach (IPersistentIdentifierGenerator idGen in pIDg) + foreach (var idGen in pIDg) + { script.AddRange(idGen.SqlCreateStrings(dialect)); + } - foreach (IAuxiliaryDatabaseObject auxDbObj in auxiliaryDatabaseObjects) + foreach (var auxDbObj in auxiliaryDatabaseObjects) { if (auxDbObj.AppliesToDialect(dialect)) { @@ -787,19 +784,19 @@ private void Validate() { bool validateProxy = PropertiesHelper.GetBoolean(Environment.UseProxyValidator, properties, true); - HashedSet allProxyErrors = null; + HashedSet<string> allProxyErrors = null; - foreach (PersistentClass clazz in classes.Values) + foreach (var clazz in classes.Values) { clazz.Validate(mapping); if (validateProxy) { - ICollection errors = ValidateProxyInterface(clazz); + ICollection<string> errors = ValidateProxyInterface(clazz); if (errors != null) { if (allProxyErrors == null) { - allProxyErrors = new HashedSet(errors); + allProxyErrors = new HashedSet<string>(errors); } else { @@ -814,13 +811,13 @@ throw new InvalidProxyTypeException(allProxyErrors); } - foreach (NHibernate.Mapping.Collection col in collections.Values) + foreach (var col in collections.Values) { col.Validate(mapping); } } - private static ICollection ValidateProxyInterface(PersistentClass persistentClass) + private static ICollection<string> ValidateProxyInterface(PersistentClass persistentClass) { if (!persistentClass.IsLazy) { @@ -857,7 +854,7 @@ log.Info("processing one-to-many association mappings"); - foreach (SecondPassCommand command in secondPasses) + foreach (var command in secondPasses) { command(classes); } @@ -866,7 +863,7 @@ log.Info("processing one-to-one association property references"); - foreach (Mappings.PropertyReference upr in propertyReferences) + foreach (var upr in propertyReferences) { PersistentClass clazz = GetClassMapping(upr.referencedClass); if (clazz == null) @@ -875,7 +872,7 @@ } Property prop = clazz.GetReferencedProperty(upr.propertyName); - ((SimpleValue)prop.Value).IsAlternateUniqueKey = true; + ((SimpleValue) prop.Value).IsAlternateUniqueKey = true; } //TODO: Somehow add the newly created foreign keys to the internal collection @@ -883,7 +880,7 @@ log.Info("processing foreign key constraints"); ISet done = new HashedSet(); - foreach (Table table in TableMappings) + foreach (var table in TableMappings) { SecondPassCompileForeignKeys(table, done); } @@ -893,7 +890,7 @@ { table.CreateForeignKeys(); - foreach (ForeignKey fk in table.ForeignKeyIterator) + foreach (var fk in table.ForeignKeyIterator) { if (!done.Contains(fk)) { @@ -902,7 +899,8 @@ string referencedEntityName = fk.ReferencedEntityName; if (string.IsNullOrEmpty(referencedEntityName)) { - throw new MappingException(string.Format("An association from the table {0} does not specify the referenced entity", fk.Table.Name)); + throw new MappingException( + string.Format("An association from the table {0} does not specify the referenced entity", fk.Table.Name)); } if (log.IsDebugEnabled) @@ -913,8 +911,8 @@ PersistentClass referencedClass; if (!classes.TryGetValue(referencedEntityName, out referencedClass)) { - string message = string.Format("An association from the table {0} refers to an unmapped class: {1}", - fk.Table.Name, referencedEntityName); + string message = string.Format("An association from the table {0} refers to an unmapped class: {1}", fk.Table.Name, + referencedEntityName); LogAndThrow(new MappingException(message)); } @@ -962,11 +960,7 @@ /// located by specified id. This is mainly intended for EJB3 implementations to be able to /// control how proxy initialization errors should be handled... /// </remarks> - public IEntityNotFoundDelegate EntityNotFoundDelegate - { - get { return entityNotFoundDelegate; } - set { entityNotFoundDelegate = value; } - } + public IEntityNotFoundDelegate EntityNotFoundDelegate { get; set; } public EventListeners EventListeners { @@ -986,9 +980,10 @@ public ISessionFactory BuildSessionFactory() { #region Way for the user to specify their own ProxyFactory + //http://jira.nhibernate.org/browse/NH-975 - IInjectableProxyFactoryFactory ipff = Environment.BytecodeProvider as IInjectableProxyFactoryFactory; + var ipff = Environment.BytecodeProvider as IInjectableProxyFactoryFactory; string pffClassName; properties.TryGetValue(Environment.ProxyFactoryFactoryClass, out pffClassName); if (ipff != null && !string.IsNullOrEmpty(pffClassName)) @@ -1096,7 +1091,7 @@ /// </returns> public Configuration AddProperties(IDictionary<string, string> additionalProperties) { - foreach (KeyValuePair<string, string> de in additionalProperties) + foreach (var de in additionalProperties) { properties.Add(de.Key, de.Value); } @@ -1129,7 +1124,7 @@ private void AddProperties(IHibernateConfiguration hc) { - foreach (KeyValuePair<string, string> kvp in hc.SessionFactory.Properties) + foreach (var kvp in hc.SessionFactory.Properties) { if (log.IsDebugEnabled) { @@ -1157,7 +1152,7 @@ /// </remarks> public Configuration Configure() { - IHibernateConfiguration hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as IHibernateConfiguration; + var hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as IHibernateConfiguration; if (hc != null && hc.SessionFactory != null) { return DoConfigure(hc); @@ -1216,12 +1211,14 @@ public Configuration Configure(Assembly assembly, string resourceName) { if (assembly == null) - throw new HibernateException("Could not configure NHibernate.", - new ArgumentNullException("assembly")); + { + throw new HibernateException("Could not configure NHibernate.", new ArgumentNullException("assembly")); + } if (resourceName == null) - throw new HibernateException("Could not configure NHibernate.", - new ArgumentNullException("resourceName")); + { + throw new HibernateException("Could not configure NHibernate.", new ArgumentNullException("resourceName")); + } Stream stream = null; try @@ -1230,9 +1227,8 @@ if (stream == null) { // resource does not exist - throw appropriate exception - throw new HibernateException("A ManifestResourceStream could not be created for the resource " + - resourceName + - " in Assembly " + assembly.FullName); + throw new HibernateException("A ManifestResourceStream could not be created for the resource " + resourceName + + " in Assembly " + assembly.FullName); } return Configure(new XmlTextReader(stream)); @@ -1259,7 +1255,7 @@ if (textReader == null) { throw new HibernateConfigException("Could not configure NHibernate.", - new ArgumentException("A null value was passed in.", "textReader")); + new ArgumentException("A null value was passed in.", "textReader")); } try @@ -1286,10 +1282,12 @@ AddProperties(hc); // Load mappings - foreach (MappingConfiguration mc in hc.SessionFactory.Mappings) + foreach (var mc in hc.SessionFactory.Mappings) { if (mc.IsEmpty()) + { throw new HibernateConfigException("<mapping> element in configuration specifies no attributes"); + } if (!string.IsNullOrEmpty(mc.Resource)) { log.Debug(hc.SessionFactory.Name + "<-" + mc.Resource + " in " + mc.Assembly); @@ -1308,7 +1306,7 @@ } // Load class-cache - foreach (ClassCacheConfiguration ccc in hc.SessionFactory.ClassesCache) + foreach (var ccc in hc.SessionFactory.ClassesCache) { string region = string.IsNullOrEmpty(ccc.Region) ? ccc.Class : ccc.Region; bool includeLazy = (ccc.Include != ClassCacheInclude.NonLazy); @@ -1316,13 +1314,14 @@ } // Load collection-cache - foreach (CollectionCacheConfiguration ccc in hc.SessionFactory.CollectionsCache) + foreach (var ccc in hc.SessionFactory.CollectionsCache) { string role = ccc.Collection; NHibernate.Mapping.Collection collection = GetCollectionMapping(role); if (collection == null) { - throw new HibernateConfigException("collection-cache Configuration: Cannot configure cache for unknown collection role " + role); + throw new HibernateConfigException( + "collection-cache Configuration: Cannot configure cache for unknown collection role " + role); } string region = string.IsNullOrEmpty(ccc.Region) ? role : ccc.Region; @@ -1330,9 +1329,9 @@ } // Events - foreach (EventConfiguration ec in hc.SessionFactory.Events) + foreach (var ec in hc.SessionFactory.Events) { - string[] listenerClasses = new string[ec.Listeners.Count]; + var listenerClasses = new string[ec.Listeners.Count]; for (int i = 0; i < ec.Listeners.Count; i++) { listenerClasses[i] = ec.Listeners[i].Class; @@ -1341,10 +1340,10 @@ SetListeners(ec.Type, listenerClasses); } // Listeners - foreach (ListenerConfiguration lc in hc.SessionFactory.Listeners) + foreach (var lc in hc.SessionFactory.Listeners) { log.Debug("Event listener: " + lc.Type + "=" + lc.Class); - SetListeners(lc.Type, new string[] { lc.Class }); + SetListeners(lc.Type, new[] {lc.Class}); } if (!string.IsNullOrEmpty(hc.SessionFactory.Name)) @@ -1360,13 +1359,13 @@ { try { - return (RootClass)GetClassMapping(clazz); + return (RootClass) GetClassMapping(clazz); } catch (InvalidCastException) { throw new HibernateConfigException( - "class-cache Configuration: You may only specify a cache for root <class> mappings " - + "(cache was specified for " + clazz + ")"); + "class-cache Configuration: You may only specify a cache for root <class> mappings " + "(cache was specified for " + + clazz + ")"); } } @@ -1379,13 +1378,13 @@ throw new HibernateConfigException("class-cache Configuration: Cache specified for unmapped class " + clazz); } - RootClass rootClass = persistentClass as RootClass; + var rootClass = persistentClass as RootClass; if (rootClass == null) { throw new HibernateConfigException( - "class-cache Configuration: You may only specify a cache for root <class> mappings " - + "(cache was specified for " + clazz + ")"); + "class-cache Configuration: You may only specify a cache for root <class> mappings " + "(cache was specified for " + + clazz + ")"); } return rootClass; @@ -1417,7 +1416,6 @@ rootClass.SetLazyPropertiesCacheable(includeLazy); } - /// <summary> /// Set up a cache for a collection role /// </summary> @@ -1535,7 +1533,7 @@ try { - XmlDocument hbmDocument = new XmlDocument(); + var hbmDocument = new XmlDocument(); hbmDocument.Load(reader); return new NamedXmlDocument(name, hbmDocument); } @@ -1589,13 +1587,8 @@ private void ValidationHandler(object o, ValidationEventArgs args) { - string message = - string.Format( - "{0}({1},{2}): XML validation error: {3}", - currentDocumentName, - args.Exception.LineNumber, - args.Exception.LinePosition, - args.Exception.Message); + string message = string.Format("{0}({1},{2}): XML validation error: {3}", currentDocumentName, + args.Exception.LineNumber, args.Exception.LinePosition, args.Exception.Message); LogAndThrow(new MappingException(message, args.Exception)); } @@ -1610,7 +1603,6 @@ #endregion private XmlSchemas schemas; - private IEntityNotFoundDelegate entityNotFoundDelegate; private XmlSchemas Schemas { @@ -1639,8 +1631,7 @@ } else { - object[] listeners = - (object[])System.Array.CreateInstance(eventListeners.GetListenerClassFor(type), listenerClasses.Length); + var listeners = (object[]) Array.CreateInstance(eventListeners.GetListenerClassFor(type), listenerClasses.Length); for (int i = 0; i < listeners.Length; i++) { try @@ -1672,7 +1663,7 @@ } else { - object[] listeners = (object[])System.Array.CreateInstance(eventListeners.GetListenerClassFor(type), 1); + var listeners = (object[]) Array.CreateInstance(eventListeners.GetListenerClassFor(type), 1); listeners[0] = listener; SetListeners(type, listeners); } @@ -1683,106 +1674,106 @@ switch (type) { case ListenerType.Autoflush: - eventListeners.AutoFlushEventListeners = new IAutoFlushEventListener[] { }; + eventListeners.AutoFlushEventListeners = new IAutoFlushEventListener[] {}; break; case ListenerType.Merge: - eventListeners.MergeEventListeners = new IMergeEventListener[] { }; + eventListeners.MergeEventListeners = new IMergeEventListener[] {}; break; case ListenerType.Create: - eventListeners.PersistEventListeners = new IPersistEventListener[] { }; + eventListeners.PersistEventListeners = new IPersistEventListener[] {}; break; case ListenerType.CreateOnFlush: - eventListeners.PersistOnFlushEventListeners = new IPersistEventListener[] { }; + eventListeners.PersistOnFlushEventListeners = new IPersistEventListener[] {}; break; case ListenerType.Delete: - eventListeners.DeleteEventListeners = new IDeleteEventListener[] { }; + eventListeners.DeleteEventListeners = new IDeleteEventListener[] {}; break; case ListenerType.DirtyCheck: - eventListeners.DirtyCheckEventListeners = new IDirtyCheckEventListener[] { }; + eventListeners.DirtyCheckEventListeners = new IDirtyCheckEventListener[] {}; break; case ListenerType.Evict: - eventListeners.EvictEventListeners = new IEvictEventListener[] { }; + eventListeners.EvictEventListeners = new IEvictEventListener[] {}; break; case ListenerType.Flush: - eventListeners.FlushEventListeners = new IFlushEventListener[] { }; + eventListeners.FlushEventListeners = new IFlushEventListener[] {}; break; case ListenerType.FlushEntity: - eventListeners.FlushEntityEventListeners = new IFlushEntityEventListener[] { }; + eventListeners.FlushEntityEventListeners = new IFlushEntityEventListener[] {}; break; case ListenerType.Load: - eventListeners.LoadEventListeners = new ILoadEventListener[] { }; + eventListeners.LoadEventListeners = new ILoadEventListener[] {}; break; case ListenerType.LoadCollection: - eventListeners.InitializeCollectionEventListeners = new IInitializeCollectionEventListener[] { }; + eventListeners.InitializeCollectionEventListeners = new IInitializeCollectionEventListener[] {}; break; case ListenerType.Lock: - eventListeners.LockEventListeners = new ILockEventListener[] { }; + eventListeners.LockEventListeners = new ILockEventListener[] {}; break; case ListenerType.Refresh: - eventListeners.RefreshEventListeners = new IRefreshEventListener[] { }; + eventListeners.RefreshEventListeners = new IRefreshEventListener[] {}; break; case ListenerType.Replicate: - eventListeners.ReplicateEventListeners = new IReplicateEventListener[] { }; + eventListeners.ReplicateEventListeners = new IReplicateEventListener[] {}; break; case ListenerType.SaveUpdate: - eventListeners.SaveOrUpdateEventListeners = new ISaveOrUpdateEventListener[] { }; + eventListeners.SaveOrUpdateEventListeners = new ISaveOrUpdateEventListener[] {}; break; case ListenerType.Save: - eventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] { }; + eventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] {}; break; case ListenerType.PreUpdate: - eventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { }; + eventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] {}; break; case ListenerType.Update: - eventListeners.UpdateEventListeners = new ISaveOrUpdateEventListener[] { }; + eventListeners.UpdateEventListeners = new ISaveOrUpdateEventListener[] {}; break; case ListenerType.PreLoad: - eventListeners.PreLoadEventListeners = new IPreLoadEventListener[] { }; + eventListeners.PreLoadEventListeners = new IPreLoadEventListener[] {}; break; case ListenerType.PreDelete: - eventListeners.PreDeleteEventListeners = new IPreDeleteEventListener[] { }; + eventListeners.PreDeleteEventListeners = new IPreDeleteEventListener[] {}; break; case ListenerType.PreInsert: - eventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { }; + eventListeners.PreInsertEventListeners = new IPreInsertEventListener[] {}; break; case ListenerType.PostLoad: - eventListeners.PostLoadEventListeners = new IPostLoadEventListener[] { }; + eventListeners.PostLoadEventListeners = new IPostLoadEventListener[] {}; break; case ListenerType.PostInsert: - eventListeners.PostInsertEventListeners = new IPostInsertEventListener[] { }; + eventListeners.PostInsertEventListeners = new IPostInsertEventListener[] {}; break; case ListenerType.PostUpdate: - eventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { }; + eventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] {}; break; case ListenerType.PostDelete: - eventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[] { }; + eventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[] {}; break; case ListenerType.PostCommitUpdate: - eventListeners.PostCommitUpdateEventListeners = new IPostUpdateEventListener[] { }; + eventListeners.PostCommitUpdateEventListeners = new IPostUpdateEventListener[] {}; break; case ListenerType.PostCommitInsert: - eventListeners.PostCommitInsertEventListeners = new IPostInsertEventListener[] { }; + eventListeners.PostCommitInsertEventListeners = new IPostInsertEventListener[] {}; break; case ListenerType.PostCommitDelete: - eventListeners.PostCommitDeleteEventListeners = new IPostDeleteEventListener[] { }; + eventListeners.PostCommitDeleteEventListeners = new IPostDeleteEventListener[] {}; break; case ListenerType.PreCollectionRecreate: - eventListeners.PreCollectionRecreateEventListeners = new IPreCollectionRecreateEventListener[] { }; + eventListeners.PreCollectionRecreateEventListeners = new IPreCollectionRecreateEventListener[] {}; break; case ListenerType.PreCollectionRemove: - eventListeners.PreCollectionRemoveEventListeners = new IPreCollectionRemoveEventListener[] { }; + eventListeners.PreCollectionRemoveEventListeners = new IPreCollectionRemoveEventListener[] {}; break; case ListenerType.PreCollectionUpdate: - eventListeners.PreCollectionUpdateEventListeners = new IPreCollectionUpdateEventListener[] { }; + eventListeners.PreCollectionUpdateEventListeners = new IPreCollectionUpdateEventListener[] {}; break; case ListenerType.PostCollectionRecreate: - eventListeners.PostCollectionRecreateEventListeners = new IPostCollectionRecreateEventListener[] { }; + eventListeners.PostCollectionRecreateEventListeners = new IPostCollectionRecreateEventListener[] {}; break; case ListenerType.PostCollectionRemove: - eventListeners.PostCollectionRemoveEventListeners = new IPostCollectionRemoveEventListener[] { }; + eventListeners.PostCollectionRemoveEventListeners = new IPostCollectionRemoveEventListener[] {}; break; case ListenerType.PostCollectionUpdate: - eventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[] { }; + eventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[] {}; break; default: log.Warn("Unrecognized listener type [" + type + "]"); @@ -1800,110 +1791,112 @@ public void SetListeners(ListenerType type, object[] listeners) { if (listeners == null) + { ClearListeners(type); + } switch (type) { case ListenerType.Autoflush: - eventListeners.AutoFlushEventListeners = (IAutoFlushEventListener[])listeners; + eventListeners.AutoFlushEventListeners = (IAutoFlushEventListener[]) listeners; break; case ListenerType.Merge: - eventListeners.MergeEventListeners = (IMergeEventListener[])listeners; + eventListeners.MergeEventListeners = (IMergeEventListener[]) listeners; break; case ListenerType.Create: - eventListeners.PersistEventListeners = (IPersistEventListener[])listeners; + eventListeners.PersistEventListeners = (IPersistEventListener[]) listeners; break; case ListenerType.CreateOnFlush: - eventListeners.PersistOnFlushEventListeners = (IPersistEventListener[])listeners; + eventListeners.PersistOnFlushEventListeners = (IPersistEventListener[]) listeners; break; case ListenerType.Delete: - eventListeners.DeleteEventListeners = (IDeleteEventListener[])listeners; + eventListeners.DeleteEventListeners = (IDeleteEventListener[]) listeners; break; case ListenerType.DirtyCheck: - eventListeners.DirtyCheckEventListeners = (IDirtyCheckEventListener[])listeners; + eventListeners.DirtyCheckEventListeners = (IDirtyCheckEventListener[]) listeners; break; case ListenerType.Evict: - eventListeners.EvictEventListeners = (IEvictEventListener[])listeners; + eventListeners.EvictEventListeners = (IEvictEventListener[]) listeners; break; case ListenerType.Flush: - eventListeners.FlushEventListeners = (IFlushEventListener[])listeners; + eventListeners.FlushEventListeners = (IFlushEventListener[]) listeners; break; case ListenerType.FlushEntity: - eventListeners.FlushEntityEventListeners = (IFlushEntityEventListener[])listeners; + eventListeners.FlushEntityEventListeners = (IFlushEntityEventListener[]) listeners; break; case ListenerType.Load: - eventListeners.LoadEventListeners = (ILoadEventListener[])listeners; + eventListeners.LoadEventListeners = (ILoadEventListener[]) listeners; break; case ListenerType.LoadCollection: - eventListeners.InitializeCollectionEventListeners = (IInitializeCollectionEventListener[])listeners; + eventListeners.InitializeCollectionEventListeners = (IInitializeCollectionEventListener[]) listeners; break; case ListenerType.Lock: - eventListeners.LockEventListeners = (ILockEventListener[])listeners; + eventListeners.LockEventListeners = (ILockEventListener[]) listeners; break; case ListenerType.Refresh: - eventListeners.RefreshEventListeners = (IRefreshEventListener[])listeners; + eventListeners.RefreshEventListeners = (IRefreshEventListener[]) listeners; break; case ListenerType.Replicate: - eventListeners.ReplicateEventListeners = (IReplicateEventListener[])listeners; + eventListeners.ReplicateEventListeners = (IReplicateEventListener[]) listeners; break; case ListenerType.SaveUpdate: - eventListeners.SaveOrUpdateEventListeners = (ISaveOrUpdateEventListener[])listeners; + eventListeners.SaveOrUpdateEventListeners = (ISaveOrUpdateEventListener[]) listeners; break; case ListenerType.Save: - eventListeners.SaveEventListeners = (ISaveOrUpdateEventListener[])listeners; + eventListeners.SaveEventListeners = (ISaveOrUpdateEventListener[]) listeners; break; case ListenerType.PreUpdate: - eventListeners.PreUpdateEventListeners = (IPreUpdateEventListener[])listeners; + eventListeners.PreUpdateEventListeners = (IPreUpdateEventListener[]) listeners; break; case ListenerType.Update: - eventListeners.UpdateEventListeners = (ISaveOrUpdateEventListener[])listeners; + eventListeners.UpdateEventListeners = (ISaveOrUpdateEventListener[]) listeners; break; case ListenerType.PreLoad: - eventListeners.PreLoadEventListeners = (IPreLoadEventListener[])listeners; + eventListeners.PreLoadEventListeners = (IPreLoadEventListener[]) listeners; break; case ListenerType.PreDelete: - eventListeners.PreDeleteEventListeners = (IPreDeleteEventListener[])listeners; + eventListeners.PreDeleteEventListeners = (IPreDeleteEventListener[]) listeners; break; case ListenerType.PreInsert: - eventListeners.PreInsertEventListeners = (IPreInsertEventListener[])listeners; + eventListeners.PreInsertEventListeners = (IPreInsertEventListener[]) listeners; break; case ListenerType.PostLoad: - eventListeners.PostLoadEventListeners = (IPostLoadEventListener[])listeners; + eventListeners.PostLoadEventListeners = (IPostLoadEventListener[]) listeners; break; case ListenerType.PostInsert: - eventListeners.PostInsertEventListeners = (IPostInsertEventListener[])listeners; + eventListeners.PostInsertEventListeners = (IPostInsertEventListener[]) listeners; break; case ListenerType.PostUpdate: - eventListeners.PostUpdateEventListeners = (IPostUpdateEventListener[])listeners; + eventListeners.PostUpdateEventListeners = (IPostUpdateEventListener[]) listeners; break; case ListenerType.PostDelete: - eventListeners.PostDeleteEventListeners = (IPostDeleteEventListener[])listeners; + eventListeners.PostDeleteEventListeners = (IPostDeleteEventListener[]) listeners; break; case ListenerType.PostCommitUpdate: - eventListeners.PostCommitUpdateEventListeners = (IPostUpdateEventListener[])listeners; + eventListeners.PostCommitUpdateEventListeners = (IPostUpdateEventListener[]) listeners; break; case ListenerType.PostCommitInsert: - eventListeners.PostCommitInsertEventListeners = (IPostInsertEventListener[])listeners; + eventListeners.PostCommitInsertEventListeners = (IPostInsertEventListener[]) listeners; break; case ListenerType.PostCommitDelete: - eventListeners.PostCommitDeleteEventListeners = (IPostDeleteEventListener[])listeners; + eventListeners.PostCommitDeleteEventListeners = (IPostDeleteEventListener[]) listeners; break; case ListenerType.PreCollectionRecreate: - eventListeners.PreCollectionRecreateEventListeners = (IPreCollectionRecreateEventListener[])listeners; + eventListeners.PreCollectionRecreateEventListeners = (IPreCollectionRecreateEventListener[]) listeners; break; case ListenerType.PreCollectionRemove: - eventListeners.PreCollectionRemoveEventListeners = (IPreCollectionRemoveEventListener[])listeners; + eventListeners.PreCollectionRemoveEventListeners = (IPreCollectionRemoveEventListener[]) listeners; break; case ListenerType.PreCollectionUpdate: - eventListeners.PreCollectionUpdateEventListeners = (IPreCollectionUpdateEventListener[])listeners; + eventListeners.PreCollectionUpdateEventListeners = (IPreCollectionUpdateEventListener[]) listeners; break; case ListenerType.PostCollectionRecreate: - eventListeners.PostCollectionRecreateEventListeners = (IPostCollectionRecreateEventListener[])listeners; + eventListeners.PostCollectionRecreateEventListeners = (IPostCollectionRecreateEventListener[]) listeners; break; case ListenerType.PostCollectionRemove: - eventListeners.PostCollectionRemoveEventListeners = (IPostCollectionRemoveEventListener[])listeners; + eventListeners.PostCollectionRemoveEventListeners = (IPostCollectionRemoveEventListener[]) listeners; break; case ListenerType.PostCollectionUpdate: - eventListeners.PostCollectionUpdateEventListeners = (IPostCollectionUpdateEventListener[])listeners; + eventListeners.PostCollectionUpdateEventListeners = (IPostCollectionUpdateEventListener[]) listeners; break; default: log.Warn("Unrecognized listener type [" + type + "]"); @@ -1922,13 +1915,13 @@ string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); - List<string> script = new List<string>(50); - foreach (Table table in TableMappings) + var script = new List<string>(50); + foreach (var table in TableMappings) { if (table.IsPhysicalTable) { ITableMetadata tableInfo = databaseMetadata.GetTableMetadata(table.Name, table.Schema ?? defaultSchema, - table.Catalog ?? defaultCatalog, table.IsQuoted); + table.Catalog ?? defaultCatalog, table.IsQuoted); if (tableInfo == null) { script.Add(table.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); @@ -1941,27 +1934,26 @@ string[] comments = table.SqlCommentStrings(dialect, defaultCatalog, defaultSchema); script.AddRange(comments); - } } - foreach (Table table in TableMappings) + foreach (var table in TableMappings) { if (table.IsPhysicalTable) { - ITableMetadata tableInfo = - databaseMetadata.GetTableMetadata(table.Name, table.Schema, table.Catalog, table.IsQuoted); + ITableMetadata tableInfo = databaseMetadata.GetTableMetadata(table.Name, table.Schema, table.Catalog, + table.IsQuoted); if (dialect.HasAlterTable) { - foreach (ForeignKey fk in table.ForeignKeyIterator) + foreach (var fk in table.ForeignKeyIterator) { if (fk.HasPhysicalConstraint) { - bool create = tableInfo == null || ( - tableInfo.GetForeignKeyMetadata(fk.Name) == null && - (!(dialect is MySQLDialect) || tableInfo.GetIndexMetadata(fk.Name) == null) - ); + bool create = tableInfo == null + || + (tableInfo.GetForeignKeyMetadata(fk.Name) == null + && (!(dialect is MySQLDialect) || tableInfo.GetIndexMetadata(fk.Name) == null)); if (create) { script.Add(fk.SqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); @@ -1969,11 +1961,10 @@ } } } - } } - foreach (IPersistentIdentifierGenerator generator in IterateGenerators(dialect)) + foreach (var generator in IterateGenerators(dialect)) { string key = generator.GeneratorKey(); if (!databaseMetadata.IsSequence(key) && !databaseMetadata.IsTable(key)) @@ -1991,38 +1982,41 @@ private IEnumerable<IPersistentIdentifierGenerator> IterateGenerators(Dialect.Dialect dialect) { - Dictionary<string, IPersistentIdentifierGenerator> generators = - new Dictionary<string, IPersistentIdentifierGenerator>(); + var generators = new Dictionary<string, IPersistentIdentifierGenerator>(); string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); - foreach (PersistentClass pc in classes.Values) + foreach (var pc in classes.Values) { if (!pc.IsInherited) { - IPersistentIdentifierGenerator ig = - pc.Identifier.CreateIdentifierGenerator(dialect, defaultCatalog, defaultSchema, (RootClass)pc) as + var ig = + pc.Identifier.CreateIdentifierGenerator(dialect, defaultCatalog, defaultSchema, (RootClass) pc) as IPersistentIdentifierGenerator; if (ig != null) + { generators[ig.GeneratorKey()] = ig; + } } } - foreach (NHibernate.Mapping.Collection collection in collections.Values) + foreach (var collection in collections.Values) { if (collection.IsIdentified) { - IPersistentIdentifierGenerator ig = - ((IdentifierCollection)collection).Identifier.CreateIdentifierGenerator(dialect, defaultCatalog, defaultSchema, - null) as IPersistentIdentifierGenerator; + var ig = + ((IdentifierCollection) collection).Identifier.CreateIdentifierGenerator(dialect, defaultCatalog, defaultSchema, + null) as IPersistentIdentifierGenerator; if (ig != null) + { generators[ig.GeneratorKey()] = ig; + } } } return generators.Values; } } -} +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/InvalidProxyTypeException.cs =================================================================== --- trunk/nhibernate/src/NHibernate/InvalidProxyTypeException.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate/InvalidProxyTypeException.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -3,6 +3,7 @@ using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; +using System.Collections.Generic; namespace NHibernate { @@ -14,22 +15,17 @@ [Serializable] public class InvalidProxyTypeException : MappingException { - private ICollection errors; - - public InvalidProxyTypeException(ICollection errors) + public InvalidProxyTypeException(ICollection<string> errors) : base(FormatMessage(errors)) { - this.errors = errors; + Errors = errors; } - public ICollection Errors - { - get { return errors; } - } + public ICollection<string> Errors { get; private set; } - private static string FormatMessage(ICollection errors) + private static string FormatMessage(IEnumerable<string> errors) { - StringBuilder result = new StringBuilder("The following types may not be used as proxies:"); + var result = new StringBuilder("The following types may not be used as proxies:"); foreach (string error in errors) { result.Append('\n').Append(error); @@ -42,7 +38,7 @@ public InvalidProxyTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { - this.errors = (ICollection) info.GetValue("errors", typeof(ICollection)); + Errors = (ICollection<string>)info.GetValue("errors", typeof(ICollection)); } [SecurityPermission(SecurityAction.LinkDemand, @@ -50,7 +46,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("errors", errors, typeof(ICollection)); + info.AddValue("errors", Errors, typeof(ICollection)); } #endregion Modified: trunk/nhibernate/src/NHibernate/Proxy/ProxyTypeValidator.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Proxy/ProxyTypeValidator.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate/Proxy/ProxyTypeValidator.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -1,6 +1,5 @@ -using System; using System.Collections; -using System.Collections.Specialized; +using System.Collections.Generic; using System.Reflection; using NHibernate.Util; @@ -8,9 +7,7 @@ { public class ProxyTypeValidator { - private ProxyTypeValidator() - { - } + private ProxyTypeValidator() {} /// <summary> /// Validates whether <paramref name="type"/> can be specified as the base class @@ -20,9 +17,9 @@ /// A collection of errors, if any, or <see langword="null" /> if none were found. /// </returns> /// <param name="type">The type to validate.</param> - public static ICollection ValidateType(System.Type type) + public static ICollection<string> ValidateType(System.Type type) { - StringCollection errors = new StringCollection(); + var errors = new List<string>(); if (type.IsInterface) { @@ -60,7 +57,7 @@ { if (member is PropertyInfo) { - PropertyInfo property = (PropertyInfo) member; + var property = (PropertyInfo) member; MethodInfo[] accessors = property.GetAccessors(false); foreach (MethodInfo accessor in accessors) @@ -70,8 +67,7 @@ } else if (member is MethodInfo) { - if (member.DeclaringType == typeof(object) - && member.Name == "GetType") + if (member.DeclaringType == typeof (object) && member.Name == "GetType") { // object.GetType is ignored continue; @@ -80,7 +76,7 @@ } else if (member is FieldInfo) { - FieldInfo memberField = (FieldInfo) member; + var memberField = (FieldInfo) member; if (memberField.IsPublic || memberField.IsAssembly || memberField.IsFamilyOrAssembly) { Error(errors, type, "field " + member.Name + " should not be public nor internal"); @@ -91,12 +87,12 @@ private static void CheckMethodIsVirtual(System.Type type, MethodInfo method, IList errors) { - if (method.DeclaringType != typeof(object) && !IsDisposeMethod(method) && - method.IsPublic || method.IsAssembly || method.IsFamilyOrAssembly) + if (method.DeclaringType != typeof (object) && !IsDisposeMethod(method) && method.IsPublic || method.IsAssembly + || method.IsFamilyOrAssembly) { - if (!method.IsVirtual || method.IsFinal) + if (!method.IsVirtual || method.IsFinal || (method.IsVirtual && method.IsAssembly)) { - Error(errors, type, "method " + method.Name + " should be virtual"); + Error(errors, type, "method " + method.Name + " should be 'public/protected virtual' or 'protected internal virtual'"); } } } @@ -108,12 +104,11 @@ private static bool HasVisibleDefaultConstructor(System.Type type) { - ConstructorInfo constructor = type.GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, - null, System.Type.EmptyTypes, null); + ConstructorInfo constructor = + type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, + System.Type.EmptyTypes, null); - return constructor != null - && !constructor.IsPrivate; + return constructor != null && !constructor.IsPrivate; } private static void CheckNotSealed(System.Type type, IList errors) @@ -124,4 +119,4 @@ } } } -} +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -92,8 +92,7 @@ // determine the id getter and setter methods from the proxy interface (if any) // determine all interfaces needed by the resulting proxy - HashedSet<System.Type> proxyInterfaces = new HashedSet<System.Type>(); - proxyInterfaces.Add(typeof(INHibernateProxy)); + var proxyInterfaces = new HashedSet<System.Type> {typeof (INHibernateProxy)}; System.Type _mappedClass = persistentClass.MappedClass; System.Type _proxyInterface = persistentClass.ProxyInterface; @@ -167,20 +166,18 @@ private static void LogPropertyAccessorsErrors(PersistentClass persistentClass) { // This method work when Environment.UseProxyValidator is off - System.Type clazz = persistentClass.MappedClass; foreach (Mapping.Property property in persistentClass.PropertyIterator) { MethodInfo method = property.GetGetter(clazz).Method; - // In NET if IsVirtual is false or IsFinal is true, then the method cannot be overridden. - if (method != null && (!method.IsVirtual || method.IsFinal)) + if (ShouldLogError(method)) { log.Error( string.Format("Getters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName, property.Name)); } method = property.GetSetter(clazz).Method; - if (method != null && (!method.IsVirtual || method.IsFinal)) + if (ShouldLogError(method)) { log.Error( string.Format("Setters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName, @@ -189,6 +186,12 @@ } } + private static bool ShouldLogError(MethodBase method) + { + // In NET if IsVirtual is false or IsFinal is true, then the method cannot be overridden. + return method != null && (!method.IsVirtual || method.IsFinal || (method.IsVirtual && method.IsAssembly)); + } + protected virtual IProxyFactory BuildProxyFactoryInternal(PersistentClass @class, IGetter getter, ISetter setter) { return Cfg.Environment.BytecodeProvider.ProxyFactoryFactory.BuildProxyFactory(); @@ -284,7 +287,7 @@ public override EntityMode EntityMode { - get { return NHibernate.EntityMode.Poco; } + get { return EntityMode.Poco; } } } } Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1408/DbResourceKey.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1408/DbResourceKey.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1408/DbResourceKey.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -31,7 +31,7 @@ public virtual DbResource Resource { get { return resource; } - internal set { resource = value; } + protected internal set { resource = value; } } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1464/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1464/Fixture.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1464/Fixture.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -1,8 +1,8 @@ using System; -using System.Collections; using NHibernate.Proxy; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; +using System.Collections.Generic; namespace NHibernate.Test.NHSpecificTest.NH1464 { @@ -61,7 +61,7 @@ [Test] public void NoExceptionForDispose() { - ICollection errs = ProxyTypeValidator.ValidateType(typeof (CPPMimic)); + ICollection<string> errs = ProxyTypeValidator.ValidateType(typeof (CPPMimic)); Assert.That(errs, Is.Null); errs = ProxyTypeValidator.ValidateType(typeof(Another)); Assert.That(errs, Is.Null); Added: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1515/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1515/Fixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/NH1515/Fixture.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using NHibernate.Proxy; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.NHSpecificTest.NH1515 +{ + [TestFixture] + public class Fixture + { + public class ClassWithInternal + { + internal virtual void DoSomething() {} + } + + public class ClassWithInternalProperty + { + internal virtual string DoSomething { get; set; } + } + + [Test] + public void NoExceptionForMethod() + { + ICollection<string> errs = ProxyTypeValidator.ValidateType(typeof(ClassWithInternal)); + Assert.That(errs, Is.Not.Null); + Assert.That(errs.Count, Is.EqualTo(1)); + } + + [Test] + public void NoExceptionForProperty() + { + ICollection<string> errs = ProxyTypeValidator.ValidateType(typeof(ClassWithInternalProperty)); + Assert.That(errs, Is.Not.Null); + Assert.That(errs.Count, Is.EqualTo(2)); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/ProxyValidator/Fixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/ProxyValidator/Fixture.cs 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate.Test/NHSpecificTest/ProxyValidator/Fixture.cs 2008-10-11 12:59:51 UTC (rev 3842) @@ -2,6 +2,7 @@ using System.Collections; using NHibernate.Proxy; using NUnit.Framework; +using System.Collections.Generic; namespace NHibernate.Test.NHSpecificTest.ProxyValidator { @@ -10,7 +11,7 @@ { private void Validate(System.Type type) { - ICollection errors = ProxyTypeValidator.ValidateType(type); + ICollection<string> errors = ProxyTypeValidator.ValidateType(type); if (errors != null) { throw new InvalidProxyTypeException(errors); Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-11 05:54:37 UTC (rev 3841) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-11 12:59:51 UTC (rev 3842) @@ -507,6 +507,7 @@ <Compile Include="NHSpecificTest\NH1508\Document.cs" /> <Compile Include="NHSpecificTest\NH1508\Fixture.cs" /> <Compile Include="NHSpecificTest\NH1508\Person.cs" /> + <Compile Include="NHSpecificTest\NH1515\Fixture.cs" /> <Compile Include="NHSpecificTest\NH280\Fixture.cs" /> <Compile Include="NHSpecificTest\NH280\Foo.cs" /> <Compile Include="NHSpecificTest\NH1018\Employee.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-11 05:54:45
|
Revision: 3841 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3841&view=rev Author: ayenderahien Date: 2008-10-11 05:54:37 +0000 (Sat, 11 Oct 2008) Log Message: ----------- fixing broken build Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs 2008-10-11 04:46:05 UTC (rev 3840) +++ trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs 2008-10-11 05:54:37 UTC (rev 3841) @@ -114,8 +114,8 @@ { StringBuilder qualifiedName = new StringBuilder(); bool quoted = false; - - if (!string.IsNullOrEmpty(catalog)) + + if (!string.IsNullOrEmpty(catalog)) { if (catalog.StartsWith(OpenQuote.ToString())) { @@ -133,12 +133,12 @@ { if (schema.StartsWith(OpenQuote.ToString())) { - schema = schema.Substring(0, schema.Length - 1); + schema = schema.Substring(1, schema.Length - 1); quoted = true; } - if (schema.EndsWith(OpenQuote.ToString())) + if (schema.EndsWith(CloseQuote.ToString())) { - schema = schema.Substring(1, schema.Length - 1); + schema = schema.Substring(0, schema.Length - 1); quoted = true; } qualifiedName.Append(schema).Append(StringHelper.Underscore); @@ -149,7 +149,7 @@ table = table.Substring(1, table.Length - 1); quoted = true; } - if (table.EndsWith(OpenQuote.ToString())) + if (table.EndsWith(CloseQuote.ToString())) { table = table.Substring(0, table.Length - 1); quoted = true; Modified: trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-11 04:46:05 UTC (rev 3840) +++ trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-11 05:54:37 UTC (rev 3841) @@ -31,7 +31,7 @@ Assert.AreEqual("SELECT id, name, email FROM Users limit 10, 5", s.ToString()); } - [Test, Ignore("was broken in r3839")] + [Test] public void QuotedSchemaNameWithSqlLite() { Table tbl = new Table(); @@ -39,7 +39,7 @@ tbl.Name = "`name`"; Assert.AreEqual("\"schema_name\"", tbl.GetQualifiedName(dialect)); - Assert.AreEqual("\"schema_table\"", dialect.Qualify("","\"schema\"", "\"table\"")); + Assert.AreEqual("\"schema_table\"", dialect.Qualify("", "\"schema\"", "\"table\"")); } [Test] @@ -51,8 +51,8 @@ Assert.AreEqual("\"name\"", tbl.GetQualifiedName(dialect)); } - [Test, Ignore("was broken in r3839")] - public void QuotedSchemaNameWithUnqoutedTableInSqlLite() + [Test] + public void QuotedSchemaNameWithUnqoutedTableInSqlLite() { Table tbl = new Table(); tbl.Schema = "`schema`"; @@ -62,8 +62,8 @@ Assert.AreEqual("\"schema_table\"", dialect.Qualify("", "\"schema\"", "table")); } - [Test, Ignore("was broken in r3839")] - public void QuotedCatalogSchemaNameWithSqlLite() + [Test] + public void QuotedCatalogSchemaNameWithSqlLite() { Table tbl = new Table(); tbl.Catalog = "dbo"; @@ -92,7 +92,7 @@ tbl.Name = "name"; Assert.AreEqual("schema_name", tbl.GetQualifiedName(dialect)); - Assert.AreEqual("schema_table", dialect.Qualify("","schema","table")); + Assert.AreEqual("schema_table", dialect.Qualify("", "schema", "table")); } } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-11 04:46:11
|
Revision: 3840 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3840&view=rev Author: fabiomaulo Date: 2008-10-11 04:46:05 +0000 (Sat, 11 Oct 2008) Log Message: ----------- - Moved ProxyFactoryFactory to a more appropriate namespace - Removed dependency from Castle/DefaultProxyFactoryFactory in actual Bytecode providers - Changed to ignore some broken test (SQLiteDialectFixture was broken in r3839) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs trunk/nhibernate/src/NHibernate/Cfg/Environment.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs Added Paths: ----------- trunk/nhibernate/src/NHibernate/Bytecode/Castle/ trunk/nhibernate/src/NHibernate/Bytecode/Castle/DefaultProxyFactoryFactory.cs Removed Paths: ------------- trunk/nhibernate/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs Copied: trunk/nhibernate/src/NHibernate/Bytecode/Castle/DefaultProxyFactoryFactory.cs (from rev 3839, trunk/nhibernate/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs) =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/Castle/DefaultProxyFactoryFactory.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Bytecode/Castle/DefaultProxyFactoryFactory.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -0,0 +1,17 @@ +using NHibernate.Proxy; +using NHibernate.Proxy.Poco.Castle; + +namespace NHibernate.Bytecode.Castle +{ + public class DefaultProxyFactoryFactory : IProxyFactoryFactory + { + #region IProxyFactoryFactory Members + + public IProxyFactory BuildProxyFactory() + { + return new CastleProxyFactory(); + } + + #endregion + } +} \ No newline at end of file Property changes on: trunk/nhibernate/src/NHibernate/Bytecode/Castle/DefaultProxyFactoryFactory.cs ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate/Bytecode/CodeDom/BytecodeProviderImpl.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -5,24 +5,40 @@ using log4net; using Microsoft.CSharp; using NHibernate.Properties; +using NHibernate.Util; namespace NHibernate.Bytecode.CodeDom { /// <summary> /// CodeDOM-based bytecode provider. /// </summary> - public class BytecodeProviderImpl : IBytecodeProvider + public class BytecodeProviderImpl : IBytecodeProvider, IInjectableProxyFactoryFactory { - private static readonly ILog log = LogManager.GetLogger(typeof(BytecodeProviderImpl)); + private static readonly ILog log = LogManager.GetLogger(typeof (BytecodeProviderImpl)); + private System.Type proxyFactoryFactory; #region IBytecodeProvider Members public IProxyFactoryFactory ProxyFactoryFactory { - get { return new DefaultProxyFactoryFactory(); } + get + { + if (proxyFactoryFactory != null) + { + try + { + return (IProxyFactoryFactory) Activator.CreateInstance(proxyFactoryFactory); + } + catch (Exception e) + { + throw new HibernateException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); + } + } + + throw new HibernateException("The ProxyFactoryFactory was not configured. Initialize the 'proxyfactory.factory_class' property of the session-factory section."); + } } - public IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) { if (clazz.IsValueType) @@ -36,13 +52,72 @@ #endregion + #region Implementation of IInjectableProxyFactoryFactory + + public void SetProxyFactoryFactory(string typeName) + { + System.Type pffc; + try + { + pffc = ReflectHelper.ClassForName(typeName); + } + catch (HibernateException he) + { + throw new HibernateException("Unable to load type '" + typeName + "' during configuration of proxy factory class.", + he); + } + + if (typeof (IProxyFactoryFactory).IsAssignableFrom(pffc) == false) + { + var he = new HibernateException(pffc.FullName + " does not implement " + typeof (IProxyFactoryFactory).FullName); + throw he; + } + proxyFactoryFactory = pffc; + } + + #endregion + + #region Nested type: Generator + public class Generator { - private CompilerParameters cp = new CompilerParameters(); - private System.Type mappedClass; - private IGetter[] getters; - private ISetter[] setters; + private const string classDef = + @"public class GetSetHelper_{0} : IReflectionOptimizer, IAccessOptimizer {{ + ISetter[] setters; + IGetter[] getters; + + public GetSetHelper_{0}(ISetter[] setters, IGetter[] getters) {{ + this.setters = setters; + this.getters = getters; + }} + public IInstantiationOptimizer InstantiationOptimizer {{ + get {{ return null; }} + }} + + public IAccessOptimizer AccessOptimizer {{ + get {{ return this; }} + }} + "; + + private const string closeGetMethod = " return ret;\n" + "}\n"; + private const string closeSetMethod = "}\n"; + + private const string header = + "using System;\n" + "using NHibernate.Property;\n" + "namespace NHibernate.Bytecode.CodeDom {\n"; + + private const string startGetMethod = + "public object[] GetPropertyValues(object obj) {{\n" + " {0} t = ({0})obj;\n" + + " object[] ret = new object[{1}];\n"; + + private const string startSetMethod = + "public void SetPropertyValues(object obj, object[] values) {{\n" + " {0} t = ({0})obj;\n"; + + private readonly CompilerParameters cp = new CompilerParameters(); + private readonly IGetter[] getters; + private readonly System.Type mappedClass; + private readonly ISetter[] setters; + /// <summary> /// ctor /// </summary> @@ -106,7 +181,10 @@ /// <param name="name"></param> private void AddAssembly(string name) { - if (name.StartsWith("System.")) return; + if (name.StartsWith("System.")) + { + return; + } if (!cp.ReferencedAssemblies.Contains(name)) { @@ -126,17 +204,14 @@ private IReflectionOptimizer Build(string code) { CodeDomProvider provider = new CSharpCodeProvider(); - CompilerResults res = provider.CompileAssemblyFromSource(cp, new string[] {code}); + CompilerResults res = provider.CompileAssemblyFromSource(cp, new[] {code}); if (res.Errors.HasErrors) { log.Debug("Compiled with error:\n" + code); foreach (CompilerError e in res.Errors) { - log.Debug( - String.Format("Line:{0}, Column:{1} Message:{2}", - e.Line, e.Column, e.ErrorText) - ); + log.Debug(String.Format("Line:{0}, Column:{1} Message:{2}", e.Line, e.Column, e.ErrorText)); } throw new InvalidOperationException(res.Errors[0].ErrorText); } @@ -150,54 +225,14 @@ Assembly assembly = res.CompiledAssembly; System.Type[] types = assembly.GetTypes(); - IReflectionOptimizer optimizer = (IReflectionOptimizer) assembly.CreateInstance(types[0].FullName, false, - BindingFlags.CreateInstance, null, - new object[] {setters, getters}, - null, null); + var optimizer = + (IReflectionOptimizer) + assembly.CreateInstance(types[0].FullName, false, BindingFlags.CreateInstance, null, + new object[] {setters, getters}, null, null); return optimizer; } - private const string header = - "using System;\n" + - "using NHibernate.Property;\n" + - "namespace NHibernate.Bytecode.CodeDom {\n"; - - private const string classDef = - @"public class GetSetHelper_{0} : IReflectionOptimizer, IAccessOptimizer {{ - ISetter[] setters; - IGetter[] getters; - - public GetSetHelper_{0}(ISetter[] setters, IGetter[] getters) {{ - this.setters = setters; - this.getters = getters; - }} - - public IInstantiationOptimizer InstantiationOptimizer {{ - get {{ return null; }} - }} - - public IAccessOptimizer AccessOptimizer {{ - get {{ return this; }} - }} - "; - - private const string startSetMethod = - "public void SetPropertyValues(object obj, object[] values) {{\n" + - " {0} t = ({0})obj;\n"; - - private const string closeSetMethod = - "}\n"; - - private const string startGetMethod = - "public object[] GetPropertyValues(object obj) {{\n" + - " {0} t = ({0})obj;\n" + - " object[] ret = new object[{1}];\n"; - - private const string closeGetMethod = - " return ret;\n" + - "}\n"; - /// <summary> /// Check if the property is public /// </summary> @@ -218,7 +253,7 @@ /// <returns>C# code</returns> private string GenerateCode() { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append(header); sb.AppendFormat(classDef, mappedClass.FullName.Replace('.', '_').Replace("+", "__")); @@ -234,18 +269,12 @@ if (type.IsValueType) { - sb.AppendFormat( - " t.{0} = values[{2}] == null ? new {1}() : ({1})values[{2}];\n", - setter.PropertyName, - type.FullName.Replace('+', '.'), - i); + sb.AppendFormat(" t.{0} = values[{2}] == null ? new {1}() : ({1})values[{2}];\n", setter.PropertyName, + type.FullName.Replace('+', '.'), i); } else { - sb.AppendFormat(" t.{0} = ({1})values[{2}];\n", - setter.PropertyName, - type.FullName.Replace('+', '.'), - i); + sb.AppendFormat(" t.{0} = ({1})values[{2}];\n", setter.PropertyName, type.FullName.Replace('+', '.'), i); } } else @@ -276,5 +305,7 @@ return sb.ToString(); } } + + #endregion } -} +} \ No newline at end of file Deleted: trunk/nhibernate/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -1,17 +0,0 @@ -using NHibernate.Proxy; -using NHibernate.Proxy.Poco.Castle; - -namespace NHibernate.Bytecode -{ - public class DefaultProxyFactoryFactory : IProxyFactoryFactory - { - #region IProxyFactoryFactory Members - - public IProxyFactory BuildProxyFactory() - { - return new CastleProxyFactory(); - } - - #endregion - } -} Modified: trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -33,7 +33,7 @@ throw new HibernateException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); } } - return new DefaultProxyFactoryFactory(); + throw new HibernateException("The ProxyFactoryFactory was not configured. Initialize the 'proxyfactory.factory_class' property of the session-factory section."); } } Modified: trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate/Bytecode/NullBytecodeProvider.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -1,4 +1,6 @@ +using System; using NHibernate.Properties; +using NHibernate.Util; namespace NHibernate.Bytecode { @@ -6,20 +8,61 @@ /// A <see cref="IBytecodeProvider" /> implementation that returns /// <see langword="null" />, disabling reflection optimization. /// </summary> - public class NullBytecodeProvider : IBytecodeProvider + public class NullBytecodeProvider : IBytecodeProvider, IInjectableProxyFactoryFactory { + private System.Type proxyFactoryFactory; + #region IBytecodeProvider Members public IProxyFactoryFactory ProxyFactoryFactory { - get { return new DefaultProxyFactoryFactory(); } + get + { + if (proxyFactoryFactory != null) + { + try + { + return (IProxyFactoryFactory) Activator.CreateInstance(proxyFactoryFactory); + } + catch (Exception e) + { + throw new HibernateException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); + } + } + throw new HibernateException("The ProxyFactoryFactory was not configured. Initialize the 'proxyfactory.factory_class' property of the session-factory section."); + } } - #endregion - public IReflectionOptimizer GetReflectionOptimizer(System.Type clazz, IGetter[] getters, ISetter[] setters) { return null; } + + #endregion + + #region Implementation of IInjectableProxyFactoryFactory + + public void SetProxyFactoryFactory(string typeName) + { + System.Type pffc; + try + { + pffc = ReflectHelper.ClassForName(typeName); + } + catch (HibernateException he) + { + throw new HibernateException("Unable to load type '" + typeName + "' during configuration of proxy factory class.", + he); + } + + if (typeof (IProxyFactoryFactory).IsAssignableFrom(pffc) == false) + { + var he = new HibernateException(pffc.FullName + " does not implement " + typeof (IProxyFactoryFactory).FullName); + throw he; + } + proxyFactoryFactory = pffc; + } + + #endregion } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Cfg/Environment.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate/Cfg/Environment.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -4,8 +4,9 @@ using System.Reflection; using log4net; using NHibernate.Bytecode; +using NHibernate.Bytecode.CodeDom; +using NHibernate.Cfg.ConfigurationSchema; using NHibernate.Util; -using NHibernate.Cfg.ConfigurationSchema; namespace NHibernate.Cfg { @@ -34,7 +35,7 @@ /// Properties in hibernate.cfg.xml override/merge properties in application configuration file where same /// property is found. For others configuration a merge is applied. /// </remarks> - public sealed class Environment + public static class Environment { private static string cachedVersion; @@ -48,9 +49,9 @@ if (cachedVersion == null) { Assembly thisAssembly = Assembly.GetExecutingAssembly(); - AssemblyInformationalVersionAttribute[] attrs = (AssemblyInformationalVersionAttribute[]) - thisAssembly.GetCustomAttributes( - typeof(AssemblyInformationalVersionAttribute), false); + var attrs = + (AssemblyInformationalVersionAttribute[]) + thisAssembly.GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false); if (attrs != null && attrs.Length > 0) { @@ -80,8 +81,10 @@ public const string SessionFactoryName = "session_factory_name"; public const string Dialect = "dialect"; + /// <summary> A default database schema (owner) name to use for unqualified tablenames</summary> public const string DefaultSchema = "default_schema"; + /// <summary> A default database catalog name to use for unqualified tablenames</summary> public const string DefaultCatalog = "default_catalog"; @@ -156,16 +159,14 @@ private static IBytecodeProvider BytecodeProviderInstance; private static bool EnableReflectionOptimizer; - private static readonly ILog log = LogManager.GetLogger(typeof(Environment)); + private static readonly ILog log = LogManager.GetLogger(typeof (Environment)); /// <summary> /// Issue warnings to user when any obsolete property names are used. /// </summary> /// <param name="props"></param> /// <returns></returns> - public static void VerifyProperties(IDictionary<string, string> props) - { - } + public static void VerifyProperties(IDictionary<string, string> props) {} static Environment() { @@ -177,6 +178,7 @@ GlobalProperties = new Dictionary<string, string>(); GlobalProperties[PropertyUseReflectionOptimizer] = bool.TrueString; + SetDefaultProxyFactoryFactory(); LoadGlobalPropertiesFromAppConfig(); VerifyProperties(GlobalProperties); @@ -189,6 +191,12 @@ } } + private static void SetDefaultProxyFactoryFactory() + { + // maitaining the optionality of set the proxyfactory.factory_class property + GlobalProperties[ProxyFactoryFactoryClass] = "NHibernate.Bytecode.Castle.DefaultProxyFactoryFactory, NHibernate"; + } + private static void LoadGlobalPropertiesFromAppConfig() { object config = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName); @@ -199,16 +207,19 @@ return; } - IHibernateConfiguration NHconfig = config as IHibernateConfiguration; - if (NHconfig == null) + var nhConfig = config as IHibernateConfiguration; + if (nhConfig == null) { - log.Info(string.Format("{0} section handler, in application configuration file, is not IHibernateConfiguration, section ignored", CfgXmlHelper.CfgSectionName)); + log.Info( + string.Format( + "{0} section handler, in application configuration file, is not IHibernateConfiguration, section ignored", + CfgXmlHelper.CfgSectionName)); return; } - GlobalProperties[PropertyBytecodeProvider] = CfgXmlHelper.ByteCodeProviderToString(NHconfig.ByteCodeProviderType); - GlobalProperties[PropertyUseReflectionOptimizer] = NHconfig.UseReflectionOptimizer.ToString(); - foreach (KeyValuePair<string, string> kvp in NHconfig.SessionFactory.Properties) + GlobalProperties[PropertyBytecodeProvider] = CfgXmlHelper.ByteCodeProviderToString(nhConfig.ByteCodeProviderType); + GlobalProperties[PropertyUseReflectionOptimizer] = nhConfig.UseReflectionOptimizer.ToString(); + foreach (KeyValuePair<string, string> kvp in nhConfig.SessionFactory.Properties) { GlobalProperties[kvp.Key] = kvp.Value; } @@ -221,23 +232,28 @@ // Save values loaded and used in static constructor if (GlobalProperties.ContainsKey(PropertyBytecodeProvider)) + { savedBytecodeProvider = GlobalProperties[PropertyBytecodeProvider]; + } if (GlobalProperties.ContainsKey(PropertyUseReflectionOptimizer)) + { savedUseReflectionOptimizer = GlobalProperties[PropertyUseReflectionOptimizer]; + } // Clean all property loaded from app.config GlobalProperties.Clear(); // Restore values loaded and used in static constructor if (savedBytecodeProvider != null) + { GlobalProperties[PropertyBytecodeProvider] = savedBytecodeProvider; + } if (savedUseReflectionOptimizer != null) + { GlobalProperties[PropertyUseReflectionOptimizer] = savedUseReflectionOptimizer; - } + } - private Environment() - { - // should not be created. + SetDefaultProxyFactoryFactory(); } /// <summary> @@ -252,12 +268,6 @@ get { return new Dictionary<string, string>(GlobalProperties); } } - [Obsolete] - public static bool UseStreamsForBinary - { - get { return true; } - } - /// <summary> /// The bytecode provider to use. /// </summary> @@ -294,9 +304,8 @@ public static IBytecodeProvider BuildBytecodeProvider(IDictionary<string, string> properties) { - string defaultBytecodeProvider = "lcg"; - string provider = PropertiesHelper.GetString(PropertyBytecodeProvider, properties, - defaultBytecodeProvider); + const string defaultBytecodeProvider = "lcg"; + string provider = PropertiesHelper.GetString(PropertyBytecodeProvider, properties, defaultBytecodeProvider); log.Info("Bytecode provider name : " + provider); return BuildBytecodeProvider(provider); } @@ -306,7 +315,7 @@ switch (providerName) { case "codedom": - return new Bytecode.CodeDom.BytecodeProviderImpl(); + return new BytecodeProviderImpl(); case "lcg": return new Bytecode.Lightweight.BytecodeProviderImpl(); case "null": @@ -317,4 +326,4 @@ } } } -} +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-10-11 04:46:05 UTC (rev 3840) @@ -452,7 +452,7 @@ <Compile Include="AdoNet\TooManyRowsAffectedException.cs" /> <Compile Include="Properties\BackFieldStrategy.cs" /> <Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" /> - <Compile Include="Bytecode\DefaultProxyFactoryFactory.cs" /> + <Compile Include="Bytecode\Castle\DefaultProxyFactoryFactory.cs" /> <Compile Include="Bytecode\IAccessOptimizer.cs" /> <Compile Include="Bytecode\IBytecodeProvider.cs" /> <Compile Include="Bytecode\IInjectableProxyFactoryFactory.cs" /> Modified: trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-11 00:01:33 UTC (rev 3839) +++ trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-11 04:46:05 UTC (rev 3840) @@ -31,7 +31,7 @@ Assert.AreEqual("SELECT id, name, email FROM Users limit 10, 5", s.ToString()); } - [Test] + [Test, Ignore("was broken in r3839")] public void QuotedSchemaNameWithSqlLite() { Table tbl = new Table(); @@ -51,8 +51,8 @@ Assert.AreEqual("\"name\"", tbl.GetQualifiedName(dialect)); } - [Test] - public void QuotedSchemaNameWithUnqoutedTableInSqlLite() + [Test, Ignore("was broken in r3839")] + public void QuotedSchemaNameWithUnqoutedTableInSqlLite() { Table tbl = new Table(); tbl.Schema = "`schema`"; @@ -62,8 +62,8 @@ Assert.AreEqual("\"schema_table\"", dialect.Qualify("", "\"schema\"", "table")); } - [Test] - public void QuotedCatalogSchemaNameWithSqlLite() + [Test, Ignore("was broken in r3839")] + public void QuotedCatalogSchemaNameWithSqlLite() { Table tbl = new Table(); tbl.Catalog = "dbo"; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-11 00:01:43
|
Revision: 3839 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3839&view=rev Author: ayenderahien Date: 2008-10-11 00:01:33 +0000 (Sat, 11 Oct 2008) Log Message: ----------- NH-1520 SQLite Dialect does not properly escape names surrounded by backticks (should learn to commit to the right branch) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs Modified: trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs 2008-10-10 23:34:34 UTC (rev 3838) +++ trunk/nhibernate/src/NHibernate/Dialect/SQLiteDialect.cs 2008-10-11 00:01:33 UTC (rev 3839) @@ -113,24 +113,52 @@ public override string Qualify(string catalog, string schema, string table) { StringBuilder qualifiedName = new StringBuilder(); + bool quoted = false; if (!string.IsNullOrEmpty(catalog)) { - if (catalog.EndsWith(CloseQuote.ToString())) - catalog = catalog.Substring(0, catalog.Length - 1); + if (catalog.StartsWith(OpenQuote.ToString())) + { + catalog = catalog.Substring(1, catalog.Length - 1); + quoted = true; + } + if (catalog.EndsWith(CloseQuote.ToString())) + { + catalog = catalog.Substring(0, catalog.Length - 1); + quoted = true; + } qualifiedName.Append(catalog).Append(StringHelper.Underscore); } if (!string.IsNullOrEmpty(schema)) { if (schema.StartsWith(OpenQuote.ToString())) - schema = schema.Substring(0, schema.Length - 1); - qualifiedName.Append(schema).Append(StringHelper.Underscore); + { + schema = schema.Substring(0, schema.Length - 1); + quoted = true; + } + if (schema.EndsWith(OpenQuote.ToString())) + { + schema = schema.Substring(1, schema.Length - 1); + quoted = true; + } + qualifiedName.Append(schema).Append(StringHelper.Underscore); } if (table.StartsWith(OpenQuote.ToString())) - table = table.Substring(1, table.Length - 1); + { + table = table.Substring(1, table.Length - 1); + quoted = true; + } + if (table.EndsWith(OpenQuote.ToString())) + { + table = table.Substring(0, table.Length - 1); + quoted = true; + } - return qualifiedName.Append(table).ToString(); + string name = qualifiedName.Append(table).ToString(); + if (quoted) + return OpenQuote + name + CloseQuote; + return name; } Modified: trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-10 23:34:34 UTC (rev 3838) +++ trunk/nhibernate/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-11 00:01:33 UTC (rev 3839) @@ -43,6 +43,48 @@ } [Test] + public void QuotedTableNameWithoutSchemaWithSqlLite() + { + Table tbl = new Table(); + tbl.Name = "`name`"; + + Assert.AreEqual("\"name\"", tbl.GetQualifiedName(dialect)); + } + + [Test] + public void QuotedSchemaNameWithUnqoutedTableInSqlLite() + { + Table tbl = new Table(); + tbl.Schema = "`schema`"; + tbl.Name = "name"; + + Assert.AreEqual("\"schema_name\"", tbl.GetQualifiedName(dialect)); + Assert.AreEqual("\"schema_table\"", dialect.Qualify("", "\"schema\"", "table")); + } + + [Test] + public void QuotedCatalogSchemaNameWithSqlLite() + { + Table tbl = new Table(); + tbl.Catalog = "dbo"; + tbl.Schema = "`schema`"; + tbl.Name = "`name`"; + + Assert.AreEqual("\"dbo_schema_name\"", tbl.GetQualifiedName(dialect)); + Assert.AreEqual("\"dbo_schema_table\"", dialect.Qualify("dbo", "\"schema\"", "\"table\"")); + } + + [Test] + public void QuotedTableNameWithSqlLite() + { + Table tbl = new Table(); + tbl.Name = "`Group`"; + + Assert.AreEqual("\"Group\"", tbl.GetQualifiedName(dialect)); + } + + + [Test] public void SchemaNameWithSqlLite() { Table tbl = new Table(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 23:34:41
|
Revision: 3838 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3838&view=rev Author: fabiomaulo Date: 2008-10-10 23:34:34 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Improved test Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs Modified: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 22:41:30 UTC (rev 3837) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 23:34:34 UTC (rev 3838) @@ -1,7 +1,12 @@ +using System; using System.Collections; using System.Xml; using NHibernate.Cfg; +using NHibernate.Criterion; +using NHibernate.Transform; using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; +using Environment=NHibernate.Cfg.Environment; namespace NHibernate.Test.EntityModeTest.Xml.Basic { @@ -13,8 +18,6 @@ get { return "NHibernate.Test"; } } - #region Overrides of TestCase - protected override IList Mappings { get @@ -27,18 +30,227 @@ } } - #endregion - protected override void Configure(Configuration configuration) { cfg.SetProperty(Environment.DefaultEntityMode, EntityModeHelper.ToString(EntityMode.Xml)); } + public void Xml() + { + string xml = + @"<account id='acb123'> + <balance>123.45</balance> + <customer id='xyz123'> + <stuff> + <foo bar='x'>foo</foo> + <foo bar='y'>bar</foo> + </stuff> + <amount>45</amount> + An example customer + <name> + <first>Fabio</first> + <last>Maulo</last> + </name> + </customer> +</account>"; + var doc1 = new XmlDocument(); + doc1.LoadXml(xml); + XmlElement acct = doc1.DocumentElement; + var cust = (XmlElement) acct.SelectSingleNode("customer"); + + xml = @"<location> + <address>Karbarook Avenue</address> +</location>"; + var doc2 = new XmlDocument(); + doc2.LoadXml(xml); + XmlElement loc = doc2.DocumentElement; + + Print(acct); + + ISession s = OpenSession(); + ITransaction t = s.BeginTransaction(); + s.Persist("Location", loc); + XmlElement eLocation = cust.OwnerDocument.CreateElement("location"); + eLocation.SetAttribute("id", "id"); + cust.AppendChild(eLocation); + s.Persist("Account", acct); + t.Commit(); + s.Close(); + + Print(loc); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.Get("Customer", "xyz123"); + Print(cust); + acct = (XmlElement) s.Get("Account", "abc123"); + Print(acct); + Assert.AreEqual(acct.SelectSingleNode("customer"), cust); + cust.SelectSingleNode("name").SelectSingleNode("first").InnerText = "Gavin A"; + + XmlElement foo3 = cust.OwnerDocument.CreateElement("foo"); + cust.SelectSingleNode("stuff").AppendChild(foo3); + foo3.InnerText = "baz"; + foo3.SetAttribute("bar", "z"); + cust.SelectSingleNode("amount").InnerText = "3"; + XmlElement eamount = cust.OwnerDocument.CreateElement("amount"); + eamount.InnerText = "56"; + cust.AppendChild(eamount); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + acct.SelectSingleNode("balance").InnerText = "3456.12"; + XmlElement eaddress = cust.OwnerDocument.CreateElement("address"); + eaddress.InnerText = "Karbarook Ave"; + cust.AppendChild(eaddress); + + Assert.AreEqual(acct.SelectSingleNode("customer"), cust); + + cust.InnerText = "Still the same example!"; + + s = OpenSession(); + t = s.BeginTransaction(); + s.SaveOrUpdate("Account", acct); + t.Commit(); + s.Close(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.Get("Customer", "xyz123"); + Print(cust); + acct = (XmlElement) s.Get("Account", "abc123"); + Print(acct); + Assert.AreEqual(acct.SelectSingleNode("customer"), cust); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.CreateCriteria("Customer").Add(Example.Create(cust)).UniqueResult(); + Print(cust); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + acct = (XmlElement) s.CreateQuery("from Account a left join fetch a.customer").UniqueResult(); + Print(acct); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + var m = + (IDictionary) + s.CreateQuery("select a as acc from Account a left join fetch a.customer").SetResultTransformer( + Transformers.AliasToEntityMap).UniqueResult(); + acct = (XmlElement) m["acc"]; + Print(acct); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + acct = (XmlElement) s.CreateQuery("from Account").UniqueResult(); + Print(acct); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.CreateQuery("from Customer c left join fetch c.stuff").UniqueResult(); + Print(cust); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.CreateQuery("from Customer c left join fetch c.morestuff").UniqueResult(); + Print(cust); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.CreateQuery("from Customer c left join fetch c.morestuff").UniqueResult(); + Print(cust); + cust = (XmlElement) s.CreateQuery("from Customer c left join fetch c.stuff").UniqueResult(); + Print(cust); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.CreateQuery("from Customer c left join fetch c.accounts").UniqueResult(); + XmlElement a1 = cust.OwnerDocument.CreateElement("account"); + XmlElement b1 = a1.OwnerDocument.CreateElement("balance"); + b1.InnerText = "12.67"; + a1.AppendChild(b1); + a1.SetAttribute("id", "lkj345"); + a1.SetAttribute("acnum", "0"); + cust.SelectSingleNode("accounts").AppendChild(a1); + + XmlElement a2 = cust.OwnerDocument.CreateElement("account"); + XmlElement b2 = a1.OwnerDocument.CreateElement("balance"); + b2.InnerText = "10000.00"; + a2.AppendChild(b2); + a2.SetAttribute("id", "hsh987"); + a2.SetAttribute("acnum", "1"); + cust.SelectSingleNode("accounts").AppendChild(a2); + + Print(cust); + t.Commit(); + s.Close(); + + Console.WriteLine(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.CreateQuery("from Customer c left join fetch c.accounts").UniqueResult(); + Print(cust); + t.Commit(); + s.Close(); + + // clean up + s = OpenSession(); + t = s.BeginTransaction(); + s.Delete("Account", acct); + s.Delete("Location", loc); + s.Delete("from Account"); + t.Commit(); + s.Close(); + } + + public static void Print(XmlNode elt) + { + Console.WriteLine("============"); + Console.WriteLine(elt.OuterXml); + Console.WriteLine("============"); + } + [Test] public void CompositeId() { const string xml = -@"<a id='1'> + @"<a id='1'> <x>foo bar</x> <b bId='1' aId='1>foo foo</b> <b bId='2' aId='1>bar bar</b> @@ -55,7 +267,7 @@ s = OpenSession(); t = s.BeginTransaction(); - a = (XmlElement)s.CreateCriteria("A").UniqueResult(); + a = (XmlElement) s.CreateCriteria("A").UniqueResult(); Assert.AreEqual(a.GetElementsByTagName("b").Count, 2); Print(a); s.Delete("A", a); @@ -63,9 +275,64 @@ s.Close(); } - public static void Print(XmlElement elt) + [Test] + public void MapIndexEmision() { - //XMLHelper.dump( elt ); + string xml = + @"<account id='acb123'> + <balance>123.45</balance> + <customer id='xyz123'> + <stuff> + <foo bar='x'>foo</foo> + <foo bar='y'>bar</foo> + </stuff> + <amount>45</amount> + An example customer + <name> + <first>Fabio</first> + <last>Maulo</last> + </name> + </customer> +</account>"; + var doc1 = new XmlDocument(); + doc1.LoadXml(xml); + XmlElement acct = doc1.DocumentElement; + var cust = (XmlElement) acct.SelectSingleNode("customer"); + Print(acct); + + xml = @"<location> + <address>Karbarook Avenue</address> +</location>"; + var doc2 = new XmlDocument(); + doc2.LoadXml(xml); + XmlElement loc = doc2.DocumentElement; + + ISession s = OpenSession(); + ITransaction t = s.BeginTransaction(); + s.Persist("Location", loc); + XmlElement loc1 = cust.OwnerDocument.CreateElement("location"); + loc1.SetAttribute("id", "id"); + cust.AppendChild(loc1); + s.Persist("Account", acct); + t.Commit(); + s.Close(); + + s = OpenSession(); + t = s.BeginTransaction(); + cust = (XmlElement) s.Get("Customer", "xyz123"); + Print(cust); + Assert.AreEqual(2, cust.SelectSingleNode("stuff").SelectNodes("foo").Count, "Incorrect stuff-map size"); + var stuffElement = (XmlElement) cust.SelectSingleNode("stuff").SelectNodes("foo")[0]; + Assert.That(stuffElement.Attributes["bar"], Is.Not.Null, "No map-key value present"); + t.Commit(); + s.Close(); + + s = OpenSession(); + t = s.BeginTransaction(); + s.Delete("Account", acct); + s.Delete("Location", loc); + t.Commit(); + s.Close(); } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-10 22:41:39
|
Revision: 3837 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3837&view=rev Author: ayenderahien Date: 2008-10-10 22:41:30 +0000 (Fri, 10 Oct 2008) Log Message: ----------- NH-1520 SQLite Dialect does not properly escape names surrounded by backticks Modified Paths: -------------- branches/static-proxies/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs Modified: branches/static-proxies/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs =================================================================== --- branches/static-proxies/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-10 21:36:28 UTC (rev 3836) +++ branches/static-proxies/src/NHibernate.Test/DialectTest/SQLiteDialectFixture.cs 2008-10-10 22:41:30 UTC (rev 3837) @@ -43,6 +43,48 @@ } [Test] + public void QuotedTableNameWithoutSchemaWithSqlLite() + { + Table tbl = new Table(); + tbl.Name = "`name`"; + + Assert.AreEqual("\"name\"", tbl.GetQualifiedName(dialect)); + } + + [Test] + public void QuotedSchemaNameWithUnqoutedTableInSqlLite() + { + Table tbl = new Table(); + tbl.Schema = "`schema`"; + tbl.Name = "name"; + + Assert.AreEqual("\"schema_name\"", tbl.GetQualifiedName(dialect)); + Assert.AreEqual("\"schema_table\"", dialect.Qualify("", "\"schema\"", "table")); + } + + [Test] + public void QuotedCatalogSchemaNameWithSqlLite() + { + Table tbl = new Table(); + tbl.Catalog = "dbo"; + tbl.Schema = "`schema`"; + tbl.Name = "`name`"; + + Assert.AreEqual("\"dbo_schema_name\"", tbl.GetQualifiedName(dialect)); + Assert.AreEqual("\"dbo_schema_table\"", dialect.Qualify("dbo", "\"schema\"", "\"table\"")); + } + + [Test] + public void QuotedTableNameWithSqlLite() + { + Table tbl = new Table(); + tbl.Name = "`Group`"; + + Assert.AreEqual("\"Group\"", tbl.GetQualifiedName(dialect)); + } + + + [Test] public void SchemaNameWithSqlLite() { Table tbl = new Table(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 21:36:37
|
Revision: 3836 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3836&view=rev Author: fabiomaulo Date: 2008-10-10 21:36:28 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Some changes in binders (walking to xml entitymode) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs Modified: trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs 2008-10-10 19:19:40 UTC (rev 3835) +++ trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs 2008-10-10 21:36:28 UTC (rev 3836) @@ -141,5 +141,11 @@ { return "false".Equals(xmlNodeValue) || "0".Equals(xmlNodeValue); } + + protected static string GetAttributeValue(XmlNode node, string attributeName) + { + XmlAttribute att = node.Attributes[attributeName]; + return att != null ? att.Value : null; + } } } \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs 2008-10-10 19:19:40 UTC (rev 3835) +++ trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs 2008-10-10 21:36:28 UTC (rev 3836) @@ -82,10 +82,11 @@ } else if ("component".Equals(name) || "dynamic-component".Equals(name)) { + string subpath = StringHelper.Qualify(entityName, propertyName); // NH: Modified from H2.1 to allow specifying the type explicitly using class attribute System.Type reflectedClass = GetPropertyType(subnode, model.MappedClass, propertyName); value = new Component(model); - BindComponent(subnode, (Component)value, reflectedClass, entityName, propertyName, true); + BindComponent(subnode, (Component)value, reflectedClass, entityName, propertyName, subpath, true); } else if ("join".Equals(name)) { @@ -124,7 +125,7 @@ if (value != null) { - Property property = CreateProperty(value, propertyName, model.MappedClass, subnode); + Property property = CreateProperty(value, propertyName, model.ClassName, subnode); if (!mutable) property.IsUpdateable = false; if (naturalId) @@ -362,19 +363,13 @@ case "dynamic-component": string subpath = StringHelper.Qualify(path, propertyName); value = new Component(join); - BindComponent( - subnode, - (Component) value, - join.PersistentClass.MappedClass, - propertyName, - subpath, - true); + BindComponent(subnode, (Component) value, join.PersistentClass.MappedClass, join.PersistentClass.ClassName, propertyName, subpath, true); break; } if (value != null) { - Mapping.Property prop = CreateProperty(value, propertyName, persistentClass.MappedClass, subnode); + Mapping.Property prop = CreateProperty(value, propertyName, persistentClass.MappedClass.AssemblyQualifiedName, subnode); prop.IsOptional = join.IsOptional; join.AddProperty(prop); } @@ -533,23 +528,27 @@ } protected void BindComponent(XmlNode node, Component model, System.Type reflectedClass, - string className, string path, bool isNullable) + string className, string parentProperty, string path, bool isNullable) { + bool isIdentifierMapper = false; + + model.RoleName = path; + XmlAttribute classNode = node.Attributes["class"]; - if ("dynamic-component".Equals(node.Name)) + if (classNode != null) { - model.IsEmbedded = false; - model.IsDynamic = true; - } - else if (classNode != null) - { model.ComponentClass = ClassForNameChecked( classNode.Value, mappings, "component class not found: {0}"); model.ComponentClassName = FullQualifiedClassName(classNode.Value, mappings); model.IsEmbedded = false; } + else if ("dynamic-component".Equals(node.Name)) + { + model.IsEmbedded = false; + model.IsDynamic = true; + } else if (reflectedClass != null) { model.ComponentClass = reflectedClass; @@ -562,6 +561,9 @@ model.IsEmbedded = true; } + string nodeName = (GetAttributeValue(node, "node") ?? GetAttributeValue(node, "name")) ?? model.Owner.NodeName; + model.NodeName = nodeName; + foreach (XmlNode subnode in node.ChildNodes) { //I am only concerned with elements that are from the nhibernate namespace @@ -612,22 +614,35 @@ : GetPropertyType(subnode, model.ComponentClass, propertyName); value = new Component(model); - BindComponent(subnode, (Component) value, subreflectedClass, className, subpath, isNullable); + BindComponent(subnode, (Component) value, subreflectedClass, className, propertyName, subpath, isNullable); } else if ("parent".Equals(name)) model.ParentProperty = propertyName; if (value != null) - model.AddProperty(CreateProperty(value, propertyName, model.ComponentClass, subnode)); + { + Property property = CreateProperty(value, propertyName, model.ComponentClassName, subnode); + if (isIdentifierMapper) + { + property.IsInsertable = false; + property.IsUpdateable = false; + } + model.AddProperty(property); + } } } - protected Mapping.Property CreateProperty(IValue value, string propertyName, System.Type parentClass, + protected Property CreateProperty(IValue value, string propertyName, string className, XmlNode subnode) { - if (parentClass != null && value.IsSimpleValue) - value.SetTypeUsingReflection(parentClass.AssemblyQualifiedName, propertyName, PropertyAccess(subnode)); + if (string.IsNullOrEmpty(propertyName)) + { + throw new MappingException(subnode.LocalName + " mapping must defined a name attribute [" + className + "]"); + } + if (!string.IsNullOrEmpty(className) && value.IsSimpleValue) + value.SetTypeUsingReflection(className, propertyName, PropertyAccess(subnode)); + // This is done here 'cos we might only know the type here (ugly!) if (value is ToOne) { @@ -638,7 +653,7 @@ } value.CreateForeignKey(); - Mapping.Property prop = new Mapping.Property(); + Property prop = new Property(); prop.Value = value; BindProperty(subnode, prop); Modified: trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs 2008-10-10 19:19:40 UTC (rev 3835) +++ trunk/nhibernate/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs 2008-10-10 21:36:28 UTC (rev 3836) @@ -529,7 +529,7 @@ else if ("composite-index".Equals(name) || "composite-map-key".Equals(name)) { Component component = new Component(model); - BindComponent(subnode, component, null, model.Role, "index", model.IsOneToMany); + BindComponent(subnode, component, null, null, null, model.Role + ".index", model.IsOneToMany); model.Index = component; } else if ("index-many-to-any".Equals(name)) @@ -618,7 +618,7 @@ { Component element = new Component(model); model.Element = element; - BindComponent(subnode, element, null, model.Role, "element", true); + BindComponent(subnode, element, null, null, null, model.Role+ ".element", true); } else if ("many-to-any".Equals(name)) { Modified: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml 2008-10-10 19:19:40 UTC (rev 3835) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml 2008-10-10 21:36:28 UTC (rev 3836) @@ -34,7 +34,7 @@ <id name="accountId" type="string" node="@id"/> <many-to-one name="customer" column="customerId" entity-name="Customer" cascade="all" embed-xml="true" /> <!--not-null="true"--> - <property name="balance" type="big_decimal" node="balance" precision="10" scale="0" /> + <property name="balance" type="big_decimal" node="balance" precision="10" scale="2" /> </class> <class entity-name="Location" node="location"> Modified: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 19:19:40 UTC (rev 3835) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 21:36:28 UTC (rev 3836) @@ -43,8 +43,10 @@ <b bId='1' aId='1>foo foo</b> <b bId='2' aId='1>bar bar</b> </a>"; + var baseXml = new XmlDocument(); + baseXml.LoadXml(xml); - XmlElement a=null; + XmlElement a = baseXml.DocumentElement; ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); s.Persist("A", a); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 19:19:47
|
Revision: 3835 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3835&view=rev Author: fabiomaulo Date: 2008-10-10 19:19:40 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Few test passed Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Mapping/Property.cs trunk/nhibernate/src/NHibernate/NHibernate.csproj trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs trunk/nhibernate/src/NHibernate/Type/NullableType.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs Added Paths: ----------- trunk/nhibernate/src/NHibernate/Properties/XmlAccessor.cs Modified: trunk/nhibernate/src/NHibernate/Mapping/Property.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Mapping/Property.cs 2008-10-10 16:29:37 UTC (rev 3834) +++ trunk/nhibernate/src/NHibernate/Mapping/Property.cs 2008-10-10 19:19:40 UTC (rev 3835) @@ -187,6 +187,11 @@ get { return PropertyAccessorFactory.GetPropertyAccessor(PropertyAccessorName); } } + public virtual string GetAccessorPropertyName(EntityMode mode) + { + return mode == EntityMode.Xml ? nodeName : Name; + } + public virtual bool IsBasicPropertyAccessor { // NH Different behavior : see IPropertyAccessor.CanAccessThroughReflectionOptimizer (ref. NH-1304) Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj =================================================================== --- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-10-10 16:29:37 UTC (rev 3834) +++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2008-10-10 19:19:40 UTC (rev 3835) @@ -1109,6 +1109,7 @@ <SubType>Code</SubType> </Compile> <Compile Include="Util\XmlHelper.cs" /> + <Compile Include="Properties\XmlAccessor.cs" /> <EmbeddedResource Include="nhibernate-configuration.xsd"> <SubType>Designer</SubType> </EmbeddedResource> Modified: trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs 2008-10-10 16:29:37 UTC (rev 3834) +++ trunk/nhibernate/src/NHibernate/Properties/PropertyAccessorFactory.cs 2008-10-10 19:19:40 UTC (rev 3835) @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using NHibernate.Type; using NHibernate.Util; +using NHibernate.Engine; namespace NHibernate.Properties { @@ -213,11 +215,20 @@ return GetPocoPropertyAccessor(property.PropertyAccessorName); case EntityMode.Map: return DynamicMapPropertyAccessor; + case EntityMode.Xml: + return GetXmlPropertyAccessor(property.GetAccessorPropertyName(modeToUse), property.Type, null); default: throw new MappingException("Unknown entity mode [" + mode + "]"); } } + private static IPropertyAccessor GetXmlPropertyAccessor(string nodeName, IType type, ISessionFactoryImplementor factory) + { + //TODO: need some caching scheme? really comes down to decision + // regarding amount of state (if any) kept on PropertyAccessors + return new XmlAccessor(nodeName, type, factory); + } + private static IPropertyAccessor GetPocoPropertyAccessor(string accessorName) { string accName = string.IsNullOrEmpty(accessorName) ? DefaultAccessorName : accessorName; Added: trunk/nhibernate/src/NHibernate/Properties/XmlAccessor.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Properties/XmlAccessor.cs (rev 0) +++ trunk/nhibernate/src/NHibernate/Properties/XmlAccessor.cs 2008-10-10 19:19:40 UTC (rev 3835) @@ -0,0 +1,425 @@ +using System; +using System.Collections; +using System.Reflection; +using System.Xml; +using NHibernate.Engine; +using NHibernate.Type; + +namespace NHibernate.Properties +{ + /// <summary> + /// Responsible for accessing property values represented as a XmlElement + /// or XmlAttribute. + /// </summary> + public class XmlAccessor : IPropertyAccessor + { + private readonly ISessionFactoryImplementor factory; + private readonly string nodeName; + private readonly IType propertyType; + + public XmlAccessor(string nodeName, IType propertyType, ISessionFactoryImplementor factory) + { + this.factory = factory; + this.nodeName = nodeName; + this.propertyType = propertyType; + } + + #region Implementation of IPropertyAccessor + + public IGetter GetGetter(System.Type theClass, string propertyName) + { + if (nodeName == null) + { + throw new MappingException("no node name for property: " + propertyName); + } + if (".".Equals(nodeName)) + { + return new TextGetter(propertyType, factory); + } + else if (nodeName.IndexOf('/') > -1) + { + return new ElementAttributeGetter(nodeName, propertyType, factory); + } + else if (nodeName.IndexOf('@') > -1) + { + return new AttributeGetter(nodeName, propertyType, factory); + } + else + { + return new ElementGetter(nodeName, propertyType, factory); + } + } + + public ISetter GetSetter(System.Type theClass, string propertyName) + { + if (nodeName == null) + { + throw new MappingException("no node name for property: " + propertyName); + } + if (".".Equals(nodeName)) + { + return new TextSetter(propertyType); + } + else if (nodeName.IndexOf('/') > -1) + { + return new ElementAttributeSetter(nodeName, propertyType); + } + else if (nodeName.IndexOf('@') > -1) + { + return new AttributeSetter(nodeName, propertyType); + } + else + { + return new ElementSetter(nodeName, propertyType); + } + } + + public bool CanAccessThroughReflectionOptimizer + { + get { return true; } + } + + #endregion + + #region Nested type: AttributeGetter + + /// <summary> For nodes like <tt>"@bar"</tt></summary> + [Serializable] + public class AttributeGetter : XmlGetter + { + private readonly string attributeName; + + public AttributeGetter(string name, IType propertyType, ISessionFactoryImplementor factory) + : base(propertyType, factory) + { + attributeName = name.Substring(1); + } + + public override object Get(object owner) + { + var ownerElement = (XmlNode) owner; + XmlNode attribute = ownerElement.Attributes[attributeName]; + return attribute == null ? null : propertyType.FromXMLNode(attribute, factory); + } + } + + #endregion + + #region Nested type: AttributeSetter + + /// <summary> For nodes like <tt>"@bar"</tt></summary> + [Serializable] + public class AttributeSetter : XmlSetter + { + private readonly string attributeName; + + public AttributeSetter(string name, IType propertyType) : base(propertyType) + { + attributeName = name.Substring(1); + } + + public override void Set(object target, object value) + { + var owner = (XmlElement) target; + XmlAttribute attribute = owner.Attributes[attributeName]; + if (value == null) + { + if (attribute != null) + { + owner.Attributes.Remove(attribute); + } + } + else + { + if (attribute == null) + { + owner.SetAttribute(attributeName, "null"); + attribute = owner.Attributes[attributeName]; + } + propertyType.SetToXMLNode(attribute, value, null); + } + } + } + + #endregion + + #region Nested type: ElementAttributeGetter + + /// <summary> For nodes like <tt>"foo/@bar"</tt></summary> + [Serializable] + public class ElementAttributeGetter : XmlGetter + { + private readonly string attributeName; + private readonly string elementName; + + public ElementAttributeGetter(string name, IType propertyType, ISessionFactoryImplementor factory) + : base(propertyType, factory) + { + elementName = name.Substring(0, (name.IndexOf('/'))); + attributeName = name.Substring(name.IndexOf('/') + 2); + } + + public override object Get(object owner) + { + var ownerElement = (XmlNode) owner; + + XmlNode element = ownerElement[elementName]; + + if (element == null) + { + return null; + } + else + { + XmlAttribute attribute = element.Attributes[attributeName]; + if (attribute == null) + { + return null; + } + else + { + return propertyType.FromXMLNode(attribute, factory); + } + } + } + } + + #endregion + + #region Nested type: ElementAttributeSetter + + /// <summary> For nodes like <tt>"foo/@bar"</tt></summary> + [Serializable] + public class ElementAttributeSetter : XmlSetter + { + private readonly string attributeName; + private readonly string elementName; + + public ElementAttributeSetter(string name, IType propertyType) : base(propertyType) + { + elementName = name.Substring(0, name.IndexOf('/')); + attributeName = name.Substring(name.IndexOf('/') + 2); + } + + public override void Set(object target, object value) + { + var owner = (XmlElement) target; + XmlElement element = owner[elementName]; + if (value == null) + { + if (element != null) + { + owner.RemoveChild(element); + } + } + else + { + XmlAttribute attribute; + if (element == null) + { + element = owner.OwnerDocument.CreateElement(elementName); + owner.AppendChild(element); + attribute = null; + } + else + { + attribute = element.Attributes[attributeName]; + } + + if (attribute == null) + { + element.SetAttribute(attributeName, "null"); + attribute = element.Attributes[attributeName]; + } + propertyType.SetToXMLNode(attribute, value, null); + } + } + } + + #endregion + + #region Nested type: ElementGetter + + /// <summary> For nodes like <tt>"foo"</tt></summary> + [Serializable] + public class ElementGetter : XmlGetter + { + private readonly string elementName; + + public ElementGetter(string name, IType propertyType, ISessionFactoryImplementor factory) + : base(propertyType, factory) + { + elementName = name; + } + + public override object Get(object owner) + { + var ownerElement = (XmlNode) owner; + XmlNode element = ownerElement[elementName]; + return element == null ? null : propertyType.FromXMLNode(element, factory); + } + } + + #endregion + + #region Nested type: ElementSetter + + /// <summary> For nodes like <tt>"foo"</tt></summary> + [Serializable] + public class ElementSetter : XmlSetter + { + private readonly string elementName; + + public ElementSetter(string name, IType propertyType) : base(propertyType) + { + elementName = name; + } + + public override void Set(object target, object value) + { + if (value != CollectionType.UnfetchedCollection) + { + var owner = (XmlElement) target; + XmlElement existing = owner[elementName]; + if (existing != null) + { + owner.RemoveChild(existing); + } + if (value != null) + { + XmlElement element = owner.OwnerDocument.CreateElement(elementName); + owner.AppendChild(element); + propertyType.SetToXMLNode(element, value, null); + } + } + } + } + + #endregion + + #region Nested type: TextGetter + + /// <summary> For nodes like <tt>"."</tt></summary> + [Serializable] + public class TextGetter : XmlGetter + { + public TextGetter(IType propertyType, ISessionFactoryImplementor factory) : base(propertyType, factory) {} + + public override object Get(object owner) + { + var ownerElement = (XmlNode) owner; + return propertyType.FromXMLNode(ownerElement, factory); + } + } + + #endregion + + #region Nested type: TextSetter + + /// <summary> For nodes like <tt>"."</tt></summary> + [Serializable] + public class TextSetter : XmlSetter + { + public TextSetter(IType propertyType) : base(propertyType) {} + + public override void Set(object target, object value) + { + var owner = (XmlNode) target; + if (!propertyType.IsXMLElement) + { + //kinda ugly, but needed for collections with a "." node mapping + if (value == null) + { + owner.InnerText = ""; //is this ok? + } + else + { + propertyType.SetToXMLNode(owner, value, null); + } + } + } + } + + #endregion + + #region Nested type: XmlGetter + + /// <summary> Defines the strategy for getting property values out of a dom4j Node.</summary> + [Serializable] + public abstract class XmlGetter : IGetter + { + protected ISessionFactoryImplementor factory; + protected IType propertyType; + + internal XmlGetter(IType propertyType, ISessionFactoryImplementor factory) + { + this.propertyType = propertyType; + this.factory = factory; + } + + #region IGetter Members + + /// <summary> Get the declared type</summary> + public virtual System.Type ReturnType + { + get { return typeof (object); } + } + + /// <summary> Optional operation (return null)</summary> + public virtual string PropertyName + { + get { return null; } + } + + /// <summary> Optional operation (return null)</summary> + public virtual MethodInfo Method + { + get { return null; } + } + + public virtual object GetForInsert(object owner, IDictionary mergeMap, ISessionImplementor session) + { + return Get(owner); + } + + public abstract object Get(object target); + + #endregion + } + + #endregion + + #region Nested type: XmlSetter + + [Serializable] + public abstract class XmlSetter : ISetter + { + protected internal IType propertyType; + + internal XmlSetter(IType propertyType) + { + this.propertyType = propertyType; + } + + #region ISetter Members + + /// <summary> Optional operation (return null)</summary> + public virtual string PropertyName + { + get { return null; } + } + + /// <summary> Optional operation (return null)</summary> + public virtual MethodInfo Method + { + get { return null; } + } + + public abstract void Set(object target, object value); + + #endregion + } + + #endregion + } +} \ No newline at end of file Property changes on: trunk/nhibernate/src/NHibernate/Properties/XmlAccessor.cs ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/nhibernate/src/NHibernate/Type/NullableType.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Type/NullableType.cs 2008-10-10 16:29:37 UTC (rev 3834) +++ trunk/nhibernate/src/NHibernate/Type/NullableType.cs 2008-10-10 19:19:40 UTC (rev 3835) @@ -345,12 +345,12 @@ public override object FromXMLNode(XmlNode xml, IMapping factory) { - return FromXMLString(xml.Value, factory); + return FromXMLString(xml.InnerText, factory); } public override void SetToXMLNode(XmlNode xml, object value, ISessionFactoryImplementor factory) { - xml.Value = ToXMLString(value, factory); + xml.InnerText = ToXMLString(value, factory); } public string ToXMLString(object value, ISessionFactoryImplementor pc) Modified: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs 2008-10-10 16:29:37 UTC (rev 3834) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs 2008-10-10 19:19:40 UTC (rev 3835) @@ -1,3 +1,4 @@ +using System; using System.Xml; using NHibernate.Mapping; using NHibernate.Properties; @@ -6,7 +7,7 @@ namespace NHibernate.Test.EntityModeTest.Xml.Accessors { - [TestFixture, Ignore("Not supported yet.")] + [TestFixture] public class XmlAccessorFixture { public static XmlElement dom = GenerateTestElement(); @@ -77,6 +78,7 @@ nameSetter.Set(root, "NHForge"); accountIdSetter.Set(root, 456L); + Console.WriteLine(dom.OuterXml); //Assert.That(new NodeComparator().Compare(dom, root) == 0); } @@ -107,7 +109,7 @@ Assert.That(name, Is.EqualTo("NHForge")); } - [Test] + [Test, Ignore("Not supported yet.")] public void StringTextExtraction() { Property property = GenerateTextProperty(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 16:29:45
|
Revision: 3834 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3834&view=rev Author: fabiomaulo Date: 2008-10-10 16:29:37 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Minor (reformatted) Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs Modified: trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-10 16:20:24 UTC (rev 3833) +++ trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-10 16:29:37 UTC (rev 3834) @@ -14,7 +14,7 @@ /// </remarks> public class BytecodeProviderImpl : IBytecodeProvider, IInjectableProxyFactoryFactory { - System.Type proxyFactoryFactory; + private System.Type proxyFactoryFactory; #region IBytecodeProvider Members @@ -37,7 +37,6 @@ } } - /// <summary> /// Generate the IReflectionOptimizer object /// </summary> @@ -45,8 +44,7 @@ /// <param name="setters">Array of setters</param> /// <param name="getters">Array of getters</param> /// <returns><see langword="null" /> if the generation fails</returns> - public IReflectionOptimizer GetReflectionOptimizer( - System.Type mappedClass, IGetter[] getters, ISetter[] setters) + public IReflectionOptimizer GetReflectionOptimizer(System.Type mappedClass, IGetter[] getters, ISetter[] setters) { return new ReflectionOptimizer(mappedClass, getters, setters); } @@ -62,17 +60,15 @@ { pffc = ReflectHelper.ClassForName(typeName); } - catch(HibernateException he) + catch (HibernateException he) { throw new HibernateException("Unable to load type '" + typeName + "' during configuration of proxy factory class.", - he); + he); } - if (typeof(IProxyFactoryFactory).IsAssignableFrom(pffc) == false) + if (typeof (IProxyFactoryFactory).IsAssignableFrom(pffc) == false) { - HibernateException he = - new HibernateException(pffc.FullName + " does not implement " + - typeof(IProxyFactoryFactory).FullName); + var he = new HibernateException(pffc.FullName + " does not implement " + typeof (IProxyFactoryFactory).FullName); throw he; } proxyFactoryFactory = pffc; @@ -80,5 +76,4 @@ #endregion } -} - +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 16:20:32
|
Revision: 3833 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3833&view=rev Author: fabiomaulo Date: 2008-10-10 16:20:24 +0000 (Fri, 10 Oct 2008) Log Message: ----------- another test to support Xml entityMode Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/MultiRepresentationFixture.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.hbm.xml trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.hbm.xml Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/MultiRepresentationFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/MultiRepresentationFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/MultiRepresentationFixture.cs 2008-10-10 16:20:24 UTC (rev 3833) @@ -0,0 +1,189 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Xml; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.EntityModeTest.Multi +{ + [TestFixture, Ignore("Not supported yet.")] + public class MultiRepresentationFixture : TestCase + { + protected override string MappingsAssembly + { + get { return "NHibernate.Test"; } + } + + protected override IList Mappings + { + get { return new[] {"EntityModeTest.Multi.Stock.hbm.xml", "EntityModeTest.Multi.Valuation.hbm.xml"}; } + } + + private class TestData + { + private readonly ISessionFactory sessions; + public long stockId; + + public TestData(ISessionFactory factory) + { + sessions = factory; + } + + public void Create() + { + ISession session = sessions.OpenSession(); + session.BeginTransaction(); + var stock = new Stock {TradeSymbol = "NHForge"}; + var valuation = new Valuation {Stock = stock, ValuationDate = DateTime.Now, Value = 200.0D}; + stock.CurrentValuation = valuation; + stock.Valuations.Add(valuation); + + session.Save(stock); + session.Save(valuation); + + session.Transaction.Commit(); + session.Close(); + + stockId = stock.Id; + } + + public void Destroy() + { + ISession session = sessions.OpenSession(); + session.BeginTransaction(); + IList<Stock> stocks = session.CreateQuery("from Stock").List<Stock>(); + foreach (Stock stock in stocks) + { + stock.CurrentValuation = null; + session.Flush(); + foreach (Valuation valuation in stock.Valuations) + { + session.Delete(valuation); + } + session.Delete(stock); + } + session.Transaction.Commit(); + session.Close(); + } + } + + [Test] + public void PocoRetreival() + { + var testData = new TestData(sessions); + testData.Create(); + + ISession session = OpenSession(); + ITransaction txn = session.BeginTransaction(); + + var stock = session.Get<Stock>(1); + Assert.That(stock.Id, Is.EqualTo(1L)); + + txn.Commit(); + session.Close(); + + testData.Destroy(); + } + + [Test] + public void XmlHQL() + { + var testData = new TestData(sessions); + testData.Create(); + + ISession session = OpenSession(); + ITransaction txn = session.BeginTransaction(); + ISession xml = session.GetSession(EntityMode.Xml); + + IList result = xml.CreateQuery("from Stock").List(); + + Assert.That(result.Count, Is.EqualTo(1L)); + var element = (XmlElement) result[0]; + Assert.That(element.Attributes["id"], Is.EqualTo(testData.stockId)); + + Console.WriteLine("**** XML: ****************************************************"); + //prettyPrint( element ); + Console.WriteLine("**************************************************************"); + + txn.Rollback(); + session.Close(); + + testData.Destroy(); + } + + [Test] + public void XmlRetreival() + { + var testData = new TestData(sessions); + testData.Create(); + + ISession session = OpenSession(); + ITransaction txn = session.BeginTransaction(); + ISession xml = session.GetSession(EntityMode.Xml); + + object rtn = xml.Get(typeof (Stock).FullName, testData.stockId); + var element = (XmlElement) rtn; + + Assert.That(element.Attributes["id"], Is.EqualTo(testData.stockId)); + + Console.WriteLine("**** XML: ****************************************************"); + //prettyPrint( element ); + Console.WriteLine("**************************************************************"); + + XmlNode currVal = element.GetElementsByTagName("currentValuation")[0]; + + Console.WriteLine("**** XML: ****************************************************"); + //prettyPrint( currVal ); + Console.WriteLine("**************************************************************"); + + txn.Rollback(); + session.Close(); + + testData.Destroy(); + } + + [Test] + public void XmlSave() + { + var testData = new TestData(sessions); + testData.Create(); + + ISession pojos = OpenSession(); + ITransaction txn = pojos.BeginTransaction(); + ISession xml = pojos.GetSession(EntityMode.Xml); + + var domDoc = new XmlDocument(); + XmlElement stock = domDoc.CreateElement("stock"); + domDoc.AppendChild(stock); + XmlElement tradeSymbol = domDoc.CreateElement("tradeSymbol"); + tradeSymbol.InnerText = "Microsoft"; + stock.AppendChild(tradeSymbol); + + XmlElement cval = domDoc.CreateElement("currentValuation"); + XmlElement val = domDoc.CreateElement("valuation"); + stock.AppendChild(cval); + //val.appendContent(stock); TODO + XmlElement valuationDate = domDoc.CreateElement("valuationDate"); + tradeSymbol.InnerText = DateTime.Now.ToString(); + val.AppendChild(valuationDate); + + XmlElement value = domDoc.CreateElement("value"); + tradeSymbol.InnerText = "121.00"; + val.AppendChild(value); + + xml.Save(typeof (Stock).FullName, stock); + xml.Flush(); + + txn.Rollback(); + pojos.Close(); + + Assert.That(!pojos.IsOpen); + Assert.That(!xml.IsOpen); + + //prettyPrint( stock ); + + testData.Destroy(); + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.cs 2008-10-10 16:20:24 UTC (rev 3833) @@ -0,0 +1,21 @@ +using Iesi.Collections.Generic; + +namespace NHibernate.Test.EntityModeTest.Multi +{ + public class Stock + { + private ISet<Valuation> valuations = new HashedSet<Valuation>(); + + public virtual long Id { get; set; } + + public virtual string TradeSymbol { get; set; } + + public virtual Valuation CurrentValuation { get; set; } + + public virtual ISet<Valuation> Valuations + { + get { return valuations; } + set { valuations = value; } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Stock.hbm.xml 2008-10-10 16:20:24 UTC (rev 3833) @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.EntityModeTest.Multi"> + + <class table="STOCK" name="Stock" node="stock"> + + <id name="Id" column="STOCK_ID" node="@id"> + <generator class="increment"/> + </id> + + <property name="TradeSymbol" type="string" column="SYMBOL"/> + + <many-to-one name="CurrentValuation" class="Valuation" column="CURR_VAL_ID" cascade="all" /> + + <set name="Valuations" cascade="all" lazy="true"> + <key column="STOCK_ID"/> + <one-to-many class="Valuation"/> + </set> + </class> + +</hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.cs 2008-10-10 16:20:24 UTC (rev 3833) @@ -0,0 +1,15 @@ +using System; + +namespace NHibernate.Test.EntityModeTest.Multi +{ + public class Valuation + { + public virtual long Id { get; set; } + + public virtual Stock Stock { get; set; } + + public virtual DateTime ValuationDate { get; set; } + + public virtual double Value { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Multi/Valuation.hbm.xml 2008-10-10 16:20:24 UTC (rev 3833) @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.EntityModeTest.Multi"> + + <class table="STOCK_VAL" name="Valuation" node="valuation"> + + <id name="Id" column="VAL_ID" node="@id"> + <generator class="increment"/> + </id> + + <many-to-one name="Stock" embed-xml="false" + class="Stock" column="STOCK_ID" cascade="none" /> + + <property name="ValuationDate" type="date" column="DT"/> + <property name="Value" type="double" column="VAL"/> + + </class> + +</hibernate-mapping> \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-10 13:58:37 UTC (rev 3832) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-10 16:20:24 UTC (rev 3833) @@ -160,6 +160,9 @@ <Compile Include="DynamicEntity\Tuplizer\TuplizerDynamicEntity.cs" /> <Compile Include="EngineTest\TypedValueFixture.cs" /> <Compile Include="EntityModeTest\Map\Basic\DynamicClassFixture.cs" /> + <Compile Include="EntityModeTest\Multi\MultiRepresentationFixture.cs" /> + <Compile Include="EntityModeTest\Multi\Stock.cs" /> + <Compile Include="EntityModeTest\Multi\Valuation.cs" /> <Compile Include="EntityModeTest\Xml\Accessors\XmlAccessorFixture.cs" /> <Compile Include="EntityModeTest\Xml\Basic\XmlFixture.cs" /> <Compile Include="EntityModeTest\Xml\Many2One\Car.cs" /> @@ -1493,7 +1496,9 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> - <Content Include="EntityModeTest\Xml\Many2One\Car.hbm.xml" /> + <EmbeddedResource Include="EntityModeTest\Multi\Stock.hbm.xml" /> + <EmbeddedResource Include="EntityModeTest\Multi\Valuation.hbm.xml" /> + <EmbeddedResource Include="EntityModeTest\Xml\Many2One\Car.hbm.xml" /> <EmbeddedResource Include="EntityModeTest\Xml\Basic\AB.hbm.xml" /> <EmbeddedResource Include="EntityModeTest\Xml\Basic\Account.hbm.xml" /> <EmbeddedResource Include="EntityModeTest\Xml\Basic\Employer.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 13:58:49
|
Revision: 3832 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3832&view=rev Author: fabiomaulo Date: 2008-10-10 13:58:37 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Ups. Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs Modified: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs 2008-10-10 13:56:51 UTC (rev 3831) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs 2008-10-10 13:58:37 UTC (rev 3832) @@ -4,7 +4,7 @@ namespace NHibernate.Test.EntityModeTest.Xml.Many2One { - [TestFixture] + [TestFixture, Ignore("Not supported yet.")] public class XmlManyToOneFixture : TestCase { protected override string MappingsAssembly This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 13:56:58
|
Revision: 3831 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3831&view=rev Author: fabiomaulo Date: 2008-10-10 13:56:51 +0000 (Fri, 10 Oct 2008) Log Message: ----------- another test to support Xml entityMode Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.hbm.xml trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarPart.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarType.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.cs 2008-10-10 13:56:51 UTC (rev 3831) @@ -0,0 +1,21 @@ +using System; +using Iesi.Collections.Generic; + +namespace NHibernate.Test.EntityModeTest.Xml.Many2One +{ + [Serializable] + public class Car + { + private ISet<CarPart> carParts = new HashedSet<CarPart>(); + + public virtual long Id { get; set; } + public virtual string Model { get; set; } + public virtual CarType CarType { get; set; } + + public ISet<CarPart> CarParts + { + get { return carParts; } + set { carParts = value; } + } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/Car.hbm.xml 2008-10-10 13:56:51 UTC (rev 3831) @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" + assembly="NHibernate.Test" + namespace="NHibernate.Test.EntityModeTest.Xml.Many2One"> + + <class name="Car" lazy="false" node="car"> + <id name="Id" node="@id" type="long"> + <generator class="increment"/> + </id> + <property name="Model" type="string" node="model"/> + <many-to-one name="CarType" node="carType" class="CarType"/> + <set name="CarParts" node="." cascade="all" generic="true"> + <key column="car" not-null="true"/> + <one-to-many class="CarPart" node="carPart" embed-xml="false"/> + </set> + </class> + + <class name="CarType" lazy="true" node="carType"> + <id name="Id" node="@id" type="long"> + <generator class="increment"/> + </id> + <property name="TypeName" type="string" node="typeName"/> + </class> + + <class name="CarPart" node="carPart"> + <id name="Id" node="@id" type="long"> + <generator class="increment"/> + </id> + <property name="PartName" type="string" node="partName"/> + </class> + +</hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarPart.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarPart.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarPart.cs 2008-10-10 13:56:51 UTC (rev 3831) @@ -0,0 +1,11 @@ +using System; + +namespace NHibernate.Test.EntityModeTest.Xml.Many2One +{ + [Serializable] + public class CarPart + { + public virtual long Id { get; set; } + public virtual string PartName { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarType.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarType.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/CarType.cs 2008-10-10 13:56:51 UTC (rev 3831) @@ -0,0 +1,11 @@ +using System; + +namespace NHibernate.Test.EntityModeTest.Xml.Many2One +{ + [Serializable] + public class CarType + { + public virtual long Id { get; set; } + public virtual string TypeName { get; set; } + } +} \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Many2One/XmlManyToOneFixture.cs 2008-10-10 13:56:51 UTC (rev 3831) @@ -0,0 +1,106 @@ +using System.Collections; +using System.Xml; +using NUnit.Framework; + +namespace NHibernate.Test.EntityModeTest.Xml.Many2One +{ + [TestFixture] + public class XmlManyToOneFixture : TestCase + { + protected override string MappingsAssembly + { + get { return "NHibernate.Test"; } + } + + protected override IList Mappings + { + get { return new[] {"EntityModeTest.Xml.Many2One.Car.hbm.xml"}; } + } + + [Test] + public void XmlManyToOne() + { + ISession s = OpenSession(); + ITransaction t = s.BeginTransaction(); + + var carType = new CarType {TypeName = "Type 1"}; + s.Save(carType); + + var car1 = new Car {CarType = carType, Model = "Model 1"}; + s.Save(car1); + + var car2 = new Car {CarType = carType, Model = "Model 2"}; + s.Save(car2); + + t.Commit(); + s.Close(); + + s = OpenSession(); + ISession xmlSession = s.GetSession(EntityMode.Xml); + t = s.BeginTransaction(); + + IList list = xmlSession.CreateQuery("from Car c join fetch c.carType order by c.model asc").List(); + + var expectedResults = new[] + { + "<car id=\"" + car1.Id + "\"><model>Model 1</model><carType id=\"" + carType.Id + + "\"><typeName>Type 1</typeName></carType></car>", + "<car id=\"" + car2.Id + "\"><model>Model 2</model><carType id=\"" + carType.Id + + "\"><typeName>Type 1</typeName></carType></car>" + }; + + for (int i = 0; i < list.Count; i++) + { + var element = (XmlElement) list[i]; + + //print(element); + Assert.That(element.InnerXml.Equals(expectedResults[i])); + } + + s.Delete("from CarType"); + s.Delete("from Car"); + + t.Commit(); + s.Close(); + } + + [Test] + public void XmlOneToMany() + { + ISession s = OpenSession(); + ITransaction t = s.BeginTransaction(); + + var carType = new CarType {TypeName = "Type 1"}; + s.Save(carType); + + var car = new Car {CarType = carType, Model = "Model 1"}; + s.Save(car); + + var carPart1 = new CarPart {PartName = "chassis"}; + car.CarParts.Add(carPart1); + + t.Commit(); + s.Close(); + + s = OpenSession(); + ISession xmlSession = s.GetSession(EntityMode.Xml); + t = s.BeginTransaction(); + + var element = (XmlElement) xmlSession.CreateQuery("from Car c join fetch c.carParts").UniqueResult(); + + string expectedResult = "<car id=\"" + car.Id + "\"><carPart>" + carPart1.Id + + "</carPart><model>Model 1</model><carType id=\"" + carType.Id + + "\"><typeName>Type 1</typeName></carType></car>"; + + //print(element); + Assert.That(element.InnerXml.Equals(expectedResult)); + + s.Delete("from CarPart"); + s.Delete("from CarType"); + s.Delete("from Car"); + + t.Commit(); + s.Close(); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-10 12:31:10 UTC (rev 3830) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-10 13:56:51 UTC (rev 3831) @@ -162,6 +162,10 @@ <Compile Include="EntityModeTest\Map\Basic\DynamicClassFixture.cs" /> <Compile Include="EntityModeTest\Xml\Accessors\XmlAccessorFixture.cs" /> <Compile Include="EntityModeTest\Xml\Basic\XmlFixture.cs" /> + <Compile Include="EntityModeTest\Xml\Many2One\Car.cs" /> + <Compile Include="EntityModeTest\Xml\Many2One\CarPart.cs" /> + <Compile Include="EntityModeTest\Xml\Many2One\CarType.cs" /> + <Compile Include="EntityModeTest\Xml\Many2One\XmlManyToOneFixture.cs" /> <Compile Include="Events\Collections\AbstractCollectionEventFixture.cs" /> <Compile Include="Events\Collections\AbstractParentWithCollection.cs" /> <Compile Include="Events\Collections\Association\AbstractAssociationCollectionEventFixture.cs" /> @@ -1489,6 +1493,7 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <Content Include="EntityModeTest\Xml\Many2One\Car.hbm.xml" /> <EmbeddedResource Include="EntityModeTest\Xml\Basic\AB.hbm.xml" /> <EmbeddedResource Include="EntityModeTest\Xml\Basic\Account.hbm.xml" /> <EmbeddedResource Include="EntityModeTest\Xml\Basic\Employer.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 12:31:21
|
Revision: 3830 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3830&view=rev Author: fabiomaulo Date: 2008-10-10 12:31:10 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Added methods to work with entity-name to ISession Possible Breaking change: - see ISession Modified Paths: -------------- trunk/nhibernate/releasenotes.txt trunk/nhibernate/src/NHibernate/ISession.cs trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs trunk/nhibernate/src/NHibernate.sln Modified: trunk/nhibernate/releasenotes.txt =================================================================== --- trunk/nhibernate/releasenotes.txt 2008-10-10 12:02:27 UTC (rev 3829) +++ trunk/nhibernate/releasenotes.txt 2008-10-10 12:31:10 UTC (rev 3830) @@ -1,3 +1,9 @@ +Build 2.1.0.GA +======================== +** BREAKING CHANGES from NH2.0.xGA to NH2.1.0 + ##### Possible Breaking Changes for external frameworks ##### + * ISession interface have additional methods + Build 2.0.1.GA ======================== ** Bug Modified: trunk/nhibernate/src/NHibernate/ISession.cs =================================================================== --- trunk/nhibernate/src/NHibernate/ISession.cs 2008-10-10 12:02:27 UTC (rev 3829) +++ trunk/nhibernate/src/NHibernate/ISession.cs 2008-10-10 12:31:10 UTC (rev 3830) @@ -453,6 +453,17 @@ void Delete(object obj); /// <summary> + /// Remove a persistent instance from the datastore. The <b>object</b> argument may be + /// an instance associated with the receiving <see cref="ISession"/> or a transient + /// instance with an identifier associated with existing persistent state. + /// This operation cascades to associated instances if the association is mapped + /// with <tt>cascade="delete"</tt>. + /// </summary> + /// <param name="entityName">The entity name for the instance to be removed. </param> + /// <param name="obj">the instance to be removed </param> + void Delete(string entityName, object obj); + + /// <summary> /// Execute a query /// </summary> /// <param name="query">A query expressed in Hibernate's query language</param> @@ -716,8 +727,23 @@ /// <returns>An ICriteria object</returns> ICriteria CreateCriteria(System.Type persistentClass, string alias); + /// <summary> + /// Create a new <c>Criteria</c> instance, for the given entity name. + /// </summary> + /// <param name="entityName">The name of the entity to Query</param> + /// <returns>An ICriteria object</returns> + ICriteria CreateCriteria(string entityName); /// <summary> + /// Create a new <c>Criteria</c> instance, for the given entity name, + /// with the given alias. + /// </summary> + /// <param name="entityName">The name of the entity to Query</param> + /// <param name="alias">The alias of the entity</param> + /// <returns>An ICriteria object</returns> + ICriteria CreateCriteria(string entityName, string alias); + + /// <summary> /// Create a new instance of <c>Query</c> for the given query string /// </summary> /// <param name="queryString">A hibernate query string</param> Modified: trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs 2008-10-10 12:02:27 UTC (rev 3829) +++ trunk/nhibernate/src/NHibernate/Impl/SessionImpl.cs 2008-10-10 12:31:10 UTC (rev 3830) @@ -1476,6 +1476,18 @@ return new CriteriaImpl(persistentClass, alias, this); } + public ICriteria CreateCriteria(string entityName, string alias) + { + CheckAndUpdateSessionStatus(); + return new CriteriaImpl(entityName, alias, this); + } + + public ICriteria CreateCriteria(string entityName) + { + CheckAndUpdateSessionStatus(); + return new CriteriaImpl(entityName, this); + } + public override IList List(CriteriaImpl criteria) { ArrayList results = new ArrayList(); Modified: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 12:02:27 UTC (rev 3829) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 12:31:10 UTC (rev 3830) @@ -53,10 +53,10 @@ s = OpenSession(); t = s.BeginTransaction(); - //a = (XmlElement)s.CreateCriteria("A").UniqueResult(); + a = (XmlElement)s.CreateCriteria("A").UniqueResult(); Assert.AreEqual(a.GetElementsByTagName("b").Count, 2); Print(a); - //s.Delete("A", a); + s.Delete("A", a); t.Commit(); s.Close(); } Modified: trunk/nhibernate/src/NHibernate.sln =================================================================== --- trunk/nhibernate/src/NHibernate.sln 2008-10-10 12:02:27 UTC (rev 3829) +++ trunk/nhibernate/src/NHibernate.sln 2008-10-10 12:31:10 UTC (rev 3830) @@ -3,6 +3,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{593DCEA7-C933-46F3-939F-D8172399AB05}" ProjectSection(SolutionItems) = preProject ..\default.build = ..\default.build + ..\releasenotes.txt = ..\releasenotes.txt EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NHibernate", "NHibernate\NHibernate.csproj", "{5909BFE7-93CF-4E5F-BE22-6293368AF01D}" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 12:02:41
|
Revision: 3829 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3829&view=rev Author: fabiomaulo Date: 2008-10-10 12:02:27 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Minor Modified Paths: -------------- trunk/nhibernate/readme.html Modified: trunk/nhibernate/readme.html =================================================================== --- trunk/nhibernate/readme.html 2008-10-10 12:00:14 UTC (rev 3828) +++ trunk/nhibernate/readme.html 2008-10-10 12:02:27 UTC (rev 3829) @@ -6,7 +6,7 @@ <h1>Welcome to NHibernate!</h1> <hr> <p> - <a href="http://www.nhibernate.org/">NHibernate</a> is a .NET based object persistence library for relational databases. + <a href="http://www.nhforge.org/">NHibernate</a> is a .NET based object persistence library for relational databases. NHibernate is a port of the excellent Java <a href="http://www.hibernate.org/">Hibernate</a> relational persistence tool. </p> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 12:00:24
|
Revision: 3828 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3828&view=rev Author: fabiomaulo Date: 2008-10-10 12:00:14 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Actualized with releasenote of branch Modified Paths: -------------- trunk/nhibernate/releasenotes.txt Modified: trunk/nhibernate/releasenotes.txt =================================================================== --- trunk/nhibernate/releasenotes.txt 2008-10-10 04:33:22 UTC (rev 3827) +++ trunk/nhibernate/releasenotes.txt 2008-10-10 12:00:14 UTC (rev 3828) @@ -1,3 +1,151 @@ +Build 2.0.1.GA +======================== +** Bug + * [NH-1293] - Changed behavior of Filters for many-to-one associations brings up possible bug when used with outer joins. + * [NH-1464] - C++ and Dispose method + * [NH-1466] - current_session_context_class = thread_static doesn't work + * [NH-1473] - IsEqual and Compare broken in EntityType + * [NH-1481] - Named Hql queries w/ Named Parameters broken after upgrade to 2.0 from 1.2.1 + * [NH-1483] - Subclass Not Loaded From Cache as Baseclass + * [NH-1488] - Table per class hierarchy and OUTER JOIN + * [NH-1490] - Wrong order of parameters in query when session uses IFilter + * [NH-1492] - Parameter mismatch enabling filters + * [NH-1499] - NullReferenceException construting Criteria query + +** Improvement + * [NH-1484] - first chance exception 'NHibernate.MappingException' when starting a webapplication + * [NH-1496] - Configuration.AddAssembly(Assembly) should do some logging if no mapping files where found + * [NH-1500] - Spelling error of NHibernate.Cfg.ConfigurationSchema.ParseColectionsCache + + +** Patch + * [NH-1034] - HQL functions - parameters support + * [NH-1434] - Some unit test supplies non-character value to LIKE: not portable across every RDBMS + * [NH-1435] - Explicitly order query in NH-1179 to ensure reliable results + * [NH-1436] - Mapping of NH-1250 not portable across every RDBMS + * [NH-1437] - Mapping of NH-1408 not portable across every RDBMS + * [NH-1438] - Some queries from FooBarTest fixture are not portable across every RDBMS + * [NH-1439] - Handle Dialect.GetIdentityColumnString(DbType type) + * [NH-1459] - Sybase dialect + * [NH-1462] - StringHelper.GetFullClassname fails to parse generic types + +Build 2.0.0.GA +======================== +** BREAKING CHANGES from NH1.2.1GA to NH2.0.0 + ##### Infrastructure ##### + * .NET 1.1 is no longer supported + * Nullables.NHibernate is no longer supported (use nullable types of .NET 2.0) + * Contrib projects moved to http://sourceforge.net/projects/nhcontrib + + ##### Compile time ##### + * NHibernate.Expression namespace was renamed to NHibernate.Criterion + * IInterceptor have additional methods. (IsUnsaved was renamed IsTransient) + * INamingStrategy + * IType + * IEntityPersister + * IVersionType + * IBatcher + * IUserCollectionType + * IEnhancedUserType + * IPropertyAccessor + * ValueTypeType renamed to PrimitiveType + + ##### Possible Breaking Changes for external frameworks ##### + * Various classes were moved between namespaces + * Various classes have been renamed (to match Hibernate 3.2 names) + * ISession interface have additional methods + * ICacheProvider + * ICriterion + * CriteriaQueryTranslator + + ##### Initialization time ##### + * <nhibernate> section, in App.config, is no longer supported and will be ignored. Configuration schema for configuration file and App.config is now identical, and the App.config section name is: <hibernate-configuration> + * <hibernate-configuration> have a different schema and all properties names are cheked + * configuration properties are no longer prefixed by "hibernate.", if before you would specify "hibernate.dialect", now you specify just "dialect" + * All named queries will be validated at initialization time, an exception will be thrown if any is not valid (can be disabled if needed) + * Stricter checks for proxying classes (all public methods must be virtual) + + ##### Run time ##### + * SaveOrUpdateCopy() returns a new instance of the entity without changing the original + * AutoFlush will not occur outside a transaction - Database transactions are never optional, all communication with the database must occur inside a transaction, whatever you read or write data. + * NHibernate will return long for count(*) queries on SQL Server + * <formula> must contain parenthesis when needed + * The HQL functions names may cause conflic in your HQL (reserved names are: substring,locate,trim,length,bit_length,coalesce,nullif,abs,mod,sqrt,upper,lower,cast,extract,concat,current_timestamp,sysdate,second,minute,hour,day,month,year,str) + * <any> when meta-type="class" the persistent type is a string containing the Class.FullName (In order to set a parameter in a query you must use SetParameter("paraName", typeof(YourClass).FullName, NHibernateUtil.ClassMetaType) ) + + ##### Mapping ##### + * <any> : default meta-type is "string" (was "class") + +Build 2.0.0.CR2 +======================== +** Sub-task + * [NH-1407] - Actualize documentation of <any> + +Build 2.0.0.CR1 +======================== +** Bug + * [NH-1361] - ProxyTypeValidator: Non-virtual public methods are accepted + * [NH-1389] - Sybase SQLAnywhere 8/9 support broken in Beta1 onword + * [NH-1399] - Database constraint names and hash collisions + * [NH-1403] - Support <any> with meta-type="class" + * [NH-1405] - composite-id property is nulled when related composite many-to-one mapping returns null. + * [NH-1406] - IQuery.SetTimeout work incorrect for ExecuteUpdate + * [NH-1408] - CriteriaTransformer don't clone a DetachedCriteria with sub DetachedCriteria + * [NH-1413] - Paging with multiple orders fail in MSSQL2005 + +** Improvement + * [NH-1304] - Reflection optimizer on != property access + * [NH-1415] - Adding multi query support to MySqlDataDriver + +** New Feature + * [NH-1412] - Allow custom accessors to define if the ReflectionOptimizer can be used. + +** Patch + * [NH-1254] - Sybase ASA10 - Dialect + Driver + * [NH-1390] - Union subclass support for PostgreSQL + +** Task + * [NH-1410] - Spelling mistake in error message: sublcass must be subclass + + +Build 2.0.0.Beta2 +======================== +** Bug + * [NH-1030] - DB2400Dialect : mod(x,y) function triggers a parse exception + * [NH-1077] - Pessimistic locking for SQL Server fails on cached objects + * [NH-1258] - Oracle Sequences mappings without Schema information throwns InvalidKeyException + * [NH-1279] - AggressiveRelease tests fail for MySQL + * [NH-1300] - Detached Entities that have many-to-one associations improperly throw LazyInitializationExceptions when accessing the association outside the loading session + * [NH-1355] - Custom Version type (IUserVersionType) not allowed + * [NH-1362] - Nested cascades on ISession.Refresh() + * [NH-1375] - Disable Multi Query support for Npgsql + * [NH-1383] - Components with (non-C#) Nullables do not follow documentation sect. 7.1 "if all component columns are null, then the entire component is null" + * [NH-1384] - Support for latest Npgsql2 (PostgreSQL) Data Provider + +** Improvement + * [NH-693] - Better error message when user forgets to supply table name + * [NH-803] - Support DML type batch sql statements + * [NH-824] - GetClassname cannot parse generic classnames + * [NH-938] - Escape characters in Like expressions + * [NH-978] - show_sql: Transaction Begin, Commit, Rollback + * [NH-1101] - component directy detection should consider null component value to be equiv to all component member's being null + * [NH-1151] - Improve Configuration to Support ASP.NET Configuration File Hierarchy and Inheritance + * [NH-1216] - SchemaExport creates varchar(255) on MySQL when Property Type is StringClob + * [NH-1236] - XML Entity support in mapping files broken + * [NH-1257] - lazy=true and fetch=join doesn't work together it will be nice to receive a WARN + * [NH-1364] - LinkedHashMap.RemoveImpl can be improved (using try/catch for common scenario) + * [NH-1382] - Oracle Dialect support for Unsigned Int (UInt32, UInt64) + +** New Feature + * [NH-1115] - Add support for "Refresh" cascade style + * [NH-1367] - Add Interceptor or Event to Batcher + + +** Task + * [NH-1144] - Apply patch for NH-1022 (Oracle command batching) to trunk + * [NH-1210] - "table" attribute documented as required when in fact optional + + Build 2.0.0.Beta1 ======================== ** Bug This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-10 04:33:35
|
Revision: 3827 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3827&view=rev Author: fabiomaulo Date: 2008-10-10 04:33:22 +0000 (Fri, 10 Oct 2008) Log Message: ----------- another initial test to support Xml entityMode Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/AB.hbm.xml trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Employer.hbm.xml trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/AB.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/AB.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/AB.hbm.xml 2008-10-10 04:33:22 UTC (rev 3827) @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> + + <class entity-name="A" table="AX" node="a"> + <id name="aId" type="int" column="aId" node="@id"/> + <property name="x" type="string"/> + <set name="bs" node="." embed-xml="true" cascade="all" inverse="true"> + <key column="aId"/> + <one-to-many class="B"/> + </set> + </class> + + + <class entity-name="B" table="BX" node="b"> + <composite-id> + <key-property name="bId" column="bId" type="int" node="@bId"/> + <key-property name="aId" column="aId" type="int" node="@aId"/> + </composite-id> + <property name="y" type="string" node="."/> + </class> + +</hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Account.hbm.xml 2008-10-10 04:33:22 UTC (rev 3827) @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> + + <class entity-name="Customer" node="customer"> + <id name="customerId" type="string" node="@id"/> + <component name="name"> + <property name="first" type="string"/> + <property name="last" type="string"/> + </component> + <property name="address" type="string" node="address"/> + <map name="stuff"> + <key column="customerId"/> + <map-key type="string" column="bar" node="@bar"/> + <element type="string" node="foo" column="foo"/> + </map> + <bag name="morestuff" node="."> + <key column="customerId"/> + <element type="integer" node="amount" column="amount"/> + </bag> + <list name="accounts" cascade="all"> + <key column="customerId2"/> + <list-index column="acctno" base="1"/> + <one-to-many entity-name="Account" node="account"/> + </list> + <many-to-one name="location" node="location/@id" entity-name="Location" embed-xml="false"/> + <property name="description" node="." type="string"/> + <set name="unembedded" embed-xml="false"> + <key column="x"/> + <element type="string" column="y" not-null="true"/> + </set> + </class> + + <class entity-name="Account" node="account"> + <id name="accountId" type="string" node="@id"/> + <many-to-one name="customer" column="customerId" entity-name="Customer" cascade="all" embed-xml="true" /> + <!--not-null="true"--> + <property name="balance" type="big_decimal" node="balance" precision="10" scale="0" /> + </class> + + <class entity-name="Location" node="location"> + <id name="id" node="@id" type="long"> + <generator class="increment"/> + </id> + <property name="address" type="string"/> + </class> + +</hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Employer.hbm.xml =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Employer.hbm.xml (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/Employer.hbm.xml 2008-10-10 04:33:22 UTC (rev 3827) @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="utf-8" ?> +<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> + + <class entity-name="Employer" node="employer"> + <id name="id" node="@id" type="long"> + <generator class="increment"/> + </id> + <property name="name" node="@name" type="string"/> + <set name="employees" node="." cascade="all,delete-orphan" fetch="join" lazy="false"> + <key not-null="true" column="employerId"/> + <one-to-many entity-name="Employee" /> + </set> + </class> + + <class entity-name="Employee" node="employee"> + <id name="id" node="@id" type="long"> + <generator class="increment"/> + </id> + <discriminator column="role" type="string" length="10"/> + <property name="name" node="@name" type="string"/> + <subclass entity-name="Techie" node="techie" /> + <subclass entity-name="Salesdude" node="sales-dude"/> + </class> + + <class entity-name="Department" node="department"> + <id name="id" node="@id" type="long"> + <generator class="increment"/> + </id> + <property name="name" node="@name" type="string"/> + <many-to-one name="manager" entity-name="Employee" cascade="all" fetch="join" lazy="false" embed-xml="true" node="manager" /> + </class> + +</hibernate-mapping> \ No newline at end of file Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Basic/XmlFixture.cs 2008-10-10 04:33:22 UTC (rev 3827) @@ -0,0 +1,69 @@ +using System.Collections; +using System.Xml; +using NHibernate.Cfg; +using NUnit.Framework; + +namespace NHibernate.Test.EntityModeTest.Xml.Basic +{ + [TestFixture, Ignore("Not supported yet.")] + public class XmlFixture : TestCase + { + protected override string MappingsAssembly + { + get { return "NHibernate.Test"; } + } + + #region Overrides of TestCase + + protected override IList Mappings + { + get + { + return new[] + { + "EntityModeTest.Xml.Basic.Account.hbm.xml", "EntityModeTest.Xml.Basic.AB.hbm.xml", + "EntityModeTest.Xml.Basic.Employer.hbm.xml" + }; + } + } + + #endregion + + protected override void Configure(Configuration configuration) + { + cfg.SetProperty(Environment.DefaultEntityMode, EntityModeHelper.ToString(EntityMode.Xml)); + } + + [Test] + public void CompositeId() + { + const string xml = +@"<a id='1'> + <x>foo bar</x> + <b bId='1' aId='1>foo foo</b> + <b bId='2' aId='1>bar bar</b> +</a>"; + + XmlElement a=null; + ISession s = OpenSession(); + ITransaction t = s.BeginTransaction(); + s.Persist("A", a); + t.Commit(); + s.Close(); + + s = OpenSession(); + t = s.BeginTransaction(); + //a = (XmlElement)s.CreateCriteria("A").UniqueResult(); + Assert.AreEqual(a.GetElementsByTagName("b").Count, 2); + Print(a); + //s.Delete("A", a); + t.Commit(); + s.Close(); + } + + public static void Print(XmlElement elt) + { + //XMLHelper.dump( elt ); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-10 00:13:56 UTC (rev 3826) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-10 04:33:22 UTC (rev 3827) @@ -161,6 +161,7 @@ <Compile Include="EngineTest\TypedValueFixture.cs" /> <Compile Include="EntityModeTest\Map\Basic\DynamicClassFixture.cs" /> <Compile Include="EntityModeTest\Xml\Accessors\XmlAccessorFixture.cs" /> + <Compile Include="EntityModeTest\Xml\Basic\XmlFixture.cs" /> <Compile Include="Events\Collections\AbstractCollectionEventFixture.cs" /> <Compile Include="Events\Collections\AbstractParentWithCollection.cs" /> <Compile Include="Events\Collections\Association\AbstractAssociationCollectionEventFixture.cs" /> @@ -1488,6 +1489,9 @@ <EmbeddedResource Include="Cascade\JobBatch.hbm.xml" /> <EmbeddedResource Include="Deletetransient\Person.hbm.xml" /> <Content Include="DynamicEntity\package.html" /> + <EmbeddedResource Include="EntityModeTest\Xml\Basic\AB.hbm.xml" /> + <EmbeddedResource Include="EntityModeTest\Xml\Basic\Account.hbm.xml" /> + <EmbeddedResource Include="EntityModeTest\Xml\Basic\Employer.hbm.xml" /> <EmbeddedResource Include="SqlTest\MSSQLIdentityInsertWithStoredProcs.hbm.xml" /> <EmbeddedResource Include="NHSpecificTest\NH1508\Mappings.hbm.xml" /> <EmbeddedResource Include="GenericTest\OrderedSetGeneric\OrderedSetFixture.hbm.xml" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-10 00:13:58
|
Revision: 3826 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3826&view=rev Author: ayenderahien Date: 2008-10-10 00:13:56 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Nitpickers defensive coding Modified Paths: -------------- branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Address.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Customer.cs Modified: branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Address.cs =================================================================== --- branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Address.cs 2008-10-10 00:08:11 UTC (rev 3825) +++ branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Address.cs 2008-10-10 00:13:56 UTC (rev 3826) @@ -1,5 +1,9 @@ namespace NHibernate.PostSharp.Proxies.Tests { + // those attributes are here until I figure out how to make PostSharp get the list of entities + // we want to weave externally, hopefully from the mapping + + // THEY WON'T BE HERE FOR FINAL VERSION - THIS CLASS WOULD BE FULLY POCO [NHibernateLazyLoadingSupport, AddNHibernateProxyAttribute] public class Address { Modified: branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Customer.cs =================================================================== --- branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Customer.cs 2008-10-10 00:08:11 UTC (rev 3825) +++ branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Customer.cs 2008-10-10 00:13:56 UTC (rev 3826) @@ -2,6 +2,10 @@ namespace NHibernate.PostSharp.Proxies.Tests { + // those attributes are here until I figure out how to make PostSharp get the list of entities + // we want to weave externally, hopefully from the mapping + + // THEY WON'T BE HERE FOR FINAL VERSION - THIS CLASS WOULD BE FULLY POCO [NHibernateLazyLoadingSupport, AddNHibernateProxyAttribute] public class Customer { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-10 00:08:16
|
Revision: 3825 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3825&view=rev Author: ayenderahien Date: 2008-10-10 00:08:11 +0000 (Fri, 10 Oct 2008) Log Message: ----------- Initial implementation of static proxies This is likely breaking NHibernate, and it is not production quality code. You need to have postsharp installed and to modify the post build process in VS to get this to work. Modified Paths: -------------- branches/static-proxies/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs branches/static-proxies/src/NHibernate/Bytecode/IProxyFactoryFactory.cs branches/static-proxies/src/NHibernate/Cfg/Configuration.cs branches/static-proxies/src/NHibernate/Engine/StatefulPersistenceContext.cs branches/static-proxies/src/NHibernate/Event/Default/DefaultSaveEventListener.cs branches/static-proxies/src/NHibernate/InvalidProxyTypeException.cs branches/static-proxies/src/NHibernate/NHibernate.csproj branches/static-proxies/src/NHibernate/NHibernateUtil.cs branches/static-proxies/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs branches/static-proxies/src/NHibernate/Type/GenericSetType.cs branches/static-proxies/src/NHibernate.Test/NHSpecificTest/NH1464/Fixture.cs branches/static-proxies/src/NHibernate.Test/NHSpecificTest/ProxyValidator/Fixture.cs branches/static-proxies/src/NHibernate.Test/ProxyInterface/CustomProxyFixture.cs branches/static-proxies/src/NHibernate.sln Added Paths: ----------- branches/static-proxies/src/NHibernate/Proxy/DynamicProxyTypeValidator.cs branches/static-proxies/src/NHibernate/Proxy/IProxyTypeValidator.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/ branches/static-proxies/src/NHibernate.PostSharp.Proxies/AddNHibernateProxyAttribute.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/IPostSharpNHibernateProxy.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/NHibernate.PostSharp.Proxies.csproj branches/static-proxies/src/NHibernate.PostSharp.Proxies/NHibernateLazyLoadingSupportAttribute.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/PostSharpInitializer.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/PostSharpProxyAdapter.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/PostSharpProxyFactory.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/PostSharpProxyFactoryFactory.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/PostSharpProxyValidator.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies/Properties/ branches/static-proxies/src/NHibernate.PostSharp.Proxies/Properties/AssemblyInfo.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/ branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Address.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Address.hbm.xml branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/App.config branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/CanCreateNHibernateSessionFactoryWithLazyLoadingAndNoVirtuals.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/ClassesAreWeavedCorrectly.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Customer.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Customer.hbm.xml branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/LoadingInstancesFromTheDatabase.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/NHibernate.PostSharp.Proxies.Tests.csproj branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Properties/ branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/Properties/AssemblyInfo.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/SavingInstanceToDatabase.cs branches/static-proxies/src/NHibernate.PostSharp.Proxies.Tests/TestCase.cs Modified: branches/static-proxies/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs =================================================================== --- branches/static-proxies/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs 2008-10-09 23:48:30 UTC (rev 3824) +++ branches/static-proxies/src/NHibernate/Bytecode/DefaultProxyFactoryFactory.cs 2008-10-10 00:08:11 UTC (rev 3825) @@ -12,6 +12,11 @@ return new CastleProxyFactory(); } - #endregion + public IProxyTypeValidator Validator + { + get { return new DynamicProxyTypeValidator(); } + } + + #endregion } } Modified: branches/static-proxies/src/NHibernate/Bytecode/IProxyFactoryFactory.cs =================================================================== --- branches/static-proxies/src/NHibernate/Bytecode/IProxyFactoryFactory.cs 2008-10-09 23:48:30 UTC (rev 3824) +++ branches/static-proxies/src/NHibernate/Bytecode/IProxyFactoryFactory.cs 2008-10-10 00:08:11 UTC (rev 3825) @@ -16,6 +16,9 @@ /// </summary> /// <returns> The lazy-load proxy factory. </returns> IProxyFactory BuildProxyFactory(); + + IProxyTypeValidator Validator { get; } + /* /// <summary> Build a proxy factory for basic proxy concerns. The return /// should be capable of properly handling newInstance() calls. Modified: branches/static-proxies/src/NHibernate/Cfg/Configuration.cs =================================================================== --- branches/static-proxies/src/NHibernate/Cfg/Configuration.cs 2008-10-09 23:48:30 UTC (rev 3824) +++ branches/static-proxies/src/NHibernate/Cfg/Configuration.cs 2008-10-10 00:08:11 UTC (rev 3825) @@ -787,19 +787,19 @@ private void Validate() { bool validateProxy = PropertiesHelper.GetBoolean(Environment.UseProxyValidator, properties, true); - HashedSet allProxyErrors = null; + HashedSet<string> allProxyErrors = null; foreach (PersistentClass clazz in classes.Values) { clazz.Validate(mapping); if (validateProxy) { - ICollection errors = ValidateProxyInterface(clazz); + ICollection<string> errors = ValidateProxyInterface(clazz); if (errors != null) { if (allProxyErrors == null) { - allProxyErrors = new HashedSet(errors); + allProxyErrors = new HashedSet<string>(errors); } else { @@ -820,21 +820,9 @@ } } - private static ICollection ValidateProxyInterface(PersistentClass persistentClass) + private static ICollection<string> ValidateProxyInterface(PersistentClass persistentClass) { - if (!persistentClass.IsLazy) - { - // Nothing to validate - return null; - } - - if (persistentClass.ProxyInterface == null) - { - // Nothing to validate - return null; - } - - return ProxyTypeValidator.ValidateType(persistentClass.ProxyInterface); + return Environment.BytecodeProvider.ProxyFactoryFactory.Validator.ValidateType(persistentClass); } /// <summary> Modified: branches/static-proxies/src/NHibernate/Engine/StatefulPersistenceContext.cs =================================================================== --- branches/static-proxies/src/NHibernate/Engine/StatefulPersistenceContext.cs 2008-10-09 23:48:30 UTC (rev 3824) +++ branches/static-proxies/src/NHibernate/Engine/StatefulPersistenceContext.cs 2008-10-10 00:08:11 UTC (rev 3825) @@ -17,1231 +17,1233 @@ namespace NHibernate.Engine { - /// <summary> - /// A <see cref="IPersistenceContext"/> represents the state of persistent "stuff" which - /// NHibernate is tracking. This includes persistent entities, collections, - /// as well as proxies generated. - /// </summary> - /// <remarks> - /// There is meant to be a one-to-one correspondence between a SessionImpl and - /// a PersistentContext. The SessionImpl uses the PersistentContext to track - /// the current state of its context. Event-listeners then use the - /// PersistentContext to drive their processing. - /// </remarks> - [Serializable] - public class StatefulPersistenceContext : IPersistenceContext, ISerializable, IDeserializationCallback - { - private const int InitCollectionSize = 8; - private static readonly ILog log = LogManager.GetLogger(typeof(StatefulPersistenceContext)); - private static readonly ILog ProxyWarnLog = LogManager.GetLogger(typeof(StatefulPersistenceContext).FullName + ".ProxyWarnLog"); + /// <summary> + /// A <see cref="IPersistenceContext"/> represents the state of persistent "stuff" which + /// NHibernate is tracking. This includes persistent entities, collections, + /// as well as proxies generated. + /// </summary> + /// <remarks> + /// There is meant to be a one-to-one correspondence between a SessionImpl and + /// a PersistentContext. The SessionImpl uses the PersistentContext to track + /// the current state of its context. Event-listeners then use the + /// PersistentContext to drive their processing. + /// </remarks> + [Serializable] + public class StatefulPersistenceContext : IPersistenceContext, ISerializable, IDeserializationCallback + { + private const int InitCollectionSize = 8; + private static readonly ILog log = LogManager.GetLogger(typeof(StatefulPersistenceContext)); + private static readonly ILog ProxyWarnLog = LogManager.GetLogger(typeof(StatefulPersistenceContext).FullName + ".ProxyWarnLog"); - public static readonly object NoRow = new object(); + public static readonly object NoRow = new object(); - [NonSerialized] - private ISessionImplementor session; + [NonSerialized] + private ISessionImplementor session; - // Loaded entity instances, by EntityKey - private readonly Dictionary<EntityKey, object> entitiesByKey; + // Loaded entity instances, by EntityKey + private readonly Dictionary<EntityKey, object> entitiesByKey; - // Loaded entity instances, by EntityUniqueKey - private readonly Dictionary<EntityUniqueKey, object> entitiesByUniqueKey; + // Loaded entity instances, by EntityUniqueKey + private readonly Dictionary<EntityUniqueKey, object> entitiesByUniqueKey; - // Identity map of EntityEntry instances, by the entity instance - private readonly IDictionary entityEntries; + // Identity map of EntityEntry instances, by the entity instance + private readonly IDictionary entityEntries; - // Entity proxies, by EntityKey - private readonly Dictionary<EntityKey, INHibernateProxy> proxiesByKey; + // Entity proxies, by EntityKey + private readonly Dictionary<EntityKey, INHibernateProxy> proxiesByKey; - // Snapshots of current database state for entities - // that have *not* been loaded - private readonly Dictionary<EntityKey, object> entitySnapshotsByKey; + // Snapshots of current database state for entities + // that have *not* been loaded + private readonly Dictionary<EntityKey, object> entitySnapshotsByKey; - // Identity map of array holder ArrayHolder instances, by the array instance - private readonly IDictionary arrayHolders; + // Identity map of array holder ArrayHolder instances, by the array instance + private readonly IDictionary arrayHolders; - // Identity map of CollectionEntry instances, by the collection wrapper - private readonly IDictionary collectionEntries; + // Identity map of CollectionEntry instances, by the collection wrapper + private readonly IDictionary collectionEntries; - // Collection wrappers, by the CollectionKey - private readonly Dictionary<CollectionKey, IPersistentCollection> collectionsByKey; + // Collection wrappers, by the CollectionKey + private readonly Dictionary<CollectionKey, IPersistentCollection> collectionsByKey; - // Set of EntityKeys of deleted objects - private readonly HashedSet<EntityKey> nullifiableEntityKeys; + // Set of EntityKeys of deleted objects + private readonly HashedSet<EntityKey> nullifiableEntityKeys; - // properties that we have tried to load, and not found in the database - private ISet<AssociationKey> nullAssociations; + // properties that we have tried to load, and not found in the database + private ISet<AssociationKey> nullAssociations; - // A list of collection wrappers that were instantiating during result set - // processing, that we will need to initialize at the end of the query - [NonSerialized] - private List<IPersistentCollection> nonlazyCollections; + // A list of collection wrappers that were instantiating during result set + // processing, that we will need to initialize at the end of the query + [NonSerialized] + private List<IPersistentCollection> nonlazyCollections; - // A container for collections we load up when the owning entity is not - // yet loaded ... for now, this is purely transient! - private Dictionary<CollectionKey, IPersistentCollection> unownedCollections; + // A container for collections we load up when the owning entity is not + // yet loaded ... for now, this is purely transient! + private Dictionary<CollectionKey, IPersistentCollection> unownedCollections; - private bool hasNonReadOnlyEntities; + private bool hasNonReadOnlyEntities; - [NonSerialized] - private int cascading; + [NonSerialized] + private int cascading; - [NonSerialized] - private bool flushing; + [NonSerialized] + private bool flushing; - [NonSerialized] - private int loadCounter; + [NonSerialized] + private int loadCounter; - [NonSerialized] - private LoadContexts loadContexts; + [NonSerialized] + private LoadContexts loadContexts; - [NonSerialized] - private BatchFetchQueue batchFetchQueue; + [NonSerialized] + private BatchFetchQueue batchFetchQueue; - /// <summary> Constructs a PersistentContext, bound to the given session. </summary> - /// <param name="session">The session "owning" this context. </param> - public StatefulPersistenceContext(ISessionImplementor session) - { - loadCounter = 0; - flushing = false; - cascading = 0; - this.session = session; + /// <summary> Constructs a PersistentContext, bound to the given session. </summary> + /// <param name="session">The session "owning" this context. </param> + public StatefulPersistenceContext(ISessionImplementor session) + { + loadCounter = 0; + flushing = false; + cascading = 0; + this.session = session; - entitiesByKey = new Dictionary<EntityKey, object>(InitCollectionSize); - entitiesByUniqueKey = new Dictionary<EntityUniqueKey, object>(InitCollectionSize); - proxiesByKey = new Dictionary<EntityKey, INHibernateProxy>(InitCollectionSize); - entitySnapshotsByKey = new Dictionary<EntityKey, object>(InitCollectionSize); - entityEntries = IdentityMap.InstantiateSequenced(InitCollectionSize); - collectionEntries = IdentityMap.InstantiateSequenced(InitCollectionSize); - collectionsByKey = new Dictionary<CollectionKey, IPersistentCollection>(InitCollectionSize); - arrayHolders = IdentityMap.Instantiate(InitCollectionSize); - nullifiableEntityKeys = new HashedSet<EntityKey>(); - InitTransientState(); - } + entitiesByKey = new Dictionary<EntityKey, object>(InitCollectionSize); + entitiesByUniqueKey = new Dictionary<EntityUniqueKey, object>(InitCollectionSize); + proxiesByKey = new Dictionary<EntityKey, INHibernateProxy>(InitCollectionSize); + entitySnapshotsByKey = new Dictionary<EntityKey, object>(InitCollectionSize); + entityEntries = IdentityMap.InstantiateSequenced(InitCollectionSize); + collectionEntries = IdentityMap.InstantiateSequenced(InitCollectionSize); + collectionsByKey = new Dictionary<CollectionKey, IPersistentCollection>(InitCollectionSize); + arrayHolders = IdentityMap.Instantiate(InitCollectionSize); + nullifiableEntityKeys = new HashedSet<EntityKey>(); + InitTransientState(); + } - private void InitTransientState() - { - loadContexts = null; - nullAssociations = new HashedSet<AssociationKey>(); - nonlazyCollections = new List<IPersistentCollection>(InitCollectionSize); - } + private void InitTransientState() + { + loadContexts = null; + nullAssociations = new HashedSet<AssociationKey>(); + nonlazyCollections = new List<IPersistentCollection>(InitCollectionSize); + } - #region IPersistenceContext Members + #region IPersistenceContext Members - public bool IsStateless - { - get { return false; } - } + public bool IsStateless + { + get { return false; } + } - /// <summary> - /// Get the session to which this persistence context is bound. - /// </summary> - public ISessionImplementor Session - { - get { return session; } - } + /// <summary> + /// Get the session to which this persistence context is bound. + /// </summary> + public ISessionImplementor Session + { + get { return session; } + } - /// <summary> - /// Retrieve this persistence context's managed load context. - /// </summary> - public LoadContexts LoadContexts - { - get - { - if (loadContexts == null) - loadContexts = new LoadContexts(this); + /// <summary> + /// Retrieve this persistence context's managed load context. + /// </summary> + public LoadContexts LoadContexts + { + get + { + if (loadContexts == null) + loadContexts = new LoadContexts(this); - return loadContexts; - } - } + return loadContexts; + } + } - /// <summary> - /// Get the <tt>BatchFetchQueue</tt>, instantiating one if necessary. - /// </summary> - public BatchFetchQueue BatchFetchQueue - { - get - { - if (batchFetchQueue == null) - batchFetchQueue = new BatchFetchQueue(this); + /// <summary> + /// Get the <tt>BatchFetchQueue</tt>, instantiating one if necessary. + /// </summary> + public BatchFetchQueue BatchFetchQueue + { + get + { + if (batchFetchQueue == null) + batchFetchQueue = new BatchFetchQueue(this); - return batchFetchQueue; - } - } + return batchFetchQueue; + } + } - /// <summary> Retrieve the set of EntityKeys representing nullifiable references</summary> - public ISet NullifiableEntityKeys - { - get { return nullifiableEntityKeys; } - } + /// <summary> Retrieve the set of EntityKeys representing nullifiable references</summary> + public ISet NullifiableEntityKeys + { + get { return nullifiableEntityKeys; } + } - /// <summary> Get the mapping from key value to entity instance</summary> - public IDictionary<EntityKey, object> EntitiesByKey - { - get { return entitiesByKey; } - } + /// <summary> Get the mapping from key value to entity instance</summary> + public IDictionary<EntityKey, object> EntitiesByKey + { + get { return entitiesByKey; } + } - /// <summary> Get the mapping from entity instance to entity entry</summary> - public IDictionary EntityEntries - { - get { return entityEntries; } - } + /// <summary> Get the mapping from entity instance to entity entry</summary> + public IDictionary EntityEntries + { + get { return entityEntries; } + } - /// <summary> Get the mapping from collection instance to collection entry</summary> - public IDictionary CollectionEntries - { - get { return collectionEntries; } - } + /// <summary> Get the mapping from collection instance to collection entry</summary> + public IDictionary CollectionEntries + { + get { return collectionEntries; } + } - /// <summary> Get the mapping from collection key to collection instance</summary> - public IDictionary<CollectionKey, IPersistentCollection> CollectionsByKey - { - get { return collectionsByKey; } - } + /// <summary> Get the mapping from collection key to collection instance</summary> + public IDictionary<CollectionKey, IPersistentCollection> CollectionsByKey + { + get { return collectionsByKey; } + } - /// <summary> How deep are we cascaded?</summary> - public int CascadeLevel - { - get { return cascading; } - } + /// <summary> How deep are we cascaded?</summary> + public int CascadeLevel + { + get { return cascading; } + } - /// <summary>Is a flush cycle currently in process?</summary> - /// <remarks>Called before and after the flushcycle</remarks> - public bool Flushing - { - get { return flushing; } - set { flushing = value; } - } + /// <summary>Is a flush cycle currently in process?</summary> + /// <remarks>Called before and after the flushcycle</remarks> + public bool Flushing + { + get { return flushing; } + set { flushing = value; } + } - /// <summary> Add a collection which has no owner loaded</summary> - public void AddUnownedCollection(CollectionKey key, IPersistentCollection collection) - { - if (unownedCollections == null) - unownedCollections = new Dictionary<CollectionKey, IPersistentCollection>(8); + /// <summary> Add a collection which has no owner loaded</summary> + public void AddUnownedCollection(CollectionKey key, IPersistentCollection collection) + { + if (unownedCollections == null) + unownedCollections = new Dictionary<CollectionKey, IPersistentCollection>(8); - unownedCollections[key] = collection; - } + unownedCollections[key] = collection; + } - /// <summary> - /// Get and remove a collection whose owner is not yet loaded, - /// when its owner is being loaded - /// </summary> - public IPersistentCollection UseUnownedCollection(CollectionKey key) - { - if (unownedCollections == null) - { - return null; - } - else - { - IPersistentCollection tempObject; - if (unownedCollections.TryGetValue(key, out tempObject)) - unownedCollections.Remove(key); - return tempObject; - } - } + /// <summary> + /// Get and remove a collection whose owner is not yet loaded, + /// when its owner is being loaded + /// </summary> + public IPersistentCollection UseUnownedCollection(CollectionKey key) + { + if (unownedCollections == null) + { + return null; + } + else + { + IPersistentCollection tempObject; + if (unownedCollections.TryGetValue(key, out tempObject)) + unownedCollections.Remove(key); + return tempObject; + } + } - /// <summary> Clear the state of the persistence context</summary> - public void Clear() - { - foreach (INHibernateProxy proxy in proxiesByKey.Values) - { - proxy.HibernateLazyInitializer.Session = null; - } + /// <summary> Clear the state of the persistence context</summary> + public void Clear() + { + foreach (INHibernateProxy proxy in proxiesByKey.Values) + { + ILazyInitializer initializer = proxy.HibernateLazyInitializer; + if (initializer != null) + initializer.Session = null; + } - ICollection collectionEntryArray = IdentityMap.ConcurrentEntries(collectionEntries); - foreach (DictionaryEntry entry in collectionEntryArray) - { - ((IPersistentCollection)entry.Key).UnsetSession(Session); - } + ICollection collectionEntryArray = IdentityMap.ConcurrentEntries(collectionEntries); + foreach (DictionaryEntry entry in collectionEntryArray) + { + ((IPersistentCollection)entry.Key).UnsetSession(Session); + } - arrayHolders.Clear(); - entitiesByKey.Clear(); - entitiesByUniqueKey.Clear(); - entityEntries.Clear(); - entitySnapshotsByKey.Clear(); - collectionsByKey.Clear(); - collectionEntries.Clear(); - if (unownedCollections != null) - { - unownedCollections.Clear(); - } - proxiesByKey.Clear(); - nullifiableEntityKeys.Clear(); - if (batchFetchQueue != null) - { - batchFetchQueue.Clear(); - } - hasNonReadOnlyEntities = false; - if (loadContexts != null) - { - loadContexts.Cleanup(); - } - } + arrayHolders.Clear(); + entitiesByKey.Clear(); + entitiesByUniqueKey.Clear(); + entityEntries.Clear(); + entitySnapshotsByKey.Clear(); + collectionsByKey.Clear(); + collectionEntries.Clear(); + if (unownedCollections != null) + { + unownedCollections.Clear(); + } + proxiesByKey.Clear(); + nullifiableEntityKeys.Clear(); + if (batchFetchQueue != null) + { + batchFetchQueue.Clear(); + } + hasNonReadOnlyEntities = false; + if (loadContexts != null) + { + loadContexts.Cleanup(); + } + } - /// <summary>False if we know for certain that all the entities are read-only</summary> - public bool HasNonReadOnlyEntities - { - get { return hasNonReadOnlyEntities; } - } + /// <summary>False if we know for certain that all the entities are read-only</summary> + public bool HasNonReadOnlyEntities + { + get { return hasNonReadOnlyEntities; } + } - private void SetHasNonReadOnlyEnties(Status value) - { - if (value == Status.Deleted || value == Status.Loaded || value == Status.Saving) - { - hasNonReadOnlyEntities = true; - } - } + private void SetHasNonReadOnlyEnties(Status value) + { + if (value == Status.Deleted || value == Status.Loaded || value == Status.Saving) + { + hasNonReadOnlyEntities = true; + } + } - /// <summary> Set the status of an entry</summary> - public void SetEntryStatus(EntityEntry entry, Status status) - { - entry.Status = status; - SetHasNonReadOnlyEnties(status); - } + /// <summary> Set the status of an entry</summary> + public void SetEntryStatus(EntityEntry entry, Status status) + { + entry.Status = status; + SetHasNonReadOnlyEnties(status); + } - /// <summary> Called after transactions end</summary> - public void AfterTransactionCompletion() - { - // Downgrade locks - foreach (EntityEntry entityEntry in entityEntries.Values) - entityEntry.LockMode = LockMode.None; - } + /// <summary> Called after transactions end</summary> + public void AfterTransactionCompletion() + { + // Downgrade locks + foreach (EntityEntry entityEntry in entityEntries.Values) + entityEntry.LockMode = LockMode.None; + } - /// <summary> - /// Get the current state of the entity as known to the underlying - /// database, or null if there is no corresponding row - /// </summary> - public object[] GetDatabaseSnapshot(object id, IEntityPersister persister) - { - EntityKey key = new EntityKey(id, persister, session.EntityMode); - object cached; - if (entitySnapshotsByKey.TryGetValue(key, out cached)) - { - return cached == NoRow ? null : (object[])cached; - } - else - { - object[] snapshot = persister.GetDatabaseSnapshot(id, session); - entitySnapshotsByKey[key] = snapshot ?? NoRow; - return snapshot; - } - } + /// <summary> + /// Get the current state of the entity as known to the underlying + /// database, or null if there is no corresponding row + /// </summary> + public object[] GetDatabaseSnapshot(object id, IEntityPersister persister) + { + EntityKey key = new EntityKey(id, persister, session.EntityMode); + object cached; + if (entitySnapshotsByKey.TryGetValue(key, out cached)) + { + return cached == NoRow ? null : (object[])cached; + } + else + { + object[] snapshot = persister.GetDatabaseSnapshot(id, session); + entitySnapshotsByKey[key] = snapshot ?? NoRow; + return snapshot; + } + } - /// <summary> - /// Retrieve the cached database snapshot for the requested entity key. - /// </summary> - /// <param name="key">The entity key for which to retrieve the cached snapshot </param> - /// <returns> The cached snapshot </returns> - /// <remarks> - /// <list type="bullet"> - /// <listheader><description>This differs from <see cref="GetDatabaseSnapshot"/> is two important respects:</description></listheader> - /// <item><description>no snapshot is obtained from the database if not already cached</description></item> - /// <item><description>an entry of NO_ROW here is interpreted as an exception</description></item> - /// </list> - /// </remarks> - public object[] GetCachedDatabaseSnapshot(EntityKey key) - { - object snapshot; - if (!entitySnapshotsByKey.TryGetValue(key, out snapshot)) - return null; + /// <summary> + /// Retrieve the cached database snapshot for the requested entity key. + /// </summary> + /// <param name="key">The entity key for which to retrieve the cached snapshot </param> + /// <returns> The cached snapshot </returns> + /// <remarks> + /// <list type="bullet"> + /// <listheader><description>This differs from <see cref="GetDatabaseSnapshot"/> is two important respects:</description></listheader> + /// <item><description>no snapshot is obtained from the database if not already cached</description></item> + /// <item><description>an entry of NO_ROW here is interpreted as an exception</description></item> + /// </list> + /// </remarks> + public object[] GetCachedDatabaseSnapshot(EntityKey key) + { + object snapshot; + if (!entitySnapshotsByKey.TryGetValue(key, out snapshot)) + return null; - if (snapshot == NoRow) - { - throw new HibernateException("persistence context reported no row snapshot for " + MessageHelper.InfoString(key.EntityName, key.Identifier)); - } - return (object[])snapshot; - } + if (snapshot == NoRow) + { + throw new HibernateException("persistence context reported no row snapshot for " + MessageHelper.InfoString(key.EntityName, key.Identifier)); + } + return (object[])snapshot; + } - /// <summary> - /// Get the values of the natural id fields as known to the underlying - /// database, or null if the entity has no natural id or there is no - /// corresponding row. - /// </summary> - public object[] GetNaturalIdSnapshot(object id, IEntityPersister persister) - { - if (!persister.HasNaturalIdentifier) - { - return null; - } + /// <summary> + /// Get the values of the natural id fields as known to the underlying + /// database, or null if the entity has no natural id or there is no + /// corresponding row. + /// </summary> + public object[] GetNaturalIdSnapshot(object id, IEntityPersister persister) + { + if (!persister.HasNaturalIdentifier) + { + return null; + } - // if the natural-id is marked as non-mutable, it is not retrieved during a - // normal database-snapshot operation... - int[] props = persister.NaturalIdentifierProperties; - bool[] updateable = persister.PropertyUpdateability; - bool allNatualIdPropsAreUpdateable = true; - for (int i = 0; i < props.Length; i++) - { - if (!updateable[props[i]]) - { - allNatualIdPropsAreUpdateable = false; - break; - } - } + // if the natural-id is marked as non-mutable, it is not retrieved during a + // normal database-snapshot operation... + int[] props = persister.NaturalIdentifierProperties; + bool[] updateable = persister.PropertyUpdateability; + bool allNatualIdPropsAreUpdateable = true; + for (int i = 0; i < props.Length; i++) + { + if (!updateable[props[i]]) + { + allNatualIdPropsAreUpdateable = false; + break; + } + } - if (allNatualIdPropsAreUpdateable) - { - // do this when all the properties are updateable since there is - // a certain likelihood that the information will already be - // snapshot-cached. - object[] entitySnapshot = GetDatabaseSnapshot(id, persister); - if (entitySnapshot == NoRow) - { - return null; - } - object[] naturalIdSnapshot = new object[props.Length]; - for (int i = 0; i < props.Length; i++) - { - naturalIdSnapshot[i] = entitySnapshot[props[i]]; - } - return naturalIdSnapshot; - } - else - { - return persister.GetNaturalIdentifierSnapshot(id, session); - } - } + if (allNatualIdPropsAreUpdateable) + { + // do this when all the properties are updateable since there is + // a certain likelihood that the information will already be + // snapshot-cached. + object[] entitySnapshot = GetDatabaseSnapshot(id, persister); + if (entitySnapshot == NoRow) + { + return null; + } + object[] naturalIdSnapshot = new object[props.Length]; + for (int i = 0; i < props.Length; i++) + { + naturalIdSnapshot[i] = entitySnapshot[props[i]]; + } + return naturalIdSnapshot; + } + else + { + return persister.GetNaturalIdentifierSnapshot(id, session); + } + } - /// <summary> Add a canonical mapping from entity key to entity instance</summary> - public void AddEntity(EntityKey key, object entity) - { - entitiesByKey[key] = entity; - BatchFetchQueue.RemoveBatchLoadableEntityKey(key); - } + /// <summary> Add a canonical mapping from entity key to entity instance</summary> + public void AddEntity(EntityKey key, object entity) + { + entitiesByKey[key] = entity; + BatchFetchQueue.RemoveBatchLoadableEntityKey(key); + } - /// <summary> - /// Get the entity instance associated with the given <tt>EntityKey</tt> - /// </summary> - public object GetEntity(EntityKey key) - { - object result; - entitiesByKey.TryGetValue(key, out result); - return result; - } + /// <summary> + /// Get the entity instance associated with the given <tt>EntityKey</tt> + /// </summary> + public object GetEntity(EntityKey key) + { + object result; + entitiesByKey.TryGetValue(key, out result); + return result; + } - /// <summary> Is there an entity with the given key in the persistence context</summary> - public bool ContainsEntity(EntityKey key) - { - return entitiesByKey.ContainsKey(key); - } + /// <summary> Is there an entity with the given key in the persistence context</summary> + public bool ContainsEntity(EntityKey key) + { + return entitiesByKey.ContainsKey(key); + } - /// <summary> - /// Remove an entity from the session cache, also clear - /// up other state associated with the entity, all except - /// for the <tt>EntityEntry</tt> - /// </summary> - public object RemoveEntity(EntityKey key) - { - object tempObject = entitiesByKey[key]; - entitiesByKey.Remove(key); - object entity = tempObject; - List<EntityUniqueKey> toRemove = new List<EntityUniqueKey>(); - foreach (KeyValuePair<EntityUniqueKey, object> pair in entitiesByUniqueKey) - { - if (pair.Value == entity) toRemove.Add(pair.Key); - } - foreach (EntityUniqueKey uniqueKey in toRemove) - { - entitiesByUniqueKey.Remove(uniqueKey); - } + /// <summary> + /// Remove an entity from the session cache, also clear + /// up other state associated with the entity, all except + /// for the <tt>EntityEntry</tt> + /// </summary> + public object RemoveEntity(EntityKey key) + { + object tempObject = entitiesByKey[key]; + entitiesByKey.Remove(key); + object entity = tempObject; + List<EntityUniqueKey> toRemove = new List<EntityUniqueKey>(); + foreach (KeyValuePair<EntityUniqueKey, object> pair in entitiesByUniqueKey) + { + if (pair.Value == entity) toRemove.Add(pair.Key); + } + foreach (EntityUniqueKey uniqueKey in toRemove) + { + entitiesByUniqueKey.Remove(uniqueKey); + } - entitySnapshotsByKey.Remove(key); - nullifiableEntityKeys.Remove(key); - BatchFetchQueue.RemoveBatchLoadableEntityKey(key); - BatchFetchQueue.RemoveSubselect(key); - return entity; - } + entitySnapshotsByKey.Remove(key); + nullifiableEntityKeys.Remove(key); + BatchFetchQueue.RemoveBatchLoadableEntityKey(key); + BatchFetchQueue.RemoveSubselect(key); + return entity; + } - /// <summary> Get an entity cached by unique key</summary> - public object GetEntity(EntityUniqueKey euk) - { - object result; - entitiesByUniqueKey.TryGetValue(euk, out result); - return result; - } + /// <summary> Get an entity cached by unique key</summary> + public object GetEntity(EntityUniqueKey euk) + { + object result; + entitiesByUniqueKey.TryGetValue(euk, out result); + return result; + } - /// <summary> Add an entity to the cache by unique key</summary> - public void AddEntity(EntityUniqueKey euk, object entity) - { - entitiesByUniqueKey[euk] = entity; - } + /// <summary> Add an entity to the cache by unique key</summary> + public void AddEntity(EntityUniqueKey euk, object entity) + { + entitiesByUniqueKey[euk] = entity; + } - /// <summary> - /// Retrieve the EntityEntry representation of the given entity. - /// </summary> - /// <param name="entity">The entity for which to locate the EntityEntry. </param> - /// <returns> The EntityEntry for the given entity. </returns> - public EntityEntry GetEntry(object entity) - { - return (EntityEntry)entityEntries[entity]; - } + /// <summary> + /// Retrieve the EntityEntry representation of the given entity. + /// </summary> + /// <param name="entity">The entity for which to locate the EntityEntry. </param> + /// <returns> The EntityEntry for the given entity. </returns> + public EntityEntry GetEntry(object entity) + { + return (EntityEntry)entityEntries[entity]; + } - /// <summary> Remove an entity entry from the session cache</summary> - public EntityEntry RemoveEntry(object entity) - { - EntityEntry tempObject = (EntityEntry)entityEntries[entity]; - entityEntries.Remove(entity); - return tempObject; - } + /// <summary> Remove an entity entry from the session cache</summary> + public EntityEntry RemoveEntry(object entity) + { + EntityEntry tempObject = (EntityEntry)entityEntries[entity]; + entityEntries.Remove(entity); + return tempObject; + } - /// <summary> Is there an EntityEntry for this instance?</summary> - public bool IsEntryFor(object entity) - { - return entityEntries.Contains(entity); - } + /// <summary> Is there an EntityEntry for this instance?</summary> + public bool IsEntryFor(object entity) + { + return entityEntries.Contains(entity); + } - /// <summary> Get the collection entry for a persistent collection</summary> - public CollectionEntry GetCollectionEntry(IPersistentCollection coll) - { - return (CollectionEntry)collectionEntries[coll]; - } + /// <summary> Get the collection entry for a persistent collection</summary> + public CollectionEntry GetCollectionEntry(IPersistentCollection coll) + { + return (CollectionEntry)collectionEntries[coll]; + } - /// <summary> Adds an entity to the internal caches.</summary> - public EntityEntry AddEntity(object entity, Status status, object[] loadedState, EntityKey entityKey, object version, - LockMode lockMode, bool existsInDatabase, IEntityPersister persister, - bool disableVersionIncrement, bool lazyPropertiesAreUnfetched) - { - AddEntity(entityKey, entity); + /// <summary> Adds an entity to the internal caches.</summary> + public EntityEntry AddEntity(object entity, Status status, object[] loadedState, EntityKey entityKey, object version, + LockMode lockMode, bool existsInDatabase, IEntityPersister persister, + bool disableVersionIncrement, bool lazyPropertiesAreUnfetched) + { + AddEntity(entityKey, entity); - return AddEntry(entity, status, loadedState, null, entityKey.Identifier, version, lockMode, existsInDatabase, persister, disableVersionIncrement, lazyPropertiesAreUnfetched); - } + return AddEntry(entity, status, loadedState, null, entityKey.Identifier, version, lockMode, existsInDatabase, persister, disableVersionIncrement, lazyPropertiesAreUnfetched); + } - /// <summary> - /// Generates an appropriate EntityEntry instance and adds it - /// to the event source's internal caches. - /// </summary> - public EntityEntry AddEntry(object entity, Status status, object[] loadedState, object rowId, object id, - object version, LockMode lockMode, bool existsInDatabase, IEntityPersister persister, - bool disableVersionIncrement, bool lazyPropertiesAreUnfetched) - { - EntityEntry e = - new EntityEntry(status, loadedState, rowId, id, version, lockMode, existsInDatabase, persister, session.EntityMode, - disableVersionIncrement, lazyPropertiesAreUnfetched); - entityEntries[entity] = e; + /// <summary> + /// Generates an appropriate EntityEntry instance and adds it + /// to the event source's internal caches. + /// </summary> + public EntityEntry AddEntry(object entity, Status status, object[] loadedState, object rowId, object id, + object version, LockMode lockMode, bool existsInDatabase, IEntityPersister persister, + bool disableVersionIncrement, bool lazyPropertiesAreUnfetched) + { + EntityEntry e = + new EntityEntry(status, loadedState, rowId, id, version, lockMode, existsInDatabase, persister, session.EntityMode, + disableVersionIncrement, lazyPropertiesAreUnfetched); + entityEntries[entity] = e; - SetHasNonReadOnlyEnties(status); - return e; - } + SetHasNonReadOnlyEnties(status); + return e; + } - /// <summary> Is the given collection associated with this persistence context?</summary> - public bool ContainsCollection(IPersistentCollection collection) - { - return collectionEntries.Contains(collection); - } + /// <summary> Is the given collection associated with this persistence context?</summary> + public bool ContainsCollection(IPersistentCollection collection) + { + return collectionEntries.Contains(collection); + } - /// <summary> Is the given proxy associated with this persistence context?</summary> - public bool ContainsProxy(INHibernateProxy proxy) - { - return proxiesByKey.ContainsValue(proxy); - } + /// <summary> Is the given proxy associated with this persistence context?</summary> + public bool ContainsProxy(INHibernateProxy proxy) + { + return proxiesByKey.ContainsValue(proxy); + } - /// <summary> - /// Takes the given object and, if it represents a proxy, reassociates it with this event source. - /// </summary> - /// <param name="value">The possible proxy to be reassociated. </param> - /// <returns> Whether the passed value represented an actual proxy which got initialized. </returns> - public bool ReassociateIfUninitializedProxy(object value) - { - // TODO H3.2 Not ported - //ElementWrapper wrapper = value as ElementWrapper; - //if (wrapper != null) - //{ - // value = wrapper.Element; - //} + /// <summary> + /// Takes the given object and, if it represents a proxy, reassociates it with this event source. + /// </summary> + /// <param name="value">The possible proxy to be reassociated. </param> + /// <returns> Whether the passed value represented an actual proxy which got initialized. </returns> + public bool ReassociateIfUninitializedProxy(object value) + { + // TODO H3.2 Not ported + //ElementWrapper wrapper = value as ElementWrapper; + //if (wrapper != null) + //{ + // value = wrapper.Element; + //} - if (!NHibernateUtil.IsInitialized(value)) - { - INHibernateProxy proxy = (INHibernateProxy)value; - ReassociateProxy(proxy.HibernateLazyInitializer, proxy); - return true; - } - else - { - return false; - } - } + if (!NHibernateUtil.IsInitialized(value)) + { + INHibernateProxy proxy = (INHibernateProxy)value; + ReassociateProxy(proxy.HibernateLazyInitializer, proxy); + return true; + } + else + { + return false; + } + } - /// <summary> - /// If a deleted entity instance is re-saved, and it has a proxy, we need to - /// reset the identifier of the proxy - /// </summary> - public void ReassociateProxy(object value, object id) - { - // TODO H3.2 Not ported - //ElementWrapper wrapper = value as ElementWrapper; - //if (wrapper != null) - //{ - // value = wrapper.Element; - //} + /// <summary> + /// If a deleted entity instance is re-saved, and it has a proxy, we need to + /// reset the identifier of the proxy + /// </summary> + public void ReassociateProxy(object value, object id) + { + // TODO H3.2 Not ported + //ElementWrapper wrapper = value as ElementWrapper; + //if (wrapper != null) + //{ + // value = wrapper.Element; + //} - if (value is INHibernateProxy) - { - if (log.IsDebugEnabled) - { - log.Debug("setting proxy identifier: " + id); - } - INHibernateProxy proxy = (INHibernateProxy)value; - ILazyInitializer li = proxy.HibernateLazyInitializer; - li.Identifier = id; - ReassociateProxy(li, proxy); - } - } + INHibernateProxy proxy = value as INHibernateProxy; + if (proxy != null && proxy.HibernateLazyInitializer != null) + { + if (log.IsDebugEnabled) + { + log.Debug("setting proxy identifier: " + id); + } + ILazyInitializer li = proxy.HibernateLazyInitializer; + li.Identifier = id; + ReassociateProxy(li, proxy); + } + } - /// <summary> - /// Associate a proxy that was instantiated by another session with this session - /// </summary> - /// <param name="li">The proxy initializer. </param> - /// <param name="proxy">The proxy to reassociate. </param> - private void ReassociateProxy(ILazyInitializer li, INHibernateProxy proxy) - { - if (li.Session != Session) - { - IEntityPersister persister = session.Factory.GetEntityPersister(li.EntityName); - EntityKey key = new EntityKey(li.Identifier, persister, session.EntityMode); - // any earlier proxy takes precedence - if (!proxiesByKey.ContainsKey(key)) - { - proxiesByKey[key] = proxy; - } - proxy.HibernateLazyInitializer.Session = Session; - } - } + /// <summary> + /// Associate a proxy that was instantiated by another session with this session + /// </summary> + /// <param name="li">The proxy initializer. </param> + /// <param name="proxy">The proxy to reassociate. </param> + private void ReassociateProxy(ILazyInitializer li, INHibernateProxy proxy) + { + if (li.Session != Session) + { + IEntityPersister persister = session.Factory.GetEntityPersister(li.EntityName); + EntityKey key = new EntityKey(li.Identifier, persister, session.EntityMode); + // any earlier proxy takes precedence + if (!proxiesByKey.ContainsKey(key)) + { + proxiesByKey[key] = proxy; + } + proxy.HibernateLazyInitializer.Session = Session; + } + } - /// <summary> - /// Get the entity instance underlying the given proxy, throwing - /// an exception if the proxy is uninitialized. If the given object - /// is not a proxy, simply return the argument. - /// </summary> - public object Unproxy(object maybeProxy) - { - // TODO H3.2 Not ported - //ElementWrapper wrapper = maybeProxy as ElementWrapper; - //if (wrapper != null) - //{ - // maybeProxy = wrapper.Element; - //} + /// <summary> + /// Get the entity instance underlying the given proxy, throwing + /// an exception if the proxy is uninitialized. If the given object + /// is not a proxy, simply return the argument. + /// </summary> + public object Unproxy(object maybeProxy) + { + // TODO H3.2 Not ported + //ElementWrapper wrapper = maybeProxy as ElementWrapper; + //if (wrapper != null) + //{ + // maybeProxy = wrapper.Element; + //} - INHibernateProxy proxy = maybeProxy as INHibernateProxy; - if (proxy != null) - { - ILazyInitializer li = proxy.HibernateLazyInitializer; - if (li.IsUninitialized) - throw new PersistentObjectException("object was an uninitialized proxy for " + li.PersistentClass.FullName); + INHibernateProxy proxy = maybeProxy as INHibernateProxy; + if (proxy != null) + { + ILazyInitializer li = proxy.HibernateLazyInitializer; + if (li.IsUninitialized) + throw new PersistentObjectException("object was an uninitialized proxy for " + li.PersistentClass.FullName); - return li.GetImplementation(); // unwrap the object - } - else - { - return maybeProxy; - } - } + return li.GetImplementation(); // unwrap the object + } + else + { + return maybeProxy; + } + } - /// <summary> - /// Possibly unproxy the given reference and reassociate it with the current session. - /// </summary> - /// <param name="maybeProxy">The reference to be unproxied if it currently represents a proxy. </param> - /// <returns> The unproxied instance. </returns> - public object UnproxyAndReassociate(object maybeProxy) - { - // TODO H3.2 Not ported - //ElementWrapper wrapper = maybeProxy as ElementWrapper; - //if (wrapper != null) - //{ - // maybeProxy = wrapper.Element; - //} + /// <summary> + /// Possibly unproxy the given reference and reassociate it with the current session. + /// </summary> + /// <param name="maybeProxy">The reference to be unproxied if it currently represents a proxy. </param> + /// <returns> The unproxied instance. </returns> + public object UnproxyAndReassociate(object maybeProxy) + { + // TODO H3.2 Not ported + //ElementWrapper wrapper = maybeProxy as ElementWrapper; + //if (wrapper != null) + //{ + // maybeProxy = wrapper.Element; + //} - if (maybeProxy is INHibernateProxy) - { - INHibernateProxy proxy = (INHibernateProxy)maybeProxy; - ILazyInitializer li = proxy.HibernateLazyInitializer; - ReassociateProxy(li, proxy); - return li.GetImplementation(); //initialize + unwrap the object - } - else - { - return maybeProxy; - } - } + INHibernateProxy proxy = maybeProxy as INHibernateProxy; + if (proxy != null && proxy.HibernateLazyInitializer != null) + { + ILazyInitializer li = proxy.HibernateLazyInitializer; + ReassociateProxy(li, proxy); + return li.GetImplementation(); //initialize + unwrap the object + } + else + { + return maybeProxy; + } + } - /// <summary> - /// Attempts to check whether the given key represents an entity already loaded within the - /// current session. - /// </summary> - /// <param name="obj">The entity reference against which to perform the uniqueness check.</param> - /// <param name="key">The entity key.</param> - public void CheckUniqueness(EntityKey key, object obj) - { - object entity = GetEntity(key); - if (entity == obj) - { - throw new AssertionFailure("object already associated, but no entry was found"); - } - if (entity != null) - { - throw new NonUniqueObjectException(key.Identifier, key.EntityName); - } - } + /// <summary> + /// Attempts to check whether the given key represents an entity already loaded within the + /// current session. + /// </summary> + /// <param name="obj">The entity reference against which to perform the uniqueness check.</param> + /// <param name="key">The entity key.</param> + public void CheckUniqueness(EntityKey key, object obj) + { + object entity = GetEntity(key); + if (entity == obj) + { + throw new AssertionFailure("object already associated, but no entry was found"); + } + if (entity != null) + { + throw new NonUniqueObjectException(key.Identifier, key.EntityName); + } + } - /// <summary> - /// If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy - /// and overwrite the registration of the old one. This breaks == and occurs only for - /// "class" proxies rather than "interface" proxies. Also init the proxy to point to - /// the given target implementation if necessary. - /// </summary> - /// <param name="proxy">The proxy instance to be narrowed. </param> - /// <param name="persister">The persister for the proxied entity. </param> - /// <param name="key">The internal cache key for the proxied entity. </param> - /// <param name="obj">(optional) the actual proxied entity instance. </param> - /// <returns> An appropriately narrowed instance. </returns> - public object NarrowProxy(INHibernateProxy proxy, IEntityPersister persister, EntityKey key, object obj) - { - bool alreadyNarrow = persister.GetConcreteProxyClass(session.EntityMode).IsAssignableFrom(proxy.GetType()); + /// <summary> + /// If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy + /// and overwrite the registration of the old one. This breaks == and occurs only for + /// "class" proxies rather than "interface" proxies. Also init the proxy to point to + /// the given target implementation if necessary. + /// </summary> + /// <param name="proxy">The proxy instance to be narrowed. </param> + /// <param name="persister">The persister for the proxied entity. </param> + /// <param name="key">The internal cache key for the proxied entity. </param> + /// <param name="obj">(optional) the actual proxied entity instance. </param> + /// <returns> An appropriately narrowed instance. </returns> + public object NarrowProxy(INHibernateProxy proxy, IEntityPersister persister, EntityKey key, object obj) + { + bool alreadyNarrow = persister.GetConcreteProxyClass(session.EntityMode).IsAssignableFrom(proxy.GetType()); - if (!alreadyNarrow) - { - if (ProxyWarnLog.IsWarnEnabled) - { - ProxyWarnLog.Warn("Narrowing proxy to " + persister.GetConcreteProxyClass(session.EntityMode) + " - this operation breaks =="); - } + if (!alreadyNarrow) + { + if (ProxyWarnLog.IsWarnEnabled) + { + ProxyWarnLog.Warn("Narrowing proxy to " + persister.GetConcreteProxyClass(session.EntityMode) + " - this operation breaks =="); + } - if (obj != null) - { - proxiesByKey.Remove(key); - return obj; //return the proxied object - } - else - { - proxy = (INHibernateProxy)persister.CreateProxy(key.Identifier, session); - proxiesByKey[key] = proxy; //overwrite old proxy - return proxy; - } - } - else - { - if (obj != null) - { - proxy.HibernateLazyInitializer.SetImplementation(obj); - } - return proxy; - } - } + if (obj != null) + { + proxiesByKey.Remove(key); + return obj; //return the proxied object + } + else + { + proxy = (INHibernateProxy)persister.CreateProxy(key.Identifier, session); + proxiesByKey[key] = proxy; //overwrite old proxy + return proxy; + } + } + else + { + if (obj != null) + { + proxy.HibernateLazyInitializer.SetImplementation(obj); + } + return proxy; + } + } - /// <summary> - /// Return the existing proxy associated with the given <tt>EntityKey</tt>, or the - /// third argument (the entity associated with the key) if no proxy exists. Init - /// the proxy to the target implementation, if necessary. - /// </summary> - public object ProxyFor(IEntityPersister persister, EntityKey key, object impl) - { - if (!persister.HasProxy || key == null) - return impl; + /// <summary> + /// Return the existing proxy associated with the given <tt>EntityKey</tt>, or the + /// third argument (the entity associated with the key) if no proxy exists. Init + /// the proxy to the target implementation, if necessary. + /// </summary> + public object ProxyFor(IEntityPersister persister, EntityKey key, object impl) + { + if (!persister.HasProxy || key == null) + return impl; - INHibernateProxy proxy; - if (proxiesByKey.TryGetValue(key, out proxy)) - { - return NarrowProxy(proxy, persister, key, impl); - } - else - { - return impl; - } - } + INHibernateProxy proxy; + if (proxiesByKey.TryGetValue(key, out proxy)) + { + return NarrowProxy(proxy, persister, key, impl); + } + else + { + return impl; + } + } - /// <summary> - /// Return the existing proxy associated with the given <tt>EntityKey</tt>, or the - /// argument (the entity associated with the key) if no proxy exists. - /// (slower than the form above) - /// </summary> - public object ProxyFor(object impl) - { - EntityEntry e = GetEntry(impl); - IEntityPersister p = e.Persister; - return ProxyFor(p, new EntityKey(e.Id, p, session.EntityMode), impl); - } + /// <summary> + /// Return the existing proxy associated with the given <tt>EntityKey</tt>, or the + /// arg... [truncated message content] |
From: <aye...@us...> - 2008-10-09 23:48:33
|
Revision: 3824 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3824&view=rev Author: ayenderahien Date: 2008-10-09 23:48:30 +0000 (Thu, 09 Oct 2008) Log Message: ----------- fixed typo Added Paths: ----------- branches/static-proxies/ Removed Paths: ------------- branches/static-proxis/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-09 23:44:55
|
Revision: 3823 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3823&view=rev Author: ayenderahien Date: 2008-10-09 23:44:53 +0000 (Thu, 09 Oct 2008) Log Message: ----------- Added Paths: ----------- branches/static-proxis/ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-09 22:45:22
|
Revision: 3822 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3822&view=rev Author: fabiomaulo Date: 2008-10-09 22:45:14 +0000 (Thu, 09 Oct 2008) Log Message: ----------- initial test to support Xml entityMode Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj Added Paths: ----------- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs Added: trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs (rev 0) +++ trunk/nhibernate/src/NHibernate.Test/EntityModeTest/Xml/Accessors/XmlAccessorFixture.cs 2008-10-09 22:45:14 UTC (rev 3822) @@ -0,0 +1,119 @@ +using System.Xml; +using NHibernate.Mapping; +using NHibernate.Properties; +using NUnit.Framework; +using NUnit.Framework.SyntaxHelpers; + +namespace NHibernate.Test.EntityModeTest.Xml.Accessors +{ + [TestFixture, Ignore("Not supported yet.")] + public class XmlAccessorFixture + { + public static XmlElement dom = GenerateTestElement(); + + private static XmlElement GenerateTestElement() + { + const string xml = +@"<company id='123'> + description... + <name>NHForge</name> + <account num='456'/> +</company>"; + + var baseXml = new XmlDocument(); + baseXml.LoadXml(xml); + return baseXml.DocumentElement; + } + + private static XmlElement GenerateRootTestElement() + { + return (new XmlDocument()).CreateElement("company"); + } + + private static Property GenerateAccountIdProperty() + { + var value = new SimpleValue {TypeName = "long"}; + + return new Property {Name = "number", NodeName = "account/@num", Value = value}; + } + + private static Property GenerateTextProperty() + { + var value = new SimpleValue {TypeName = "string"}; + + return new Property {Name = "text", NodeName = ".", Value = value}; + } + + private static Property GenerateNameProperty() + { + var value = new SimpleValue {TypeName = "string"}; + + return new Property {Name = "name", NodeName = "name", Value = value}; + } + + private static Property GenerateIdProperty() + { + var value = new SimpleValue {TypeName = "long"}; + + return new Property {Name = "id", NodeName = "@id", Value = value}; + } + + [Test] + public void CompanyElementGeneration() + { + ISetter idSetter = PropertyAccessorFactory.GetPropertyAccessor(GenerateIdProperty(), EntityMode.Xml).GetSetter(null, + null); + ISetter nameSetter = + PropertyAccessorFactory.GetPropertyAccessor(GenerateNameProperty(), EntityMode.Xml).GetSetter(null, null); + ISetter textSetter = + PropertyAccessorFactory.GetPropertyAccessor(GenerateTextProperty(), EntityMode.Xml).GetSetter(null, null); + ISetter accountIdSetter = + PropertyAccessorFactory.GetPropertyAccessor(GenerateAccountIdProperty(), EntityMode.Xml).GetSetter(null, null); + + XmlNode root = GenerateRootTestElement(); + + idSetter.Set(root, 123L); + textSetter.Set(root, "description..."); + nameSetter.Set(root, "NHForge"); + accountIdSetter.Set(root, 456L); + + //Assert.That(new NodeComparator().Compare(dom, root) == 0); + } + + [Test] + public void LongAttributeExtraction() + { + Property property = GenerateIdProperty(); + IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); + var id = (long) getter.Get(dom); + Assert.That(id, Is.EqualTo(123L)); + } + + [Test] + public void LongElementAttributeExtraction() + { + Property property = GenerateAccountIdProperty(); + IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); + var id = (long) getter.Get(dom); + Assert.That(id, Is.EqualTo(456L)); + } + + [Test] + public void StringElementExtraction() + { + Property property = GenerateNameProperty(); + IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); + var name = (string) getter.Get(dom); + Assert.That(name, Is.EqualTo("NHForge")); + } + + [Test] + public void StringTextExtraction() + { + Property property = GenerateTextProperty(); + IGetter getter = PropertyAccessorFactory.GetPropertyAccessor(property, EntityMode.Xml).GetGetter(null, null); + var name = (string) getter.Get(dom); + Assert.That(name, Is.EqualTo("description...")); + } + } +} \ No newline at end of file Modified: trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj =================================================================== --- trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-09 21:42:15 UTC (rev 3821) +++ trunk/nhibernate/src/NHibernate.Test/NHibernate.Test.csproj 2008-10-09 22:45:14 UTC (rev 3822) @@ -160,6 +160,7 @@ <Compile Include="DynamicEntity\Tuplizer\TuplizerDynamicEntity.cs" /> <Compile Include="EngineTest\TypedValueFixture.cs" /> <Compile Include="EntityModeTest\Map\Basic\DynamicClassFixture.cs" /> + <Compile Include="EntityModeTest\Xml\Accessors\XmlAccessorFixture.cs" /> <Compile Include="Events\Collections\AbstractCollectionEventFixture.cs" /> <Compile Include="Events\Collections\AbstractParentWithCollection.cs" /> <Compile Include="Events\Collections\Association\AbstractAssociationCollectionEventFixture.cs" /> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-09 21:42:26
|
Revision: 3821 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3821&view=rev Author: ayenderahien Date: 2008-10-09 21:42:15 +0000 (Thu, 09 Oct 2008) Log Message: ----------- reverting previous commit, should learn to _read_ the code. Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs Modified: trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-09 21:21:58 UTC (rev 3820) +++ trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-09 21:42:15 UTC (rev 3821) @@ -68,7 +68,7 @@ he); } - if (pffc is IProxyFactoryFactory == false) + if (typeof(IProxyFactoryFactory).IsAssignableFrom(pffc) == false) { HibernateException he = new HibernateException(pffc.FullName + " does not implement " + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <aye...@us...> - 2008-10-09 21:22:09
|
Revision: 3820 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3820&view=rev Author: ayenderahien Date: 2008-10-09 21:21:58 +0000 (Thu, 09 Oct 2008) Log Message: ----------- minor Modified Paths: -------------- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs Modified: trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs =================================================================== --- trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-09 18:31:36 UTC (rev 3819) +++ trunk/nhibernate/src/NHibernate/Bytecode/Lightweight/BytecodeProviderImpl.cs 2008-10-09 21:21:58 UTC (rev 3820) @@ -68,7 +68,7 @@ he); } - if (typeof(IProxyFactoryFactory).IsAssignableFrom(pffc) == false) + if (pffc is IProxyFactoryFactory == false) { HibernateException he = new HibernateException(pffc.FullName + " does not implement " + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fab...@us...> - 2008-10-09 18:31:39
|
Revision: 3819 http://nhibernate.svn.sourceforge.net/nhibernate/?rev=3819&view=rev Author: fabiomaulo Date: 2008-10-09 18:31:36 +0000 (Thu, 09 Oct 2008) Log Message: ----------- Minor (added reference to the Jira ticket) Modified Paths: -------------- trunk/nhibernate/src/NHibernate.Test/SqlTest/IdentityInsertWithStoredProcsTest.cs Modified: trunk/nhibernate/src/NHibernate.Test/SqlTest/IdentityInsertWithStoredProcsTest.cs =================================================================== --- trunk/nhibernate/src/NHibernate.Test/SqlTest/IdentityInsertWithStoredProcsTest.cs 2008-10-09 18:19:03 UTC (rev 3818) +++ trunk/nhibernate/src/NHibernate.Test/SqlTest/IdentityInsertWithStoredProcsTest.cs 2008-10-09 18:31:36 UTC (rev 3819) @@ -1,8 +1,8 @@ -using NHibernate.Cfg; using NUnit.Framework; namespace NHibernate.Test.SqlTest { + // http://jira.nhibernate.org/browse/NH-727 public abstract class IdentityInsertWithStoredProcsTest : TestCase { protected override string MappingsAssembly This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |