/// <summary>
        /// Configures the <see paramref="app"/> instance and its modules.
        /// </summary>
        /// <remarks>
        /// When called, configures <see paramref="app"/> using the <see cref="IApplicationContext"/> instance
        /// provided in <paramref name="appContext"/> and the templates available in
        /// <see cref="ApplicationTemplate"/> and <see cref="ModuleTemplates"/>.
        /// </remarks>
        /// <param name="appContext">the application context instance to be used for resolving object references.</param>
        /// <param name="app">the <see cref="HttpApplication"/> instance to be configured.</param>
        public static void Configure(IConfigurableApplicationContext appContext, HttpApplication app)
        {
            IObjectDefinition applicationDefinition = s_applicationDefinition;

            if (s_applicationDefinition != null)
            {
                appContext.ObjectFactory.ConfigureObject(app, "ApplicationTemplate", applicationDefinition);
            }

            lock (s_moduleDefinitions.SyncRoot)
            {
                HttpModuleCollection modules = app.Modules;
                foreach (DictionaryEntry moduleEntry in s_moduleDefinitions)
                {
                    string            moduleName = (string)moduleEntry.Key;
                    IObjectDefinition od         = s_moduleDefinitions[moduleName];
                    IHttpModule       module     = modules[moduleName];
                    if (module != null)
                    {
                        appContext.ObjectFactory.ConfigureObject(module, moduleName, od);
                    }
                    else
                    {
                        throw ConfigurationUtils.CreateConfigurationException(string.Format("failed applying module template '{0}' - no matching module found", moduleName));
                    }
                }
            }
        }
Example #2
0
        /// <summary>
        /// Create a handler instance for the given URL.
        /// </summary>
        /// <param name="appContext">the application context corresponding to the current request</param>
        /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
        /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
        /// <param name="physicalPath">The physical path of the requested resource.</param>
        /// <returns>A handler instance for the current request.</returns>
        protected override IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath)
        {
            IHttpHandler handler;

            string appRelativeVirtualPath             = WebUtils.GetAppRelativePath(rawUrl);
            NamedObjectDefinition namedPageDefinition = FindWebObjectDefinition(appRelativeVirtualPath, appContext.ObjectFactory);

            if (namedPageDefinition != null)
            {
                // is this a nested call (HttpServerUtility.Transfer() or HttpServerUtility.Execute())?
                if (context.Handler != null)
                {
                    // all deps can/must be resolved now
                    handler = (IHttpHandler)appContext.GetObject(namedPageDefinition.Name, typeof(IHttpHandler), null);
                }
                else
                {
                    // execution pipeline "entry-point" - create page instance only
                    // and defer configuration to PreRequestHandlerExecute step
                    handler = (IHttpHandler)appContext.CreateObject(namedPageDefinition.Name, typeof(IHttpHandler), null);
                    WebSupportModule.ConfigureHandler(context, handler, appContext, namedPageDefinition.Name, true);
                }
            }
            else
            {
                handler = WebObjectUtils.CreateHandler(rawUrl);
                // let WebSupportModule handle configuration
                handler = WebSupportModule.ConfigureHandler(context, handler, appContext, rawUrl, false);
            }

            return(handler);
        }
        /// <summary>
        /// Processes HTTP request.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, <see langword="Request"/>, <see langword="Response"/>, <see langword="Session"/>, and <see langword="Server"/>)<see langword=""/> used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse res = context.Response;

            res.BufferOutput = true;

            RenderHeader(res.Output, context.Request.ApplicationPath);


            IConfigurableApplicationContext appContext =
                WebApplicationContext.Current as IConfigurableApplicationContext;

            if (appContext == null)
            {
                throw new InvalidOperationException(
                          "Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
            }

            IList <string> names = appContext.GetObjectDefinitionNames();

            foreach (string name in names)
            {
                RenderObjectDefinition(res.Output, name, appContext.ObjectFactory.GetObjectDefinition(name));
            }

            RenderFooter(res.Output);
        }
        public void GetCheckedApplicationContextThrowsExceptionsOnNonConfigurableContexts()
        {
            TestHandlerFactory              f = A.Fake <TestHandlerFactory>(options => options.CallsBaseMethods());
            IApplicationContext             simpleAppContext  = A.Fake <IApplicationContext>();
            IConfigurableApplicationContext allowedAppContext = A.Fake <IConfigurableApplicationContext>();

            A.CallTo(() => f.GetContextStub("/NullContext")).Returns(null);
            A.CallTo(() => f.GetContextStub("/NonConfigurableContext")).Returns(simpleAppContext);
            A.CallTo(() => f.GetContextStub("/AllowedContext")).Returns(allowedAppContext);

            // (context == null) -> ArgumentException
            try
            {
                f.GetCheckedApplicationContext("/NullContext");
                Assert.Fail("should throw ArgumentException");
            }
            catch (ArgumentException)
            {
            }

            // !(context is IConfigurableApplicationContext) -> InvalidOperationException
            try
            {
                f.GetCheckedApplicationContext("/NonConfigurableContext");
                Assert.Fail("should throw InvalidOperationException");
            }
            catch (InvalidOperationException)
            {
            }

            // (context is IConfigurableApplicationContext) -> OK
            Assert.AreSame(allowedAppContext, f.GetCheckedApplicationContext("/AllowedContext"));
        }
Example #5
0
        public void DoesntCacheNonReusableHandlers()
        {
            MockRepository     mocks = new MockRepository();
            TestHandlerFactory f     = (TestHandlerFactory)mocks.PartialMock(typeof(TestHandlerFactory));
            IHttpHandler       nonReusableHandler = (IHttpHandler)mocks.DynamicMock(typeof(IHttpHandler));

            Expect.Call(nonReusableHandler.IsReusable).Return(false);
            IHttpHandler nonReusableHandler2 = (IHttpHandler)mocks.DynamicMock(typeof(IHttpHandler));

            Expect.Call(nonReusableHandler2.IsReusable).Return(false);
            IConfigurableApplicationContext appCtx = (IConfigurableApplicationContext)mocks.DynamicMock(typeof(IConfigurableApplicationContext));

            // if (IHttpHandler.IsReusable == false) => always create new handler instance
            // - CreateHandlerInstance() is called for each request
            using (Record(mocks))
            {
                Expect.Call(f.GetContextStub("notreusable")).Return(appCtx);
                Expect.Call(f.CreateHandlerInstanceStub(appCtx, null, null, "notreusable", null)).Return(nonReusableHandler);
                Expect.Call(f.GetContextStub("notreusable")).Return(appCtx);
                Expect.Call(f.CreateHandlerInstanceStub(appCtx, null, null, "notreusable", null)).Return(nonReusableHandler2);
            }
            using (Playback(mocks))
            {
                Assert.AreSame(nonReusableHandler, f.GetHandler(null, null, "notreusable", null));
                Assert.AreSame(nonReusableHandler2, f.GetHandler(null, null, "notreusable", null));
            }
        }
Example #6
0
        /// <summary>
        /// Configures the current IHttpHandler as specified by <see cref="Spring.Web.Support.PageHandlerFactory" />. If the
        /// <see cref="Spring.Web.Support.PageHandlerFactory" /> is not executed for the current request and an instance of
        /// <see cref="Page" /> is served revalidate if the instance should be configured.
        /// </summary>
        private void OnConfigureHandler(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HandlerConfigurationMetaData hCfg = (HandlerConfigurationMetaData)LogicalThreadContext.GetData(CURRENTHANDLER_OBJECTDEFINITION);

            if (hCfg != null)
            {
                // app.Context.Handler = // TODO: check, if this makes sense (EE)
                ConfigureHandlerNow(app.Context.Handler, hCfg.ApplicationContext, hCfg.ObjectDefinitionName, hCfg.IsContainerManaged);
            }
            else
            {
                Page page = app.Context.Handler as Page;
                if (!IsPageWithRouteHandler(page))
                {
                    return;
                }

                // In case of Routing pages are not handled by the PageHandlerFactory therefore no HandlerConfigurationMetaData
                // is set.
                IConfigurableApplicationContext applicationContext = (IConfigurableApplicationContext)WebApplicationContext.Current;
                string normalizedVirtualPath = WebUtils.GetNormalizedVirtualPath(page.AppRelativeVirtualPath);

                ControlInterceptor.EnsureControlIntercepted(applicationContext, page);
                ConfigureHandlerNow(page, applicationContext, normalizedVirtualPath, true);
            }
        }
Example #7
0
        /// <summary>
        /// Registers object definition with specified <c>id</c> for <c>T</c> type.
        /// </summary>
        /// <typeparam name="T">Type of configured object.</typeparam>
        /// <param name="ctx">Context for the registration</param>
        /// <param name="id">Object id.</param>
        /// <returns>Next build stage.</returns>
        public static IScopeBuildStage <T> RegisterNamed <T>(this IConfigurableApplicationContext ctx, string id)
        {
            var builder = new ObjectDefinitionBuilder <T>(id);

            ctx.ObjectFactory.RegisterObjectDefinition(id, builder.Definition);
            return(builder);
        }
Example #8
0
        public void GetCheckedApplicationContextThrowsExceptionsOnNonConfigurableContexts()
        {
            MockRepository                  mocks             = new MockRepository();
            TestHandlerFactory              f                 = (TestHandlerFactory)mocks.PartialMock(typeof(TestHandlerFactory));
            IApplicationContext             simpleAppContext  = (IApplicationContext)mocks.DynamicMock(typeof(IApplicationContext));
            IConfigurableApplicationContext allowedAppContext = (IConfigurableApplicationContext)mocks.DynamicMock(typeof(IConfigurableApplicationContext));

            using (Record(mocks))
            {
                Expect.Call(f.GetContextStub("/NullContext")).Return(null);
                Expect.Call(f.GetContextStub("/NonConfigurableContext")).Return(simpleAppContext);
                Expect.Call(f.GetContextStub("/AllowedContext")).Return(allowedAppContext);
            }

            // (context == null) -> ArgumentException
            try
            {
                f.GetCheckedApplicationContext("/NullContext");
                Assert.Fail("should throw ArgumentException");
            }
            catch (ArgumentException)
            {}

            // !(context is IConfigurableApplicationContext) -> InvalidOperationException
            try
            {
                f.GetCheckedApplicationContext("/NonConfigurableContext");
                Assert.Fail("should throw InvalidOperationException");
            }
            catch (InvalidOperationException)
            {}

            // (context is IConfigurableApplicationContext) -> OK
            Assert.AreSame(allowedAppContext, f.GetCheckedApplicationContext("/AllowedContext"));
        }
        /// <summary>
        /// Obtains a handler by mapping <paramref name="rawUrl"/> to the list of patterns in <paramref name="handlerMappings"/>.
        /// </summary>
        /// <param name="appContext">the application context corresponding to the current request</param>
        /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
        /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
        /// <param name="physicalPath">The physical path of the requested resource.</param>
        /// <param name="handlerMappings"></param>
        /// <param name="handlerWithFactoryTable"></param>
        /// <returns>A handler instance for processing the current request.</returns>
        protected IHttpHandler MapHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath, HandlerMap handlerMappings, IDictionary handlerWithFactoryTable)
        {
            // resolve handler instance by mapping the url to the list of patterns
            HandlerMapEntry handlerMapEntry = handlerMappings.MapPath(rawUrl);

            if (handlerMapEntry == null)
            {
                throw new HttpException(404, HttpStatusCode.NotFound.ToString());
            }
            object handlerObject = appContext.GetObject(handlerMapEntry.HandlerObjectName);

            if (handlerObject is IHttpHandler)
            {
                return((IHttpHandler)handlerObject);
            }
            else if (handlerObject is IHttpHandlerFactory)
            {
                // keep a reference to the issuing factory for later ReleaseHandler call
                IHttpHandlerFactory factory = (IHttpHandlerFactory)handlerObject;
                IHttpHandler        handler = factory.GetHandler(context, requestType, rawUrl, physicalPath);
                lock (handlerWithFactoryTable.SyncRoot)
                {
                    handlerWithFactoryTable.Add(handler, factory);
                }
                return(handler);
            }

            throw new HttpException((int)HttpStatusCode.NotFound, HttpStatusCode.NotFound.ToString());
        }
Example #10
0
        /// <summary>
        /// Registers this module for all events required by the Spring.Web framework
        /// </summary>
        public virtual void Init(HttpApplication app)
        {
            lock (typeof(WebSupportModule))
            {
                s_log.Debug("Initializing Application instance");
                if (!s_isInitialized)
                {
                    HttpModuleCollection modules = app.Modules;
                    foreach (string moduleKey in modules.AllKeys)
                    {
                        if (modules[moduleKey] is SessionStateModule)
                        {
                            HookSessionEvent((SessionStateModule)modules[moduleKey]);
                        }
                    }
                }
                s_isInitialized = true;

                // signal, that VirtualEnvironment is ready to accept
                // handler registrations for EndRequest and EndSession events
                VirtualEnvironment.SetInitialized();
            }

            app.PreRequestHandlerExecute += new EventHandler(OnConfigureHandler);
            app.EndRequest += new EventHandler(VirtualEnvironment.RaiseEndRequest);

#if NET_2_0
            // TODO: this is only a workaround to get us up & running in IIS7/integrated mode
            // We must review all code for relative virtual paths - they must be resolved to application-relative paths
            // during parsing of the object definitions
            bool hideRequestResponse = false;
            if (ContextHideRequestResponse != null)
            {
                hideRequestResponse = (bool)ContextHideRequestResponse.GetValue(app.Context);
                ContextHideRequestResponse.SetValue(app.Context, false);
            }
#endif
            try
            {
                // ensure context is instantiated
                IConfigurableApplicationContext appContext = WebApplicationContext.GetRootContext() as IConfigurableApplicationContext;
                // configure this app + it's module instances
                if (appContext == null)
                {
                    throw new InvalidOperationException("Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
                }

                HttpApplicationConfigurer.Configure(appContext, app);
            }
            finally
            {
#if NET_2_0
                if (ContextHideRequestResponse != null)
                {
                    ContextHideRequestResponse.SetValue(app.Context, hideRequestResponse);
                }
#endif
            }
        }
Example #11
0
        public static IFactoryObject GetFactoryObject(this IConfigurableApplicationContext applicationContext, string name)
        {
            // In Spring.NET the factory object itself of an object can be retrieved by prefixing its name
            // with an ampersand "&".
            var factoryObjectName = $"&{name}";

            return((IFactoryObject)applicationContext.GetObject(factoryObjectName));
        }
Example #12
0
        public static void RegisterSingleton(this IConfigurableApplicationContext context, Type type)
        {
            ObjectDefinitionBuilder definitionBuilder = ObjectDefinitionBuilder.RootObjectDefinition(new DefaultObjectDefinitionFactory(), type)
                                                        .SetAutowireMode(AutoWiringMode.AutoDetect)
                                                        .SetSingleton(true);

            context.ObjectFactory.RegisterObjectDefinition(type.FullName, definitionBuilder.ObjectDefinition);
        }
Example #13
0
        public static void RegisterPrototype <T>(this IConfigurableApplicationContext context)
        {
            ObjectDefinitionBuilder definitionBuilder = ObjectDefinitionBuilder.RootObjectDefinition(new DefaultObjectDefinitionFactory(), typeof(T))
                                                        .SetAutowireMode(AutoWiringMode.AutoDetect)
                                                        .SetSingleton(false);

            context.ObjectFactory.RegisterObjectDefinition(Guid.NewGuid().ToString(), definitionBuilder.ObjectDefinition);
        }
Example #14
0
 public Can_host_in_another_app_domain()
 {
     applicationContext = new StaticApplicationContext();
     new RhinoServiceBusConfiguration()
     .UseSpring(applicationContext)
     .UseStandaloneConfigurationFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AnotherBus.config"))
     .Configure();
 }
Example #15
0
 public static void RegisterSingletons <TBasedOn>(this IConfigurableApplicationContext context, Assembly assembly)
 {
     assembly.GetTypes()
     .Where(t => typeof(TBasedOn).IsAssignableFrom(t) &&
            !t.IsInterface &&
            !t.IsAbstract)
     .ToList()
     .ForEach(type => RegisterSingleton(context, type));
 }
Example #16
0
        public override void CreateContainer()
        {
            if (applicationContext == null)
            {
                applicationContext = new StaticApplicationContext();
            }

            ConfigureContainer();
        }
Example #17
0
        /// <summary>
        /// Registers an object instance as a singleton in the Spring container
        /// </summary>
        /// <param name="alias">the name of the singleton object/bean</param>
        /// <param name="instance">the object instance that will be registered as singleton</param>
        private void RegisterSingletonInstance(string alias, object instance)
        {
            IConfigurableApplicationContext configurableContext = springContainer as IConfigurableApplicationContext;

            if (configurableContext != null && !springContainer.ContainsObjectDefinition(alias))
            {
                configurableContext.ObjectFactory.RegisterSingleton(alias, instance);
            }
        }
        public void AfterPropertiesSet()
        {
            IConfigurableApplicationContext ctx = applicationContext as IConfigurableApplicationContext;

            if (ctx == null)
            {
                throw new InvalidOperationException(
                          "Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
            }
            configurableApplicationContext = ctx;
        }
Example #19
0
 public static IObjectDefinition GetObjectDefinition(this IConfigurableApplicationContext applicationContext,
                                                     string name)
 {
     try
     {
         return(((AbstractApplicationContext)applicationContext).GetObjectDefinition(name));
     }
     catch (InvalidCastException e)
     {
         throw new InvalidOperationException($"Cannot register object definition with name: {name}", e);
     }
 }
Example #20
0
 public static void RegisterObjectDefinition(this IConfigurableApplicationContext applicationContext,
                                             string name, IObjectDefinition definition)
 {
     try
     {
         ((AbstractApplicationContext)applicationContext).RegisterObjectDefinition(name, definition);
     }
     catch (InvalidCastException e)
     {
         throw new InvalidOperationException($"Cannot register object definition with name: {name}", e);
     }
 }
Example #21
0
        /// <summary>
        /// Create a handler instance for the given URL.
        /// </summary>
        /// <param name="appContext">the application context corresponding to the current request</param>
        /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
        /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
        /// <param name="physicalPath">The physical path of the requested resource.</param>
        /// <returns>A handler instance for processing the current request.</returns>
        protected override IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath)
        {
            IHttpHandler handler = _innerFactory.GetHandler(context, requestType, rawUrl, physicalPath);

            // find a matching object definition
            string appRelativeVirtualPath = WebUtils.GetAppRelativePath(rawUrl);
            NamedObjectDefinition nod     = FindWebObjectDefinition(appRelativeVirtualPath, appContext.ObjectFactory);
            string objectDefinitionName   = (nod != null) ? nod.Name : rawUrl;

            handler = WebSupportModule.ConfigureHandler(context, handler, appContext, objectDefinitionName, (nod != null));
            return(handler);
        }
        /// <summary>
        /// Create a handler instance for the given URL.
        /// </summary>
        /// <param name="appContext">the application context corresponding to the current request</param>
        /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
        /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
        /// <param name="physicalPath">The physical path of the requested resource.</param>
        /// <returns>A handler instance for processing the current request.</returns>
        protected override IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath)
        {
            IHttpHandler handler = _innerFactory.GetHandler(context, requestType, rawUrl, physicalPath);

            // find a matching object definition
            string appRelativeVirtualPath = WebUtils.GetAppRelativePath(rawUrl);
            NamedObjectDefinition nod = FindWebObjectDefinition(appRelativeVirtualPath, appContext.ObjectFactory);
            string objectDefinitionName = (nod != null) ? nod.Name : rawUrl;

            handler = WebSupportModule.ConfigureHandler(context, handler, appContext, objectDefinitionName, (nod != null));
            return handler;
        }
Example #23
0
        /// <summary>
        /// Gets the Spring IDbProvider given the ISessionFactory.
        /// </summary>
        /// <remarks>The matching is performed by comparing the assembly qualified
        /// name string of the hibernate Driver.ConnectionType to those in
        /// the DbProviderFactory definitions.  No connections are created
        /// in performing this comparison.</remarks>
        /// <param name="sessionFactory">The session factory.</param>
        /// <returns>The corresponding IDbProvider, null if no mapping was found.</returns>
        /// <exception cref="InvalidOperationException">If DbProviderFactory's ApplicaitonContext is not
        /// an instance of IConfigurableApplicaitonContext.</exception>
        public static IDbProvider GetDbProvider(ISessionFactory sessionFactory)
        {
            ISessionFactoryImplementor sfi = sessionFactory as ISessionFactoryImplementor;

            if (sfi != null)
            {
                IConnectionProvider cp = sfi.ConnectionProvider as IConnectionProvider;
                if (cp != null)
                {
                    IConfigurableApplicationContext ctx =
                        Spring.Data.Common.DbProviderFactory.ApplicationContext as IConfigurableApplicationContext;
                    if (ctx == null)
                    {
                        throw new InvalidOperationException(
                                  "Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
                    }

#if NET_1_1
                    DriverBase db = cp.Driver as DriverBase;
#else
                    IDriver db = cp.Driver;
#endif
                    if (db != null)
                    {
                        Type hibCommandType = db.CreateCommand().GetType();

                        string[] providerNames = ctx.GetObjectNamesForType(typeof(DbProvider), true, false);
                        string   hibCommandAQN = hibCommandType.AssemblyQualifiedName;
                        foreach (string providerName in providerNames)
                        {
                            IObjectDefinition                     objectdef    = ctx.ObjectFactory.GetObjectDefinition(providerName);
                            ConstructorArgumentValues             ctorArgs     = objectdef.ConstructorArgumentValues;
                            ConstructorArgumentValues.ValueHolder vh           = ctorArgs.NamedArgumentValues["dbmetadata"] as ConstructorArgumentValues.ValueHolder;
                            IObjectDefinition                     od           = ((ObjectDefinitionHolder)vh.Value).ObjectDefinition;
                            ConstructorArgumentValues             dbmdCtorArgs = od.ConstructorArgumentValues;
                            string commandType = dbmdCtorArgs.GetArgumentValue("commandType", typeof(string)).Value as string;

                            if (hibCommandAQN.Equals(commandType))
                            {
                                IDbProvider prov = Spring.Data.Common.DbProviderFactory.GetDbProvider(providerName);
                                return(prov);
                            }
                        }
                    }
                    else
                    {
                        log.Info("Could not derive IDbProvider from SessionFactory");
                    }
                }
            }
            return(null);
        }
Example #24
0
        /// <summary>
        /// Returns an appropriate <see cref="System.Web.IHttpHandler"/> implementation.
        /// </summary>
        /// <param name="context">
        /// An instance of the <see cref="System.Web.HttpContext"/> class that
        /// provides references to intrinsic server objects.
        /// </param>
        /// <param name="requestType">
        /// The HTTP method of the request.
        /// </param>
        /// <param name="url">The request URL.</param>
        /// <param name="physicalPath">
        /// The physical path of the requested resource.
        /// </param>
        /// <returns>
        /// A new <see cref="System.Web.IHttpHandler"/> object that processes
        /// the request.
        /// </returns>
        public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string physicalPath)
        {
            bool isDebug = Log.IsDebugEnabled;

            #region Instrumentation

            if (isDebug)
            {
                Log.Debug(string.Format("GetHandler():resolving url '{0}'", url));
            }

            #endregion

            IHttpHandler handler = null;
            lock (_reusableHandlerCache.SyncRoot)
            {
                handler = (IHttpHandler)_reusableHandlerCache[url];
            }

            if (handler != null)
            {
                #region Instrumentation

                if (isDebug)
                {
                    Log.Debug(string.Format("GetHandler():resolved url '{0}' from reusable handler cache", url));
                }

                #endregion

                return(handler);
            }

            lock (_reusableHandlerCache.SyncRoot)
            {
                handler = (IHttpHandler)_reusableHandlerCache[url];
                if (handler == null)
                {
                    IConfigurableApplicationContext appContext = GetCheckedApplicationContext(url);

                    handler = CreateHandlerInstance(appContext, context, requestType, url, physicalPath);

                    ApplyDependencyInjectionInfrastructure(handler, appContext);

                    if (handler.IsReusable)
                    {
                        _reusableHandlerCache[url] = handler;
                    }
                }
                return(handler);
            }
        }
Example #25
0
        /// <summary>
        /// Set custom locations dirty. This will cause them to be reloaded
        /// from the cache before the next test case is executed.
        /// </summary>
        /// <remarks>
        /// Call this method only if you change the state of a singleton
        /// object, potentially affecting future tests.
        /// </remarks>
        /// <param name="locations">Locations </param>
        protected void SetDirty(string[] locations)
        {
            String keyString = ContextKeyString(locations);
            IConfigurableApplicationContext ctx =
                (IConfigurableApplicationContext)contextKeyToContextMap[keyString];

            contextKeyToContextMap.Remove(keyString);

            if (ctx != null)
            {
                ctx.Dispose();
            }
        }
Example #26
0
        /// <summary>
        /// Caches application context.
        /// </summary>
        /// <param name="key">Key to use.</param>
        /// <param name="context">Context to cache.</param>
        public void AddContext(object key, IConfigurableApplicationContext context)
        {
            AssertUtils.ArgumentNotNull(context, "context", "ApplicationContext must not be null");
            string keyString = ContextKeyString(key);

            contextKeyToContextMap.Add(keyString, context);

            if (RegisterContextWithContextRegistry &&
                !ContextRegistry.IsContextRegistered(context.Name))
            {
                ContextRegistry.RegisterContext(context);
            }
        }
        /// <summary>
        /// 为容器注册实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="container"></param>
        /// <param name="alias"></param>
        /// <param name="instance"></param>
        public static void RegisterInstance <T>(this IApplicationContext container, string alias, T instance) where T : class
        {
            IConfigurableApplicationContext configurableContext = container as IConfigurableApplicationContext;

            if (configurableContext != null && !container.ContainsObjectDefinition(alias) && !container.ContainsObject(alias))
            {
                configurableContext.ObjectFactory.RegisterSingleton(alias, instance);
            }
            else if (configurableContext != null && !container.ContainsObjectDefinition(typeof(T).FullName) && !container.ContainsObject(typeof(T).FullName))
            {
                configurableContext.ObjectFactory.RegisterSingleton(typeof(T).FullName, instance);
            }
        }
 public virtual void SetUp()
 {
     this.applicationContext = GetContext(ContextKey);
     InjectDependencies();
     try
     {
         OnSetUp();
     }
     catch (Exception ex)
     {
         logger.Error("Setup error", ex);
         throw;
     }
 }
        public void CachesReusableHandlers()
        {
            TestHandlerFactory f = A.Fake <TestHandlerFactory>(options => options.CallsBaseMethods());
            IHttpHandler       reusableHandler     = A.Fake <IHttpHandler>();
            IConfigurableApplicationContext appCtx = A.Fake <IConfigurableApplicationContext>();

            // if (IHttpHandler.IsReusable == true) => always returns the same handler instance
            // - CreateHandlerInstance() is only called once
            A.CallTo(() => reusableHandler.IsReusable).Returns(true);
            A.CallTo(() => f.GetContextStub("reusable")).Returns(appCtx);
            A.CallTo(() => f.CreateHandlerInstanceStub(appCtx, null, null, "reusable", null)).Returns(reusableHandler);

            Assert.AreSame(reusableHandler, f.GetHandler(null, null, "reusable", null));
            Assert.AreSame(reusableHandler, f.GetHandler(null, null, "reusable", null));
        }
Example #30
0
        public static void RegisterSingleton(this IConfigurableApplicationContext context, Type type, string name, params object[] constructorArguments)
        {
            ObjectDefinitionBuilder definitionBuilder = ObjectDefinitionBuilder.RootObjectDefinition(new DefaultObjectDefinitionFactory(), type)
                                                        .SetAutowireMode(AutoWiringMode.AutoDetect)
                                                        .SetSingleton(true);

            if (constructorArguments != null && constructorArguments.Length > 0)
            {
                foreach (object argument in constructorArguments)
                {
                    definitionBuilder.AddConstructorArg(argument);
                }
            }

            context.ObjectFactory.RegisterObjectDefinition(name, definitionBuilder.ObjectDefinition);
        }
Example #31
0
        ///<summary>
        /// TODO
        ///</summary>
        ///<param name="handler"></param>
        ///<param name="applicationContext"></param>
        ///<param name="name"></param>
        ///<param name="isContainerManaged"></param>
        private static IHttpHandler ConfigureHandlerNow(IHttpHandler handler, IConfigurableApplicationContext applicationContext, string name, bool isContainerManaged)
        {
            if (isContainerManaged)
            {
                s_log.Debug(string.Format("configuring managed handler using application context '{0}' and name '{1}'", applicationContext, name));
                handler = (IHttpHandler)applicationContext.ObjectFactory.ConfigureObject(handler, name);
            }
            else
            {
                s_log.Debug(string.Format("configuring unmanaged handler using application context '{0}' and name '{1}'", applicationContext, name));
                // at a minimum we'll apply ObjectPostProcessors
                handler = (IHttpHandler)applicationContext.ObjectFactory.ApplyObjectPostProcessorsBeforeInitialization(handler, name);
                handler = (IHttpHandler)applicationContext.ObjectFactory.ApplyObjectPostProcessorsAfterInitialization(handler, name);
            }

            return(handler);
        }
 public abstract IHttpHandler CreateHandlerInstanceStub(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string url, string physicalPath);
Example #33
0
        /// <summary>
        /// Create a handler instance for the given URL.
        /// </summary>
        /// <param name="appContext">the application context corresponding to the current request</param>
        /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
        /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
        /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
        /// <param name="physicalPath">The physical path of the requested resource.</param>
        /// <returns>A handler instance for the current request.</returns>
        protected override IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath)
        {
            IHttpHandler handler;

            string appRelativeVirtualPath = WebUtils.GetAppRelativePath(rawUrl);
            NamedObjectDefinition namedPageDefinition = FindWebObjectDefinition(appRelativeVirtualPath, appContext.ObjectFactory);

            if (namedPageDefinition != null)
            {
                // is this a nested call (HttpServerUtility.Transfer() or HttpServerUtility.Execute())?
                if (context.Handler != null)
                {
                    // all deps can/must be resolved now
                    handler = (IHttpHandler)appContext.GetObject(namedPageDefinition.Name, typeof(IHttpHandler), null);
                }
                else
                {
                    // execution pipeline "entry-point" - create page instance only 
                    // and defer configuration to PreRequestHandlerExecute step
                    handler = (IHttpHandler)appContext.CreateObject(namedPageDefinition.Name, typeof(IHttpHandler), null);
                    WebSupportModule.ConfigureHandler(context, handler, appContext, namedPageDefinition.Name, true);
                }
            }
            else
            {
                handler = WebObjectUtils.CreateHandler(rawUrl);
                // let WebSupportModule handle configuration
                handler = WebSupportModule.ConfigureHandler(context, handler, appContext, rawUrl, false);
            }

            return handler;
        }
 public void AfterPropertiesSet()
 {
     IConfigurableApplicationContext ctx = applicationContext as IConfigurableApplicationContext;
     if (ctx == null)
     {
         throw new InvalidOperationException(
             "Implementations of IApplicationContext must also implement IConfigurableApplicationContext");
     }
     configurableApplicationContext = ctx;
 }
Example #35
0
 ///<summary>
 /// TODO
 ///</summary>
 ///<param name="applicationContext"></param>
 ///<param name="name"></param>
 ///<param name="isContainerManaged"></param>
 private static void SetCurrentHandlerConfiguration(IConfigurableApplicationContext applicationContext, string name, bool isContainerManaged)
 {
     LogicalThreadContext.SetData(CURRENTHANDLER_OBJECTDEFINITION, new HandlerConfigurationMetaData(applicationContext, name, isContainerManaged));
 }
 public virtual void SetUp()
 {
     this.applicationContext = GetContext(ContextKey);
     InjectDependencies();
     try
     {
         OnSetUp();
     }
     catch (Exception ex)
     {
         logger.Error("Setup error", ex);
         throw;
     }
 }
 /// <summary>
 /// Create a handler instance for the given URL.
 /// </summary>
 /// <param name="appContext">the application context corresponding to the current request</param>
 /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
 /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
 /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
 /// <param name="physicalPath">The physical path of the requested resource.</param>
 /// <returns>A handler instance for the current request.</returns>
 protected override IHttpHandler CreateHandlerInstance( IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath )
 {
     throw new NotSupportedException();
 }
        private Type ExportObject(EnterpriseServicesExporter exporter, FileInfo assemblyFile, IConfigurableApplicationContext appCtx, string objectName)
        {
            exporter.ObjectFactory = appCtx.ObjectFactory;
            exporter.Assembly = Path.GetFileNameWithoutExtension(assemblyFile.Name);
            exporter.ApplicationName = exporter.Assembly;
            exporter.AccessControl = new ApplicationAccessControlAttribute(false);
            exporter.UseSpring = true;

            ServicedComponentExporter exp = new ServicedComponentExporter();
            exp.TargetName = objectName;
            exp.ObjectName = objectName + "Service";
            exp.TypeAttributes = new ArrayList();
            exp.TypeAttributes.Add(new TransactionAttribute(TransactionOption.RequiresNew));
            exp.AfterPropertiesSet();

            exporter.Components.Add(exp);

            Assembly assembly = exporter.GenerateComponentAssembly(assemblyFile);
            exporter.RegisterServicedComponents(assemblyFile);
            return assembly.GetType(objectName + "Service");
        }
Example #39
0
 public HandlerConfigurationMetaData(IConfigurableApplicationContext applicationContext, string objectDefinitionName, bool isContainerManaged)
 {
     ApplicationContext = applicationContext;
     ObjectDefinitionName = objectDefinitionName;
     IsContainerManaged = isContainerManaged;
 }
Example #40
0
        ///<summary>
        /// TODO
        ///</summary>
        ///<param name="handler"></param>
        ///<param name="applicationContext"></param>
        ///<param name="name"></param>
        ///<param name="isContainerManaged"></param>
        private static IHttpHandler ConfigureHandlerNow(IHttpHandler handler, IConfigurableApplicationContext applicationContext, string name, bool isContainerManaged)
        {
            if (isContainerManaged)
            {
                s_log.Debug(string.Format("configuring managed handler using application context '{0}' and name '{1}'", applicationContext, name));
                handler = (IHttpHandler)applicationContext.ObjectFactory.ConfigureObject(handler, name);
            }
            else
            {
                s_log.Debug(string.Format("configuring unmanaged handler using application context '{0}' and name '{1}'", applicationContext, name));
                // at a minimum we'll apply ObjectPostProcessors
                handler = (IHttpHandler)applicationContext.ObjectFactory.ApplyObjectPostProcessorsBeforeInitialization(handler, name);
                handler = (IHttpHandler)applicationContext.ObjectFactory.ApplyObjectPostProcessorsAfterInitialization(handler, name);
            }

            return handler;
        }
 protected override IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string url, string physicalPath )
 {
     return CreateHandlerInstanceStub(appContext, context, requestType, url, physicalPath);
 }
        /// <summary>
        /// Obtains a handler by mapping <paramref name="rawUrl"/> to the list of patterns in <paramref name="handlerMappings"/>.
        /// </summary>
	    /// <param name="appContext">the application context corresponding to the current request</param>
	    /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
	    /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
	    /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
	    /// <param name="physicalPath">The physical path of the requested resource.</param>
        /// <param name="handlerMappings"></param>
        /// <param name="handlerWithFactoryTable"></param>
	    /// <returns>A handler instance for processing the current request.</returns>
	    protected IHttpHandler MapHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath, HandlerMap handlerMappings, IDictionary handlerWithFactoryTable)
	    {
            // resolve handler instance by mapping the url to the list of patterns
	        HandlerMapEntry handlerMapEntry = handlerMappings.MapPath(rawUrl);
	        if (handlerMapEntry == null)
	        {
	            throw new HttpException(404, HttpStatusCode.NotFound.ToString());
	        }
	        object handlerObject = appContext.GetObject(handlerMapEntry.HandlerObjectName);

	        if (handlerObject is IHttpHandler)
	        {
	            return (IHttpHandler) handlerObject;
	        }
	        else if (handlerObject is IHttpHandlerFactory)
	        {
                // keep a reference to the issuing factory for later ReleaseHandler call
	            IHttpHandlerFactory factory = (IHttpHandlerFactory) handlerObject;
	            IHttpHandler handler = factory.GetHandler(context, requestType, rawUrl, physicalPath);
	            lock(handlerWithFactoryTable.SyncRoot)
	            {
	                handlerWithFactoryTable.Add(handler, factory);
	            }
	            return handler;
	        }

	        throw new HttpException((int)HttpStatusCode.NotFound, HttpStatusCode.NotFound.ToString());
	    }
	    /// <summary>
	    /// Create a handler instance for the given URL. Will try to find a match of <paramref name="rawUrl"/> onto patterns in <see cref="HandlerMap"/>. 
	    /// If a match is found, delegates the call to the matching <see cref="IHttpHandlerFactory.GetHandler"/> method.
	    /// </summary>
	    /// <param name="appContext">the application context corresponding to the current request</param>
	    /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
	    /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
	    /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
	    /// <param name="physicalPath">The physical path of the requested resource.</param>
	    /// <returns>A handler instance for processing the current request.</returns>
	    protected override IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath)
	    {
	        return MapHandlerInstance(appContext, context, requestType, rawUrl, physicalPath, s_handlerMap, _handlerWithFactoryTable);
	    }
 public IApplicationContext InitialiseContext()
 {
     applicationContext = GetContext(ContextKey);
     InjectDependencies();
     return applicationContext;
 }
 public SpringBuilder(AbstractRhinoServiceBusConfiguration config, IConfigurableApplicationContext applicationContext)
 {
     this.config = config;
     this.applicationContext = applicationContext;
     config.BuildWith(this);
 }
 public ConsumerInterceptor(IConsumerInterceptor interceptor, IConfigurableApplicationContext applicationContext)
 {
     this.interceptor = interceptor;
     this.applicationContext = applicationContext;
 }
 public MessageQueueMetadataCache(IConfigurableApplicationContext configurableApplicationContext)
 {
     this.configurableApplicationContext = configurableApplicationContext;
 }
        /// <summary>
        /// Caches application context.
        /// </summary>
        /// <param name="key">Key to use.</param>
        /// <param name="context">Context to cache.</param>
	    public void AddContext(object key, IConfigurableApplicationContext context) 
        {
            AssertUtils.ArgumentNotNull(context, "context", "ApplicationContext must not be null");
            string keyString = ContextKeyString(key);
            contextKeyToContextMap.Add(keyString, context);

            if (RegisterContextWithContextRegistry
                && !ContextRegistry.IsContextRegistered(context.Name))
            {
                ContextRegistry.RegisterContext(context);
            }
	    }
Example #49
0
 /// <summary>
 /// Configures the specified handler instance using the object definition <paramref name="name"/>.
 /// </summary>
 /// <remarks>
 /// TODO
 /// </remarks>
 /// <param name="context"></param>
 /// <param name="handler"></param>
 /// <param name="applicationContext"></param>
 /// <param name="name"></param>
 /// <param name="isContainerManaged"></param>
 /// <returns></returns>
 public static IHttpHandler ConfigureHandler(HttpContext context, IHttpHandler handler, IConfigurableApplicationContext applicationContext, string name, bool isContainerManaged)
 {
     if (context.Handler != null)
     {
         s_log.Debug(string.Format("previous handler is present - configuring handler now using application context '{0}' and name '{1}'", applicationContext, name));
         // this is a Server.Execute() or Server.Transfer() request -> configure immediately
         return ConfigureHandlerNow(handler, applicationContext, name, isContainerManaged);
     }
     else
     {
         // remember the resolved object definition name for applying it during PreRequestHandlerExecute
         s_log.Debug(string.Format("no previous handler is present - defer handler configuration using application context '{0}' and name '{1}'", applicationContext, name));
         SetCurrentHandlerConfiguration(applicationContext, name, isContainerManaged);
         return handler;
     }
 }
        /// <summary>
        /// Configures the <see paramref="app"/> instance and its modules.
        /// </summary>
        /// <remarks>
        /// When called, configures <see paramref="app"/> using the <see cref="IApplicationContext"/> instance 
        /// provided in <paramref name="appContext"/> and the templates available in
        /// <see cref="ApplicationTemplate"/> and <see cref="ModuleTemplates"/>.
        /// </remarks>
        /// <param name="appContext">the application context instance to be used for resolving object references.</param>
        /// <param name="app">the <see cref="HttpApplication"/> instance to be configured.</param>
        public static void Configure(IConfigurableApplicationContext appContext, HttpApplication app)
        {
            IObjectDefinition applicationDefinition = s_applicationDefinition;
            if (s_applicationDefinition != null)
            {                
                appContext.ObjectFactory.ConfigureObject(app, "ApplicationTemplate", applicationDefinition);
            }
            
            lock(s_moduleDefinitions.SyncRoot)
            {
                HttpModuleCollection modules = app.Modules;
                foreach(DictionaryEntry moduleEntry in s_moduleDefinitions)
                {
					string moduleName = (string) moduleEntry.Key;
                    IObjectDefinition od = s_moduleDefinitions[moduleName];
                    IHttpModule module = modules[moduleName];
                    if (module != null)
                    {
                        appContext.ObjectFactory.ConfigureObject(module, moduleName, od);
                    }
                    else
                    {
                        throw ConfigurationUtils.CreateConfigurationException(string.Format("failed applying module template '{0}' - no matching module found", moduleName));
                    }
                }
            }
        }
 /// <summary>
 /// Create a handler instance for the given URL.
 /// </summary>
 /// <param name="appContext">the application context corresponding to the current request</param>
 /// <param name="context">The <see cref="HttpContext"/> instance for this request.</param>
 /// <param name="requestType">The HTTP data transfer method (GET, POST, ...)</param>
 /// <param name="rawUrl">The requested <see cref="HttpRequest.RawUrl"/>.</param>
 /// <param name="physicalPath">The physical path of the requested resource.</param>
 /// <returns>A handler instance for processing the current request.</returns>
 protected abstract IHttpHandler CreateHandlerInstance(IConfigurableApplicationContext appContext, HttpContext context, string requestType, string rawUrl, string physicalPath);