예제 #1
0
        public void BasicActionTest()
        {
            //Setup Application Contact with mocks. Sets ApplicaitonContext.Current
            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            //Setup UmbracoContext with mocks. Sets UmbracoContext.Current
            UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var controller = new BasicTestSurfaceController();
            var res        = controller.BasicTestAction();
            var model      = res.Model as object;

            Assert.IsNotNull(model);
        }
예제 #2
0
        public void BasicPublishedContent3Test()
        {
            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var test_name = "test";

            //using a helper that I made to setup common fields
            var mockContent = BasicHelpers.GetPublishedContentMock(test_name);

            //setup umbracohelper.assignedcontentitem by setting the publishedcontent request of the umbracocontext
            ctx.PublishedContentRequest = new PublishedContentRequest(new Uri("http://test.com"), ctx.RoutingContext,
                                                                      Mock.Of <IWebRoutingSection>(section => section.UrlProviderMode == UrlProviderMode.AutoLegacy.ToString()),
                                                                      s => new string[] { })
            {
                PublishedContent = mockContent.Object
            };

            var res   = new BasicTestSurfaceController().BasicPublishedContentAction();
            var model = res.Model as string;

            Assert.AreEqual(test_name, model);
        }
예제 #3
0
        public ContactUsTreeControllerTests()
        {
            var logger = Substitute.For <ILogger>();

            var dbContext = new DatabaseContext(
                Substitute.For <IDatabaseFactory>(),
                logger,
                new SqlSyntaxProviders(new ISqlSyntaxProvider[0])
                );

            var appContext = ApplicationContext.EnsureContext(
                dbContext,
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(logger, Substitute.For <IProfiler>()),
                true
                );

            var httpContext = Substitute.For <HttpContextBase>();

            UmbracoContext.EnsureContext(
                httpContext,
                appContext,
                new WebSecurity(httpContext, appContext),
                Substitute.For <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(),
                true
                );
        }
예제 #4
0
        public void BasicPublishedContent2Test()
        {
            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            //instead of using the implemenation of IPublishedContent, we mock IPublishedContent
            var mockContent = new Mock <IPublishedContent>();

            //We need to manually setup each field that is needed
            mockContent.Setup(s => s.Name).Returns("test");
            //give our content to the umbraco helper which will be given to the controller
            var helper = new UmbracoHelper(ctx, mockContent.Object);

            var controller = new BasicTestSurfaceController(ctx, helper);
            var res        = controller.BasicPublishedContentAction();
            var model      = res.Model as string;

            Assert.IsNotNull(mockContent.Object.Name, model);
        }
예제 #5
0
        public static void RenewLifeMembers()
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current ?? new HttpContext(new SimpleWorkerRequest("temp.aspx", "", new StringWriter())));

            var context = UmbracoContext.EnsureContext(httpContext, ApplicationContext.Current, new WebSecurity(httpContext, ApplicationContext.Current), UmbracoConfig.For.UmbracoSettings(), UrlProviderResolver.Current.Providers, false);


            DataManager dm          = new DataManager(context);
            var         memberships = dm.GetCurrentMemberships();

            foreach (var m in memberships)
            {
                if (m.MembershipType == MembershipType.Life && m.EndDate.Date == DateTime.UtcNow.Date)
                {
                    //create new membership for user
                    var newMembership = new Membership();
                    newMembership.Member         = m.Member;
                    newMembership.MembershipType = MembershipType.Life;
                    newMembership.IsSubscription = false;
                    newMembership.StartDate      = m.StartDate.AddYears(1);
                    newMembership.EndDate        = m.EndDate.AddYears(1);

                    dm.AddOrUpdateMembership(newMembership);
                }
            }
        }
        public void BasicApiCurrentUserTest()
        {
            var mockUser = new Mock <IUser>();

            var mockWebSerc = new Mock <WebSecurity>(null, null);

            mockWebSerc.Setup(s => s.CurrentUser).Returns(mockUser.Object);

            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                mockWebSerc.Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var controller = new BasicUmbracoApiController(); //don't really care about the helper here

            var model = controller.BasicUserAction();

            Assert.IsNotNull(model);
        }
예제 #7
0
        public ContextMocker(string[] qKeys = null)
        {
            ILogger     loggerMock   = Mock.Of <ILogger>();
            IProfiler   profilerMock = Mock.Of <IProfiler>();
            IDictionary dictionary   = Mock.Of <IDictionary>();// this is related to injecting the dictionary into the mocked UmbracoHelper

            var session         = new Mock <HttpSessionStateBase>();
            var contextBaseMock = new Mock <HttpContextBase>();

            contextBaseMock.Setup(ctx => ctx.Session).Returns(session.Object);
            contextBaseMock.SetupGet(ctx => ctx.Items).Returns(dictionary);//// this is related to injecting the dictionary into the mocked UmbracoHelper

            if (qKeys != null)
            {
                var requestMock = new Mock <HttpRequestBase>();
                requestMock.SetupGet(r => r.Url).Returns(new Uri("http://imaginary.com"));
                var mockedQstring = new Mock <NameValueCollection>();

                foreach (var k in qKeys)
                {
                    mockedQstring.Setup(r => r.Get(It.Is <string>(s => s.Contains(k)))).Returns("example_value_" + k);
                }

                requestMock.SetupGet(r => r.QueryString).Returns(mockedQstring.Object);
                contextBaseMock.SetupGet(p => p.Request).Returns(requestMock.Object);
            }

            WebSecurity             webSecurityMock            = new Mock <WebSecurity>(null, null).Object;
            IUmbracoSettingsSection umbracoSettingsSectionMock = Mock.Of <IUmbracoSettingsSection>();

            HttpContextBaseMock    = contextBaseMock.Object;
            ApplicationContextMock = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(loggerMock, profilerMock));
            UmbracoContextMock     = UmbracoContext.EnsureContext(contextBaseMock.Object, ApplicationContextMock, webSecurityMock, umbracoSettingsSectionMock, Enumerable.Empty <IUrlProvider>(), true);
        }
예제 #8
0
        public void BasicPublishedContent1Test()
        {
            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var test_name = "test";

            //create an instance of our test implemention of IPublisheContent
            var content = new TestPublishedContent()
            {
                Name = test_name
            };
            //setup a helper object which will be given to the surface controller
            var helper = new UmbracoHelper(ctx, content);
            //we use a surface controller that takes in th context and helper so that we can setup them for our needs
            var controller = new BasicTestSurfaceController(ctx, helper);
            var res        = controller.BasicPublishedContentAction();
            var model      = res.Model as string;

            Assert.AreEqual(test_name, model);
        }
예제 #9
0
        private UmbracoContext GetUmbracoContext()
        {
            try
            {
                if (HttpContext.Current == null || HttpContext.Current.Request == null)
                {
                    LogHelper.Info <ElasticPublishedContentMediaIndexer>(() => "Skipped creating UmbracoContext as HttpContext is unavailable.");
                    return(null);
                }

                LogHelper.Info <ElasticPublishedContentMediaIndexer>(() => "Creating new UmbracoContext using UmbracoContext.EnsureContext.");

                var httpContext = new HttpContextWrapper(HttpContext.Current);

                return(UmbracoContext.EnsureContext(httpContext,
                                                    ApplicationContext.Current,
                                                    new WebSecurity(httpContext, ApplicationContext.Current),
                                                    UmbracoConfig.For.UmbracoSettings(),
                                                    UrlProviderResolver.Current.Providers,
                                                    false));
            }
            catch (HttpException ex)
            {
                LogHelper.Error <ElasticPublishedContentMediaIndexer>("Skipped creating UmbracoContext as HttpContext is unavailable.", ex);
                return(null);
            }
        }
예제 #10
0
        public void Can_Mock_Umbraco_Helper_Get_Url()
        {
            var appCtx = new ApplicationContext(
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()));

            var umbCtx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(),
                true);

            var urlHelper = new Mock <IUrlProvider>();

            urlHelper.Setup(provider => provider.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <int>(), It.IsAny <Uri>(), It.IsAny <UrlProviderMode>()))
            .Returns("/hello/world/1234");

            var helper = new UmbracoHelper(umbCtx,
                                           Mock.Of <IPublishedContent>(),
                                           Mock.Of <ITypedPublishedContentQuery>(),
                                           Mock.Of <IDynamicPublishedContentQuery>(),
                                           Mock.Of <ITagQuery>(),
                                           Mock.Of <IDataTypeService>(),
                                           new UrlProvider(umbCtx, new[]
            {
                urlHelper.Object
            }, UrlProviderMode.Auto), Mock.Of <ICultureDictionary>(),
                                           Mock.Of <IUmbracoComponentRenderer>(),
                                           new MembershipHelper(umbCtx, Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>()));

            Assert.AreEqual("/hello/world/1234", helper.Url(1234));
        }
예제 #11
0
        public void Can_Lookup_Content()
        {
            var appCtx = new ApplicationContext(
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()));

            var umbCtx = UmbracoContext.EnsureContext(
                new Mock <HttpContextBase>().Object,
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
                Enumerable.Empty <IUrlProvider>(),
                true);

            var helper = new UmbracoHelper(
                umbCtx,
                Mock.Of <IPublishedContent>(),
                Mock.Of <ITypedPublishedContentQuery>(query => query.TypedContent(It.IsAny <int>()) ==
                                                      //return mock of IPublishedContent for any call to GetById
                                                      Mock.Of <IPublishedContent>(content => content.Id == 2)),
                Mock.Of <IDynamicPublishedContentQuery>(),
                Mock.Of <ITagQuery>(),
                Mock.Of <IDataTypeService>(),
                new UrlProvider(umbCtx, Enumerable.Empty <IUrlProvider>()),
                Mock.Of <ICultureDictionary>(),
                Mock.Of <IUmbracoComponentRenderer>(),
                new MembershipHelper(umbCtx, Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>()));

            var ctrl   = new TestSurfaceController(umbCtx, helper);
            var result = ctrl.GetContent(2) as PublishedContentResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Content.Id);
        }
예제 #12
0
        public void Can_Mock_Umbraco_Helper()
        {
            var appCtx = new ApplicationContext(
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>()));

            var umbCtx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(),
                true);

            var helper = new UmbracoHelper(umbCtx,
                                           Mock.Of <IPublishedContent>(),
                                           Mock.Of <ITypedPublishedContentQuery>(),
                                           Mock.Of <IDynamicPublishedContentQuery>(),
                                           Mock.Of <ITagQuery>(),
                                           Mock.Of <IDataTypeService>(),
                                           new UrlProvider(umbCtx, new[] { Mock.Of <IUrlProvider>() }, UrlProviderMode.Auto), Mock.Of <ICultureDictionary>(),
                                           Mock.Of <IUmbracoComponentRenderer>(),
                                           new MembershipHelper(umbCtx, Mock.Of <MembershipProvider>(), Mock.Of <RoleProvider>()));

            Assert.Pass();
        }
예제 #13
0
        public static void EnsureContext()
        {
            if (UmbracoContext.Current != null)
            {
                return;
            }

            var request     = new SimpleWorkerRequest("", "", "", null, new StringWriter());
            var httpContext = new HttpContextWrapper(new HttpContext(request));

            Mock <WebSecurity> webSecurity = new Mock <WebSecurity>(httpContext, ApplicationContext.Current);
            var currentUser = Mock.Of <IUser>(u =>
                                              u.IsApproved &&
                                              u.Name == Utility.RandomString() &&
                                              u.Id == Utility.CurrentUserId);

            webSecurity.Setup(x => x.CurrentUser).Returns(currentUser);

            UmbracoContext.EnsureContext(
                httpContext,
                ApplicationContext.Current,
                webSecurity.Object,
                UmbracoConfig.For.UmbracoSettings(),
                Mock.Of <IEnumerable <IUrlProvider> >(),
                false);
        }
예제 #14
0
        public void Setup()
        {
            var settings = SettingsForTests.GenerateMockSettings();

            SettingsForTests.ConfigureSettings(settings);

            var logger = Mock.Of <ILogger>();

            var applicationContext = ApplicationContext.EnsureContext(
                new DatabaseContext(
                    Mock.Of <IDatabaseFactory>(),
                    logger,
                    new SqlSyntaxProviders(new ISqlSyntaxProvider[0])
                    ),
                new ServiceContext(
                    contentService: Mock.Of <IContentService>() //, ...
                    ),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(logger, Mock.Of <IProfiler>()),
                true
                );

            var httpContext = Mock.Of <HttpContextBase>();

            umbracoContext = UmbracoContext.EnsureContext(
                httpContext,
                applicationContext,
                new WebSecurity(httpContext, applicationContext),
                settings,
                new List <IUrlProvider>(),
                true,
                false
                );
        }
        public void Matches_Default_Index()
        {
            var globalSettings = TestObjects.GetGlobalSettings();
            var attr           = new RenderIndexActionSelectorAttribute();
            var req            = new RequestContext();
            //var appCtx = new ApplicationContext(
            //    CacheHelper.CreateDisabledCacheHelper(),
            //    new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()));
            var umbCtx = UmbracoContext.EnsureContext(
                Current.UmbracoContextAccessor,
                Mock.Of <HttpContextBase>(),
                Mock.Of <IPublishedSnapshotService>(),
                new Mock <WebSecurity>(null, null, globalSettings).Object,
                TestObjects.GetUmbracoSettings(),
                Enumerable.Empty <IUrlProvider>(),
                globalSettings,
                new TestVariationContextAccessor(),
                true);
            var ctrl = new MatchesDefaultIndexController {
                UmbracoContext = umbCtx
            };
            var controllerCtx = new ControllerContext(req, ctrl);
            var result        = attr.IsValidForRequest(controllerCtx,
                                                       GetRenderMvcControllerIndexMethodFromCurrentType(ctrl.GetType()));

            Assert.IsTrue(result);
        }
예제 #16
0
        private static void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            IContent doc = e.PublishedEntities.First();
            ILog     log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            // we might want to cancel the publish event if it came from a scheduled publish
            // we can check if the node has an active workflow, in which case it should not publish, and it's likely from the scheduler
            // if the publish is scheduled, there is no httpContext

            try
            {
                // if a context exists, sweet, let it go
                if (null != HttpContext.Current)
                {
                    return;
                }

                // ensure we have http context for queries
                HttpContext httpContext = new HttpContext(
                    new HttpRequest(string.Empty, "http://tempuri.org", string.Empty),
                    new HttpResponse(new StringWriter()));

                HttpContextBase httpContextBase = new HttpContextWrapper(httpContext);

                UmbracoContext.EnsureContext(
                    httpContextBase,
                    ApplicationContext.Current,
                    new WebSecurity(httpContextBase, ApplicationContext.Current),
                    UmbracoConfig.For.UmbracoSettings(),
                    UrlProviderResolver.Current.Providers,
                    false);

                var instancesService = new InstancesService();
                IEnumerable <WorkflowInstancePoco> instances = instancesService.GetForNodeByStatus(doc.Id, new List <int>
                {
                    (int)WorkflowStatus.PendingApproval,
                    (int)WorkflowStatus.Rejected,
                    (int)WorkflowStatus.Resubmitted
                });

                List <WorkflowInstancePoco> orderedInstances = instances.OrderByDescending(i => i.CompletedDate).ToList();

                // if any incomplete workflows exists, cancel the publish
                // this will clear the release date, which is ok as it has passed
                // and the change will be released when the workflow completes
                if (!orderedInstances.Any())
                {
                    return;
                }

                e.Cancel = true;

                log.Info($"Scheduled publish for {doc.Name} cancelled due to active workflow");
            }
            catch (Exception ex)
            {
                log.Error($"Error in scheduled publish validation for {doc.Name}", ex);
            }
        }
예제 #17
0
        private static UmbracoContext CreateUmbracoContext()
        {
            var context = HttpContext.Current != null ? HttpContext.Current : new HttpContext(new HttpRequest("", "http://localhost/", ""), new HttpResponse(null));
            var result  = UmbracoContext.EnsureContext(new HttpContextWrapper(context),
                                                       ApplicationContext.Current);

            return(result);
        }
예제 #18
0
        // can't create context before resolution is frozen!
        protected override void FreezeResolution()
        {
            base.FreezeResolution();

            var httpContext = new StandaloneHttpContext();

            UmbracoContext.EnsureContext(httpContext, ApplicationContext.Current);
        }
예제 #19
0
        public void EnsureUmbracoContext()
        {
            var appContext = ApplicationContext.EnsureContext(new DatabaseContext(Moq.Mock.Of <IDatabaseFactory2>(), Moq.Mock.Of <ILogger>(),
                                                                                  new SqlSyntaxProviders(new[] { Moq.Mock.Of <ISqlSyntaxProvider>() })), new ServiceContext(), CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(
                                                                  Moq.Mock.Of <ILogger>(), Moq.Mock.Of <IProfiler>()), true);

            var context = UmbracoContext.EnsureContext(Moq.Mock.Of <HttpContextBase>(), appContext, new Mock <WebSecurity>(null, null).Object, Moq.Mock.Of <IUmbracoSettingsSection>(),
                                                       Enumerable.Empty <IUrlProvider>(), true);
        }
예제 #20
0
 public Global()
 {
     //we don't want to put the Umbraco module in, but we need to ensure an UmbracoContext on each request,
     // so we'll chuck it in here for now.
     this.BeginRequest += (sender, args) =>
     {
         var httpContext = ((HttpApplication)sender).Context;
         UmbracoContext.EnsureContext(new HttpContextWrapper(httpContext), ApplicationContext.Current);
     };
 }
        /// <summary>
        /// Gets an Umbraco Context instance for non pipeline requiests.
        /// </summary>
        /// <returns>The <see cref="UmbracoContext"/></returns>
        private UmbracoContext EnsureUmbracoContext()
        {
            HttpContextBase            context         = this.HttpContext;
            ApplicationContext         application     = ApplicationContext.Current;
            WebSecurity                security        = new WebSecurity(context, application);
            IUmbracoSettingsSection    umbracoSettings = UmbracoConfig.For.UmbracoSettings();
            IEnumerable <IUrlProvider> providers       = UrlProviderResolver.Current.Providers;

            return(UmbracoContext.EnsureContext(context, application, security, umbracoSettings, providers, false));
        }
 private static UmbracoContext MockUmbracoContext(ApplicationContext appCtx)
 {
     return(UmbracoContext.EnsureContext(
                new Mock <HttpContextBase>().Object,
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
                Enumerable.Empty <IUrlProvider>(),
                true));
 }
        public void ParseLocalLinks(string input, string result)
        {
            var serviceCtxMock = new TestObjects(null).GetServiceContextMock();

            //setup a mock entity service from the service context to return an integer for a GUID
            var entityService = Mock.Get(serviceCtxMock.EntityService);
            //entityService.Setup(x => x.GetId(It.IsAny<Guid>(), It.IsAny<UmbracoObjectTypes>()))
            //    .Returns((Guid id, UmbracoObjectTypes objType) =>
            //    {
            //        return Attempt.Succeed(1234);
            //    });

            //setup a mock url provider which we'll use fo rtesting
            var testUrlProvider = new Mock <IUrlProvider>();

            testUrlProvider
            .Setup(x => x.GetUrl(It.IsAny <UmbracoContext>(), It.IsAny <IPublishedContent>(), It.IsAny <UrlProviderMode>(), It.IsAny <string>(), It.IsAny <Uri>()))
            .Returns((UmbracoContext umbCtx, IPublishedContent content, UrlProviderMode mode, string culture, Uri url) => UrlInfo.Url("/my-test-url"));

            var globalSettings = SettingsForTests.GenerateMockGlobalSettings();

            var contentType      = new PublishedContentType(666, "alias", PublishedItemType.Content, Enumerable.Empty <string>(), Enumerable.Empty <PublishedPropertyType>(), ContentVariation.Nothing);
            var publishedContent = Mock.Of <IPublishedContent>();

            Mock.Get(publishedContent).Setup(x => x.Id).Returns(1234);
            Mock.Get(publishedContent).Setup(x => x.ContentType).Returns(contentType);
            var contentCache = Mock.Of <IPublishedContentCache>();

            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <int>())).Returns(publishedContent);
            Mock.Get(contentCache).Setup(x => x.GetById(It.IsAny <Guid>())).Returns(publishedContent);
            var snapshot = Mock.Of <IPublishedSnapshot>();

            Mock.Get(snapshot).Setup(x => x.Content).Returns(contentCache);
            var snapshotService = Mock.Of <IPublishedSnapshotService>();

            Mock.Get(snapshotService).Setup(x => x.CreatePublishedSnapshot(It.IsAny <string>())).Returns(snapshot);

            using (var umbCtx = UmbracoContext.EnsureContext(
                       Umbraco.Web.Composing.Current.UmbracoContextAccessor,
                       Mock.Of <HttpContextBase>(),
                       snapshotService,
                       new Mock <WebSecurity>(null, null, globalSettings).Object,
                       //setup a quick mock of the WebRouting section
                       Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of <IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == "AutoLegacy")),
                       //pass in the custom url provider
                       new[] { testUrlProvider.Object },
                       globalSettings,
                       new TestVariationContextAccessor(),
                       true))
            {
                var output = TemplateUtilities.ParseInternalLinks(input, umbCtx.UrlProvider);

                Assert.AreEqual(result, output);
            }
        }
예제 #24
0
        private void Setup()
        {
            ILogger                 loggerMock                 = Mock.Of <ILogger>();
            IProfiler               profilerMock               = Mock.Of <IProfiler>();
            HttpContextBase         contextBaseMock            = Mock.Of <HttpContextBase>();
            WebSecurity             webSecurityMock            = new Mock <WebSecurity>(null, null).Object;
            IUmbracoSettingsSection umbracoSettingsSectionMock = Mock.Of <IUmbracoSettingsSection>();

            ApplicationContext.Current = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(loggerMock, profilerMock));
            UmbracoContext.Current     = UmbracoContext.EnsureContext(contextBaseMock, ApplicationContext.Current, webSecurityMock, umbracoSettingsSectionMock, Enumerable.Empty <IUrlProvider>(), true);
        }
예제 #25
0
        private static UmbracoContext CreateUmbracoContext()
        {
            var context            = HttpContext.Current ?? new HttpContext(new HttpRequest("", "http://localhost/", ""), new HttpResponse(null));
            var httpContextWrapper = new HttpContextWrapper(context);
            var umbracoSettings    = UmbracoConfig.For.UmbracoSettings();
            var urlProvider        = UrlProviderResolver.Current.Providers;
            var webSecurity        = new WebSecurity(httpContextWrapper, ApplicationContext.Current);
            var result             = UmbracoContext.EnsureContext(httpContextWrapper, ApplicationContext.Current, webSecurity, umbracoSettings, urlProvider, false);

            return(result);
        }
        public void BasicCurrentUserTest()
        {
            var routeData = new RouteData();

            var mockUser = new Mock <IUser>();

            var mockWebSerc = new Mock <WebSecurity>(null, null);

            mockWebSerc.Setup(s => s.CurrentUser).Returns(mockUser.Object);

            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                mockWebSerc.Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var content = new Mock <IPublishedContent>();

            content.Setup(s => s.Name).Returns("test");

            ctx.PublishedContentRequest = new PublishedContentRequest(new Uri("http://test.com"), ctx.RoutingContext,
                                                                      Mock.Of <IWebRoutingSection>(section => section.UrlProviderMode == UrlProviderMode.AutoLegacy.ToString()),
                                                                      s => new string[] { })
            {
                PublishedContent = content.Object
            };

            //The reoute definition will contain the current page request object and be passed into the route data
            var routeDefinition = new RouteDefinition
            {
                PublishedContentRequest = ctx.PublishedContentRequest
            };

            //We create a route data object to be given to the Controller context
            routeData.DataTokens.Add(UmbConstants.Web.PublishedDocumentRequestDataToken, ctx.PublishedContentRequest);

            var controller = new BasicRenderMvcController(ctx, new UmbracoHelper(ctx)); //don't really care about the helper here

            controller.ControllerContext = new System.Web.Mvc.ControllerContext(ctx.HttpContext, routeData, controller);

            var res   = controller.BasicGetSecurityAction() as PartialViewResult;
            var model = res.Model as IUser;

            Assert.IsNotNull(model);
        }
예제 #27
0
        internal UmbracoContext GetUmbracoContext()
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current ?? new HttpContext(new SimpleWorkerRequest("temp.aspx", "", new StringWriter())));

            return(UmbracoContext.EnsureContext(
                       httpContext,
                       ApplicationContext.Current,
                       new WebSecurity(httpContext, ApplicationContext.Current),
                       UmbracoConfig.For.UmbracoSettings(),
                       UrlProviderResolver.Current.Providers,
                       false));
        }
예제 #28
0
        private static void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs <IContent> e)
        {
            IContent doc = e.PublishedEntities.First();

            // we might want to cancel the publish event if it came from a scheduled publish
            // we can check if the node has an active workflow, in which case it should not publish, and it's likely from the scheduler
            // if the publish is scheduled, there is no httpContext

            try
            {
                // if a context exists, sweet, let it go
                if (null != HttpContext.Current)
                {
                    return;
                }

                // ensure we have http context for queries
                HttpContext httpContext = new HttpContext(
                    new HttpRequest(string.Empty, "http://tempuri.org", string.Empty),
                    new HttpResponse(new StringWriter()));

                HttpContextBase httpContextBase = new HttpContextWrapper(httpContext);

                UmbracoContext.EnsureContext(
                    httpContextBase,
                    ApplicationContext.Current,
                    new WebSecurity(httpContextBase, ApplicationContext.Current),
                    UmbracoConfig.For.UmbracoSettings(),
                    UrlProviderResolver.Current.Providers,
                    false);

                var pr = new PocoRepository();
                List <WorkflowInstancePoco> instances = pr.InstancesByNodeAndStatus(doc.Id, new List <int>
                {
                    (int)WorkflowStatus.PendingApproval,
                    (int)WorkflowStatus.Rejected,
                    (int)WorkflowStatus.Resubmitted
                })
                                                        .OrderByDescending(i => i.CompletedDate).ToList();

                // if any incomplete workflows exists, cancel the publish
                // this will clear the release date, which is ok as it has passed
                // and the change will be released when the workflow completes
                if (instances.Any())
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }
예제 #29
0
 private void OnBeginRequest(object sender, EventArgs e)
 {
     UmbracoContext.EnsureContext(
         new HttpContextWrapper(HttpContext.Current),
         ApplicationContext.EnsureContext(
             new DatabaseContext(new FakeDatabaseFactory()),
             new ServiceContext(null, null, null, null, null, null, null, null, null, null, null, null, null),
             new CacheHelper(),
             true
             )
         );
 }
예제 #30
0
        public void BasicCurrentPageTest()
        {
            var appCtx = ApplicationContext.EnsureContext(
                new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })),
                new ServiceContext(),
                CacheHelper.CreateDisabledCacheHelper(),
                new ProfilingLogger(
                    Mock.Of <ILogger>(),
                    Mock.Of <IProfiler>()), true);

            var ctx = UmbracoContext.EnsureContext(
                Mock.Of <HttpContextBase>(),
                appCtx,
                new Mock <WebSecurity>(null, null).Object,
                Mock.Of <IUmbracoSettingsSection>(),
                Enumerable.Empty <IUrlProvider>(), true);

            var contentMock = new Mock <IPublishedContent>();

            contentMock.Setup(s => s.Name).Returns("test");

            var content = contentMock.Object;

            //setup published content request. This sets the current content on the Umbraco Context and will be used later
            ctx.PublishedContentRequest = new PublishedContentRequest(new Uri("http://test.com"), ctx.RoutingContext,
                                                                      Mock.Of <IWebRoutingSection>(section => section.UrlProviderMode == UrlProviderMode.AutoLegacy.ToString()),
                                                                      s => new string[] { })
            {
                PublishedContent = content
            };

            //The reoute definition will contain the current page request object and be passed into the route data
            var routeDefinition = new RouteDefinition
            {
                PublishedContentRequest = ctx.PublishedContentRequest
            };

            //We create a route data object to be given to the Controller context
            var routeData = new RouteData();

            routeData.DataTokens.Add("umbraco-route-def", routeDefinition);

            var controller = new BasicTestSurfaceController();

            //Setting the controller context will provide the route data, route def, publushed content request, and current page to the surface controller
            controller.ControllerContext = new System.Web.Mvc.ControllerContext(ctx.HttpContext, routeData, controller);

            var res   = controller.BasicCurrentPageAction();
            var model = res.Model as string;

            Assert.AreEqual(content.Name, model);
        }