コード例 #1
0
        public static PublishedModelFactory CreateDefaultPublishedModelFactory(this IServiceProvider factory)
        {
            TypeLoader typeLoader = factory.GetRequiredService <TypeLoader>();
            IPublishedValueFallback publishedValueFallback = factory.GetRequiredService <IPublishedValueFallback>();
            IEnumerable <Type>      types = typeLoader
                                            .GetTypes <PublishedElementModel>()                     // element models
                                            .Concat(typeLoader.GetTypes <PublishedContentModel>()); // content models

            return(new PublishedModelFactory(types, publishedValueFallback));
        }
コード例 #2
0
        /// <inheritdoc/>
        public bool HasConflictingRoutes(out string controllerName)
        {
            var controllers = _typeLoader.GetTypes <UmbracoApiControllerBase>().ToList();

            foreach (Type controller in controllers)
            {
                var potentialConflicting = controllers.Where(x => x.Name == controller.Name).ToArray();
                if (potentialConflicting.Length > 1)
                {
                    //If we have any with same controller name and located in the same area, then it is a confict.
                    var conflicting = potentialConflicting
                                      .Select(x => x.GetCustomAttribute <PluginControllerAttribute>())
                                      .GroupBy(x => x?.AreaName)
                                      .Any(x => x?.Count() > 1);

                    if (conflicting)
                    {
                        controllerName = controller.Name;
                        return(true);
                    }
                }
            }

            controllerName = string.Empty;
            return(false);
        }
コード例 #3
0
    private static void DrawPopup <T>(Object target, GenericField <T> field, Rect rect, bool allowNull) where T : ScriptableObject
    {
        List <Type>   availableTypes = TypeLoader.GetTypes(field.Type);
        List <string> options        = availableTypes.Select(x => x.Name).ToList();
        int           index          = GetIndex(field);

        if (allowNull)
        {
            options.Insert(0, "null");
        }

        if (options.Count == 0)
        {
            EditorGUI.HelpBox(rect, $"No options found for {field.Type}", MessageType.Error);
            return;
        }

        int newIndex = EditorGUI.Popup(rect, index, options.ToArray());

        if (newIndex != index)
        {
            // Since we insert "null" at 0, we have to move the index one value down to match the actual type list
            if (allowNull)
            {
                newIndex--;
            }

            Type newType = availableTypes[newIndex];

            RemoveInstance(field);
            AddInstance(target, field, newType);

            AssetDatabase.SaveAssets();
        }
    }
コード例 #4
0
    private static int GetIndex <T>(GenericField <T> field) where T : ScriptableObject
    {
        if (field.Instance == null)
        {
            return(0);
        }

        return(TypeLoader.GetTypes(field.Type).IndexOf(field.Instance.GetType()));
    }
コード例 #5
0
    /// <returns>True if unable to create instance</returns>
    private static bool EnsureInstanceExists <T>(Object target, GenericField <T> field) where T : ScriptableObject
    {
        if (field.Instance == null)
        {
            List <Type> availableTypes = TypeLoader.GetTypes(field.Type);

            if (availableTypes.Count == 0)
            {
                return(true);
            }

            AddInstance(target, field, availableTypes[0]);
        }

        return(false);
    }
コード例 #6
0
    /// <returns>Whether the type has changed</returns>
    public bool DrawPopup(Rect rect, SerializedProperty element)
    {
        List <Type> availableTypes = TypeLoader.GetTypes(typeof(T)).ToList();

        string[] options = availableTypes.Select(x => x.Name).ToArray();

        int currentIndex = availableTypes.IndexOf(element.objectReferenceValue.GetType());
        int newIndex     = EditorGUI.Popup(rect, currentIndex, options);

        if (newIndex != currentIndex)
        {
            int indexOfElement = targetList.IndexOf(element.objectReferenceValue);
            ChangeType(indexOfElement, availableTypes[newIndex]);
            return(true);
        }

        return(false);
    }
コード例 #7
0
        /// <summary>
        /// Scan for deploy <see cref="IServiceConnector"/> in assemblies for known UDI types.
        /// </summary>
        /// <param name="typeLoader"></param>
        public static void ScanDeployServiceConnectorsForUdiTypes(TypeLoader typeLoader)
        {
            if (typeLoader is null)
            {
                throw new ArgumentNullException(nameof(typeLoader));
            }

            if (_scanned)
            {
                return;
            }

            lock (ScanLocker)
            {
                // Scan for unknown UDI types
                // there is no way we can get the "registered" service connectors, as registration
                // happens in Deploy, not in Core, and the Udi class belongs to Core - therefore, we
                // just pick every service connectors - just making sure that not two of them
                // would register the same entity type, with different udi types (would not make
                // much sense anyways)
                var connectors = typeLoader.GetTypes <IServiceConnector>();
                var result     = new Dictionary <string, UdiType>();
                foreach (var connector in connectors)
                {
                    var attrs = connector.GetCustomAttributes <UdiDefinitionAttribute>(false);
                    foreach (var attr in attrs)
                    {
                        if (result.TryGetValue(attr.EntityType, out var udiType) && udiType != attr.UdiType)
                        {
                            throw new Exception(string.Format("Entity type \"{0}\" is declared by more than one IServiceConnector, with different UdiTypes.", attr.EntityType));
                        }
                        result[attr.EntityType] = attr.UdiType;
                    }
                }

                // merge these into the known list
                foreach (var item in result)
                {
                    UdiParser.RegisterUdiType(item.Key, item.Value);
                }

                _scanned = true;
            }
        }
コード例 #8
0
        public void AllComposers()
        {
            var typeLoader = new TypeLoader(AppCaches.Disabled.RuntimeCache, IOHelper.MapPath("~/App_Data/TEMP"), Mock.Of <IProfilingLogger>());

            var register    = MockRegister();
            var composition = new Composition(register, typeLoader, Mock.Of <IProfilingLogger>(), MockRuntimeState(RuntimeLevel.Run));

            var types        = typeLoader.GetTypes <IComposer>().Where(x => x.FullName.StartsWith("Umbraco.Core.") || x.FullName.StartsWith("Umbraco.Web"));
            var composers    = new Composers(composition, types, Enumerable.Empty <Attribute>(), Mock.Of <IProfilingLogger>());
            var requirements = composers.GetRequirements();
            var report       = Composers.GetComposersReport(requirements);

            Console.WriteLine(report);
            var composerTypes = composers.SortComposers(requirements);

            foreach (var type in composerTypes)
            {
                Console.WriteLine(type);
            }
        }
コード例 #9
0
        public void AllComposers()
        {
            ITypeFinder typeFinder = TestHelper.GetTypeFinder();
            var         typeLoader = new TypeLoader(typeFinder, new VaryingRuntimeHash(), AppCaches.Disabled.RuntimeCache, new DirectoryInfo(TestHelper.GetHostingEnvironment().MapPathContentRoot(Constants.SystemDirectories.TempData)), Mock.Of <ILogger <TypeLoader> >(), Mock.Of <IProfiler>());

            IServiceCollection register = MockRegister();
            var builder = new UmbracoBuilder(register, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader());

            var allComposers = typeLoader.GetTypes <IComposer>().ToList();
            var types        = allComposers.Where(x => x.FullName.StartsWith("Umbraco.Core.") || x.FullName.StartsWith("Umbraco.Web")).ToList();
            var composers    = new ComposerGraph(builder, types, Enumerable.Empty <Attribute>(), Mock.Of <ILogger <ComposerGraph> >());
            Dictionary <Type, List <Type> > requirements = composers.GetRequirements();
            string report = ComposerGraph.GetComposersReport(requirements);

            Console.WriteLine(report);
            IEnumerable <Type> composerTypes = composers.SortComposers(requirements);

            foreach (Type type in composerTypes)
            {
                Console.WriteLine(type);
            }
        }
コード例 #10
0
 /// <summary>
 /// Gets all classes implementing IPackageAction.
 /// </summary>
 public static IEnumerable <Type> GetPackageActions(this TypeLoader mgr)
 {
     return(mgr.GetTypes <IPackageAction>());
 }
コード例 #11
0
 /// <summary>
 /// Gets all classes implementing ICacheRefresher.
 /// </summary>
 public static IEnumerable <Type> GetCacheRefreshers(this TypeLoader mgr)
 {
     return(mgr.GetTypes <ICacheRefresher>());
 }
コード例 #12
0
 /// <summary>
 /// Gets all classes implementing <see cref="IDataEditor"/>.
 /// </summary>
 public static IEnumerable <Type> GetDataEditors(this TypeLoader mgr)
 {
     return(mgr.GetTypes <IDataEditor>());
 }
コード例 #13
0
 public IEnumerable <ConfigurationEditorModel> GetConfigurationEditors <TContentmentListItem>(bool onlyPublic = false, bool ignoreFields = false)
     where TContentmentListItem : class, IContentmentListItem
 {
     return(GetConfigurationEditors <TContentmentListItem>(_typeLoader.GetTypes <TContentmentListItem>(), onlyPublic, ignoreFields));
 }
コード例 #14
0
    public void AddEntry(ReorderableList list)
    {
        List <Type> availableTypes = TypeLoader.GetTypes(typeof(T));

        AddObject(availableTypes[0]);
    }
コード例 #15
0
        public void StandaloneTest()
        {
            IFactory factory = null;

            // clear
            foreach (var file in Directory.GetFiles(Path.Combine(IOHelper.MapPath("~/App_Data")), "NuCache.*"))
            {
                File.Delete(file);
            }

            // settings
            // reset the current version to 0.0.0, clear connection strings
            ConfigurationManager.AppSettings[Constants.AppSettings.ConfigurationStatus] = "";
            // FIXME: we need a better management of settings here (and, true config files?)

            // create the very basic and essential things we need
            var logger          = new ConsoleLogger();
            var profiler        = new LogProfiler(logger);
            var profilingLogger = new ProfilingLogger(logger, profiler);
            var appCaches       = new AppCaches(); // FIXME: has HttpRuntime stuff?
            var databaseFactory = new UmbracoDatabaseFactory(logger, new Lazy <IMapperCollection>(() => factory.GetInstance <IMapperCollection>()));
            var typeLoader      = new TypeLoader(appCaches.RuntimeCache, IOHelper.MapPath("~/App_Data/TEMP"), profilingLogger);
            var mainDom         = new SimpleMainDom();
            var runtimeState    = new RuntimeState(logger, null, null, new Lazy <IMainDom>(() => mainDom), new Lazy <IServerRegistrar>(() => factory.GetInstance <IServerRegistrar>()));

            // create the register and the composition
            var register    = RegisterFactory.Create();
            var composition = new Composition(register, typeLoader, profilingLogger, runtimeState);

            composition.RegisterEssentials(logger, profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, runtimeState);

            // create the core runtime and have it compose itself
            var coreRuntime = new CoreRuntime();

            coreRuntime.Compose(composition);

            // determine actual runtime level
            runtimeState.DetermineRuntimeLevel(databaseFactory, logger);
            Console.WriteLine(runtimeState.Level);
            // going to be Install BUT we want to force components to be there (nucache etc)
            runtimeState.Level = RuntimeLevel.Run;

            var composerTypes = typeLoader.GetTypes <IComposer>()                                              // all of them
                                .Where(x => !x.FullName.StartsWith("Umbraco.Tests."))                          // exclude test components
                                .Where(x => x != typeof(WebInitialComposer) && x != typeof(WebFinalComposer)); // exclude web runtime
            var composers = new Composers(composition, composerTypes, Enumerable.Empty <Attribute>(), profilingLogger);

            composers.Compose();

            // must registers stuff that WebRuntimeComponent would register otherwise
            // FIXME: UmbracoContext creates a snapshot that it does not register with the accessor
            //  and so, we have to use the UmbracoContextPublishedSnapshotAccessor
            //  the UmbracoContext does not know about the accessor
            //  else that would be a catch-22 where they both know about each other?
            //composition.Register<IPublishedSnapshotAccessor, TestPublishedSnapshotAccessor>(Lifetime.Singleton);
            composition.Register <IPublishedSnapshotAccessor, UmbracoContextPublishedSnapshotAccessor>(Lifetime.Singleton);
            composition.Register <IUmbracoContextAccessor, TestUmbracoContextAccessor>(Lifetime.Singleton);
            composition.Register <IVariationContextAccessor, TestVariationContextAccessor>(Lifetime.Singleton);
            composition.Register <IDefaultCultureAccessor, TestDefaultCultureAccessor>(Lifetime.Singleton);
            composition.Register <ISiteDomainHelper>(_ => Mock.Of <ISiteDomainHelper>(), Lifetime.Singleton);
            composition.Register(_ => Mock.Of <IImageUrlGenerator>(), Lifetime.Singleton);
            composition.RegisterUnique(f => new DistributedCache());
            composition.WithCollectionBuilder <UrlProviderCollectionBuilder>().Append <DefaultUrlProvider>();
            composition.RegisterUnique <IDistributedCacheBinder, DistributedCacheBinder>();
            composition.RegisterUnique <IExamineManager>(f => ExamineManager.Instance);
            composition.RegisterUnique <IUmbracoContextFactory, UmbracoContextFactory>();
            composition.RegisterUnique <IMacroRenderer, MacroRenderer>();
            composition.RegisterUnique <MediaUrlProviderCollection>(_ => new MediaUrlProviderCollection(Enumerable.Empty <IMediaUrlProvider>()));

            // initialize some components only/individually
            composition.WithCollectionBuilder <ComponentCollectionBuilder>()
            .Clear()
            .Append <DistributedCacheBinderComponent>();

            // configure
            composition.Configs.Add(SettingsForTests.GetDefaultGlobalSettings);
            composition.Configs.Add(SettingsForTests.GetDefaultUmbracoSettings);

            // create and register the factory
            Current.Factory = factory = composition.CreateFactory();

            // instantiate and initialize components
            var components = factory.GetInstance <ComponentCollection>();

            // do stuff
            Console.WriteLine(runtimeState.Level);

            // install
            if (true || runtimeState.Level == RuntimeLevel.Install)
            {
                var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var file = databaseFactory.Configured ? Path.Combine(path, "UmbracoNPocoTests.sdf") : Path.Combine(path, "Umbraco.sdf");
                if (File.Exists(file))
                {
                    File.Delete(file);
                }

                // create the database file
                // databaseBuilder.ConfigureEmbeddedDatabaseConnection() can do it too,
                // but then it wants to write the connection string to web.config = bad
                var connectionString = databaseFactory.Configured ? databaseFactory.ConnectionString : "Data Source=|DataDirectory|\\Umbraco.sdf;Flush Interval=1;";
                using (var engine = new SqlCeEngine(connectionString))
                {
                    engine.CreateDatabase();
                }

                //var databaseBuilder = factory.GetInstance<DatabaseBuilder>();
                //databaseFactory.Configure(DatabaseBuilder.EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe);
                //databaseBuilder.CreateDatabaseSchemaAndData();

                if (!databaseFactory.Configured)
                {
                    databaseFactory.Configure(DatabaseBuilder.EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe);
                }

                var scopeProvider = factory.GetInstance <IScopeProvider>();
                using (var scope = scopeProvider.CreateScope())
                {
                    var creator = new DatabaseSchemaCreator(scope.Database, logger);
                    creator.InitializeDatabaseSchema();
                    scope.Complete();
                }
            }

            // done installing
            runtimeState.Level = RuntimeLevel.Run;

            components.Initialize();

            // instantiate to register events
            // should be done by Initialize?
            // should we invoke Initialize?
            _ = factory.GetInstance <IPublishedSnapshotService>();

            // at that point, Umbraco can run!
            // though, we probably still need to figure out what depends on HttpContext...
            var contentService = factory.GetInstance <IContentService>();
            var content        = contentService.GetById(1234);

            Assert.IsNull(content);

            // create a document type and a document
            var contentType = new ContentType(-1)
            {
                Alias = "ctype", Name = "ctype"
            };

            factory.GetInstance <IContentTypeService>().Save(contentType);
            content = new Content("test", -1, contentType);
            contentService.Save(content);

            // assert that it is possible to get the document back
            content = contentService.GetById(content.Id);
            Assert.IsNotNull(content);
            Assert.AreEqual("test", content.Name);

            // need an UmbracoCOntext to access the cache
            // FIXME: not exactly pretty, should not depend on HttpContext
            var httpContext             = Mock.Of <HttpContextBase>();
            var umbracoContextFactory   = factory.GetInstance <IUmbracoContextFactory>();
            var umbracoContextReference = umbracoContextFactory.EnsureUmbracoContext(httpContext);
            var umbracoContext          = umbracoContextReference.UmbracoContext;

            // assert that there is no published document
            var pcontent = umbracoContext.Content.GetById(content.Id);

            Assert.IsNull(pcontent);

            // but a draft document
            pcontent = umbracoContext.Content.GetById(true, content.Id);
            Assert.IsNotNull(pcontent);
            Assert.AreEqual("test", pcontent.Name());
            Assert.IsTrue(pcontent.IsDraft());

            // no published URL
            Assert.AreEqual("#", pcontent.Url());

            // now publish the document + make some unpublished changes
            contentService.SaveAndPublish(content);
            content.Name = "testx";
            contentService.Save(content);

            // assert that snapshot has been updated and there is now a published document
            pcontent = umbracoContext.Content.GetById(content.Id);
            Assert.IsNotNull(pcontent);
            Assert.AreEqual("test", pcontent.Name());
            Assert.IsFalse(pcontent.IsDraft());

            // but the URL is the published one - no draft URL
            Assert.AreEqual("/test/", pcontent.Url());

            // and also an updated draft document
            pcontent = umbracoContext.Content.GetById(true, content.Id);
            Assert.IsNotNull(pcontent);
            Assert.AreEqual("testx", pcontent.Name());
            Assert.IsTrue(pcontent.IsDraft());

            // and the published document has a URL
            Assert.AreEqual("/test/", pcontent.Url());

            umbracoContextReference.Dispose();
            mainDom.Stop();
            components.Terminate();

            // exit!
        }
コード例 #16
0
        public void ValidateComposition()
        {
            // this is almost what CoreRuntime does, without
            // - managing MainDom
            // - configuring for unhandled exceptions, assembly resolution, application root path
            // - testing for database, and for upgrades (runtime level)
            // - assigning the factory to Current.Factory

            // create the very basic and essential things we need
            var logger          = new ConsoleLogger();
            var profiler        = Mock.Of <IProfiler>();
            var profilingLogger = new ProfilingLogger(logger, profiler);
            var appCaches       = AppCaches.Disabled;
            var databaseFactory = Mock.Of <IUmbracoDatabaseFactory>();
            var typeLoader      = new TypeLoader(appCaches.RuntimeCache, IOHelper.MapPath("~/App_Data/TEMP"), profilingLogger);
            var runtimeState    = Mock.Of <IRuntimeState>();

            Mock.Get(runtimeState).Setup(x => x.Level).Returns(RuntimeLevel.Run);
            var mainDom = Mock.Of <IMainDom>();

            Mock.Get(mainDom).Setup(x => x.IsMainDom).Returns(true);

            // create the register and the composition
            var register    = RegisterFactory.Create();
            var composition = new Composition(register, typeLoader, profilingLogger, runtimeState);

            composition.RegisterEssentials(logger, profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, runtimeState);

            // create the core runtime and have it compose itself
            var coreRuntime = new CoreRuntime();

            coreRuntime.Compose(composition);

            // get the components
            // all of them?
            var composerTypes = typeLoader.GetTypes <IComposer>();

            // filtered
            composerTypes = composerTypes
                            .Where(x => !x.FullName.StartsWith("Umbraco.Tests"));
            // single?
            //var componentTypes = new[] { typeof(CoreRuntimeComponent) };
            var composers = new Composers(composition, composerTypes, Enumerable.Empty <Attribute>(), profilingLogger);

            // get components to compose themselves
            composers.Compose();

            // create the factory
            var factory = composition.CreateFactory();

            // at that point Umbraco is fully composed
            // but nothing is initialized (no maindom, nothing - beware!)
            // to actually *run* Umbraco standalone, better use a StandaloneRuntime
            // that would inherit from CoreRuntime and ensure everything starts

            // get components to initialize themselves
            //components.Initialize(factory);

            // and then, validate
            var lightInjectContainer = (LightInject.ServiceContainer)factory.Concrete;
            var results = lightInjectContainer.Validate().ToList();

            foreach (var resultGroup in results.GroupBy(x => x.Severity).OrderBy(x => x.Key))
            {
                Console.WriteLine($"{resultGroup.Key}: {resultGroup.Count()}");
            }

            foreach (var resultGroup in results.GroupBy(x => x.Severity).OrderBy(x => x.Key))
            {
                foreach (var result in resultGroup)
                {
                    Console.WriteLine();
                    Console.Write(ToText(result));
                }
            }

            Assert.AreEqual(0, results.Count);
        }
コード例 #17
0
 internal static IEnumerable <Type> GetUmbracoApiControllers(this TypeLoader mgr)
 {
     return(mgr.GetTypes <UmbracoApiController>());
 }
コード例 #18
0
 internal static IEnumerable <Type> GetSurfaceControllers(this TypeLoader mgr)
 {
     return(mgr.GetTypes <SurfaceController>());
 }
コード例 #19
0
 /// <summary>
 ///     Gets all types implementing <see cref="PackageMigrationPlan" />
 /// </summary>
 /// <param name="mgr"></param>
 /// <returns></returns>
 public static IEnumerable <Type> GetPackageMigrationPlans(this TypeLoader mgr) =>
 mgr.GetTypes <PackageMigrationPlan>();
コード例 #20
0
 /// <summary>
 ///     Gets all types implementing <see cref="IAction" />
 /// </summary>
 /// <param name="mgr"></param>
 /// <returns></returns>
 public static IEnumerable <Type> GetActions(this TypeLoader mgr) => mgr.GetTypes <IAction>();
コード例 #21
0
 /// <summary>
 ///     Gets all types implementing <see cref="IDataEditor" />.
 /// </summary>
 public static IEnumerable <Type> GetDataEditors(this TypeLoader mgr) => mgr.GetTypes <IDataEditor>();
コード例 #22
0
ファイル: CoreRuntime.cs プロジェクト: dinc5150/Umbraco-CMS
        // getters can be implemented by runtimes inheriting from CoreRuntime

        /// <summary>
        /// Gets all composer types.
        /// </summary>
        protected virtual IEnumerable <Type> GetComposerTypes(TypeLoader typeLoader)
        => typeLoader.GetTypes <IComposer>();
コード例 #23
0
 /// <summary>
 ///     Gets all types implementing <see cref="SurfaceController" />.
 /// </summary>
 internal static IEnumerable <Type> GetSurfaceControllers(this TypeLoader typeLoader)
 => typeLoader.GetTypes <SurfaceController>();
コード例 #24
0
 /// <summary>
 /// Gets all types implementing <see cref="UmbracoApiController"/>.
 /// </summary>
 public static IEnumerable <Type> GetUmbracoApiControllers(this TypeLoader typeLoader)
 => typeLoader.GetTypes <UmbracoApiController>();
コード例 #25
0
 public static IEnumerable <Type> ResolveFindMeTypes(this TypeLoader resolver)
 {
     return(resolver.GetTypes <TypeLoaderTests.IFindMe>());
 }