Пример #1
0
        public IBeanContextHolder <I> CreateService <I>(String contextName, IBackgroundWorkerParamDelegate <IBeanContextFactory> registerPhaseDelegate, params Type[] serviceModuleTypes)
        {
            CheckNotDisposed();
            IBeanContextInitializer beanContextInitializer = RegisterBean <BeanContextInitializer>().Finish();

            if (contextName == null && registerPhaseDelegate == null && serviceModuleTypes.Length == 1)
            {
                contextName = serviceModuleTypes[0].Name;
            }
            BeanContextFactory childBeanContextFactory = beanContextFactory.CreateChildContextFactory(beanContextInitializer, this);
            IServiceContext    childContext            = childBeanContextFactory.Create(contextName, this, registerPhaseDelegate, serviceModuleTypes);

            writeLock.Lock();
            try
            {
                if (children == null)
                {
                    children = new IdentityHashSet <IServiceContext>();
                }
                children.Add(childContext);
            }
            finally
            {
                writeLock.Unlock();
            }
            return(new BeanContextHolder <I>(childContext));
        }
Пример #2
0
        public virtual void SetUp()
        {
            ParamChecker.AssertNull(beanContext, "Must never happen");

            beanContext = BeanContextFactory.CreateBootstrap(typeof(ChildContextHandleChildFactoryTestModule));
            beanContext = beanContext.CreateService(typeof(ChildContextHandleTestModule));
        }
Пример #3
0
        public IBeanConfiguration GetBeanConfiguration(BeanContextFactory beanContextFactory, String beanName)
        {
            CheckNotDisposed();
            IBeanConfiguration beanConfiguration = beanContextFactory.GetBeanConfiguration(beanName);

            if (beanConfiguration == null && parent != null)
            {
                return(parent.GetBeanConfiguration(beanName));
            }
            return(beanConfiguration);
        }
Пример #4
0
        public void RebuildContext(MethodInfo frameworkMethod)
        {
            DisposeContext();
            Properties.ResetApplication();
            Properties.LoadBootstrapPropertyFile();

            Properties baseProps = new Properties(Properties.Application);

            ExtendProperties(frameworkMethod, baseProps);

            LinkedHashSet <Type> testClassLevelTestFrameworkModulesList = new LinkedHashSet <Type>();
            LinkedHashSet <Type> testClassLevelTestModulesList          = new LinkedHashSet <Type>();

            testClassLevelTestModulesList.AddAll(BuildTestModuleList(frameworkMethod));
            testClassLevelTestFrameworkModulesList.AddAll(BuildFrameworkTestModuleList(frameworkMethod));

            Type[] frameworkModules   = testClassLevelTestFrameworkModulesList.ToArray();
            Type[] applicationModules = testClassLevelTestModulesList.ToArray();

            testClassLevelContext = BeanContextFactory.CreateBootstrap(baseProps);
            bool success = false;

            try
            {
                IServiceContext currentBeanContext = testClassLevelContext;
                if (frameworkModules.Length > 0)
                {
                    currentBeanContext = currentBeanContext.CreateService(delegate(IBeanContextFactory childContextFactory)
                    {
                        RebuildContextDetails(childContextFactory);
                    }, frameworkModules);
                }
                if (applicationModules.Length > 0)
                {
                    currentBeanContext = currentBeanContext.CreateService(applicationModules);
                }
                currentBeanContext.RegisterWithLifecycle(originalTestInstance).Finish();
                beanContext = currentBeanContext;
                success     = true;
            }
            finally
            {
                if (!success && testClassLevelContext != null)
                {
                    testClassLevelContext.GetService <IThreadLocalCleanupController>().CleanupThreadLocal();
                }
            }
        }
Пример #5
0
        static void Main(String[] args)
        {
            Properties.Application.FillWithCommandLineArgs(args);
            Properties.LoadBootstrapPropertyFile();

            Properties props = Properties.Application;

            IServiceContext bootstrapContext = BeanContextFactory.CreateBootstrap(props, typeof(IocModule));

            try
            {
                bootstrapContext.CreateService(typeof(ParserModule));
            }
            finally
            {
                bootstrapContext.Dispose();
            }
        }
Пример #6
0
        public V Finish()
        {
            BeanContextFactory         beanContextFactory     = serviceContext.GetBeanContextFactory();
            IBeanContextInitializer    beanContextInitializer = beanContextFactory.GetBeanContextInitializer();
            IList <IBeanConfiguration> beanConfHierarchy      = beanContextInitializer.FillParentHierarchyIfValid(serviceContext, beanContextFactory, beanConfiguration);

            V bean = beanInstance;

            if (bean == null)
            {
                Type beanType = this.beanType;
                if (beanType == null)
                {
                    beanType = beanContextInitializer.ResolveTypeInHierarchy(beanConfHierarchy);
                }
                bean = (V)Activator.CreateInstance(beanType);
            }

            bean = (V)beanContextInitializer.InitializeBean(serviceContext, beanContextFactory, beanConfiguration, bean, beanConfHierarchy, joinLifecycle);
            return(bean);
        }
Пример #7
0
        public static IAmbethPlatformContext Create(Properties props, Type[] providerModules, Type[] frameworkModules, Type[] bootstrapModules,
                                                    IInitializingModule[] providerModuleInstances, IInitializingModule[] frameworkModuleInstances,
                                                    IInitializingModule[] bootstrapModuleInstances)
        {
            ParamChecker.AssertParamNotNull(props, "props");

            IServiceContext       bootstrapContext = null;
            AmbethPlatformContext apc = new AmbethPlatformContext();

            try
            {
                IInitializingModule[] providerModuleInstancesCopy = new IInitializingModule[providerModuleInstances.Length + 1];
                Array.Copy(providerModuleInstances, 0, providerModuleInstancesCopy, 0, providerModuleInstances.Length);
                providerModuleInstancesCopy[providerModuleInstancesCopy.Length - 1] = new AmbethPlatformContextModule(apc);
                providerModuleInstances = providerModuleInstancesCopy;

                bootstrapContext = BeanContextFactory.CreateBootstrap(props, providerModules, providerModuleInstances);

                IList <IModuleProvider> moduleProviders = bootstrapContext.GetImplementingObjects <IModuleProvider>();
                for (int a = moduleProviders.Count; a-- > 0;)
                {
                    IModuleProvider moduleProvider     = moduleProviders[a];
                    Type[]          mpFrameworkModules = moduleProvider.GetFrameworkModules();
                    Type[]          mpBootstrapModules = moduleProvider.GetBootstrapModules();
                    frameworkModules = ModuleUtil.MergeModules(mpFrameworkModules, frameworkModules);
                    bootstrapModules = ModuleUtil.MergeModules(mpBootstrapModules, bootstrapModules);
                }
                IServiceContext frameworkBeanContext = bootstrapContext;

                if (frameworkModules.Length > 0 || frameworkModuleInstances.Length > 0)
                {
                    frameworkBeanContext = bootstrapContext.CreateService("framework", delegate(IBeanContextFactory childContextFactory)
                    {
                        for (int a = frameworkModuleInstances.Length; a-- > 0;)
                        {
                            childContextFactory.RegisterExternalBean(frameworkModuleInstances[a]);
                        }
                    }, frameworkModules);
                }

                ILightweightTransaction transaction = frameworkBeanContext.GetService <ILightweightTransaction>(false);
                if (transaction != null)
                {
                    ILogger log = LoggerFactory.GetLogger(typeof(AmbethPlatformContext), props);
                    if (log.InfoEnabled)
                    {
                        log.Info("Starting initial database transaction to receive metadata for OR-Mappings...");
                    }
                    transaction.RunInTransaction(delegate()
                    {
                        // Intended blank
                    });
                    if (log.InfoEnabled)
                    {
                        log.Info("Initial database transaction processed successfully");
                    }
                }
                IServiceContext applicationBeanContext = frameworkBeanContext;

                if (bootstrapModules.Length > 0 || bootstrapModuleInstances.Length > 0)
                {
                    applicationBeanContext = frameworkBeanContext.CreateService("application", delegate(IBeanContextFactory childContextFactory)
                    {
                        for (int a = bootstrapModuleInstances.Length; a-- > 0;)
                        {
                            childContextFactory.RegisterExternalBean(bootstrapModuleInstances[a]);
                        }
                    }, bootstrapModules);
                }
                apc.beanContext = applicationBeanContext;
                return(apc);
            }
            catch (Exception)
            {
                if (bootstrapContext != null)
                {
                    IThreadLocalCleanupController tlCleanupController = bootstrapContext.GetService <IThreadLocalCleanupController>();
                    bootstrapContext.Dispose();
                    tlCleanupController.CleanupThreadLocal();
                }
                throw;
            }
        }
Пример #8
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            String configFolder         = "config";
            String fileName             = "Minerva.properties";
            String filePath             = configFolder + "\\" + fileName;
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite();

            Stream primaryPropertyStream = null;

            try
            {
                storage.CreateDirectory("config");
                primaryPropertyStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, storage);
            }
            catch (IsolatedStorageException)
            {
                // Intended blank
            }
            catch (FileNotFoundException)
            {
                // Intended blank
            }

            String             urlString          = "/Minerva.Client;component/" + filePath;
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(urlString, UriKind.Relative));

            if (streamResourceInfo == null)
            {
#if DEVELOP
                urlString = "/Minerva.Client;component/" + configFolder + "/Osthus.properties";
#else
                urlString = "/Minerva.Client;component/" + configFolder + "/Osthus_Production.properties";
#endif
                streamResourceInfo = Application.GetResourceStream(new Uri(urlString, UriKind.Relative));
            }

            Properties properties = Properties.Application;

            if (streamResourceInfo != null)
            {
                properties.Load(streamResourceInfo.Stream);
            }

            String servicePort = DictionaryExtension.ValueOrDefault(e.InitParams, "serviceport");
            String serviceHost = DictionaryExtension.ValueOrDefault(e.InitParams, "servicehost");

            DictionaryExtension.Loop(e.InitParams, delegate(String key, String value)
            {
                properties.Set(key, value);
            });

            if (servicePort != null)
            {
                properties[ServiceConfigurationConstants.ServiceHostPort] = servicePort;
            }
            if (serviceHost != null)
            {
                properties[ServiceConfigurationConstants.ServiceHostName] = serviceHost;
            }

            properties.Load(primaryPropertyStream);

            Properties.System[ServiceWCFConfigurationConstants.TransferObjectsScope] = ".+";
            Properties.System[EventConfigurationConstants.PollingActive]             = "true";
            Properties.System[ServiceConfigurationConstants.NetworkClientMode]       = "true";
            Properties.System[ServiceConfigurationConstants.GenericTransferMapping]  = "false";
            Properties.System[ServiceConfigurationConstants.IndependentMetaData]     = "false";

            properties[ServiceConfigurationConstants.ServiceBaseUrl] = "${" + ServiceConfigurationConstants.ServiceProtocol + "}://"
                                                                       + "${" + ServiceConfigurationConstants.ServiceHostName + "}" + ":"
                                                                       + "${" + ServiceConfigurationConstants.ServiceHostPort + "}"
                                                                       + "${" + ServiceConfigurationConstants.ServicePrefix + "}";

            properties[ServiceConfigurationConstants.ServiceProtocol] = "http";
            properties[ServiceConfigurationConstants.ServiceHostName] = "localhost.";
            properties[ServiceConfigurationConstants.ServiceHostPort] = "9080";
            properties[ServiceConfigurationConstants.ServicePrefix]   = "/helloworld";

            LoggerFactory.LoggerType = typeof(De.Osthus.Ambeth.Log.ClientLogger);

            Log = LoggerFactory.GetLogger(typeof(App), properties);

            if (Log.InfoEnabled)
            {
                ISet <String> allPropertiesSet = properties.CollectAllPropertyKeys();

                List <String> allPropertiesList = new List <String>(allPropertiesSet);

                allPropertiesList.Sort();

                Log.Info("Property environment:");
                foreach (String property in allPropertiesList)
                {
                    Log.Info("Property " + property + "=" + properties[property]);
                }
            }

            Type         type         = storage.GetType();
            PropertyInfo propertyInfo = null;
            while (type != null)
            {
                propertyInfo = type.GetProperty("RootDirectory", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
                if (propertyInfo != null)
                {
                    break;
                }
                type = type.BaseType;
            }
            AssemblyHelper.RegisterAssemblyFromType(typeof(BytecodeModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CacheBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CacheBytecodeModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CacheDataChangeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(DataChangeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(EventBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(IocBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(MergeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(CompositeIdModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(PrivilegeBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(SecurityBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(ServiceBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(MethodDescription));

            AssemblyHelper.RegisterAssemblyFromType(typeof(MinervaCoreBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(RESTBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(XmlBootstrapModule));
            AssemblyHelper.RegisterAssemblyFromType(typeof(FilterDescriptor));

            AssemblyHelper.RegisterAssemblyFromType(typeof(HelloWorldModule));
            AssemblyHelper.InitAssemblies("ambeth\\..+", "minerva\\..+");

            properties[XmlConfigurationConstants.PackageScanPatterns]   = @"De\.Osthus(?:\.Ambeth|\.Minerva)(?:\.[^\.]+)*(?:\.Transfer|\.Model|\.Service)\..+";
            properties[CacheConfigurationConstants.FirstLevelCacheType] = "SINGLETON";
            properties[CacheConfigurationConstants.OverwriteToManyRelationsInChildCache] = "false";
            properties[CacheConfigurationConstants.UpdateChildCache]        = "true";
            properties[MinervaCoreConfigurationConstants.EntityProxyActive] = "true";
            properties[ServiceConfigurationConstants.TypeInfoProviderType]  = typeof(MergeTypeInfoProvider).FullName;

            // Set this to false, to test with mocks (offline)
            bool Online = true;

            properties[CacheConfigurationConstants.CacheServiceBeanActive]           = Online.ToString();
            properties[EventConfigurationConstants.EventServiceBeanActive]           = Online.ToString();
            properties[MergeConfigurationConstants.MergeServiceBeanActive]           = Online.ToString();
            properties[SecurityConfigurationConstants.SecurityServiceBeanActive]     = Online.ToString();
            properties[HelloWorldConfigurationConstants.HelloWorldServiceBeanActive] = Online.ToString();
            properties[MergeConfigurationConstants.MergeServiceMockType]             = typeof(HelloWorldMergeMock).FullName;
//already default:            properties[RESTConfigurationConstants.HttpAcceptEncodingZipped] = "true";
//already default:            properties[RESTConfigurationConstants.HttpContentEncodingZipped] = "true";
//already default:            properties[RESTConfigurationConstants.HttpUseClient] = "true";

            IServiceContext bootstrapContext = BeanContextFactory.CreateBootstrap(properties);

            try
            {
                // Create child context and override root context
                BeanContext = bootstrapContext.CreateService(delegate(IBeanContextFactory bcf)
                {
                    bcf.RegisterAnonymousBean <MainPageModule>();
                    bcf.RegisterAnonymousBean(typeof(HelloWorldModule));
                    AssemblyHelper.HandleTypesFromCurrentDomainWithAnnotation <FrameworkModuleAttribute>(delegate(Type bootstrapModuleType)
                    {
                        //if (!typeof(IInitializingBootstrapMockModule).IsAssignableFrom(bootstrapModuleType))
                        {
                            if (Log.InfoEnabled)
                            {
                                Log.Info("Autoresolving bootstrap module: '" + bootstrapModuleType.FullName + "'");
                            }
                            bcf.RegisterAnonymousBean(bootstrapModuleType);
                        }
                    });
                    bcf.RegisterExternalBean("app", this);
                }, typeof(RESTBootstrapModule));
                FlattenHierarchyProxy.Context = BeanContext;

                BeanContext.GetService <IThreadPool>().Queue(delegate()
                {
                    double result  = BeanContext.GetService <IHelloWorldService>().DoFunnyThings(5, "hallo");
                    double result2 = BeanContext.GetService <IHelloWorldService>().DoFunnyThings(6, "hallo");
                    if (Math.Abs(result - result2) != 1)
                    {
                        throw new Exception("Process execution failed with unexpected result value: " + result + "/" + result2);
                    }
                    Log.Info("" + result);
                    //Type enhancedType = BeanContext.GetService<IBytecodeEnhancer>().GetEnhancedType(typeof(TestEntity), EntityEnhancementHint.HOOK);
                    //TestEntity instance = (TestEntity)Activator.CreateInstance(enhancedType);
                    //instance.Id = 1;
                    //IEntityMetaData metaData = BeanContext.GetService<IEntityMetaDataProvider>().GetMetaData(enhancedType);
                    //IObjRelation result3 = ((IValueHolderContainer)instance).GetSelf("Relation");
                    //Object targetCache = ((IValueHolderContainer)instance).TargetCache;
                    //((IValueHolderContainer)instance).TargetCache = new ChildCache();
                    //Console.WriteLine("TestT");
                });
                SynchronizationContext syncContext = BeanContext.GetService <SynchronizationContext>();

                syncContext.Post((object state) =>
                {
                    RootVisual = BeanContext.GetService <UIElement>("mainPage");
                }, null);
            }
            catch (Exception ex)
            {
                if (Log.ErrorEnabled)
                {
                    Log.Error(ex);
                }
                throw;
            }
        }
Пример #9
0
        public void Dispose()
        {
            if (disposed || disposing)
            {
                return;
            }
            ILogger log;

            IServiceContext[] childrenCopy = null;
            writeLock.Lock();
            try
            {
                if (disposed || disposing)
                {
                    return;
                }
                log = GetService <ILoggerCache>().GetCachedLogger(this, typeof(ServiceContext));
                if (log.DebugEnabled)
                {
                    // Safe the toString-method for debugging purpose. Because this is not possible anymore if the context
                    // has been disposed and all bean-references have been cleared
                    toStringBackup = StringBuilderUtil.Concat(delegate(StringBuilder sb)
                    {
                        PrintContent(sb);
                    });
                }
                else
                {
                    toStringBackup = "n/a";
                }
                disposing = true;
                if (children != null && children.Count > 0)
                {
                    childrenCopy = new IServiceContext[children.Count];
                    children.CopyTo(childrenCopy, 0);
                    children.Clear();
                }
            }
            finally
            {
                writeLock.Unlock();
            }
            if (childrenCopy != null)
            {
                foreach (IServiceContext childContext in childrenCopy)
                {
                    try
                    {
                        childContext.Dispose();
                    }
                    catch (Exception e)
                    {
                        if (log.ErrorEnabled)
                        {
                            log.Error(e);
                        }
                    }
                }
            }
            writeLock.Lock();
            try
            {
                if (parent != null)
                {
                    parent.ChildContextDisposed(this);
                    parent = null;
                }
                if (this.linkContainers != null)
                {
                    IList <ILinkContainer> linkContainers = this.linkContainers;
                    this.linkContainers = null;
                    for (int a = linkContainers.Count; a-- > 0;)
                    {
                        ILinkContainer listenerContainer = linkContainers[a];
                        try
                        {
                            listenerContainer.Unlink();
                        }
                        catch (System.Exception e)
                        {
                            if (failOnError)
                            {
                                throw;
                            }
                            if (log.ErrorEnabled)
                            {
                                log.Error(e);
                            }
                        }
                    }
                }
                if (this.disposableObjects != null)
                {
                    IList <Object> disposableObjects = this.disposableObjects;
                    this.disposableObjects = null;
                    for (int a = disposableObjects.Count; a-- > 0;)
                    {
                        Object disposableObject = disposableObjects[a];
                        if (disposableObject is WeakReference)
                        {
                            disposableObject = ((WeakReference)disposableObject).Target;
                        }
                        if (disposableObject is IDisposableBean)
                        {
                            try
                            {
                                ((IDisposableBean)disposableObject).Destroy();
                            }
                            catch (System.Exception e)
                            {
                                if (failOnError)
                                {
                                    throw;
                                }
                                if (log.ErrorEnabled)
                                {
                                    log.Error(e);
                                }
                            }
                        }
                        else if (disposableObject is IDisposable)
                        {
                            try
                            {
                                ((IDisposable)disposableObject).Dispose();
                            }
                            catch (System.Exception e)
                            {
                                if (failOnError)
                                {
                                    throw;
                                }
                                if (log.ErrorEnabled)
                                {
                                    log.Error(e);
                                }
                            }
                        }
                        else if (disposableObject is IBackgroundWorkerParamDelegate <IServiceContext> )
                        {
                            try
                            {
                                ((IBackgroundWorkerParamDelegate <IServiceContext>)disposableObject).Invoke(this);
                            }
                            catch (System.Exception e)
                            {
                                if (failOnError)
                                {
                                    throw;
                                }
                                if (log.ErrorEnabled)
                                {
                                    log.Error(e);
                                }
                            }
                        }
                    }
                }

                if (nameToServiceDict != null)
                {
                    nameToServiceDict.Clear();
                }
                typeToServiceDict.Clear();
                if (postProcessors != null)
                {
                    postProcessors.Clear();
                }
                if (preProcessors != null)
                {
                    preProcessors.Clear();
                }
                beanContextFactory.Dispose();
            }
            finally
            {
                writeLock.Unlock();
                beanContextFactory = null;
                linkContainers     = null;
                nameToServiceDict  = null;
                postProcessors     = null;
                preProcessors      = null;
                parent             = null;
                disposed           = true;
                running            = false;
            }
        }
Пример #10
0
 public void SetBeanContextFactory(BeanContextFactory beanContextFactory)
 {
     CheckNotDisposed();
     this.beanContextFactory = beanContextFactory;
 }