Beispiel #1
0
        public XmlStoreHiveTests()
        {
            using (DisposableTimer.TraceDuration <XmlStoreHiveTests>("Start setup", "End setup"))
            {
                // Create reader
                var xmlPath =
                    Path.Combine(
                        Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Substring("file:\\\\".Length + 1)),
                        "App_Data\\umbraco.config");

                _fakeFrameworkContext = new FakeFrameworkContext();

                _dataContextFactory        = new DataContextFactory(xmlPath);
                _readOnlyUnitOfWorkFactory = new ReadOnlyUnitOfWorkFactory();
                _directHiveReadProvider    = new HiveReadProvider(new HiveProviderSetup(_fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), _readOnlyUnitOfWorkFactory, null, _dataContextFactory));

                // Create writer
                _readWriteUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory();
                _writeProvider = new HiveReadWriteProvider(new HiveProviderSetup(_fakeFrameworkContext, "rw-unit-tester", new FakeHiveProviderBootstrapper(), null, _readWriteUnitOfWorkFactory, _dataContextFactory));



                // Create hive wrappers for the readers and writers
                var governorRUowFactory = new ReadOnlyUnitOfWorkFactoryWrapper(new[] { _directHiveReadProvider });

                var governorRWUowFactory = new ReadWriteUnitOfWorkFactoryWrapper(new[] { _writeProvider });

                _hiveReadProviderViaGovernor      = new Framework.Hive.PersistenceGovernor.HiveReadProvider(new HiveProviderSetup(_fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), governorRUowFactory, null, null), new[] { _directHiveReadProvider });
                _hiveReadWriteProviderViaGovernor = new Framework.Hive.PersistenceGovernor.HiveReadWriteProvider(new HiveProviderSetup(_fakeFrameworkContext, "rw-unit-tester", new FakeHiveProviderBootstrapper(), null, governorRWUowFactory, null), new[] { _writeProvider });
            }
        }
        public void Can_Bulk_Insert()
        {
            // Arrange
            var db = DatabaseContext.Database;

            var servers = new List <ServerRegistrationDto>();

            for (var i = 0; i < 1000; i++)
            {
                servers.Add(new ServerRegistrationDto
                {
                    Address        = "address" + i,
                    ComputerName   = "computer" + i,
                    DateRegistered = DateTime.Now,
                    IsActive       = true,
                    LastNotified   = DateTime.Now
                });
            }

            // Act
            using (DisposableTimer.TraceDuration <PetaPocoExtensionsTest>("starting insert", "finished insert"))
            {
                db.BulkInsertRecords(servers);
            }

            // Assert
            Assert.That(db.ExecuteScalar <int>("SELECT COUNT(*) FROM umbracoServer"), Is.EqualTo(1000));
        }
        public PersistenceAssertionBuilder <T> RunAssertionsWithQuery(IHiveReadProvider readerProvider, IHiveReadWriteProvider writeProvider, T mockedEntity, Func <HiveId, Expression <Func <T, bool> > > expression)
        {
            HiveId generatedId;

            object[] checkValuesAfterCommitting = GetCheckValuesAfterCommitting(writeProvider, out generatedId, mockedEntity);

            using (DisposableTimer.TraceDuration <NHibernateHiveTests>("Start read", "End read"))
            {
                using (var unit = readerProvider.CreateReadOnlyUnitOfWork())
                {
                    var result = unit.ReadRepository.QueryContext.Query <T>().Where(expression(generatedId)).FirstOrDefault();

                    Assert.IsNotNull(result,
                                     "No entity was retrieved back from the datastore for query {0} (id was {1})",
                                     expression,
                                     generatedId);

                    Assert.IsTrue(generatedId == result.Id);

                    LogHelper.TraceIfEnabled <PersistenceAssertionBuilder <T> >("Item owned by {0}, retrieved from {1}", () => result.PersistenceMetadata.OwnerProviderAlias, () => result.PersistenceMetadata.ReturnedByProviderAlias);

                    for (int i = 0; i < _valuesAndAssertions.Count; i++)
                    {
                        _valuesAndAssertions[i].Item2.Invoke(result, checkValuesAfterCommitting[i]);
                    }
                }
            }

            return(this);
        }
        public virtual CacheCreationResult <T> GetOrCreate <T>(string key, Func <CacheValueOf <T> > callback)
        {
            var inheritorType = GetType();

            LogHelper.TraceIfEnabled(inheritorType, "In GetOrCreate for {0}", key.ToString);
            using (DisposableTimer.TraceDuration(inheritorType, "Start GetOrCreate", "End GetOrCreate"))
            {
                var existing = Get <T>(key);
                if (existing != null)
                {
                    LogHelper.TraceIfEnabled <AbstractCacheProvider>("Item existed");
                    var existingCast = existing as CacheValueOf <T>;
                    if (existingCast != null)
                    {
                        return(new CacheCreationResult <T>(false, false, true, existingCast));
                    }
                    return(new CacheCreationResult <T>(false, false, true, default(CacheValueOf <T>), true));
                }

                LogHelper.TraceIfEnabled(inheritorType, "Item did not exist");
                var newValue = callback.Invoke();
                var result   = AddOrChange(key, newValue);
                return(new CacheCreationResult <T>(result.WasUpdated, result.WasInserted, false, newValue));
            }
        }
        public PersistenceAssertionBuilder <T> RunAssertions(IHiveReadProvider readerProvider, IHiveReadWriteProvider writeProvider, T mockedEntity)
        {
            HiveId generatedId;

            object[] checkValuesAfterCommitting = GetCheckValuesAfterCommitting(writeProvider, out generatedId, mockedEntity);

            using (DisposableTimer.TraceDuration <NHibernateHiveTests>("Start read", "End read"))
            {
                using (var unit = readerProvider.CreateReadOnlyUnitOfWork())
                {
                    var result = unit.ReadRepository.GetEntity <T>(generatedId);

                    Assert.IsNotNull(result, "No entity was retrieved back from the datastore with id {0}", generatedId);

                    Assert.AreEqual(generatedId, result.Id, "Got a different value back from the database for the Id");

                    LogHelper.TraceIfEnabled <PersistenceAssertionBuilder <T> >("Item owned by {0}, retrieved from {1}", () => result.PersistenceMetadata.OwnerProviderAlias, () => result.PersistenceMetadata.ReturnedByProviderAlias);

                    for (int i = 0; i < _valuesAndAssertions.Count; i++)
                    {
                        _valuesAndAssertions[i].Item2.Invoke(result, checkValuesAfterCommitting[i]);
                    }
                }
                _postWriteCallback.Invoke();
            }

            return(this);
        }
        public void RemoveRelation(IRelationById item, AbstractScopedCache repositoryScopedCache)
        {
            var sessionIdAsString = GetSessionId().ToString("n");

            using (DisposableTimer.TraceDuration <NhSessionHelper>("In RemoveRelation for session " + sessionIdAsString, "End RemoveRelation for session " + sessionIdAsString))
            {
                var relationType = GetOrCreateNodeRelationType(item.Type.RelationName, repositoryScopedCache);

                // Nh should handle this for us but got an error with mappings atm in SqlCe (APN 09/11/11)
                // Clear session cache to make sure it loads all of the tags in order to delete them all
                NhSession.Flush();

                // Clear the repository cache of this relation in case one has been added and then removed in the same unit of work
                var cacheKey = GenerateCacheKeyForRelation(item, relationType);
                repositoryScopedCache.InvalidateItems(cacheKey);

                var sourceIdValue      = (Guid)item.SourceId.Value;
                var destinationIdValue = (Guid)item.DestinationId.Value;

                var existingRelation = GetDbRelation(relationType.Alias, sourceIdValue, destinationIdValue).ToArray();

                if (existingRelation.Any())
                {
                    existingRelation.ForEach(x => NhSession.Delete(x));
                }
            }
        }
 /// <summary>
 /// Executes the controller action
 /// </summary>
 private static void ExecuteControllerAction(ControllerContext context, IController controller)
 {
     using (DisposableTimer.TraceDuration <UmbracoPageResult>("Executing Umbraco RouteDefinition controller", "Finished"))
     {
         controller.Execute(context.RequestContext);
     }
 }
Beispiel #8
0
 public void Benchmark_Original_Finder()
 {
     using (DisposableTimer.TraceDuration <TypeFinderTests>("Starting test", "Finished test"))
     {
         using (DisposableTimer.TraceDuration <TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType"))
         {
             for (var i = 0; i < 1000; i++)
             {
                 Assert.Greater(TypeFinderOriginal.FindClassesOfType <DisposableObject>(_assemblies).Count(), 0);
             }
         }
         using (DisposableTimer.TraceDuration <TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute"))
         {
             for (var i = 0; i < 1000; i++)
             {
                 Assert.Greater(TypeFinderOriginal.FindClassesOfTypeWithAttribute <TestEditor, MyTestAttribute>(_assemblies).Count(), 0);
             }
         }
         using (DisposableTimer.TraceDuration <TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute"))
         {
             for (var i = 0; i < 1000; i++)
             {
                 Assert.Greater(TypeFinderOriginal.FindClassesWithAttribute <XsltExtensionAttribute>(_assemblies).Count(), 0);
             }
         }
     }
 }
        //#region ISearchableTree Members

        //public virtual TreeSearchJsonResult Search(string searchText)
        //{
        //    //TODO: do the searching!

        //    //for now, i'm just going to return dummy data that i know is in demo data just to get the ui working
        //    var result = new TreeSearchJsonResult(new[]
        //                {
        //                    new SearchResultItem { Id = new HiveId(1050).ToString(), Rank = 0, Title = "Go further", Description="this is a node" },
        //                    new SearchResultItem { Id = new HiveId(1060).ToString(), Rank = 0, Title = "Functionality", Description="this is a node" }
        //                });

        //    return result;
        //}

        //#endregion

        /// <summary>
        /// Customize the root node
        /// </summary>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        protected override TreeNode CreateRootNode(FormCollection queryStrings)
        {
            if (RootNodeId == ActualRootNodeId)
            {
                var n = base.CreateRootNode(queryStrings);
                AddMenuItemsToRootNode(n, queryStrings);
                return(n);
            }
            else
            {
                var hiveProvider = GetHiveProvider(RootNodeId, queryStrings);

                using (var securityUow = hiveProvider.CreateReadonly <ISecurityStore>())
                    using (var uow = hiveProvider.CreateReadonly <IContentStore>())
                    {
                        //Get the items and ensure Browse permissions are applied
                        var childIds = new[] { RootNodeId };

                        using (DisposableTimer.TraceDuration <ContentTreeController>("FilterWithPermissions", "FilterWithPermissions"))
                        {
                            childIds = childIds.FilterWithPermissions(
                                BackOfficeRequestContext.Application.Security,
                                ((UmbracoBackOfficeIdentity)User.Identity).Id,
                                uow,
                                securityUow,
                                new ViewPermission().Id
                                ).ToArray();
                        }

                        if (childIds.Length == 1)
                        {
                            var node     = uow.Repositories.Get <TypedEntity>(childIds[0]);
                            var treeNode = ConvertEntityToTreeNode(node, RootNodeId, queryStrings, uow);

                            //add the tree id to the root
                            treeNode.AdditionalData.Add("treeId", TreeId.ToString("N"));
                            treeNode.HasChildren = true; // Force true so that recycle bin is displayed

                            //add the tree-root css class
                            treeNode.Style.AddCustom("tree-root");

                            //node.AdditionalData.Add("id", node.HiveId.ToString());
                            //node.AdditionalData.Add("title", node.Title);

                            //check if the tree is searchable and add that to the meta data as well
                            if (this is ISearchableTree)
                            {
                                treeNode.AdditionalData.Add("searchable", "true");
                            }

                            AddMenuItemsToNode(treeNode, queryStrings);

                            return(treeNode);
                        }
                    }
            }

            return(null);
        }
Beispiel #10
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            using (DisposableTimer.TraceDuration <InternationalizeAttribute>("Checking if should set thread culture automatically", "Done check"))
            {
                if (!filterContext.ActionParameters.ContainsKey("model"))
                {
                    LogHelper.TraceIfEnabled <InternationalizeAttribute>("filterContext.ActionParameters didn't contain model");
                    return;
                }

                var model = filterContext.ActionParameters["model"] as IRebelRenderModel;
                if (model == null)
                {
                    LogHelper.TraceIfEnabled <InternationalizeAttribute>("filterContext.ActionParameters didn't contain model that was IRebelRenderModel");
                    return;
                }
                if (!model.IsLoaded)
                {
                    LogHelper.TraceIfEnabled <InternationalizeAttribute>("filterContext.ActionParameters didn't contained model but it wasn't loaded yet");
                    return;
                }

                var currentNodeId = model.CurrentNode.Id;

                //TODO: Cache this

                using (var uow = ApplicationContext.Hive.OpenReader <IContentStore>())
                {
                    var ancestorIds = uow.Repositories.GetAncestorsIdsOrSelf(currentNodeId,
                                                                             FixedRelationTypes.DefaultRelationType);
                    foreach (var ancestorId in ancestorIds)
                    {
                        var languageRelation =
                            uow.Repositories.GetParentRelations(ancestorId, FixedRelationTypes.LanguageRelationType).
                            SingleOrDefault();

                        if (languageRelation == null)
                        {
                            continue;
                        }

                        var metaDatum = languageRelation.MetaData.FirstOrDefault(x => x.Key == "IsoCode");
                        if (metaDatum == null)
                        {
                            return;
                        }
                        var isoCode = metaDatum.Value;

                        LogHelper.TraceIfEnabled <InternationalizeAttribute>("Setting thread culture to {0}", () => isoCode);

                        Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(isoCode);
                        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(isoCode);

                        return;
                    }
                }
            }
        }
 private string Cache(string key, Func <string> value)
 {
     using (DisposableTimer.TraceDuration <DefaultRenderModelFactory>("Begin Parsing HTML", "End Parsing HTML"))
     {
         return(_context
                .FrameworkContext.Caches.ExtendedLifetime.GetOrCreate(
                    key, value, new StaticCachePolicy(TimeSpan.FromDays(LongTime))).Value.Item);
     }
 }
        /// <summary>Adds a dependency demand builder to the container and instructs it to register its dependencies.</summary>
        /// <param name="demandBuilder">The demand builder.</param>
        /// <returns>.</returns>
        public IContainerBuilder AddDependencyDemandBuilder(IDependencyDemandBuilder demandBuilder)
        {
            Mandate.ParameterNotNull(demandBuilder, "demandBuilder");

            using (DisposableTimer.TraceDuration <AbstractContainerBuilder>("Start AddDependencyDemandBuilder " + demandBuilder.GetType().Name, "End AddDependencyDemandBuilder"))
            {
                demandBuilder.Build(this, Context);
                return(this);
            }
        }
 public void PartialTrustShouldFail()
 {
     LogHelper.TraceIfEnabled <FakeFixture>("In PartialTrustShouldFail, about to try to access a private field");
     using (DisposableTimer.TraceDuration <FakeFixture>("PartialTrustShouldFail", "PartialTrustShouldFail"))
     {
         var fieldInfo = typeof(Int32).GetField("m_value", BindingFlags.Instance | BindingFlags.NonPublic);
         var value     = fieldInfo.GetValue(1);
         LogHelper.TraceIfEnabled <FakeFixture>("value: {0}", () => value);
     }
 }
 public static void UpdateSchema(global::NHibernate.Cfg.Configuration configuration)
 {
     using (new WriteLockDisposable(SchemaValidationLocker))
     {
         using (DisposableTimer.TraceDuration <ProviderBootstrapper>("Begin db schema update", "End db schema update"))
         {
             var schema = new SchemaUpdate(configuration);
             schema.Execute(x => LogHelper.TraceIfEnabled <ProviderBootstrapper>("NHibernate generated the following update Sql: \n" + x), true);
         }
     }
 }
Beispiel #15
0
 /// <summary>
 /// Creates or returns an existing IUmbracoRenderModel based on the request data
 /// </summary>
 /// <param name="httpContext"></param>
 /// <param name="rawUrl"></param>
 /// <returns></returns>
 public IUmbracoRenderModel Create(HttpContextBase httpContext, string rawUrl)
 {
     using (DisposableTimer.TraceDuration <DefaultRenderModelFactory>("Begin find/create context", "End find/create"))
     {
         return(_applicationContext.FrameworkContext.ScopedCache.GetOrCreateTyped <IUmbracoRenderModel>(ResponseLifecycleCacheKey, () =>
         {
             LogHelper.TraceIfEnabled <DefaultRenderModelFactory>("IUmbracoRenderModel requires creation");
             var model = new UmbracoRenderModel(_applicationContext, () => ResolveItem(httpContext, rawUrl));
             return model;
         }));
     }
 }
        internal void ExecuteCommit()
        {
            //need to send Examine all of the stuff to index for this unit of work

            //we need to 'stagger' the operations as it will be much faster to send all of the "Adds" to Examine at once and then each "Delete" one at a time.
            //because of the way Examine works, we also need to 'stagger' the index categories as well

            using (DisposableTimer.TraceDuration <ExamineTransaction>("Start adding indexes to Examine queue", "End adding indexes to Examine queue"))
            {
                var examineOperations = new List <IndexOperation>();

                //we track the TypedEntity revisions committed for 2 reasons (we're tracking the TypedEntity item in the revision):
                //  1: see below notes
                //  2: we need to update the status changed date if the status has in fact 'changed' since we need to reference in-memory objects as well
                var revisionsCommitted = new List <Tuple <TypedEntity, RevisionData> >();

                //this will get all of the lazy ids generated so we can use the values
                // to lookup some entities.
                var ids = _itemsToIndex.Where(x => x.OperationType == IndexOperationType.Add).Select(x => x.Id.Value)
                          .Concat(_itemsToIndex
                                  .Where(x => x.Fields.ContainsKey(FixedIndexedFields.EntityId) && x.OperationType == IndexOperationType.Add)
                                  .Select(x => x.Fields[FixedIndexedFields.EntityId].FieldValue.ToString()))
                          .Distinct()
                          .ToArray();

                while (_itemsToIndex.Any())
                {
                    var op = _itemsToIndex.Last();

                    examineOperations.Add(_frameworkContext.TypeMappers.Map <IndexOperation>(op));

                    //if its a typed entity revision:
                    // - track it so we can perform index cleanup on revisions
                    // - check status changed dates so we can ensure they are correct
                    if (op.IsRevision())
                    {
                        revisionsCommitted.Add(
                            EnsureCorrectStatusChangedDate(op, revisionsCommitted));
                    }

                    EnsureRelationEntities(op, ids);

                    //'dequeue' the item from the list
                    _itemsToIndex.RemoveAt(_itemsToIndex.Count - 1);
                }

                //now we have all of the indexing operations ready, lets do it
                ExamineManager.PerformIndexing(examineOperations.ToArray());

                //do some cleanup of the index data
                CleanupIndexedRevisions(revisionsCommitted);
            }
        }
Beispiel #17
0
        public virtual void ReloadTexts()
        {
            using (DisposableTimer.TraceDuration <TextManager>("Start ReloadTexts", "End ReloadTexts"))
            {
                var oldCache = _textCache;

                var newTexts = Texts.Get();
                TextHash = HashToString(ComputeHash(newTexts));

                var newCache = newTexts
                               .Where(text => text.Quality != TextQuality.PlaceHolder)
                               .Fold((text) => text,
                                     (text) =>
                                     new LocalizedTextCacheEntry {
                    Text = text
                });

                if (oldCache != null)
                {
                    //Not too pretty... Find text entries in the old cache that equals those in the new and reuse them
                    foreach (var ns in oldCache)
                    {
                        Dictionary <string, Dictionary <string, LocalizedTextCacheEntry> > newNs;
                        if (newCache.TryGetValue(ns.Key, out newNs))
                        {
                            foreach (var key in ns.Value)
                            {
                                Dictionary <string, LocalizedTextCacheEntry> newKey;
                                if (newNs.TryGetValue(key.Key, out newKey))
                                {
                                    foreach (var lang in key.Value)
                                    {
                                        LocalizedTextCacheEntry newEntry;
                                        if (newKey.TryGetValue(lang.Key, out newEntry))
                                        {
                                            var oldEntry = lang.Value;
                                            if (oldEntry.Text.Equals(newEntry.Text))
                                            {
                                                //Reuse
                                                newKey[lang.Key] = lang.Value;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                _textCache = newCache;
            }
        }
Beispiel #18
0
        /// <summary>
        /// Executes the task in the current context synchronously. Executes the tasks matching the specified trigger name.
        /// </summary>
        /// <param name="triggerName">Name of the trigger.</param>
        /// <param name="context">The context.</param>
        /// <param name="canceled">if set to <c>true</c> taks was canceled.</param>
        /// <returns></returns>
        public ApplicationTaskManager ExecuteInContext(string triggerName, TaskExecutionContext context, out bool canceled)
        {
            canceled            = false;
            context.TriggerName = triggerName;
            using (DisposableTimer.TraceDuration <ApplicationTaskManager>("Raising trigger: " + triggerName, "End trigger " + triggerName))
            {
                try
                {
                    var tasks = _tasks
                                .Where(x => String.Compare(x.Metadata.TriggerName, triggerName, StringComparison.InvariantCultureIgnoreCase) == 0)
                                .ToArray();

                    foreach (var task in tasks)
                    {
                        var continueOnFailure = task.Metadata.ContinueOnError;
                        var abstractTask      = task.Value;
                        try
                        {
                            using (DisposableTimer.TraceDuration(abstractTask.GetType(), "[START] Executing " + abstractTask.ToString(), "[END] Executing " + abstractTask.ToString()))
                            {
                                abstractTask.Execute(context);
                            }

                            if (context.Cancel && !continueOnFailure)
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            var name = abstractTask != null?abstractTask.GetType().Name : "<unknown; task was null>";

                            context.Exceptions.Add(ex);
                            LogHelper.Error <ApplicationTaskManager>(
                                String.Format("Error running a task trigger {0} for task {1}", triggerName, name), ex);
                            if (!continueOnFailure)
                            {
                                break;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Error <ApplicationTaskManager>("Error running a task trigger " + triggerName, e);
                }
            }

            return(this);
        }
        public NHibernateInMemoryRepository(IFrameworkContext fakeFrameworkContext, ISessionFactory sessionFactory = null, ISession sessionForTest = null)
        {
            using (DisposableTimer.TraceDuration <NHibernateInMemoryRepository>("Start setup", "End setup"))
            {
                if (sessionFactory == null && sessionForTest == null)
                {
                    var builder = new NHibernateConfigBuilder("data source=:memory:", "unit-tester",
                                                              SupportedNHDrivers.SqlLite, "thread_static", false);
                    var config = builder.BuildConfiguration();
                    _sessionFactory = config.BuildSessionFactory();
                    SessionForTest  = _sessionFactory.OpenSession();

                    // See http://stackoverflow.com/questions/4325800/testing-nhibernate-with-sqlite-no-such-table-schema-is-generated
                    // and also http://nhforge.org/doc/nh/en/index.html#architecture-current-session
                    // regarding contextual sessions and GetCurrentSession()

                    // We pass in our own TextWriter because a bug in VS's testing framework means directly passing in Console.Out causes an ObjectDisposedException
                    new SchemaExport(config).Execute(false, true, false, SessionForTest.Connection, _schemaWriter);
                }
                else
                {
                    _sessionFactory = sessionFactory;
                    SessionForTest  = sessionForTest;
                }

                _dataContextFactory = new DataContextFactory(fakeFrameworkContext, SessionForTest, true);

                // Create reader
                ReadOnlyUnitOfWorkFactory = new ReadOnlyUnitOfWorkFactory();
                _hiveReadProvider         = new HiveReadProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), ReadOnlyUnitOfWorkFactory, null, _dataContextFactory));

                // Create writer
                ReadWriteUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory();
                _writeProvider             = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "rw-unit-tester", new FakeHiveProviderBootstrapper(), ReadOnlyUnitOfWorkFactory, ReadWriteUnitOfWorkFactory, _dataContextFactory));

                //setup nhibernate mappers
                var manualMapper = new ManualMapper(new NhLookupHelper(_dataContextFactory), _writeProvider);
                fakeFrameworkContext.TypeMappers.Add(new Lazy <AbstractTypeMapper, TypeMapperMetadata>(() => manualMapper, new TypeMapperMetadata(true)));


                // Create hive wrappers for the readers and writers
                var governorRUowFactory = new ReadOnlyUnitOfWorkFactoryWrapper(new[] { _hiveReadProvider });

                var governorRWUowFactory = new ReadWriteUnitOfWorkFactoryWrapper(new[] { _writeProvider });

                _hiveReadProviderViaGovernor      = new Framework.Hive.PersistenceGovernor.HiveReadProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, null, null), new[] { _hiveReadProvider });
                _hiveReadWriteProviderViaGovernor = new Framework.Hive.PersistenceGovernor.HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "rw-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, governorRWUowFactory, null), new[] { _writeProvider });
            }
        }
        /// <summary>
        /// This gets all tasks found in configuration blocks and dynamically creates real task definitions from them
        /// and registers them with the task manager with the trigger name of the package they were found in
        /// </summary>
        /// <param name="context"></param>
        public override void Execute(TaskExecutionContext context)
        {
            using (DisposableTimer.TraceDuration <ConfigurationTaskBuilder>("Building configuration tasks", "End building configuration tasks"))
            {
                //get all tasks in configuration
                foreach (var t in ApplicationContext.Settings.Tasks)
                {
                    //create a new config task context with the configuration task's parameters
                    var configTaskContext = new ConfigurationTaskContext(ApplicationContext, t.Parameters, t);

                    //create a new instance of the configuration task
                    var task = (ConfigurationTask)Activator.CreateInstance(t.TaskType, new[] { configTaskContext });
                    var meta = new TaskMetadata(null)
                    {
                        ComponentType   = task.GetType(),
                        ContinueOnError = true,
                        Id = Guid.NewGuid(),
                    };
                    //now we need to check the trigger name, if it is either post-package-install or pre-package-uninstall
                    //then we need to check if this task has been registered with a package. If so, then we change the trigger
                    //to be PackageFolderName-post-package-install so that the task only executes for the current packages installation
                    //changes. If its neither of these names, then we just use the normal trigger
                    if ((t.Trigger.InvariantEquals(TaskTriggers.PostPackageInstall) || t.Trigger.InvariantEquals(TaskTriggers.PrePackageUninstall)) &&
                        !t.PackageFolder.IsNullOrWhiteSpace())
                    {
                        var parts          = t.PackageFolder.Split(Path.DirectorySeparatorChar);
                        var packageName    = parts[parts.Length - 1];
                        var newTriggername = packageName + "-" + t.Trigger;
                        var t1             = t;
                        LogHelper.TraceIfEnabled <ConfigurationTaskBuilder>("Found {0} config task of type {1} for package, registering it as {2}", () => t1.Trigger, () => t1.TaskType.Name, () => newTriggername);
                        //ok, we've got a task declared on a package for post package install or pre package uninstall, so need to update the trigger accordingly
                        meta.TriggerName = newTriggername;
                    }
                    else
                    {
                        //nope, this is a task declared in config that is not a package... unexpected but i guess it could happen
                        //so we just use the normal trigger that it was declared with.
                        var t1 = t;
                        LogHelper.TraceIfEnabled <ConfigurationTaskBuilder>("Found {0} config task of type {1} outside of a package", () => t1.Trigger, () => t1.TaskType.Name);
                        meta.TriggerName = t.Trigger;
                    }

                    //create a new task definition
                    var taskDefinition = new Lazy <AbstractTask, TaskMetadata>(() => task, meta);
                    //add the definition to the manager
                    ApplicationContext.FrameworkContext.TaskManager.AddTask(taskDefinition);
                }
            }
        }
        public void MapAndMerge(AbstractEntity entity, MappingEngineCollection mappers)
        {
            using (DisposableTimer.TraceDuration <NhSessionHelper>("Start MapAndMerge for entity " + entity.Id, "End MapAndMerge"))
                using (NhProfilerLogging.Start(NhSession, "MapAndMerge",
                                               new OdbcParameter("entity", entity)))
                {
                    var rdbmsEntity = mappers.MapToIntent <IReferenceByGuid>(entity);

                    // Track ID generation on the Rdbms object so that it can be pinged to the AbstractEntity upon Save/Update commit
                    rdbmsEntity = NhSession.Merge(rdbmsEntity) as IReferenceByGuid;

                    //InnerDataContext.NhibernateSession.SaveOrUpdate(rdbmsEntity);
                    mappers.Map(rdbmsEntity, entity, rdbmsEntity.GetType(), entity.GetType());
                }
        }
Beispiel #22
0
        protected void FlushQueue()
        {
            if (_forceStop)
            {
                return;
            }
            using (new WriteLockDisposable(_flushLocker))
            {
                if (_forceStop)
                {
                    return;
                }

                LogHelper.TraceIfEnabled <IndexController>("Checking for items in FlushQueue");
                IndexModificationBatch batch = null;
                var success = Queue.Batches.TryDequeue(out batch);

                if (!success)
                {
                    return;
                }

                using (DisposableTimer.TraceDuration <IndexController>("Creating a worker and flushing", "Worker for FlushQueue finished"))
                    using (var worker = CreateTransactionWorker())
                    {
                        try
                        {
                            while (success && !_forceStop)
                            {
                                EnactBatch(worker, batch);
                                _flushCount++;
                                success = Queue.Batches.TryDequeue(out batch);
                            }
                            worker.Commit();
                            if (_flushCount % 50 == 0)
                            {
                                worker.TryOptimizeDeletions();
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error <IndexController>("Failed to flush the queue: " + ex.Message, ex);
                            worker.TryRollback();
                            throw;
                        }
                    }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Creates or returns an existing IRebelRenderModel based on the request data
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="rawUrl"></param>
        /// <returns></returns>
        public IRebelRenderModel Create(HttpContextBase httpContext, string rawUrl)
        {
            bool isPreview = false;

            bool.TryParse(httpContext.Request.QueryString[ContentEditorModel.PreviewQuerystringKey], out isPreview);

            if (isPreview)
            {
                return(new RebelRenderModel(_applicationContext, () => ResolveItem(httpContext, rawUrl, isPreview)));
            }
            using (DisposableTimer.TraceDuration <DefaultRenderModelFactory>("Begin find/create context", "End find/create"))
            {
                string key = string.Format("Model:{0}", rawUrl);
                return(GetOrCreateRebelRenderModel(httpContext, rawUrl, key));
            }
        }
Beispiel #24
0
 /// <summary>
 /// Parses all patterns. Regarding thread safety: An exception will occur if texts are changed while this method executes
 /// </summary>
 public void ParseAllPatterns()
 {
     using (DisposableTimer.TraceDuration <TextManager>("Start ParseAllPatterns", "End ParseAllPatterns"))
     {
         foreach (var keys in _textCache.Values)
         {
             foreach (var translations in keys.Values)
             {
                 foreach (var entry in translations.Values)
                 {
                     EnsureEvaluator(entry);
                 }
             }
         }
     }
 }
Beispiel #25
0
        public void HiveEntityExtensions_GetAllIdentifiableItems_Perf()
        {
            // Arrange
            var items = EnumerableExtensions.Range(count => HiveModelCreationHelper.MockTypedEntity(HiveId.ConvertIntToGuid(count + 1)), 250).ToArray();

            // Act & Assert
            using (DisposableTimer.TraceDuration <GroupActorTests>("Starting getting all dependents", "Finished"))
            {
                var allGraph = new List <IReferenceByHiveId>();
                foreach (var typedEntity in items)
                {
                    allGraph.AddRange(typedEntity.GetAllIdentifiableItems().ToArray());
                }
                LogHelper.TraceIfEnabled <GroupActorTests>("Found {0} items", () => allGraph.Count);
            }
        }
Beispiel #26
0
 /// <summary>
 /// Returns the hash string for all found plugins/folders
 /// </summary>
 /// <returns></returns>
 internal static string GetPluginsHash(IEnumerable <FileInfo> plugins, bool generateNew = false)
 {
     if (generateNew || _pluginsHash.IsNullOrWhiteSpace())
     {
         using (DisposableTimer.TraceDuration <PluginManager>("Determining hash of plugins on disk", "Hash determined"))
         {
             var hashCombiner = new HashCodeCombiner();
             //add each unique folder to the hash
             foreach (var i in plugins.Select(x => x.Directory).DistinctBy(x => x.FullName))
             {
                 hashCombiner.AddFolder(i);
             }
             _pluginsHash = hashCombiner.GetCombinedHashCode();
         }
     }
     return(_pluginsHash);
 }
        /// <summary>
        /// Get the child tree nodes for the id specified
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        protected override IEnumerable <TreeNode> GetChildTreeNodes(HiveId parentId, FormCollection queryStrings)
        {
            var hiveProvider = GetHiveProvider(parentId, queryStrings);

            using (var securityUow = hiveProvider.CreateReadonly <ISecurityStore>())
                using (var uow = hiveProvider.CreateReadonly <IContentStore>())
                {
                    //Get the items and ensure Browse permissions are applied
                    var childIds = GetChildContentIds(parentId, uow);

                    using (DisposableTimer.TraceDuration <ContentTreeController>("FilterWithPermissions", "FilterWithPermissions"))
                    {
                        childIds = childIds.FilterWithPermissions(
                            BackOfficeRequestContext.Application.Security,
                            ((UmbracoBackOfficeIdentity)User.Identity).Id,
                            uow,
                            securityUow,
                            new ViewPermission().Id
                            ).ToArray();
                    }

                    IEnumerable <TypedEntity> children = null;

                    using (DisposableTimer.TraceDuration <ContentTreeController>("Get childIds", "Get childIds"))
                    {
                        children = uow.Repositories.Get <TypedEntity>(true, childIds);
                    }

                    //var items = uow.Repositories
                    //    .GetEntityByRelationType<TypedEntity>(FixedRelationTypes.ContentTreeRelationType, parentId)
                    //    .FilterWithPermissions<TypedEntity>(
                    //        new BrowsePermission().Id,
                    //        BackOfficeRequestContext.Application.Security,
                    //        ((UmbracoBackOfficeIdentity)User.Identity).Id);

                    //lookup all the items, conver to a custom object of the tree node & entity, then populate the
                    //icon based on the EntitySchema of the item.
                    return(children.Select(x => ConvertEntityToTreeNode(x, parentId, queryStrings, uow))
                           .Where(x => x != null));
                }
        }
        /// <summary>Add dependency demand builders from the assembly of the given type.</summary>
        /// <param name="exampleType">Type from which to infer assembly.</param>
        /// <returns>.</returns>
        public IContainerBuilder AddDemandsFromAssemblyOf(Type exampleType)
        {
            Mandate.ParameterNotNull(exampleType, "exampleType");

            using (DisposableTimer.TraceDuration <AbstractContainerBuilder>("Start AddDemandsFromAssemblyOf", "End AddDemandsFromAssemblyOf"))
            {
                Type[] typesInAssembly = exampleType.Assembly.GetTypes();

                IEnumerable <Type> typesImplementingInterface = typesInAssembly
                                                                .Where(type => typeof(IDependencyDemandBuilder).IsAssignableFrom(type));

                IEnumerable <IDependencyDemandBuilder> demandBuilders = typesImplementingInterface
                                                                        .Select(component => Activator.CreateInstance(component) as IDependencyDemandBuilder);

                demandBuilders
                .ToList()
                .ForEach(x => AddDependencyDemandBuilder(x));

                return(this);
            }
        }
Beispiel #29
0
        public override void ExecuteResult(ControllerContext context)
        {
            //since we could be returning the current page from a surface controller posted values in which the routing values are changed, we
            //need to revert these values back to nothing in order for the normal page to render again.
            context.RouteData.DataTokens["area"]       = null;
            context.RouteData.DataTokens["Namespaces"] = null;

            //validate that the current page execution is not being handled by the normal umbraco routing system
            if (!context.RouteData.DataTokens.ContainsKey("umbraco-route-def"))
            {
                throw new InvalidOperationException("Can only use " + typeof(UmbracoPageResult).Name + " in the context of an Http POST when using a SurfaceController form");
            }

            var routeDef = (RouteDefinition)context.RouteData.DataTokens["umbraco-route-def"];

            //ensure the original template is reset
            context.RouteData.Values["action"] = routeDef.ActionName;

            //ensure ModelState is copied across
            routeDef.Controller.ViewData.ModelState.Merge(context.Controller.ViewData.ModelState);

            //ensure TempData and ViewData is copied across
            foreach (var d in context.Controller.ViewData)
            {
                routeDef.Controller.ViewData[d.Key] = d.Value;
            }
            routeDef.Controller.TempData = context.Controller.TempData;

            using (DisposableTimer.TraceDuration <UmbracoPageResult>("Executing Umbraco RouteDefinition controller", "Finished"))
            {
                try
                {
                    ((IController)routeDef.Controller).Execute(context.RequestContext);
                }
                finally
                {
                    routeDef.Controller.DisposeIfDisposable();
                }
            }
        }
        public void MapAndMerge <T>(Revision <T> entity, MappingEngineCollection mappers) where T : class, IVersionableEntity
        {
            HiveId hiveId   = entity.MetaData != null ? entity.MetaData.Id : HiveId.Empty;
            HiveId entityId = entity.Item != null ? entity.Item.Id : HiveId.Empty;

            using (DisposableTimer.TraceDuration <NhSessionHelper>("Start MapAndMerge for revision " + hiveId + " entity " + entityId, "End MapAndMerge"))
                using (NhProfilerLogging.Start(NhSession, "MapAndMerge<T> (Revision<T>)",
                                               new OdbcParameter("entity", entity)))
                {
                    var rdbmsEntity = mappers.MapToIntent <IReferenceByGuid>(entity);

                    // Track ID generation on the Rdbms object so that it can be pinged to the AbstractEntity upon Save/Update commit
                    rdbmsEntity = NhSession.Merge(rdbmsEntity) as IReferenceByGuid;

                    // 16th Jan 12 (APN) NH is not flushing if the above merged entity is queried before the transaction is committed, despite
                    // the flushmode being Auto. So, explicit call to Flush here pending a bugfix/ better solution
                    NhSession.Flush();

                    //InnerDataContext.NhibernateSession.SaveOrUpdate(rdbmsEntity);
                    mappers.Map(rdbmsEntity, entity, rdbmsEntity.GetType(), entity.GetType());
                }
        }