/// <summary>
        /// Determines the Umbraco document (if any) matching the http request.
        /// </summary>
        /// <returns>A value indicating whether a document and template nave been found.</returns>
        internal bool LookupDocument()
        {
            const string tracePrefix = "LookupDocument: ";

            LogHelper.Debug <PublishedContentRequest>("{0}Path=\"{1}\"", () => tracePrefix, () => _publishedContentRequest.Uri.AbsolutePath);

            // look for the document
            // the first successful resolver, if any, will set this.Node, and may also set this.Template
            // some lookups may implement caching

            using (DisposableTimer.DebugDuration <PluginManager>(
                       string.Format("{0}Begin resolvers", tracePrefix),
                       string.Format("{0}End resolvers, {1}", tracePrefix, (_publishedContentRequest.HasNode ? "a document was found" : "no document was found"))))
            {
                _routingContext.DocumentLookups.Any(lookup => lookup.TrySetDocument(_publishedContentRequest));
            }

            // fixme - not handling umbracoRedirect
            // should come after internal redirects
            // so after ResolveDocument2() => docreq.IsRedirect => handled by the module!

            // handle not-found, redirects, access, template
            LookupDocument2();

            // handle umbracoRedirect (moved from umbraco.page)
            FollowRedirect();

            bool resolved = _publishedContentRequest.HasNode && _publishedContentRequest.HasTemplate;

            return(resolved);
        }
        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 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);
        }
 /// <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);
     }
 }
        /// <summary>
        /// The RegEx matches any HTML attribute values that start with a tilde (~), those that match are passed to ResolveUrl to replace the tilde with the application path.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="preview"></param>
        /// <returns></returns>
        /// <remarks>
        /// When used with a Virtual-Directory set-up, this would resolve all URLs correctly.
        /// The recommendation is that the "ResolveUrlsFromTextString" option (in umbracoSettings.config) is set to false for non-Virtual-Directory installs.
        /// </remarks>
        public static string ResolveUrlsFromTextString(string text)
        {
            if (UmbracoSettings.ResolveUrlsFromTextString == false)
            {
                return(text);
            }

            using (var timer = DisposableTimer.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
            {
                // find all relative urls (ie. urls that contain ~)
                var tags = ResolveUrlPattern.Matches(text);
                LogHelper.Debug(typeof(IOHelper), "After regex: " + timer.Stopwatch.ElapsedMilliseconds + " matched: " + tags.Count);
                foreach (Match tag in tags)
                {
                    var url = "";
                    if (tag.Groups[1].Success)
                    {
                        url = tag.Groups[1].Value;
                    }

                    // The richtext editor inserts a slash in front of the url. That's why we need this little fix
                    //                if (url.StartsWith("/"))
                    //                    text = text.Replace(url, ResolveUrl(url.Substring(1)));
                    //                else
                    if (String.IsNullOrEmpty(url) == false)
                    {
                        var resolvedUrl = (url.Substring(0, 1) == "/") ? IOHelper.ResolveUrl(url.Substring(1)) : IOHelper.ResolveUrl(url);
                        text = text.Replace(url, resolvedUrl);
                    }
                }
            }

            return(text);
        }
Beispiel #6
0
 public BootManager(HttpApplication app)
 {
     _timer = DisposableTimer.Start(timer => LogHelper.TraceIfEnabled <BootManager>("Application start took {0}ms", () => timer));
     _app   = app;
     LogHelper.TraceIfEnabled <BootManager>("Created");
     _rebelWireup = new RebelContainerBuilder <HttpApplication>(_app);
 }
	    public virtual IBootManager Initialize()
		{
			if (_isInitialized)
				throw new InvalidOperationException("The boot manager has already been initialized");

	        InitializeProfilerResolver();

            _timer = DisposableTimer.DebugDuration<CoreBootManager>("Umbraco application starting", "Umbraco application startup complete");

			//create database and service contexts for the app context
			var dbFactory = new DefaultDatabaseFactory(GlobalSettings.UmbracoConnectionName);
		    Database.Mapper = new PetaPocoMapper();
			var dbContext = new DatabaseContext(dbFactory);
			var serviceContext = new ServiceContext(
				new PetaPocoUnitOfWorkProvider(dbFactory), 
				new FileUnitOfWorkProvider(), 
				new PublishingStrategy());

            CreateApplicationContext(dbContext, serviceContext);

            InitializeApplicationEventsResolver();

			InitializeResolvers();

            //initialize the DatabaseContext
            dbContext.Initialize();

            //now we need to call the initialize methods
            ApplicationEventsResolver.Current.ApplicationEventHandlers
                .ForEach(x => x.OnApplicationInitialized(UmbracoApplication, ApplicationContext));

			_isInitialized = true;

			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));
            }
        }
Beispiel #9
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 });
            }
        }
Beispiel #10
0
        public virtual void RegisterMacroEngines(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_macroEnginesRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterMacroEngines start took {0}ms", () => timer);
                _macroEnginesRegistered = true;
            }))
            {
                //now register each type in the container and also add it to our collection);
                foreach (var t in FindTypesInRequiredAssemblies <AbstractMacroEngine>(typeFinder))
                {
                    var engineType = t;
                    RegisterComponent <AbstractMacroEngine, MacroEngineAttribute, MacroEngineMetadata>(
                        t, builder, true,
                        (pluginDef, attribute, registrar) =>
                        registrar
                        .WithMetadata <MacroEngineMetadata, string>(am => am.EngineName, attribute.EngineName)
                        .WithMetadata <MacroEngineMetadata, bool>(am => am.IsInternalRebelEngine,
                                                                  engineType.GetCustomAttributes(typeof(RebelMacroEngineAttribute), false).Any())
                        .ScopedAs.Singleton());                                         //only need one each
                }
            }
        }
        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));
        }
Beispiel #12
0
        /// <summary>
        /// Register the tree controllers
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="typeFinder"></param>
        public virtual void RegisterTreeControllers(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_treeControllersRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterTreeControllers start took {0}ms", () => timer);
                _treeControllersRegistered = true;
            }))
            {
                //now register each type in the container and also add it to our collection
                foreach (var t in FindTypesInRequiredAssemblies <TreeController>(typeFinder))
                {
                    var treeType = t;

                    RegisterComponent <TreeController, TreeAttribute, TreeMetadata>(t, builder, true,
                                                                                    (pluginDef, attribute, registrar) =>
                                                                                    registrar
                                                                                    .WithMetadata <EditorMetadata, string>(am => am.ControllerName, RebelController.GetControllerName(treeType))
                                                                                    .WithMetadata <TreeMetadata, string>(am => am.TreeTitle, attribute.TreeTitle)
                                                                                    .WithMetadata <TreeMetadata, bool>(am => am.IsInternalRebelTree,
                                                                                                                       treeType.GetCustomAttributes(typeof(RebelTreeAttribute), false).Any()));
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Registers all tasks.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="typeFinder">The type finder.</param>
        /// <remarks></remarks>
        public virtual void RegisterTasks(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_tasksRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterTasks start took {0}ms", () => timer);
                _tasksRegistered = true;
            }))
            {
                foreach (var t in FindTypesInRequiredAssemblies <AbstractTask>(typeFinder))
                {
                    RegisterComponent <AbstractTask, TaskAttribute, TaskMetadata>(t, builder, false,
                                                                                  (pluginDef, attribute, registrar) =>
                    {
                        //if there's no attribute since we're not requiring that all AbstractTasks have one,
                        //then don't register it into IoC as it might be something like our 'Delegate' task
                        //or another custom one that is added to the task manager at runtime
                        if (attribute == null)
                        {
                            return;
                        }

                        registrar
                        .WithMetadata <TaskMetadata, string>(metadata => metadata.TriggerName, attribute.Trigger)
                        .WithMetadata <TaskMetadata, bool>(metadata => metadata.ContinueOnError, attribute.ContinueOnFailure)
                        .ScopedAs.Singleton();
                    });         //only need one each
                }
            }
        }
Beispiel #14
0
        public void Get_All_Published_Content_Of_Type()
        {
            var result     = PrimeDbWithLotsOfContent();
            var contentSvc = (ContentService)ServiceContext.ContentService;

            var countOfPublished = result.Count(x => x.Published);
            var contentTypeId    = result.First().ContentTypeId;

            using (DisposableTimer.DebugDuration <PerformanceTests>("Getting published content of type normally"))
            {
                //do this 10x!
                for (var i = 0; i < 10; i++)
                {
                    //clear the cache to make this test valid
                    RuntimeCacheProvider.Current.Clear();
                    //get all content items that are published of this type
                    var published = contentSvc.GetContentOfContentType(contentTypeId).Where(content => content.Published);
                    Assert.AreEqual(countOfPublished, published.Count(x => x.ContentTypeId == contentTypeId));
                }
            }

            using (DisposableTimer.DebugDuration <PerformanceTests>("Getting published content of type optimized"))
            {
                //do this 10x!
                for (var i = 0; i < 10; i++)
                {
                    //clear the cache to make this test valid
                    RuntimeCacheProvider.Current.Clear();
                    //get all content items that are published of this type
                    var published = contentSvc.GetPublishedContentOfContentType(contentTypeId);
                    Assert.AreEqual(countOfPublished, published.Count(x => x.ContentTypeId == contentTypeId));
                }
            }
        }
Beispiel #15
0
        /// <summary>
        /// Finds & Registers the Surface controllers
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="typeFinder"></param>
        public virtual void RegisterSurfaceControllers(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_surfaceControllersRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterSurfaceControllers start took {0}ms", () => timer);
                _surfaceControllersRegistered = true;
            }))
            {
                //now register each type in the container and also add it to our collection);
                foreach (var t in FindTypesInRequiredAssemblies <SurfaceController>(typeFinder))
                {
                    var surfaceType = t;

                    RegisterComponent <SurfaceController, SurfaceAttribute, SurfaceMetadata>(
                        t, builder, false,
                        (pluginDef, attribute, registrar) =>
                        registrar
                        .WithMetadata <SurfaceMetadata, string>(am => am.ControllerName, RebelController.GetControllerName(surfaceType))
                        .WithMetadata <SurfaceMetadata, bool>(am => am.HasChildActionMacros,
                                                              surfaceType.GetMethods().Any(a => a.GetCustomAttributes(typeof(ChildActionOnlyAttribute), false).Any())));
                }
            }
        }
Beispiel #16
0
 public BootManager(HttpApplication app)
 {
     _timer = DisposableTimer.Start(timer => LogHelper.TraceIfEnabled<BootManager>("Application start took {0}ms", () => timer));
     _app = app;
     LogHelper.TraceIfEnabled<BootManager>("Created");
     _rebelWireup = new RebelContainerBuilder<HttpApplication>(_app);
 }
Beispiel #17
0
        public override bool PerformRun()
        {
            if (_appContext == null)
            {
                return(true);                     // repeat...
            }
            switch (_appContext.GetCurrentServerRole())
            {
            case ServerRole.Slave:
                LogHelper.Debug <LogScrubber>("Does not run on slave servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                LogHelper.Debug <LogScrubber>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_appContext.MainDom.IsMainDom == false)
            {
                LogHelper.Debug <LogScrubber>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            using (DisposableTimer.DebugDuration <LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
            {
                Log.CleanLogs(GetLogScrubbingMaximumAge(_settings));
            }

            return(true); // repeat
        }
        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));
                }
            }
        }
        public override bool PerformRun()
        {
            if (_appContext == null)
            {
                return(true);                     // repeat...
            }
            switch (_appContext.GetCurrentServerRole())
            {
            case ServerRole.Slave:
                LogHelper.Debug <LogScrubber>("Does not run on replica servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                LogHelper.Debug <LogScrubber>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_appContext.MainDom.IsMainDom == false)
            {
                LogHelper.Debug <LogScrubber>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            // running on a background task, and Log.CleanLogs uses the old SqlHelper,
            // better wrap in a scope and ensure it's all cleaned up and nothing leaks
            using (var scope = ApplicationContext.Current.ScopeProvider.CreateScope())
                using (DisposableTimer.DebugDuration <LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
                {
                    Log.CleanLogs(GetLogScrubbingMaximumAge(_settings));
                    scope.Complete();
                }

            return(true); // repeat
        }
        /// <summary>
        /// Gets a collection of the given type from the given <see cref="IEnumerable{IPublishedContent}"/>.
        /// </summary>
        /// <param name="items">
        /// The <see cref="IEnumerable{IPublishedContent}"/> to convert.
        /// </param>
        /// <param name="type">
        /// The <see cref="Type"/> of items to return.
        /// </param>
        /// <param name="documentTypeAlias">
        /// The document type alias.
        /// </param>
        /// <param name="convertingType">
        /// The <see cref="Action{ConvertingTypeEventArgs}"/> to fire when converting.
        /// </param>
        /// <param name="convertedType">
        /// The <see cref="Action{ConvertedTypeEventArgs}"/> to fire when converted.
        /// </param>
        /// <param name="culture">
        /// The <see cref="CultureInfo"/>.
        /// </param>
        /// <returns>
        /// The resolved <see cref="IEnumerable{T}"/>.
        /// </returns>
        public static IEnumerable <object> As(
            this IEnumerable <IPublishedContent> items,
            Type type,
            string documentTypeAlias = null,
            Action <ConvertingTypeEventArgs> convertingType = null,
            Action <ConvertedTypeEventArgs> convertedType   = null,
            CultureInfo culture = null)
        {
            using (DisposableTimer.DebugDuration <IEnumerable <object> >(string.Format("IEnumerable As ({0})", documentTypeAlias)))
            {
                IEnumerable <object> typedItems;
                if (string.IsNullOrWhiteSpace(documentTypeAlias))
                {
                    typedItems = items.Select(x => x.As(type, convertingType, convertedType, culture));
                }
                else
                {
                    typedItems = items.Where(x => documentTypeAlias.InvariantEquals(x.DocumentTypeAlias))
                                 .Select(x => x.As(type, convertingType, convertedType, culture));
                }

                // We need to cast back here as nothing is strong typed anymore.
                return((IEnumerable <object>)EnumerableInvocations.Cast(type, typedItems));
            }
        }
Beispiel #21
0
        internal static string ResolveUrlsFromTextString(string text)
        {
            if (UmbracoSettings.ResolveUrlsFromTextString)
            {
                using (var timer = DisposableTimer.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
                {
                    // find all relative urls (ie. urls that contain ~)
                    var tags = ResolveUrlPattern.Matches(text);
                    LogHelper.Debug(typeof(IOHelper), "After regex: " + timer.Stopwatch.ElapsedMilliseconds + " matched: " + tags.Count);
                    foreach (Match tag in tags)
                    {
                        string url = "";
                        if (tag.Groups[1].Success)
                        {
                            url = tag.Groups[1].Value;
                        }

                        if (string.IsNullOrEmpty(url) == false)
                        {
                            string resolvedUrl = (url.Substring(0, 1) == "/") ? ResolveUrl(url.Substring(1)) : ResolveUrl(url);
                            text = text.Replace(url, resolvedUrl);
                        }
                    }
                }
            }
            return(text);
        }
Beispiel #22
0
 /// <summary>
 /// Loads the specified item. To be called from the OnLoad method of Item.
 /// </summary>
 /// <param name="item">The item.</param>
 public virtual void Load(Item item)
 {
     using (DisposableTimer.DebugDuration <ItemRenderer>(string.Format("Item: {0}", item.Field)))
     {
         ParseMacros(item);
     }
 }
Beispiel #23
0
        internal static string ResolveUrlsFromTextString(string text)
        {
            if (UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString)
            {
                using (DisposableTimer.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
                {
                    // find all relative urls (ie. urls that contain ~)
                    var tags = ResolveUrlPattern.Matches(text);

                    foreach (Match tag in tags)
                    {
                        string url = "";
                        if (tag.Groups[1].Success)
                        {
                            url = tag.Groups[1].Value;
                        }

                        if (String.IsNullOrEmpty(url) == false)
                        {
                            string resolvedUrl = (url.Substring(0, 1) == "/") ? ResolveUrl(url.Substring(1)) : ResolveUrl(url);
                            text = text.Replace(url, resolvedUrl);
                        }
                    }
                }
            }
            return(text);
        }
Beispiel #24
0
        /// <summary>
        /// Parses the macros inside the text, by creating child elements for each item.
        /// </summary>
        /// <param name="item">The item.</param>
        protected virtual void ParseMacros(Item item)
        {
            // do nothing if the macros have already been rendered
            if (item.Controls.Count > 0)
            {
                return;
            }

            string elementText = GetFieldContents(item);

            using (DisposableTimer.DebugDuration <ItemRenderer>("Parsing Macros"))
            {
                MacroTagParser.ParseMacros(
                    elementText,

                    //callback for when a text block is parsed
                    textBlock => item.Controls.Add(new LiteralControl(textBlock)),

                    //callback for when a macro is parsed:
                    (macroAlias, attributes) =>
                {
                    var macroControl = new Macro
                    {
                        Alias = macroAlias
                    };
                    foreach (var i in attributes.Where(i => macroControl.Attributes[i.Key] == null))
                    {
                        macroControl.Attributes.Add(i.Key, i.Value);
                    }
                    item.Controls.Add(macroControl);
                });
            }
        }
Beispiel #25
0
        /// <summary>
        /// Registers all menu items
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="typeFinder"></param>
        public virtual void RegisterMenuItems(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_menuItemsRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterMenuItems start took {0}ms", () => timer);
                _menuItemsRegistered = true;
            }))
            {
                foreach (var t in FindTypesInRequiredAssemblies <MenuItem>(typeFinder))
                {
                    RegisterComponent <MenuItem, MenuItemAttribute, MenuItemMetadata>(t, builder, true,
                                                                                      (pluginDef, attribute, registrar) =>
                                                                                      registrar
                                                                                      .WithMetadata <MenuItemMetadata, string>(am => am.Title, attribute.Title)
                                                                                      .WithMetadata <MenuItemMetadata, bool>(am => am.SeperatorBefore, attribute.SeparatorBefore)
                                                                                      .WithMetadata <MenuItemMetadata, bool>(am => am.SeperatorAfter, attribute.SeparatorAfter)
                                                                                      .WithMetadata <MenuItemMetadata, string>(am => am.Icon, attribute.Icon)
                                                                                      .WithMetadata <MenuItemMetadata, string>(am => am.OnClientClick, attribute.OnClientClick)
                                                                                      .ScopedAs.Singleton()); //only need one each
                }
            }
        }
Beispiel #26
0
        /// <summary>
        /// Returns the recursive value using a legacy strategy of looking at the xml cache and the splitPath in the elements collection
        /// </summary>
        /// <param name="elements"></param>
        /// <returns></returns>
        private string GetRecursiveValueLegacy(IDictionary elements)
        {
            using (DisposableTimer.DebugDuration <item>("Checking recusively"))
            {
                var content = "";

                var umbracoXml = presentation.UmbracoContext.Current.GetXml();

                var splitpath = (String[])elements["splitpath"];
                for (int i = 0; i < splitpath.Length - 1; i++)
                {
                    XmlNode element = umbracoXml.GetElementById(splitpath[splitpath.Length - i - 1]);

                    if (element == null)
                    {
                        continue;
                    }

                    var xpath       = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "./{0}";
                    var currentNode = element.SelectSingleNode(string.Format(xpath, _fieldName));

                    //continue if all is null
                    if (currentNode == null || currentNode.FirstChild == null || string.IsNullOrEmpty(currentNode.FirstChild.Value) || string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim()))
                    {
                        continue;
                    }

                    HttpContext.Current.Trace.Write("item.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]);
                    content = currentNode.FirstChild.Value;
                    break;
                }

                return(content);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Registers all RebelPropertyEditors
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="typeFinder"></param>
        public virtual void RegisterPropertyEditors(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_propEditorsRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterPropertyEditors start took {0}ms", () => timer);
                _propEditorsRegistered = true;
            }))
            {
                foreach (var t in FindTypesInRequiredAssemblies <PropertyEditor>(typeFinder))
                {
                    var propEditorType = t;

                    //builder.ForType(propEditorType).Register();

                    RegisterComponent <PropertyEditor, PropertyEditorAttribute, PropertyEditorMetadata>(t, builder, true,
                                                                                                        (pluginDef, attribute, registrar) =>
                                                                                                        registrar
                                                                                                        .WithMetadata <PropertyEditorMetadata, string>(am => am.Name, attribute.Name)
                                                                                                        .WithMetadata <PropertyEditorMetadata, string>(am => am.Alias, attribute.Alias)
                                                                                                        .WithMetadata <PropertyEditorMetadata, bool>(am => am.IsContentPropertyEditor, attribute.IsContentPropertyEditor)
                                                                                                        .WithMetadata <PropertyEditorMetadata, bool>(am => am.IsParameterEditor, attribute.IsParameterEditor)
                                                                                                        .WithMetadata <PropertyEditorMetadata, bool>(am => am.IsInternalRebelEditor,
                                                                                                                                                     propEditorType.GetCustomAttributes(typeof(RebelPropertyEditorAttribute), false).Any()));
                }
            }
        }
Beispiel #28
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);
             }
         }
     }
 }
Beispiel #29
0
        /// <summary>
        /// Registers the permissions.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="typeFinder">The type finder.</param>
        public virtual void RegisterPermissions(IContainerBuilder builder, TypeFinder typeFinder)
        {
            if (_permissionsRegistered)
            {
                return;
            }

            using (DisposableTimer.Start(timer =>
            {
                LogHelper.TraceIfEnabled <RebelComponentRegistrar>("RegisterPermissions start took {0}ms", () => timer);
                _permissionsRegistered = true;
            }))
            {
                foreach (var t in FindTypesInRequiredAssemblies <Permission>(typeFinder))
                {
                    RegisterComponent <Permission, PermissionAttribute, PermissionMetadata>(t, builder, true,
                                                                                            (pluginDef, attribute, registrar) =>
                                                                                            registrar
                                                                                            .WithMetadata <PermissionMetadata, string>(metadata => metadata.Name, attribute.Name)
                                                                                            .WithMetadata <PermissionMetadata, string>(metadata => metadata.Type, attribute.Type)
                                                                                            .WithMetadata <PermissionMetadata, UserType>(metadata => metadata.UserType, attribute.UserType)
                                                                                            .ScopedAs.Singleton()); //only need one each
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Returns an ActionResult for the specified Macro.
        /// </summary>
        /// <param name="macroAlias"></param>
        /// <param name="currentControllerContext"></param>
        /// <param name="isForRichTextEditor">If the request is to render the contents in the back office rich text editor</param>
        /// <param name="resolveContent">callback to get the 'Content' model</param>
        public ActionResult RenderMacro(
            string macroAlias,
            IDictionary <string, string> macroParams,
            ControllerContext currentControllerContext,
            bool isForRichTextEditor,
            Func <Content> resolveContent)
        {
            using (DisposableTimer.Start(timer =>
                                         LogHelper.TraceIfEnabled <MacroRenderer>("RenderMacro for {0} took {1}ms", () => macroAlias, () => timer)))
            {
                try
                {
                    // get the macro's model
                    var macroModel = GetMacroModel(macroAlias);

                    if (isForRichTextEditor && !macroModel.Item1.RenderContentInEditor)
                    {
                        return(NoRichTextRenderMode(macroAlias));
                    }
                    else
                    {
                        return(GetMacroResult(macroAlias, () => macroModel.Item1, resolveContent, macroParams, currentControllerContext));
                    }
                }
                catch (ApplicationException ex)
                {
                    //if there's an exception, display a friendly message and log the error
                    var txt   = "Macro.RenderingFailed.Message".Localize(this, new { Error = ex.Message, MacroName = macroAlias });
                    var title = "Macro.RenderingFailed.Title".Localize();
                    LogHelper.Error <MacroRenderer>(txt, ex);
                    return(MacroError(txt, title));
                }
            }
        }
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            var defaultValue = new ArchetypeModel();

            if (source == null)
            {
                return(defaultValue);
            }

            var sourceString = source.ToString();

            if (!sourceString.DetectIsJson())
            {
                return(defaultValue);
            }

            using (var timer = DisposableTimer.DebugDuration <ArchetypeValueConverter>(string.Format("ConvertDataToSource ({0})", propertyType != null ? propertyType.PropertyTypeAlias : "null")))
            {
                var archetype = ArchetypeHelper.Instance.DeserializeJsonToArchetype(sourceString,
                                                                                    (propertyType != null ? propertyType.DataTypeId : -1),
                                                                                    (propertyType != null ? propertyType.ContentType : null));

                return(archetype);
            }
        }
        private static void ContextOnEndRequest(object sender, EventArgs eventArgs)
        {
            var app     = (HttpApplication)sender;
            var context = app.Context;

            if (context.Error != null)
            {
                return;                        //rollback on error
            }
            //completes the current request scope if there's not errors pending
            var scope = GetTransactionScope(context);

            var requestId = context.GetRequestId();

            if (scope != null)
            {
                using (DisposableTimer.StartNew("[TransactionScopeHttpModule]: Commiting Transaction for request [{0}]".Fmt(requestId)))
                {
                    scope.Complete();
                }
            }
            else
            {
                Trace.TraceWarning("[TransactionScopeHttpModule]: No TransactionScope found for Current Request: [{0}]. Error ?", requestId);
            }
        }
Beispiel #33
0
		public virtual IBootManager Initialize()
		{
			if (_isInitialized)
				throw new InvalidOperationException("The boot manager has already been initialized");

			LogHelper.Info<CoreBootManager>("Umbraco application starting");
			_timer = DisposableTimer.Start(x => LogHelper.Info<CoreBootManager>("Umbraco application startup complete" + " (took " + x + "ms)"));

			//create the ApplicationContext
			ApplicationContext = ApplicationContext.Current = new ApplicationContext();

			InitializeResolvers();

			_isInitialized = true;

			return this;
		}
Beispiel #34
0
        public override IBootManager Initialize()
        {
            if (_isInitialized)
                throw new InvalidOperationException("The Merchello core boot manager has already been initialized");

            OnMerchelloInit();

            _timer = DisposableTimer.DebugDuration<CoreBootManager>("Merchello starting", "Merchello startup complete");

            // create the service context for the MerchelloAppContext
            var connString = ConfigurationManager.ConnectionStrings[MerchelloConfiguration.Current.Section.DefaultConnectionStringName].ConnectionString;
            var providerName = ConfigurationManager.ConnectionStrings[MerchelloConfiguration.Current.Section.DefaultConnectionStringName].ProviderName;
            var serviceContext = new ServiceContext(new PetaPocoUnitOfWorkProvider(connString, providerName));

            CreateMerchelloContext(serviceContext);

            _isInitialized = true;

            return this;
        }
        /// <summary>
        /// The initialize.
        /// </summary>
        /// <returns>
        /// The <see cref="IBootManager"/>.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Throws an exception if Gleaner is already initialized
        /// </exception>
        public virtual void Initialize()
        {
            if (IsInitialized)
            {
                throw new InvalidOperationException("The Gleaner core boot manager has already been initialized");
            }

            _timer = DisposableTimer.DebugDuration<CoreBootManager>("Gleaner starting", "Gleaner startup complete");

            // create the service context for the GleanerAppContext
            var serviceContext = new ServiceContext();

            var cache = ApplicationContext.Current == null
                ? new CacheHelper(
                    new ObjectCacheRuntimeCacheProvider(),
                    new StaticCacheProvider(),
                    new NullCacheProvider())
                : ApplicationContext.Current.ApplicationCache;

            CreateGleanerContext(serviceContext, cache);

            IsInitialized = true;
        }
Beispiel #36
0
        /// <summary>
        /// The initialize.
        /// </summary>
        /// <returns>
        /// The <see cref="IBootManager"/>.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Throws an exception if Merchello is already initialized
        /// </exception>
        public override IBootManager Initialize()
        {
            if (IsInitialized)
                throw new InvalidOperationException("The Merchello core boot manager has already been initialized");

            OnMerchelloInit();

            _timer = DisposableTimer.DebugDuration<CoreBootManager>("Merchello starting", "Merchello startup complete");
 
            // create the service context for the MerchelloAppContext   
            var connString = ConfigurationManager.ConnectionStrings[MerchelloConfiguration.Current.Section.DefaultConnectionStringName].ConnectionString;
            var providerName = ConfigurationManager.ConnectionStrings[MerchelloConfiguration.Current.Section.DefaultConnectionStringName].ProviderName;

            _unitOfWorkProvider = new PetaPocoUnitOfWorkProvider(connString, providerName);

            var serviceContext = new ServiceContext(_unitOfWorkProvider);


            var cache = ApplicationContext.Current == null
                            ? new CacheHelper(
                                    new ObjectCacheRuntimeCacheProvider(),
                                    new StaticCacheProvider(),
                                    new NullCacheProvider())
                            : ApplicationContext.Current.ApplicationCache;
            
            InitializeGatewayResolver(serviceContext, cache);
            
            CreateMerchelloContext(serviceContext, cache);

            InitializeResolvers();

            InitializeObserverSubscriptions();

            IsInitialized = true;            

            return this;
        }