Advertisement
Guest User

NHibernate additional stuff (all merged together)

a guest
Aug 6th, 2011
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.05 KB | None | 0 0
  1.     public class NHibernateRepositoryConfigurer
  2.     {
  3.         // Main configuration used while building the session factory.
  4.         public FluentConfiguration Configuration { get; private set; }
  5.         public ISessionFactory SessionFactory { get; private set; }
  6.  
  7.         private readonly NHibernateRepositoryConfiguration repositoryConfiguration;
  8.  
  9.         public NHibernateRepositoryConfigurer()
  10.         {
  11.             repositoryConfiguration = new NHibernateRepositoryConfiguration();
  12.             Configure();
  13.         }
  14.  
  15.         public NHibernateRepositoryConfigurer(NHibernateRepositoryConfiguration repositoryConfiguration)
  16.         {
  17.             this.repositoryConfiguration = repositoryConfiguration;
  18.             Configure();
  19.         }
  20.  
  21.         private void Configure()
  22.         {
  23.             var autoPersistenceModel = AutoMap.Assemblies(repositoryConfiguration.Assemblies)
  24.                 .Where(repositoryConfiguration.AutomappingExpression);
  25.  
  26.             Configuration = Fluently.Configure()
  27.                 // See the corresponding basic configuration. Defaulted to in-memory
  28.                 // SQLite database with SQL log enabled.
  29.                 .Database(repositoryConfiguration.PersistenceConfigurer)
  30.                 .Mappings(x =>
  31.                           {
  32.                               x.AutoMappings.Add(autoPersistenceModel);
  33.  
  34.                               foreach (var assembly in repositoryConfiguration.Assemblies)
  35.                               {
  36.                                   x.FluentMappings.AddFromAssembly(assembly);
  37.                               }
  38.                           });
  39.  
  40.             // Deploy the corresponding session factory (one per configurer instance).
  41.             SessionFactory = Configuration.BuildSessionFactory();
  42.         }
  43.     }
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.     public class NHibernateRepositoryConfiguration
  53.     {
  54.         public Assembly[] Assemblies =
  55.             new[] { Assembly.GetAssembly(typeof(IRepositoryEntity)) };
  56.        
  57.         public Func<Type, bool> AutomappingExpression =
  58.             (x => typeof(IRepositoryEntity).IsAssignableFrom(x));
  59.        
  60.         public IPersistenceConfigurer PersistenceConfigurer =
  61.             SQLiteConfiguration.Standard.InMemory().ShowSql();
  62.     }
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.     public class NHibernateRepositoryFactory
  72.     {
  73.         public FluentConfiguration Configuration { get; set; }
  74.  
  75.         public ISessionFactory RetrieveSessionFactory()
  76.         {
  77.             var autoPersistenceModel = AutoMap.AssemblyOf<RepositoryEntity>()
  78.                 .Where(x => !x.IsGenericType && x.IsSubclassOf(typeof(RepositoryEntity)));
  79.  
  80.             Configuration = Fluently.Configure()
  81.                 .Database(SQLiteConfiguration.Standard.ShowSql().InMemory)
  82.                 .Mappings(x =>
  83.                           {
  84.                               x.FluentMappings.AddFromAssemblyOf<RepositoryEntity>();
  85.                               x.AutoMappings.Add(autoPersistenceModel);
  86.                           });
  87.  
  88.             return Configuration.BuildSessionFactory();
  89.         }
  90.     }
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108.  
  109.  
  110.     using ISampleUnitProxy = IUnitProxy<SampleUnitDescriptor>;
  111.     using ISampleUnit = IUnit<SampleUnitDescriptor, Decimal>;
  112.     using SampleUnitProxy = BinaryUnitProxy<SampleUnitDescriptor>;
  113.     using SampleUnit = BinaryUnit<SampleUnitDescriptor, Decimal>;
  114.  
  115.     public class RepositoryTestingPackage
  116.     {
  117.         public IQueryable<ISampleUnitProxy> SampleProxySequence { get; private set; }
  118.         public IQueryable<SampleNonUnitEntity> SampleNonUnitEntitySequence { get; private set; }
  119.        
  120.         public Mock<IRepository> RepositoryMock { get; private set; }
  121.  
  122.         // Set of arbitrary timestamps and values for testing.
  123.         public String Name1 = "Name1";
  124.         public String Name2 = "Name2";
  125.         public Decimal Value1 = (Decimal) 25.0;
  126.         public Decimal Value2 = (Decimal) 48.0;
  127.         public DateTime Time1 = new DateTime(2000, 1, 1);
  128.         public DateTime Time2 = new DateTime(2000, 2, 1);
  129.  
  130.         public RepositoryTestingPackage()
  131.         {
  132.             SampleNonUnitEntitySequence = new List<SampleNonUnitEntity>
  133.                                  {
  134.                                      new SampleNonUnitEntity
  135.                                      {
  136.                                          Value = Value1
  137.                                      },
  138.                                      new SampleNonUnitEntity
  139.                                      {
  140.                                          Value = Value2
  141.                                      }
  142.                                  }.AsQueryable();
  143.  
  144.             // Setup the unit proxy sequence to be used in the tests.
  145.             // Note that the used repository mock only handles the retrieval
  146.             // of the entities of the 'ITestUnitProxy' type.
  147.             SampleProxySequence = new List<ISampleUnitProxy>
  148.                                 {
  149.                                     new SampleUnit
  150.                                     {
  151.                                         Descriptor = new SampleUnitDescriptor { Name = Name1, Timestamp = Time1 },
  152.                                         Value = Value1
  153.                                     }.ToProxy(),
  154.                                     new SampleUnit
  155.                                     {
  156.                                         Descriptor = new SampleUnitDescriptor { Name = Name2, Timestamp = Time2 },
  157.                                         Value = Value2
  158.                                     }.ToProxy()
  159.                                 }.AsQueryable();
  160.  
  161.             RepositoryMock = new Mock<IRepository>();
  162.  
  163.             RepositoryMock.Setup(x => x.RetrieveEntities<ISampleUnitProxy>())
  164.                 .Returns(SampleProxySequence);
  165.  
  166.             RepositoryMock.Setup(x => x.RetrieveEntities(
  167.                 // Handle the variant of the 'RetrieveEntities' function that receives
  168.                 // a lambda predicate and filters the corresponding elements.
  169.                 It.IsAny<Expression<Func<ISampleUnitProxy, bool>>>()))
  170.                 // The result is the 'SampleProxySequence' sequence filtered using the
  171.                 // corresponding expression.
  172.                 .Returns(
  173.                     ((Expression<Func<ISampleUnitProxy, bool>> expression) =>
  174.                      SampleProxySequence.Where(expression)));
  175.  
  176.             // We do not provide mock implementations for the corresponding 'Add' and 'Remove'
  177.             // methods, because things could get complicated here and actually we only have
  178.             // to check that these methods are getting called, but not their effect.
  179.         }
  180.     }
  181.  
  182.  
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204.  
  205.  
  206.  
  207.  
  208.  
  209.  
  210.     using ISampleUnitProxy = IUnitProxy<SampleUnitDescriptor>;
  211.     using ISampleUnit = IUnit<SampleUnitDescriptor, Decimal>;
  212.     using SampleUnitProxy = BinaryUnitProxy<SampleUnitDescriptor>;
  213.     using SampleUnit = BinaryUnit<SampleUnitDescriptor, Decimal>;
  214.  
  215.     public abstract class RepositoryTester
  216.     {
  217.         protected readonly RepositoryTestingPackage RepositoryTestingPackage;
  218.         protected readonly IRepository Repository;
  219.  
  220.         protected RepositoryTester(IRepository repository)
  221.         {
  222.             RepositoryTestingPackage = new RepositoryTestingPackage();
  223.  
  224.             Repository = repository;
  225.             repository.AddEntities(RepositoryTestingPackage.SampleProxySequence);
  226.             repository.AddEntities(RepositoryTestingPackage.SampleNonUnitEntitySequence);
  227.         }
  228.  
  229.         [Fact]
  230.         public void RetrieveAllEntities()
  231.         {
  232.             var result = Repository.RetrieveEntities<ISampleUnitProxy>();
  233.  
  234.             Assert.Equal(RepositoryTestingPackage.SampleProxySequence.Count(), result.Count());
  235.         }
  236.  
  237.         [Fact]
  238.         public void RetrieveEntitiesByExpression()
  239.         {
  240.             var result = Repository.RetrieveEntities<ISampleUnitProxy>(
  241.                 x => x.Descriptor.Name == RepositoryTestingPackage.Name1);
  242.  
  243.             Assert.Equal(1, result.Count());
  244.             Assert.Equal(RepositoryTestingPackage.Name1, result.First().Descriptor.Name);
  245.         }
  246.  
  247.         [Fact]
  248.         public void RetrieveEntitiesWithDifferentTypes()
  249.         {
  250.             var result1 = Repository.RetrieveEntities<ISampleUnitProxy>();
  251.             var result2 = Repository.RetrieveEntities<SampleNonUnitEntity>();
  252.  
  253.             Assert.Equal(2, result1.Count());
  254.             Assert.Equal(2, result2.Count());
  255.         }
  256.  
  257.         [Fact]
  258.         public void AddNewEntity()
  259.         {
  260.             // Assumed to be new for the test value sequence.
  261.             var unit = new SampleUnit
  262.                        {
  263.                            Descriptor = new SampleUnitDescriptor
  264.                                         {
  265.                                             Name = "New",
  266.                                             Timestamp = RepositoryTestingPackage.Time1
  267.                                         },
  268.                            Value = RepositoryTestingPackage.Value1
  269.                        }.ToProxy();
  270.  
  271.             Repository.AddEntities(Enumerable.Repeat(unit, 1).AsQueryable());
  272.  
  273.             var result = Repository.RetrieveEntities<ISampleUnitProxy>();
  274.  
  275.             Assert.Equal(3, result.Count());
  276.         }
  277.  
  278.         [Fact]
  279.         public void UpdateEntity()
  280.         {
  281.             var sequence = Repository.RetrieveEntities<ISampleUnitProxy>();
  282.  
  283.             var unit = sequence.Where(x => x.Descriptor.Name.Equals(RepositoryTestingPackage.Name1));
  284.             // Update the corresponding value and commit it to the repository.
  285.             unit.First().Descriptor.Name = "Changed";
  286.             Repository.AddEntities(unit);
  287.  
  288.             var result = Repository.RetrieveEntities<ISampleUnitProxy>(x => x.Descriptor.Name == "Changed");
  289.  
  290.             Assert.Equal(1, result.Count());
  291.         }
  292.  
  293.         [Fact]
  294.         public void UpdateEntityThroughProxy()
  295.         {
  296.             ISampleUnitProxy unitProxy = Repository.RetrieveEntities<ISampleUnitProxy>(
  297.                 x => x.Descriptor.Name == RepositoryTestingPackage.Name1).First();
  298.  
  299.             var unit = unitProxy.ToUnit<Decimal>();
  300.             // Update the corresponding value and commit it to the repository.
  301.             // Unit is transformed to proxy before the actual commit.
  302.             unit.Value = 196;
  303.             Repository.AddEntities(unit.ToProxy());
  304.  
  305.             // Ensure that the value was updated and no copies were done.
  306.             var result = Repository.RetrieveEntities<ISampleUnitProxy>();
  307.             Assert.Equal(2, result.Count());
  308.  
  309.             var updatedUnit = result.ToList().Where(x => x.ToUnit<Decimal>().Value == ((Decimal) 196.0));
  310.             Assert.Equal(1, updatedUnit.Count());
  311.         }
  312.  
  313.         [Fact]
  314.         public void RemoveAllEntities()
  315.         {
  316.             Repository.RemoveEntities<ISampleUnitProxy>();
  317.  
  318.             var result = Repository.RetrieveEntities<ISampleUnitProxy>();
  319.  
  320.             Assert.Equal(0, result.Count());
  321.         }
  322.  
  323.         [Fact]
  324.         public void RemoveSelectedEntities()
  325.         {
  326.             var sequence = Repository.RetrieveEntities<ISampleUnitProxy>();
  327.  
  328.             Repository.RemoveEntities(sequence.First(), sequence.First());
  329.  
  330.             var result = Repository.RetrieveEntities<ISampleUnitProxy>();
  331.  
  332.             Assert.Equal(1, result.Count());
  333.         }
  334.  
  335.         [Fact]
  336.         public void RemoveEntitiesByExpression()
  337.         {
  338.             Repository.RemoveEntities<ISampleUnitProxy>(
  339.                 x => x.Descriptor.Timestamp == RepositoryTestingPackage.Time1);
  340.  
  341.             var result = Repository.RetrieveEntities<ISampleUnitProxy>();
  342.  
  343.             Assert.Equal(1, result.Count());
  344.             Assert.Equal(RepositoryTestingPackage.Time2, result.First().Descriptor.Timestamp);
  345.         }
  346.     }
  347.  
  348.     public class MemoryRepositoryTests : RepositoryTester
  349.     {
  350.         public MemoryRepositoryTests() : base(new MemoryRepository()) {}
  351.     }
  352.  
  353.     public class NHibernateRepositoryTests : RepositoryTester
  354.     {
  355.         // NHibernate repository configuration used exclusively for testing.
  356.         // Differs from the default repository configuration in terms of the assembly
  357.         // used for entity automapping.
  358.         private static readonly NHibernateRepositoryConfiguration RepositoryConfiguration =
  359.             new NHibernateRepositoryConfiguration
  360.             {
  361.                 Assemblies = new[] { Assembly.GetExecutingAssembly() }
  362.             };
  363.  
  364.         public NHibernateRepositoryTests()
  365.             : base(new NHibernateRepository(new NHibernateRepositoryConfigurer(RepositoryConfiguration))) {}
  366.  
  367.         [Fact]
  368.         public void VerifyTestingMappings()
  369.         {
  370.             var repositoryConfigurer = new NHibernateRepositoryConfigurer(RepositoryConfiguration);
  371.  
  372.             Assert.DoesNotThrow(
  373.                 () =>
  374.                 {
  375.                     using (var session = repositoryConfigurer.SessionFactory.OpenSession())
  376.                     {
  377.                         new SchemaExport(repositoryConfigurer.Configuration.BuildConfiguration())
  378.                             .Execute(true, true, false, session.Connection, null);
  379.  
  380.                         new PersistenceSpecification<SampleUnitDescriptor>(session)
  381.                             .CheckProperty(x => x.Id, 1)
  382.                             .CheckProperty(x => x.Name, "Name1")
  383.                             .CheckProperty(x => x.Timestamp, new DateTime(2000, 10, 10))
  384.                             .VerifyTheMappings();
  385.  
  386.                         new PersistenceSpecification<SampleNonUnitEntity>(session)
  387.                             .CheckProperty(x => x.Id, 1)
  388.                             .CheckProperty(x => x.Value, (Decimal) 20.0)
  389.                             .VerifyTheMappings();
  390.                     }
  391.                 });
  392.         }
  393.  
  394.         internal class EntityWithoutPersister : RepositoryEntity { }
  395.  
  396.         [Fact]
  397.         public void RetrieveImpossibleType()
  398.         {
  399.             Assert.Throws<MappingException>(
  400.                 () => Repository.RetrieveEntities<EntityWithoutPersister>().Count());
  401.         }
  402.     }
  403.  
  404.  
  405.  
  406.  
  407.  
  408.  
  409.  
  410.  
  411.  
  412.  
  413.  
  414.  
  415.  
  416.  
  417.  
  418.  
  419.  
  420.  
  421.  
  422.     public sealed class BinaryUnitProxyMapping : ClassMap<BinaryUnitProxy<SampleUnitDescriptor>>
  423.     {
  424.         public BinaryUnitProxyMapping()
  425.         {
  426.             Id(x => x.Id);
  427.             References(x => x.Descriptor).Cascade.All();
  428.             Map(x => x.SerializedValue);
  429.         }
  430.     }
  431.  
  432.  
  433.  
  434.  
  435.  
  436.  
  437.  
  438.  
  439.  
  440.  
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448.     public class SampleUnitDescriptor : RepositoryEntity, IEquatable<SampleUnitDescriptor>
  449.     {
  450.         public virtual String Name { get; set; }
  451.         public virtual DateTime Timestamp { get; set; }
  452.  
  453.         #region Autogenerated equality checking methods
  454.  
  455.         public virtual bool Equals(SampleUnitDescriptor other)
  456.         {
  457.             if (ReferenceEquals(null, other)) return false;
  458.             if (ReferenceEquals(this, other)) return true;
  459.  
  460.             return Equals(other.Name, Name) && other.Timestamp.Equals(Timestamp);
  461.         }
  462.  
  463.         public override bool Equals(Object other)
  464.         {
  465.             if (ReferenceEquals(null, other)) return false;
  466.             if (ReferenceEquals(this, other)) return true;
  467.  
  468.             if (other.GetType() != typeof(SampleUnitDescriptor)) return false;
  469.  
  470.             return Equals((SampleUnitDescriptor)other);
  471.         }
  472.  
  473.         public override int GetHashCode()
  474.         {
  475.             unchecked
  476.             {
  477.                 return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ Timestamp.GetHashCode();
  478.             }
  479.         }
  480.  
  481.         public static bool operator ==(SampleUnitDescriptor left, SampleUnitDescriptor right)
  482.         {
  483.             return Equals(left, right);
  484.         }
  485.  
  486.         public static bool operator !=(SampleUnitDescriptor left, SampleUnitDescriptor right)
  487.         {
  488.             return !Equals(left, right);
  489.         }
  490.  
  491.         #endregion
  492.     }
  493.  
  494.     // using SampleUnitValue = Decimal;
  495.  
  496.     public class SampleNonUnitEntity : RepositoryEntity
  497.     {
  498.         public virtual Decimal Value { get; set; }
  499.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement