public CacheTestSetupHelper()
        {
            _cacheReference = new MemoryCache("unit-tester");

            var metadata = new ProviderMetadata("cache", new Uri("cache://"), false, true);
            var frameworkContext = new FakeFrameworkContext();

            var schemaRepositoryFactory = new SchemaRepositoryFactory(
                metadata,
                new NullProviderRevisionRepositoryFactory<EntitySchema>(metadata, frameworkContext),
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));

            var revisionRepositoryFactory = new EntityRevisionRepositoryFactory(
                metadata,
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));

            var entityRepositoryFactory = new EntityRepositoryFactory(
                metadata,
                revisionRepositoryFactory,
                schemaRepositoryFactory,
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));
            var unitFactory = new ProviderUnitFactory(entityRepositoryFactory);
            var readonlyUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory);
            ProviderSetup = new ProviderSetup(unitFactory, metadata, frameworkContext, new NoopProviderBootstrapper(), 0);
            ReadonlyProviderSetup = new ReadonlyProviderSetup(readonlyUnitFactory, metadata, frameworkContext, new NoopProviderBootstrapper(), 0);
        }
        public ExamineTestSetupHelper(FakeFrameworkContext frameworkContext = null, bool isPassthrough = false)
        {
            var examineWorkingFolder = new DirectoryInfo(Path.Combine(Common.CurrentAssemblyDirectory, "Examine", Guid.NewGuid().ToString() + Thread.CurrentThread.ManagedThreadId));
            if (!examineWorkingFolder.Exists)
                Directory.CreateDirectory(examineWorkingFolder.FullName);

            //clear out old folders
            var parentFolder = examineWorkingFolder.Parent;
            foreach(var f in parentFolder.GetDirectories().Where(x => x.CreationTimeUtc < DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(5))))
            {
                try
                {
                    Directory.Delete(f.FullName, true);
                }
                catch (IOException)
                {
                    //ignore
                }
            }

            LogHelper.TraceIfEnabled<ExamineTestSetupHelper>("Index setup in folder {0}", () => examineWorkingFolder.FullName);

            //var disk = new Lucene.Net.Store.RAMDirectory();
            var disk = new Lucene.Net.Store.SimpleFSDirectory(examineWorkingFolder);

            Indexer = new UmbracoExamineIndexer(
                new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29),
                SynchronizationType.Synchronized,
                disk);

            _fakeFrameworkContext = frameworkContext ?? new FakeFrameworkContext();
            

            Searcher = new LuceneSearcher(new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29), disk);
            ExamineManager = new ExamineManager(new[] { Searcher }, new[] { Indexer }, Searcher);
            ExamineHelper = new ExamineHelper(ExamineManager, _fakeFrameworkContext, false); //false to not use cache

            var examineMapper = new ExamineModelMapper(ExamineHelper, _fakeFrameworkContext);
            _fakeFrameworkContext.SetTypeMappers(new FakeTypeMapperCollection(new AbstractMappingEngine[] { examineMapper, new FrameworkModelMapper(_fakeFrameworkContext) }));

            var providerMetadata = new ProviderMetadata("r-examine-unit-tester", new Uri("tester://"), true, isPassthrough);
 
            var revisionSchemaSessionFactory = new NullProviderRevisionRepositoryFactory<EntitySchema>(providerMetadata, FrameworkContext);
            var revisionRepositoryFactory = new RevisionRepositoryFactory(providerMetadata, FrameworkContext, ExamineHelper);
            //var revisionRepositoryFactory = new NullProviderRevisionSessionFactory<TypedEntity>(providerMetadata, FrameworkContext);
            var schemaRepositoryFactory = new SchemaRepositoryFactory(providerMetadata, revisionSchemaSessionFactory, FrameworkContext, ExamineHelper);
            var entityRepositoryFactory = new EntityRepositoryFactory(providerMetadata, revisionRepositoryFactory, schemaRepositoryFactory, FrameworkContext, ExamineHelper);

            var readUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory);
            var unitFactory = new ProviderUnitFactory(entityRepositoryFactory);

            ProviderSetup = new ProviderSetup(unitFactory, providerMetadata, FrameworkContext, null, 0);
            ReadonlyProviderSetup = new ReadonlyProviderSetup(readUnitFactory, providerMetadata, FrameworkContext, null, 0);

            //ensure that the index exists
            Indexer.CreateIndex(true);
        }
        public IoHiveTestSetupHelper(string supportedExtensions, FakeFrameworkContext frameworkContext = null)
        {
            FrameworkContext = frameworkContext ?? new FakeFrameworkContext();
            TestDirectory = GetTestDirectory();
            ProviderMetadata = new ProviderMetadata("test-provider", new Uri("storage://"), true, false);
            Settings = new Settings(supportedExtensions, TestDirectory.FullName, TestDirectory.FullName, String.Empty, String.Empty, "~/");
            EntityRepositoryFactory = new EntityRepositoryFactory(ProviderMetadata, null, null, Settings, FrameworkContext);
            EntityRepository = EntityRepositoryFactory.GetRepository() as EntityRepository;

            var readonlyFactory = new ReadonlyProviderUnitFactory(EntityRepositoryFactory);
            var factory = new ProviderUnitFactory(EntityRepositoryFactory);

            ReadonlyProviderSetup = new ReadonlyProviderSetup(readonlyFactory, ProviderMetadata, FrameworkContext, new NoopProviderBootstrapper(), 0);
            ProviderSetup = new ProviderSetup(factory, ProviderMetadata, FrameworkContext, new NoopProviderBootstrapper(), 0);
        }
        public MembershipWrapperTestSetupHelper(FakeFrameworkContext frameworkContext = null)
        {
            //clear out the Roles/Users xml files for the test membership provider
            var current = new DirectoryInfo(Common.CurrentAssemblyDirectory);
            while (current.Parent.GetDirectories("App_Data").SingleOrDefault() == null)
            {
                current = current.Parent;
            }
            var appData = current.Parent.GetDirectories("App_Data").Single();
            foreach (var f in appData.GetFiles("*.xml"))
            {
                f.Delete();
            }
            foreach (var f in appData.GetFiles("*.orig"))
            {
                f.CopyTo(Path.Combine(f.Directory.FullName, Path.GetFileNameWithoutExtension(f.Name) + ".xml"));
            }

            _fakeFrameworkContext = frameworkContext ?? new FakeFrameworkContext();
            var attributeTypeRegistry = new CmsAttributeTypeRegistry();
            var mapper = new MembershipWrapperModelMapper(attributeTypeRegistry, _fakeFrameworkContext);
            _fakeFrameworkContext.SetTypeMappers(new FakeTypeMapperCollection(new AbstractMappingEngine[] { mapper, new FrameworkModelMapper(_fakeFrameworkContext) }));

            var providerMetadata = new ProviderMetadata("r-unit-tester", new Uri("tester://"), true, false);

            //need to reset our custom membership provider before each test
            var membershipProvider = global::System.Web.Security.Membership.Providers.Cast<MembershipProvider>().OfType<CustomXmlMembershipProvider>().Single();
            membershipProvider.Reset();

            var configuredProviders = new List<ProviderElement>(new[] {new ProviderElement() {Name = "test", WildcardCharacter = "*"}});

            var revisionSchemaFactory = new NullProviderRevisionRepositoryFactory<EntitySchema>(providerMetadata, _fakeFrameworkContext);
            var revisionRepositoryFactory = new NullProviderRevisionRepositoryFactory<TypedEntity>(providerMetadata, _fakeFrameworkContext);
            var schemaRepositoryFactory = new NullProviderSchemaRepositoryFactory(providerMetadata, _fakeFrameworkContext);
            var entityRepositoryFactory = new EntityRepositoryFactory(providerMetadata, revisionRepositoryFactory, schemaRepositoryFactory, _fakeFrameworkContext,
                                                                      new Lazy<IEnumerable<MembershipProvider>>(() => global::System.Web.Security.Membership.Providers.Cast<MembershipProvider>()),
                                                                      configuredProviders);

            var readUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory);
            var unitFactory = new ProviderUnitFactory(entityRepositoryFactory);

            ProviderSetup = new ProviderSetup(unitFactory, providerMetadata, _fakeFrameworkContext, null, 0);
            ReadonlyProviderSetup = new ReadonlyProviderSetup(readUnitFactory, providerMetadata, _fakeFrameworkContext, null, 0);
        }
        public NhibernateTestSetupHelper(string dataSource, SupportedNHDrivers supportedNhDrivers, string sessionContext, bool executeSchema, FakeFrameworkContext frameworkContext = null, bool useNhProf = false)
        {
            var builder = new NHibernateConfigBuilder(dataSource, "unit-tester", supportedNhDrivers, sessionContext, false, useNhProf);
            NhConfigurationCacheKey cacheKey;
            Config = builder.BuildConfiguration(false, out cacheKey);
            SessionFactory = SessionFactoryCache.GetOrAdd(cacheKey, key => Config.BuildSessionFactory());
            SessionForTest = SessionFactory.OpenSession();
            var schemaWriter = new StringWriter(new StringBuilder());
            if (executeSchema) new SchemaExport(Config).Execute(false, true, false, SessionForTest.Connection, schemaWriter);

            FakeFrameworkContext = frameworkContext ?? new FakeFrameworkContext();
            
            //var dataContextFactory = new DataContextFactory(fakeFrameworkContext, SessionForTest, true);

            //var readWriteRepositoryUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory();
            //var writer = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), null, readWriteRepositoryUnitOfWorkFactory, dataContextFactory));

            var providerMetadata = new ProviderMetadata("r-unit-tester", new Uri("tester://"), true, false);
            //var schemaRepositoryFactory = new NullProviderSchemaRepositoryFactory(providerMetadata, fakeFrameworkContext);
            //var revisionRepositoryFactory = new NullProviderRevisionRepositoryFactory<TypedEntity>(providerMetadata, fakeFrameworkContext);

            var revisionSchemaSessionFactory = new NullProviderRevisionRepositoryFactory<EntitySchema>(providerMetadata,
                                                                                                    FakeFrameworkContext);

            var revisionRepositoryFactory = new RevisionRepositoryFactory(providerMetadata, FakeFrameworkContext, SessionForTest, true);

            var schemaRepositoryFactory = new SchemaRepositoryFactory(providerMetadata, revisionSchemaSessionFactory,
                                                                FakeFrameworkContext, SessionForTest, true);

            var entityRepositoryFactory = new EntityRepositoryFactory(providerMetadata, revisionRepositoryFactory,
                                                                schemaRepositoryFactory, FakeFrameworkContext,
                                                                SessionForTest, true);

            var readUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory);
            var unitFactory = new ProviderUnitFactory(entityRepositoryFactory);
            ProviderSetup = new ProviderSetup(unitFactory, providerMetadata, FakeFrameworkContext, null, 0);
            ReadonlyProviderSetup = new ReadonlyProviderSetup(readUnitFactory, providerMetadata, FakeFrameworkContext, null, 0);

            Func<AbstractMappingEngine> addTypemapper = () => new ManualMapperv2(new NhLookupHelper(entityRepositoryFactory), providerMetadata);
            FakeFrameworkContext.TypeMappers.Add(new Lazy<AbstractMappingEngine, TypeMapperMetadata>(addTypemapper, new TypeMapperMetadata(true)));
        }
 public ReadonlyProviderSetup(ReadonlyProviderUnitFactory unitFactory, ProviderMetadata providerMetadata, IFrameworkContext frameworkContext, AbstractProviderBootstrapper bootstrapper, int priorityOrdinal)
     : base(providerMetadata, frameworkContext, bootstrapper, priorityOrdinal)
 {
     ReadonlyUnitFactory = unitFactory;
 }
        private ReadonlyProviderSetup GetReaderProvider(ProviderMetadata providerMetadata,
                                                        RevisionRepositoryFactory revisionRepositoryFactory,
                                                        SchemaRepositoryFactory schemaRepositoryFactory,
                                                        IFrameworkContext frameworkContext,
                                                        ProviderDependencyHelper dependencyHelper, Configuration config)
        {
            AbstractReadonlyEntityRepositoryFactory readonlyEntityRepositoryFactory =
                new EntityRepositoryFactory(providerMetadata, revisionRepositoryFactory, schemaRepositoryFactory,
                                            frameworkContext, dependencyHelper);

            var readonlyUnitFactory = new ReadonlyProviderUnitFactory(readonlyEntityRepositoryFactory);
            AbstractProviderBootstrapper bootstrapper = new ProviderBootstrapper(config, null);
            var singleReader = new ReadonlyProviderSetup(readonlyUnitFactory, providerMetadata, frameworkContext,
                                                         bootstrapper, 0);
            return singleReader;
        }
        public void Build(IContainerBuilder containerBuilder, IBuilderContext context)
        {
            var config2 = context.ConfigurationResolver.GetConfigSection(HiveConfigSection.ConfigXmlKey) as HiveConfigSection;

            if (config2 == null)
                throw new ConfigurationErrorsException(string.Format("Cannot find {0} section in application configuration.", HiveConfigSection.ConfigXmlKey));

            var providerMapElements = DeepConfigManager.Default.GetPluginSettings<HiveConfigSection, ProviderMappingElementCollection>(HiveConfigSection.ConfigXmlKey, x => x.ProviderMappings).SelectMany(x => x);
            var mappings = providerMapElements.Distinct().ToArray();

            var mergedMappings = mappings.Select(x => new
                {
                    MappingName = x.Key,
                    Original = x,
                    ReadWriters = mappings.Where(y => y.Key == x.Key).SelectMany(y => y.ReadWriters).Distinct().ToArray(),
                    Readers = mappings.Where(y => y.Key == x.Key).SelectMany(y => y.Readers).Distinct().ToArray(),
                    UriMatches = mappings.Where(y => y.Key == x.Key).SelectMany(y => y.UriMatches).Distinct().ToArray(),
                    TotalOriginalsWithSameKey = mappings.Count(y => y.Key == x.Key)
                }).ToArray();

            foreach (var providerMapping in mergedMappings.DistinctBy(x => x.MappingName))
            {
                // Check for duplicates in config
                var mappingName = providerMapping.MappingName;

                if (providerMapping.TotalOriginalsWithSameKey > 1)
                    LogHelper.TraceIfEnabled<HiveDemandBuilder>("Warning: more than one provider group has been specified in Hive configuration with key '{0}', possibly as a result of a plugin's config. {1} sets of configuration have been merged.".InvariantFormat(mappingName, providerMapping.TotalOriginalsWithSameKey));

                var mappedReaderKeys = providerMapping.Readers.OrderBy(x => x.Ordinal).Select(x => x.ProviderKey).ToArray();
                var mappedReadWriterKeys = providerMapping.ReadWriters.OrderBy(x => x.Ordinal).Select(x => x.ProviderKey).ToArray();

                foreach (ReadWriterTypeReferenceElement readWriter in providerMapping.ReadWriters)
                {
                    // Register ProviderSetups for each read-writer
                    ReadWriterTypeReferenceElement writer = readWriter;
                    var mappingKey = mappingName;
                    containerBuilder.ForFactory(x =>
                            {
                                var metadata = new ProviderMetadata(writer.ProviderKey, null, false, writer.IsPassthrough);

                                var getBootstrapper = x.TryResolve<AbstractProviderBootstrapper>(writer.ProviderKey);
                                if (!getBootstrapper.Success)
                                    LogHelper.Warn<HiveDemandBuilder>("No bootstrapper was registered for Hive provider {0}", writer.ProviderKey);

                                var getRepositoryFactory = x.TryResolve<AbstractEntityRepositoryFactory>(writer.ProviderKey);
                                if (getRepositoryFactory.Success)
                                {
                                    var unitFactory = new ProviderUnitFactory(getRepositoryFactory.Value);
                                    return new ProviderSetup(unitFactory, metadata, x.Resolve<IFrameworkContext>(),
                                                             getBootstrapper.Value, 0);
                                }

                                LogHelper.Warn<HiveDemandBuilder>(
                                    "Config '{0}' wants read-write provider with key {1} but it's not registered - check the available providers section. Error: {2}",
                                    mappingKey, writer.ProviderKey, getRepositoryFactory.Error.Message);

                                // We couldn't get a session factory, so register an "UninstalledProviderSetup" instead
                                return new UninstalledProviderSetup(metadata, x.Resolve<IFrameworkContext>(), getBootstrapper.Value, 0);
                            })
                        //.KnownAsSelf()
                        .Named<ProviderSetup>(writer.ProviderKey)
                        .ScopedAs.Singleton();
                }

                foreach (ReaderTypeReferenceElement reader in providerMapping.Readers)
                {
                    // Register ReadonlyProviderSetups for each reader
                    ReaderTypeReferenceElement readerLocalCopy = reader;
                    var mappingKey = mappingName;
                    containerBuilder.ForFactory(x =>
                            {
                                var metadata = new ProviderMetadata(readerLocalCopy.ProviderKey, null, false, readerLocalCopy.IsPassthrough);

                                var getBootstrapper = x.TryResolve<AbstractProviderBootstrapper>(readerLocalCopy.ProviderKey);
                                if (!getBootstrapper.Success)
                                    LogHelper.Warn<HiveDemandBuilder>("No bootstrapper was registered for Hive provider {0}", readerLocalCopy.ProviderKey);

                                var getRepositoryFactory = x.TryResolve<AbstractEntityRepositoryFactory>(readerLocalCopy.ProviderKey);
                                if (getRepositoryFactory.Success)
                                {
                                    var unitFactory = new ReadonlyProviderUnitFactory(getRepositoryFactory.Value);
                                    return new ReadonlyProviderSetup(unitFactory, metadata,
                                                                     x.Resolve<IFrameworkContext>(),
                                                                     getBootstrapper.Value, 0);
                                }

                                LogHelper.Warn<HiveDemandBuilder>(
                                    "Config '{0}' wants reader provider with key {1} but it's not registered or can't be instantiated - check the available providers section. Error: {2}",
                                    mappingKey, readerLocalCopy.ProviderKey, getRepositoryFactory.Error.Message);

                                // We couldn't get a session factory, so register an "UninstalledReadonlyProviderSetup" instead
                                return new UninstalledReadonlyProviderSetup(metadata, x.Resolve<IFrameworkContext>(), getBootstrapper.Value, 0);
                            })
                        //.KnownAsSelf()
                        .Named<ReadonlyProviderSetup>(readerLocalCopy.ProviderKey)
                        .ScopedAs.Singleton();
                }


                // Register IUriMatches for each mapping group
                foreach (UriMatchElement uriMatch in providerMapping.UriMatches)
                {
                    // Copy to a locally-scoped instance since the variable usage is wrapped in an anon delegate for later use
                    var match = uriMatch;

                    containerBuilder.ForFactory(x =>
                                                    {
                                                        if (!Uri.IsWellFormedUriString(match.UriPattern, UriKind.Absolute))
                                                            throw new InvalidOperationException("Hive config is invalid: '{0}' needs to be changed to a valid absolute Uri".InvariantFormat(match.UriPattern));

                                                        return new WildcardUriMatch(new Uri(match.UriPattern));
                                                    })
                        .Named<WildcardUriMatch>(mappingName)
                        .ScopedAs.Singleton();
                }

                // For every mapping group in config, register a DefaultHiveMappingGroup
                // with a constructor which accepts the map key, and all the available readers and writers which
                // map the keys selected in this group
                containerBuilder.ForFactory(
                    x => GenerateMappingGroup(mappingName, x, mappedReadWriterKeys, mappedReaderKeys))
                    .KnownAsSelf() // Register unnamed as well as named services to aid passing all registered groups into ctor params of type IEnumerable<ProviderMappingGroup>
                    .Named<ProviderMappingGroup>(mappingName)
                    .ScopedAs.Singleton();

            }

            //TODO: Remove magic strings for perf counter declarations
            containerBuilder
                .ForInstanceOfType(new HiveCounterManager("Hive 5.0", "TBD", "DEV"))
                .ScopedAs.Singleton();

            containerBuilder.ForFactory(x =>
                {
                    var groups = x.ResolveAll<ProviderMappingGroup>().DistinctBy(y => y.Key);
                    var framework = x.Resolve<IFrameworkContext>();
                    var perf = x.TryResolve<HiveCounterManager>();
                    return new HiveManager(groups, perf.Success ? perf.Value : null, framework);
                })
                .KnownAs<IHiveManager>()
                .KnownAsSelf()
                .ScopedAs.Singleton();

            containerBuilder.ForFactory(x => GetCacheWatcherTaskFactory(x, TaskTriggers.Hive.PostAddOrUpdateOnUnitComplete))
                .KnownAs<Lazy<AbstractTask, TaskMetadata>>()
                .ScopedAs.Singleton();

            containerBuilder.ForFactory(x => GetCacheWatcherTaskFactory(x, TaskTriggers.Hive.PostReadEntity))
                .KnownAs<Lazy<AbstractTask, TaskMetadata>>()
                .ScopedAs.Singleton();
        }
        public void FileProvider_ViaManager_GetRelations_DefaultRelationType()
        {
            // Arrange
            var ioTestSetup = new IoHiveTestSetupHelper();
            var unitFactory = new ProviderUnitFactory(ioTestSetup.EntityRepositoryFactory);
            var readonlyUnitFactory = new ReadonlyProviderUnitFactory(ioTestSetup.EntityRepositoryFactory);
            var provider = new ProviderSetup(unitFactory, ioTestSetup.ProviderMetadata, null, null, 0);
            var readonlyProvider = new ReadonlyProviderSetup(readonlyUnitFactory, ioTestSetup.ProviderMetadata, null, null, 0);

            var providerMappingGroup = new ProviderMappingGroup("default", new WildcardUriMatch("storage://*"), readonlyProvider, provider, ioTestSetup.FrameworkContext);

            var manager = new HiveManager(new[] { providerMappingGroup }, ioTestSetup.FrameworkContext);

            var actualFile = ioTestSetup.TestDirectory.GetFiles(ioTestSetup.Settings.SupportedExtensions, SearchOption.AllDirectories)
                .Where(x => x.FullName.Replace(ioTestSetup.Settings.AbsoluteRootedPath, string.Empty).Contains(@"\"))
                .Last();
            var parentFolder = actualFile.Directory;

            // Act
            using (var store = manager.OpenReader<IFileStore>())
            {
                var file = store.Repositories.Get<File>(new HiveId(actualFile.FullName));
                var parentRelations = store.Repositories.GetParentRelations(file.Id, FixedRelationTypes.DefaultRelationType);
                var parentsViaHandyMethod = store.Repositories.GetParentFileRelations(file);
                var firstParentRelation = store.Repositories.Get<File>(parentRelations.First().SourceId);

                //Assert
                // Check for iterator block mistakes
                Assert.That(parentRelations, Is.EquivalentTo(parentsViaHandyMethod));
                Assert.That(parentRelations.Count(), Is.GreaterThanOrEqualTo(1));
                Assert.AreEqual(parentFolder.FullName.NormaliseDirectoryPath(), firstParentRelation.RootedPath.NormaliseDirectoryPath());
            }
        }