示例#1
0
        public void Activate()
        {
            var appBuilder = new AppBuilder();

            appBuilder.Properties["host.AppName"] = _shellSettings.Name;

            var orderedMiddlewares = _owinMiddlewareProviders
                                     .SelectMany(p => p.GetOwinMiddlewares())
                                     .OrderBy(obj => obj.Priority, new FlatPositionComparer());

            foreach (var middleware in orderedMiddlewares)
            {
                middleware.Configure(appBuilder);
            }

            // Register the Orchard middleware after all others.
            appBuilder.UseOrchard();

            var pipeline  = appBuilder.Build();
            var allRoutes = new List <RouteDescriptor>();

            allRoutes.AddRange(_routeProviders.SelectMany(provider => provider.GetRoutes()));
            allRoutes.AddRange(_httpRouteProviders.SelectMany(provider => provider.GetRoutes()));

            _routePublisher.Publish(allRoutes, pipeline);
            _modelBinderPublisher.Publish(_modelBinderProviders.SelectMany(provider => provider.GetModelBinders()));

            using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                using (var events = scope.Resolve <Owned <IOrchardShellEvents> >()) {
                    events.Value.Activated();
                }
            }

            _sweepGenerator.Activate();
        }
示例#2
0
        public Func <object, TResult> BuildBackgroundFunction <TResult>(Func <object, TResult> function, bool catchExceptions = true)
        {
            var taskContext = new TaskContext(_workContextAccessor.GetContext());

            return((state) =>
            {
                using (var scope = _workContextAccessor.CreateWorkContextScope())
                {
                    taskContext.Transcribe(_workContextAccessor.GetContext());

                    if (catchExceptions)
                    {
                        try
                        {
                            return function(state);
                        }
                        catch (Exception ex)
                        {
                            if (ex.IsFatal())
                            {
                                throw;
                            }
                            Logger.Error(ex, "Background task failed with exception " + ex.Message);
                            return default(TResult);
                        }
                    }
                    else
                    {
                        return function(state);
                    }
                }
            });
        }
        public void Activated()
        {
            // Global configuration is application-wide, thus should happen only once.
            if (_shellSettings.Name != ShellSettings.DefaultName)
            {
                return;
            }

            // ISiteService couldn't be resolved because there is no work context during shell startup, that's
            // the reason for the custom work context.
            // See: https://github.com/OrchardCMS/Orchard/issues/4852
            using (var wc = _wca.CreateWorkContextScope())
            {
                var settings = wc.Resolve <ITelemetrySettingsAccessor>().GetDefaultSettings();

                if (string.IsNullOrEmpty(settings.InstrumentationKey))
                {
                    return;
                }

                if (settings.ApplicationWideLogCollectionIsEnabled)
                {
                    wc.Resolve <ILoggerSetup>().SetupAiAppender(Constants.DefaultLogAppenderName, settings.InstrumentationKey);
                    wc.Resolve <IStartupLogEntriesCollector>().ReLogStartupLogEntriesIfNew();
                }

                TelemetryConfiguration.Active.InstrumentationKey = settings.InstrumentationKey;
                wc.Resolve <ITelemetryConfigurationFactory>().PopulateWithCommonConfiguration(TelemetryConfiguration.Active);
            }
        }
 public void ProcessRequest(HttpContext context)
 {
     using (_workContextAccessor.CreateWorkContextScope(new HttpContextWrapper(context)))
     {
         _httpHandler.ProcessRequest(context);
     }
 }
 public void DoWork()
 {
     using (var scope = _workContextAccessor.CreateWorkContextScope()) {
         // resolve the manager and invoke it
         var manager = scope.Resolve <IBackgroundService>();
         manager.Sweep();
     }
 }
示例#6
0
 private void DoWork()
 {
     using (var scope = _workContextAccessor.CreateWorkContextScope())
     {
         var manager = scope.Resolve <IBackgroundService>();
         manager.Sweep();
     }
 }
示例#7
0
        public CoeveryInstanceContext(IWorkContextAccessor workContextAccessor)
        {
            _workContext = workContextAccessor.GetContext();

            if (_workContext == null)
            {
                _workContextScope = workContextAccessor.CreateWorkContextScope();
                _workContext      = _workContextScope.WorkContext;
            }
        }
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            IComponentRegistration registration;

            if (constructorString == null)
            {
                throw new ArgumentNullException("constructorString");
            }

            if (constructorString == string.Empty)
            {
                throw new ArgumentOutOfRangeException("constructorString");
            }

            if (HostContainer == null)
            {
                throw new InvalidOperationException();
            }

            // Create work context
            IRunningShellTable runningShellTable = HostContainer.Resolve <IRunningShellTable>();
            ShellSettings      shellSettings     = runningShellTable.Match(baseAddresses.First().Host, baseAddresses.First().LocalPath);

            IBoyingHost          BoyingHost          = HostContainer.Resolve <IBoyingHost>();
            ShellContext         shellContext        = BoyingHost.GetShellContext(shellSettings);
            IWorkContextAccessor workContextAccessor = shellContext.LifetimeScope.Resolve <IWorkContextAccessor>();
            WorkContext          workContext         = workContextAccessor.GetContext();

            if (workContext == null)
            {
                using (IWorkContextScope workContextScope = workContextAccessor.CreateWorkContextScope())
                {
                    ILifetimeScope lifetimeScope = workContextScope.Resolve <ILifetimeScope>();
                    registration = GetRegistration(lifetimeScope, constructorString);
                }
            }
            else
            {
                ILifetimeScope lifetimeScope = workContext.Resolve <ILifetimeScope>();
                registration = GetRegistration(lifetimeScope, constructorString);
            }

            if (registration == null)
            {
                throw new InvalidOperationException();
            }

            if (!registration.Activator.LimitType.IsClass)
            {
                throw new InvalidOperationException();
            }

            return(CreateServiceHost(workContextAccessor, registration, registration.Activator.LimitType, baseAddresses));
        }
        public RabbitInstanceContext(IWorkContextAccessor workContextAccessor)
        {
            _workContext = workContextAccessor.GetContext();

            if (_workContext != null)
            {
                return;
            }
            _workContextScope = workContextAccessor.CreateWorkContextScope();
            _workContext      = _workContextScope.WorkContext;
        }
示例#10
0
        public void DoWork()
        {
            using (var scope = workContextAccessor.CreateWorkContextScope())
            {
                var transactionManager = scope.Resolve <ITransactionManager>();
                transactionManager.Demand();

                // resolve the manager and invoke it
                var manager = scope.Resolve <IBackgroundService>();
                manager.Sweep();
            }
        }
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            // This filter is not reentrant (multiple executions within the same request are
            // not supported) so child actions are ignored completely.
            if (filterContext.IsChildAction)
            {
                return;
            }

            if (AdminFilter.IsApplied(filterContext.RequestContext))
            {
                return;
            }

            var workContext = mWorkContextAccessor.GetContext();

            var currentCulture  = workContext.CurrentCulture;
            var currentSite     = workContext.CurrentSite;
            var currentUser     = workContext.CurrentUser;
            var currentCalendar = workContext.CurrentCalendar;
            var currentTheme    = workContext.CurrentTheme;
            var currentTimeZone = workContext.CurrentTimeZone;

            var response      = filterContext.HttpContext.Response;
            var captureStream = new PlaceholderStream(response.Filter);

            response.Filter = captureStream;
            captureStream.TransformStream += stream =>
            {
                using (var scope = mWorkContextAccessor.CreateWorkContextScope(_requestContext.HttpContext))
                {
                    scope.WorkContext.CurrentCulture  = currentCulture;
                    scope.WorkContext.CurrentSite     = currentSite;
                    scope.WorkContext.CurrentUser     = currentUser;
                    scope.WorkContext.CurrentCalendar = currentCalendar;
                    scope.WorkContext.CurrentTheme    = currentTheme;
                    scope.WorkContext.CurrentTimeZone = currentTimeZone;

                    var html = filterContext.HttpContext.Request.ContentEncoding.GetString(stream.ToArray());
                    html = scope.Resolve <IPlaceholderService>().ResolvePlaceholders(html);

                    var buffer = filterContext.HttpContext.Request.ContentEncoding.GetBytes(html);

                    return(new MemoryStream(buffer));
                };
            };
        }
示例#12
0
            public override async Task ProcessRequestAsync(HttpContext context)
            {
                using (_workContextAccessor.CreateWorkContextScope(new HttpContextWrapper(context))) {
                    var environment = context.Items["owin.Environment"] as IDictionary <string, object>;

                    if (environment == null)
                    {
                        // It seems Owin is disabled by the owin:AutomaticAppStartup=false appSettings configuration.
                        environment = new Dictionary <string, object>();
                    }

                    environment["tomelt.Handler"] = new Func <Task>(async() => {
                        await Task.Factory.FromAsync(
                            _httpAsyncHandler.BeginProcessRequest,
                            _httpAsyncHandler.EndProcessRequest,
                            context,
                            null);
                    });

                    await _pipeline.Invoke(environment);
                }
            }
示例#13
0
        public void Activated()
        {
            _messageBus.Subscribe(Channel, (channel, tenantName) => {
                // todo: this only handles changed tenants, we should consider handling started and stopped tenants

                using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                    var shellSettings = scope.Resolve <ShellSettings>();
                    if (shellSettings != null && shellSettings.Name == tenantName)
                    {
                        // todo: this doesn't work as the new tenants list is lost right after
                        var shellSettingsManagerEventHandler = scope.Resolve <IShellSettingsManagerEventHandler>();
                        shellSettingsManagerEventHandler.Saved(shellSettings);

                        var orchardHost = scope.Resolve <IOrchardHost>() as DefaultOrchardHost;
                        if (orchardHost != null)
                        {
                            var startUpdatedShellsMethod = typeof(DefaultOrchardHost).GetMethod("StartUpdatedShells", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                            startUpdatedShellsMethod.Invoke(orchardHost, null);
                        }
                    }
                }
            });
        }
示例#14
0
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var captureHandlerIsAttached = false;

            try {
                // This filter is not reentrant (multiple executions within the same request are
                // not supported) so child actions are ignored completely.
                if (filterContext.IsChildAction || !_isCachingRequest)
                {
                    return;
                }

                Logger.Debug("Item '{0}' was rendered.", _cacheKey);


                if (!ResponseIsCacheable(filterContext))
                {
                    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    filterContext.HttpContext.Response.Cache.SetNoStore();
                    filterContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0));
                    return;
                }

                // Determine duration and grace time.
                var cacheDuration  = _cacheRouteConfig != null && _cacheRouteConfig.Duration.HasValue ? _cacheRouteConfig.Duration.Value : CacheSettings.DefaultCacheDuration;
                var cacheGraceTime = _cacheRouteConfig != null && _cacheRouteConfig.GraceTime.HasValue ? _cacheRouteConfig.GraceTime.Value : CacheSettings.DefaultCacheGraceTime;

                // Include each content item ID as tags for the cache entry.
                var contentItemIds = _displayedContentItemHandler.GetDisplayed().Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray();

                // Capture the response output using a custom filter stream.
                var response      = filterContext.HttpContext.Response;
                var captureStream = new CaptureStream(response.Filter);
                response.Filter = captureStream;

                // Add ETag header for the newly created item
                var etag = Guid.NewGuid().ToString("n");
                if (HttpRuntime.UsingIntegratedPipeline)
                {
                    if (response.Headers.Get("ETag") == null)
                    {
                        response.Headers["ETag"] = etag;
                    }
                }

                captureStream.Captured += (output) => {
                    try {
                        // Since this is a callback any call to injected dependencies can result in an Autofac exception: "Instances
                        // cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed."
                        // To prevent access to the original lifetime scope a new work context scope should be created here and dependencies
                        // should be resolved from it.

                        using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                            var cacheItem = new CacheItem()
                            {
                                CachedOnUtc       = _now,
                                Duration          = cacheDuration,
                                GraceTime         = cacheGraceTime,
                                Output            = output,
                                ContentType       = response.ContentType,
                                QueryString       = filterContext.HttpContext.Request.Url.Query,
                                CacheKey          = _cacheKey,
                                InvariantCacheKey = _invariantCacheKey,
                                Url        = filterContext.HttpContext.Request.Url.AbsolutePath,
                                Tenant     = scope.Resolve <ShellSettings>().Name,
                                StatusCode = response.StatusCode,
                                Tags       = new[] { _invariantCacheKey }.Union(contentItemIds).ToArray(),
                                ETag       = etag
                            };

                            // Write the rendered item to the cache.
                            var cacheStorageProvider = scope.Resolve <IOutputCacheStorageProvider>();
                            cacheStorageProvider.Set(_cacheKey, cacheItem);

                            Logger.Debug("Item '{0}' was written to cache.", _cacheKey);

                            // Also add the item tags to the tag cache.
                            var tagCache = scope.Resolve <ITagCache>();
                            foreach (var tag in cacheItem.Tags)
                            {
                                tagCache.Tag(tag, _cacheKey);
                            }
                        }
                    }
                    finally {
                        // Always release the cache key lock when the request ends.
                        ReleaseCacheKeyLock();
                    }
                };

                captureHandlerIsAttached = true;
            }
            finally {
                // If the response filter stream capture handler was attached then we'll trust
                // it to release the cache key lock at some point in the future when the stream
                // is flushed; otherwise we'll make sure we'll release it here.
                if (!captureHandlerIsAttached)
                {
                    ReleaseCacheKeyLock();
                }
            }
        }
示例#15
0
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            // Check if this path is "home"
            if (!string.IsNullOrEmpty(httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2)))
            {
                return(null);
            }

            using (var scope = _workContextAccessor.CreateWorkContextScope(httpContext)) {
                const string area        = "Contents";
                var          aliasHolder = scope.Resolve <IAliasHolder>();
                var          aliasMap    = aliasHolder.GetMap(area);

                if (!aliasMap.Any())
                {
                    return(null);
                }

                IDictionary <string, string> routeValues;
                if (!aliasMap.TryGetAlias(string.Empty, out routeValues) || !routeValues.ContainsKey("Id"))
                {
                    return(null);
                }

                int contentItemId = int.TryParse(routeValues["Id"], out contentItemId) ? contentItemId : 0;

                var contentManager = scope.Resolve <IContentManager>();

                var contentItem      = contentItemId > 0 ? contentManager.Get(contentItemId) : null;
                var localizationPart = contentItem != null?contentItem.Get <LocalizationPart>() : null;

                if (localizationPart == null)
                {
                    return(null);
                }

                var cultureService = scope.Resolve <ICultureService>();
                var currentCulture = cultureService.GetCurrentCulture();

                if (localizationPart.Culture != null && string.Compare(localizationPart.Culture.Culture, currentCulture, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    var masterContentItem = localizationPart.MasterContentItem != null ? localizationPart.MasterContentItem.ContentItem : contentItem;

                    var localizationService = scope.Resolve <ILocalizationService>();

                    localizationPart = localizationService.GetLocalizedContentItem(masterContentItem, currentCulture);

                    contentItemId = localizationPart != null ? localizationPart.Id : masterContentItem.Id;

                    routeValues["Id"] = contentItemId.ToString(CultureInfo.InvariantCulture.NumberFormat);
                }

                var data = new RouteData(this, new MvcRouteHandler());
                foreach (var routeValue in routeValues)
                {
                    var key = routeValue.Key;
                    data.Values.Add(key.EndsWith("-") ? key.Substring(0, key.Length - 1) : key, routeValue.Value);
                }

                data.Values["area"]     = area;
                data.DataTokens["area"] = area;

                return(data);
            }
        }