Exemplo n.º 1
0
        public void FromNetCoreAppVersionParsesVersionProperly(string netCoreAppVersion, TargetFrameworkMoniker expectedTfm, string expectedMsBuildMoniker)
        {
            var runtime = CoreRuntime.FromNetCoreAppVersion(netCoreAppVersion);

            Assert.Equal(expectedTfm, runtime.TargetFrameworkMoniker);
            Assert.Equal(expectedMsBuildMoniker, runtime.MsBuildMoniker);
        }
Exemplo n.º 2
0
        public void FromProductVersionParsesVersionProperly(TargetFrameworkMoniker expectedTfm, string expectedMsBuildMoniker, string productName, string productVersion)
        {
            var runtime = CoreRuntime.FromProductVersion(productVersion, productName);

            Assert.Equal(expectedTfm, runtime.TargetFrameworkMoniker);
            Assert.Equal(expectedMsBuildMoniker, runtime.MsBuildMoniker);
        }
        internal static Runtime GetCurrentRuntime()
        {
            //do not change the order of conditions because it may cause incorrect determination of runtime
            if (IsMono)
            {
                return(MonoRuntime.Default);
            }
            if (IsFullFramework)
            {
                return(ClrRuntime.GetCurrentVersion());
            }
            if (IsWasm)
            {
                return(WasmRuntime.Default);
            }
            if (IsNetCore)
            {
                return(CoreRuntime.GetCurrentVersion());
            }
            if (IsCoreRT)
            {
                return(CoreRtRuntime.GetCurrentVersion());
            }

            throw new NotSupportedException("Unknown .NET Runtime");
        }
        public void TryGetVersionFromRuntimeDirectoryHandlesValidInput(string runtimeDirectory, TargetFrameworkMoniker expectedTfm, string expectedMsBuildMoniker)
        {
            Assert.True(CoreRuntime.TryGetVersionFromRuntimeDirectory(runtimeDirectory, out Version version));

            var runtime = CoreRuntime.FromVersion(version);

            Assert.Equal(expectedTfm, runtime.TargetFrameworkMoniker);
            Assert.Equal(expectedMsBuildMoniker, runtime.MsBuildMoniker);
        }
        public void TryGetVersionFromFrameworkNameHandlesValidInput(string frameworkName, RuntimeMoniker expectedTfm, string expectedMsBuildMoniker)
        {
            Assert.True(CoreRuntime.TryGetVersionFromFrameworkName(frameworkName, out Version version));

            var runtime = CoreRuntime.FromVersion(version);

            Assert.Equal(expectedTfm, runtime.RuntimeMoniker);
            Assert.Equal(expectedMsBuildMoniker, runtime.MsBuildMoniker);
        }
        public void TryGetVersionFromProductInfoHandlesValidInput(TargetFrameworkMoniker expectedTfm, string expectedMsBuildMoniker, string productName, string productVersion)
        {
            Assert.True(CoreRuntime.TryGetVersionFromProductInfo(productVersion, productName, out Version version));

            var runtime = CoreRuntime.FromVersion(version);

            Assert.Equal(expectedTfm, runtime.TargetFrameworkMoniker);
            Assert.Equal(expectedMsBuildMoniker, runtime.MsBuildMoniker);
        }
Exemplo n.º 7
0
        public void CallingThreadPrincipal_WhenUserIsSet_DoesNotChange()
        {
            var currentThreadPrincipal = Thread.CurrentPrincipal;

            var runtime = new CoreRuntime(new RuntimeConfiguration());

            runtime.Execute(new ExecutionMetadata {
                JobType = typeof(TestJob).AssemblyQualifiedName, UserId = "bla"
            });

            Assert.AreEqual(currentThreadPrincipal, Thread.CurrentPrincipal);
        }
Exemplo n.º 8
0
        protected string GetTargetFrameworkMoniker()
        {
            if (!string.IsNullOrEmpty(targetFrameworkMoniker))
            {
                return(targetFrameworkMoniker);
            }
            if (!RuntimeInformation.IsNetCore)
            {
                throw new NotSupportedException("You must specify the target framework moniker in explicit way using builder.TargetFrameworkMoniker(tfm) method");
            }

            return(CoreRuntime.GetCurrentVersion().MsBuildMoniker);
        }
Exemplo n.º 9
0
        public ForkedRuntime(RuntimeConfiguration runtimeConfiguration)
        {
            if (runtimeConfiguration == null)
            {
                throw new ArgumentNullException(nameof(runtimeConfiguration));
            }

            this.coreRuntime = new CoreRuntime(runtimeConfiguration);

            // Wire Events to publish status
            this.coreRuntime.Initializing += (sender, args) => this.forkedExecutionRestClient.PublishState(JobRunState.Initializing);
            this.coreRuntime.Starting     += (sender, args) => this.forkedExecutionRestClient.PublishState(JobRunState.Processing);

            this.coreRuntime.Ended += this.CoreRuntimeOnEnded;
        }
Exemplo n.º 10
0
        public void ExecutingThreadPrincipal_WhenExecuting_CallbackIsCalled()
        {
            IPrincipal executingThreadPrincipal = null;

            RunCallBackTestJob.Callback = () => executingThreadPrincipal = Thread.CurrentPrincipal;

            var runtime = new CoreRuntime(new RuntimeConfiguration());

            runtime.Execute(new ExecutionMetadata {
                JobType = typeof(RunCallBackTestJob).AssemblyQualifiedName
            });

            RunCallBackTestJob.Reset();

            Assert.IsNotNull(executingThreadPrincipal);
        }
Exemplo n.º 11
0
        public void ExecutingThreadPrincipal_WhenUserIsSet_DoesChangePrincipal()
        {
            IPrincipal executingThreadPrincipal = null;

            RunCallBackTestJob.Callback = () => executingThreadPrincipal = Thread.CurrentPrincipal;

            var runtime = new CoreRuntime(new RuntimeConfiguration());

            runtime.Execute(new ExecutionMetadata {
                JobType = typeof(RunCallBackTestJob).AssemblyQualifiedName, UserId = "anything"
            });

            RunCallBackTestJob.Reset();

            Assert.AreNotEqual(executingThreadPrincipal.Identity.Name, Thread.CurrentPrincipal.Identity.Name);
        }
Exemplo n.º 12
0
        public void ConfigurableServiceProviderIsSet_WhenExecuting_RegistrationIsCalled()
        {
            var serviceProvider = new CustomActivator();

            var runtime = new CoreRuntime(new RuntimeConfiguration {
                ServiceProvider = serviceProvider
            });

            runtime.Execute(new ExecutionMetadata {
                JobType = typeof(TestJob).AssemblyQualifiedName
            });

            #pragma warning disable CS0618 // Type or member is obsolete
            Assert.AreEqual(1, serviceProvider.RegisteredInstances.OfType <RuntimeContext>().Count(), "There should be a single registration of the RuntimeContext");
            #pragma warning restore CS0618 // Type or member is obsolete
        }
Exemplo n.º 13
0
        public void ThreadPrincipal_InExecutingThread_AuthenticationTypeIsSet()
        {
            IPrincipal executingThreadPrincipal = null;

            RunCallBackTestJob.Callback = () => executingThreadPrincipal = Thread.CurrentPrincipal;
            var userName = "******";

            var runtime = new CoreRuntime(new RuntimeConfiguration());

            runtime.Execute(new ExecutionMetadata {
                JobType = typeof(RunCallBackTestJob).AssemblyQualifiedName, UserId = userName
            });

            RunCallBackTestJob.Reset();

            Assert.AreEqual("JobbrIdentity", executingThreadPrincipal.Identity.AuthenticationType);
        }
Exemplo n.º 14
0
        private static IConfig Create()
        {
            var net472 = Job.Default.WithRuntime(ClrRuntime.Net472).WithDefault().AsBaseline();
            var core21 = Job.Default.WithRuntime(CoreRuntime.Core21).WithDefault();
            var core31 = Job.Default.WithRuntime(CoreRuntime.Core31).WithDefault();
            var net50  = Job.Default.WithRuntime(CoreRuntime.CreateForNewVersion("net5.0", "NET 5.0")).WithDefault();

            return(new ManualConfig()
                   .AddLogger(DefaultConfig.Instance.GetLoggers().ToArray())
                   .AddAnalyser(DefaultConfig.Instance.GetAnalysers().ToArray())
                   .AddValidator(DefaultConfig.Instance.GetValidators().ToArray())
                   .AddColumnProvider(DefaultConfig.Instance.GetColumnProviders().Select(p => new FilteredColumnProvider(p)).ToArray())
                   .WithOptions(ConfigOptions.DisableLogFile)
                   .AddExporter(MarkdownExporter.GitHub)
                   .AddDiagnoser(MemoryDiagnoser.Default)
                   .WithArtifactsPath(@"..\..\..")
                   .AddJob(net472, core21, core31, net50));
        }
Exemplo n.º 15
0
        public void ConfigurableServiceProviderIsSet_WhenExecuting_ContextMatchesMetaInfo()
        {
            var serviceProvider = new CustomActivator();

            var userName    = "******";
            var userDisplay = "Schnyder, Michael";

            var runtime = new CoreRuntime(new RuntimeConfiguration {
                ServiceProvider = serviceProvider
            });

            runtime.Execute(new ExecutionMetadata {
                JobType = typeof(TestJob).AssemblyQualifiedName, UserId = userName, UserDisplayName = userDisplay
            });

            #pragma warning disable CS0618 // Type or member is obsolete
            var ctx = serviceProvider.RegisteredInstances.OfType <RuntimeContext>().Single();

            Assert.AreEqual(userName, ctx.UserId);
            Assert.AreEqual(userDisplay, ctx.UserDisplayName);
            #pragma warning restore CS0618 // Type or member is obsolete
        }
Exemplo n.º 16
0
        private static IConfig Create()
        {
            var net472 = Job.Default.WithRuntime(ClrRuntime.Net472).WithDefault().AsBaseline();
            var core21 = Job.Default.WithRuntime(CoreRuntime.Core21).WithDefault();
            var core31 = Job.Default.WithRuntime(CoreRuntime.Core31).WithDefault();

            // TODO: workaround, remove after BDN update released
            //var net50  = Job.Default.WithRuntime(CoreRuntime.CreateForNewVersion("net5.0", ".NET 5.0")).WithDefault();
            var net50 = Job.Default.WithRuntime(CoreRuntime.CreateForNewVersion("netcoreapp5.0", ".NET 5.0")).WithDefault();

            return(new ManualConfig()
                   .AddLogger(DefaultConfig.Instance.GetLoggers().ToArray())
                   .AddAnalyser(DefaultConfig.Instance.GetAnalysers().ToArray())
                   .AddValidator(DefaultConfig.Instance.GetValidators().ToArray())
                   .AddColumnProvider(DefaultConfig.Instance.GetColumnProviders().Select(p => new FilteredColumnProvider(p)).ToArray())
                   .WithOptions(ConfigOptions.DisableLogFile)
                   .AddExporter(MarkdownExporter.GitHub)
                   .AddDiagnoser(MemoryDiagnoser.Default)
                   .WithArtifactsPath(@"..\..\..")
                   // disable 2.1/3.1 for now to save time
                   .AddJob(net472 /*, core21*/, core31, net50));
        }
Exemplo n.º 17
0
 public DryCoreJobAttribute() : base(Job.Dry.With(CoreRuntime.GetCurrentVersion()))
 {
 }
 [InlineData("Microsoft .NET Framework", "4.6.26614.01 @BuiltBy: dlab14-DDVSOWINAGE018 @Commit: a536e7eec55c538c94639cefe295aa672996bf9b")] // this is an actual output for 2.0 but it simply does not contain enough info
 public void TryGetVersionFromProductInfoHandlesInvalidInput(string productName, string productVersion)
 {
     Assert.False(CoreRuntime.TryGetVersionFromProductInfo(productVersion, productName, out _));
 }
Exemplo n.º 19
0
 public CoreJobAttribute() : base(Job.Default.With(CoreRuntime.GetCurrentVersion()))
 {
 }
 public void TryGetVersionFromRuntimeDirectoryHandlesInvalidInput(string runtimeDirectory)
 {
     Assert.False(CoreRuntime.TryGetVersionFromRuntimeDirectory(runtimeDirectory, out _));
 }
 public void TryGetVersionFromFrameworkNameHandlesInvalidInput(string frameworkName)
 {
     Assert.False(CoreRuntime.TryGetVersionFromFrameworkName(frameworkName, out _));
 }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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!
        }