Ejemplo n.º 1
0
        internal static void SetupMocksForPost(ServiceContext serviceContext)
        {
            var mockMemberService = Mock.Get(serviceContext.MemberService);
            mockMemberService.Setup(x => x.GetById(It.IsAny<int>())).Returns(() => ModelMocks.SimpleMockedMember());
            mockMemberService.Setup(x => x.CreateMember(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
                .Returns(() => ModelMocks.SimpleMockedMember(8888));
            mockMemberService.Setup(x => x.CreateMember(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IMemberType>()))
               .Returns(() => ModelMocks.SimpleMockedMember(8888));

            var mockMemberTypeService = Mock.Get(serviceContext.MemberTypeService);
            mockMemberTypeService.Setup(x => x.Get(It.IsAny<string>())).Returns(ModelMocks.SimpleMockedMemberType());

            var mockDataTypeService = Mock.Get(serviceContext.DataTypeService);
            mockDataTypeService.Setup(x => x.GetPreValuesCollectionByDataTypeId(It.IsAny<int>())).Returns(new PreValueCollection(Enumerable.Empty<PreValue>()));

            var mockServiceProvider = new Mock<IServiceProvider>();
            mockServiceProvider.Setup(x => x.GetService(It.IsAny<Type>())).Returns(new ModelMocks.SimplePropertyEditor());

            Func<IEnumerable<Type>> producerList = Enumerable.Empty<Type>;
            var mockPropertyEditorResolver = new Mock<PropertyEditorResolver>(
                Mock.Of<IServiceProvider>(),
                Mock.Of<ILogger>(),
                producerList);

            mockPropertyEditorResolver.Setup(x => x.PropertyEditors).Returns(new[] { new ModelMocks.SimplePropertyEditor() });

            PropertyEditorResolver.Current = mockPropertyEditorResolver.Object;
        }
Ejemplo n.º 2
0
 public XmlRssHandler()
 {
     umbContext = UmbracoContext.Current;
     appContext = ApplicationContext.Current;
     services = appContext.Services;
     helper = new UmbracoHelper( umbContext );
 }
Ejemplo n.º 3
0
	    public virtual IBootManager Initialize()
		{
			if (_isInitialized)
				throw new InvalidOperationException("The boot manager has already been initialized");

	        InitializeProfilerResolver();

            _timer = DisposableTimer.DebugDuration<CoreBootManager>("Umbraco application starting", "Umbraco application startup complete");

			//create database and service contexts for the app context
			var dbFactory = new DefaultDatabaseFactory(GlobalSettings.UmbracoConnectionName);
		    Database.Mapper = new PetaPocoMapper();
			var dbContext = new DatabaseContext(dbFactory);
			var serviceContext = new ServiceContext(
				new PetaPocoUnitOfWorkProvider(dbFactory), 
				new FileUnitOfWorkProvider(), 
				new PublishingStrategy());

            CreateApplicationContext(dbContext, serviceContext);

            InitializeApplicationEventsResolver();

			InitializeResolvers();

            //initialize the DatabaseContext
            dbContext.Initialize();

            //now we need to call the initialize methods
            ApplicationEventsResolver.Current.ApplicationEventHandlers
                .ForEach(x => x.OnApplicationInitialized(UmbracoApplication, ApplicationContext));

			_isInitialized = true;

			return this;
		}
Ejemplo n.º 4
0
        public SystemSettingsTreeController()
        {
            Services = ApplicationContext.Current.Services;
            contentType_settings = Services.ContentTypeService.GetContentType("Setting");


        }
        protected override ApiController CreateController(Type controllerType, HttpRequestMessage msg, UmbracoHelper helper, ITypedPublishedContentQuery qry, ServiceContext serviceContext, BaseSearchProvider searchProvider)
        {
            _onServicesCreated(msg, helper.UmbracoContext, qry, serviceContext, searchProvider);

            //Create the controller with all dependencies
            var ctor = controllerType.GetConstructor(new[]
                {
                    typeof(UmbracoContext),
                    typeof(UmbracoHelper),
                    typeof(BaseSearchProvider)
                });

            if (ctor == null)
            {
                throw new MethodAccessException("Could not find the required constructor for the controller");
            }

            var created = (ApiController)ctor.Invoke(new object[]
                    {
                        //ctor args
                        helper.UmbracoContext,
                        helper,
                        searchProvider
                    });

            return created;
        }
Ejemplo n.º 6
0
 public void Can_Create_Service_Context()
 {
     var svcCtx = new ServiceContext(
         new Mock<IContentService>().Object,
         new Mock<IMediaService>().Object,
         new Mock<IContentTypeService>().Object,
         new Mock<IDataTypeService>().Object,
         new Mock<IFileService>().Object,
         new Mock<ILocalizationService>().Object,
         new PackagingService(
             new Mock<IContentService>().Object,
             new Mock<IContentTypeService>().Object,
             new Mock<IMediaService>().Object,
             new Mock<IDataTypeService>().Object,
             new Mock<IFileService>().Object,
             new Mock<ILocalizationService>().Object,
             new RepositoryFactory(true),
             new Mock<IDatabaseUnitOfWorkProvider>().Object),
         new Mock<IEntityService>().Object,
         new RelationService(
             new Mock<IDatabaseUnitOfWorkProvider>().Object,
             new RepositoryFactory(true),
             new Mock<IEntityService>().Object));
     Assert.Pass();
 }
Ejemplo n.º 7
0
    	/// <summary>
        /// Constructor
        /// </summary>        
        internal ApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext)
			:this()
    	{
    		if (dbContext == null) throw new ArgumentNullException("dbContext");
    		if (serviceContext == null) throw new ArgumentNullException("serviceContext");

			_databaseContext = dbContext;
			_services = serviceContext;			
    	}
Ejemplo n.º 8
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="dbContext"></param>
 /// <param name="serviceContext"></param>
 /// <param name="cache"></param>
 public ApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext, CacheHelper cache)
 {
     if (dbContext == null) throw new ArgumentNullException("dbContext");
     if (serviceContext == null) throw new ArgumentNullException("serviceContext");
     if (cache == null) throw new ArgumentNullException("cache");
     _databaseContext = dbContext;
     _services = serviceContext;
     ApplicationCache = cache;
 }
Ejemplo n.º 9
0
	    /// <summary>
	    /// A method used to create and ensure that a global ApplicationContext singleton is created.
	    /// </summary>
	    /// <param name="cache"></param>
	    /// <param name="replaceContext">
	    /// If set to true will replace the current singleton instance - This should only be used for unit tests or on app 
	    /// startup if for some reason the boot manager is not the umbraco boot manager.
	    /// </param>
	    /// <param name="dbContext"></param>
	    /// <param name="serviceContext"></param>
	    /// <returns></returns>
	    /// <remarks>
	    /// This is NOT thread safe 
	    /// </remarks>
	    public static ApplicationContext EnsureContext(DatabaseContext dbContext, ServiceContext serviceContext, CacheHelper cache, bool replaceContext)
        {
            if (ApplicationContext.Current != null)
            {
                if (!replaceContext)
                    return ApplicationContext.Current;
            }
            var ctx = new ApplicationContext(dbContext, serviceContext, cache);
            ApplicationContext.Current = ctx;
            return ApplicationContext.Current;
        }
Ejemplo n.º 10
0
        private void Activator(HttpRequestMessage httpRequestMessage, UmbracoContext umbracoContext, ITypedPublishedContentQuery arg3, ServiceContext serviceContext, BaseSearchProvider searchProvider)
        {
            _activator(httpRequestMessage, umbracoContext, arg3, serviceContext, searchProvider);

            Mapper.Initialize(configuration =>
            {
                var contentRepresentationMapper = new ContentModelMapper();
                contentRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);

                var mediaRepresentationMapper = new MediaModelMapper();
                mediaRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);

                var memberRepresentationMapper = new MemberModelMapper();
                memberRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);

                var relationRepresentationMapper = new RelationModelMapper();
                relationRepresentationMapper.ConfigureMappings(configuration, umbracoContext.Application);
            });
        }
Ejemplo n.º 11
0
 public Packaging(ServiceContext serviceContext)
 {
     _serviceContext = serviceContext;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AddMembershipTypeAndGroup"/> class.
 /// </summary>
 public AddMembershipTypeAndGroup()
 {
     _services = ApplicationContext.Current.Services;
 }
        IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            if (typeof(UmbracoApiControllerBase).IsAssignableFrom(controllerType))
            {
                var owinContext = request.GetOwinContext();

                //Create mocked services that we are going to pass to the callback for unit tests to modify
                // before passing these services to the main container objects
                var mockedTypedContent = Mock.Of<ITypedPublishedContentQuery>();
                var mockedContentService = Mock.Of<IContentService>();
                var mockedContentTypeService = Mock.Of<IContentTypeService>();
                var mockedMediaService = Mock.Of<IMediaService>();
                var mockedMemberService = Mock.Of<IMemberService>();
                var mockedTextService = Mock.Of<ILocalizedTextService>();
                var mockedDataTypeService = Mock.Of<IDataTypeService>();

                var serviceContext = new ServiceContext(
                    dataTypeService:mockedDataTypeService,
                    contentTypeService:mockedContentTypeService,
                    contentService: mockedContentService,
                    mediaService: mockedMediaService,
                    memberService: mockedMemberService,
                    localizedTextService: mockedTextService);

                //new app context
                var appCtx = ApplicationContext.EnsureContext(
                    new DatabaseContext(Mock.Of<IDatabaseFactory>(), Mock.Of<ILogger>(), Mock.Of<ISqlSyntaxProvider>(), "test"),
                    //pass in mocked services
                    serviceContext,
                    CacheHelper.CreateDisabledCacheHelper(),
                    new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()),
                    true);

                //httpcontext with an auth'd user
                var httpContext = Mock.Of<HttpContextBase>(http => http.User == owinContext.Authentication.User);
                //chuck it into the props since this is what MS does when hosted
                request.Properties["MS_HttpContext"] = httpContext;

                var backofficeIdentity = (UmbracoBackOfficeIdentity)owinContext.Authentication.User.Identity;

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

                //mock CurrentUser
                webSecurity.Setup(x => x.CurrentUser)
                    .Returns(Mock.Of<IUser>(u => u.IsApproved == true
                                                 && u.IsLockedOut == false
                                                 && u.AllowedSections == backofficeIdentity.AllowedApplications
                                                 && u.Email == "*****@*****.**"
                                                 && u.Id == (int)backofficeIdentity.Id
                                                 && u.Language == "en"
                                                 && u.Name == backofficeIdentity.RealName
                                                 && u.StartContentId == backofficeIdentity.StartContentNode
                                                 && u.StartMediaId == backofficeIdentity.StartMediaNode
                                                 && u.Username == backofficeIdentity.Username));

                //mock Validate
                webSecurity.Setup(x => x.ValidateCurrentUser())
                    .Returns(() => true);

                var umbCtx = UmbracoContext.EnsureContext(
                    //set the user of the HttpContext
                    httpContext,
                    appCtx,
                    webSecurity.Object,
                    Mock.Of<IUmbracoSettingsSection>(section => section.WebRouting == Mock.Of<IWebRoutingSection>(routingSection => routingSection.UrlProviderMode == UrlProviderMode.Auto.ToString())),
                    Enumerable.Empty<IUrlProvider>(),
                    true); //replace it

                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 membershipHelper = new MembershipHelper(umbCtx, Mock.Of<MembershipProvider>(), Mock.Of<RoleProvider>());

                var umbHelper = new UmbracoHelper(umbCtx,
                    Mock.Of<IPublishedContent>(),
                    mockedTypedContent,
                    Mock.Of<IDynamicPublishedContentQuery>(),
                    Mock.Of<ITagQuery>(),
                    Mock.Of<IDataTypeService>(),
                    new UrlProvider(umbCtx, new[]
                    {
                        urlHelper.Object
                    }, UrlProviderMode.Auto),
                    Mock.Of<ICultureDictionary>(),
                    Mock.Of<IUmbracoComponentRenderer>(),
                    membershipHelper);

                var searchProvider = Mock.Of<BaseSearchProvider>();

                return CreateController(controllerType, request, umbHelper, mockedTypedContent, serviceContext, searchProvider);
            }
            //default
            return base.Create(request, controllerDescriptor, controllerType);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FastTrackDataInstaller"/> class.
        /// </summary>
        public FastTrackDataInstaller()
        {
            _services = ApplicationContext.Current.Services;

            var templates = new[] { "ftProduct", "ftPayment", "ftPaymentMethod", "ftBillingAddress", "ftShipRateQuote", "ftShippingAddress", "ftChangePassword", "ftForgotPassword" };

            _templates = ApplicationContext.Current.Services.FileService.GetTemplates(templates);
        }
        private void Init(ServiceContext services, int sourceDataTypeId, int targetDataTypeId, bool updatePropertyTypes, bool publish, bool isTest)
        {
            this.Services = services;

            this.SourceDataTypeDefinition = services.DataTypeService.GetAllDataTypeDefinitions(sourceDataTypeId).FirstOrDefault();
            this.TargetDataTypeDefinition = services.DataTypeService.GetAllDataTypeDefinitions(targetDataTypeId).FirstOrDefault();

            this.IsTest = isTest;
            this.ShouldPublish = publish;
            this.ShouldUpdatePropertyTypes = updatePropertyTypes;

            this.AffectedContent = new List<AffectedContent>();

            this.AffectedDocTypes = new List<IContentType>();
            var parentDocTypes = new List<IContentType>();

            parentDocTypes.AddRange(services.ContentTypeService.GetAllContentTypes().Where(x => x.PropertyTypes.Where(y => y.DataTypeDefinitionId == sourceDataTypeId).Any()));

            //add their children
            foreach (var parentDocType in parentDocTypes)
            {
                this.AffectedDocTypes.AddRange(services.ContentTypeService.GetContentTypeChildren(parentDocType.Id));
            }

            //add in parents
            this.AffectedDocTypes.AddRange(parentDocTypes);

            foreach (var docType in this.AffectedDocTypes)
            {
                foreach (var content in services.ContentService.GetContentOfContentType(docType.Id).Where(x => !x.Trashed))
                {
                    foreach (var propertyType in content.PropertyTypes.Where(x => x.DataTypeDefinitionId == sourceDataTypeId))
                    {
                        this.AffectedContent.Add(new AffectedContent()
                        {
                            Content = content,
                            PropertyType = propertyType
                        });
                    }
                }
            }

            PropertyResults = new List<PropertyResult>();
        }
        private void SetupMocksForPost(ServiceContext serviceContext)
        {
            var mockRelationService = Mock.Get(serviceContext.RelationService);
            mockRelationService.Setup(x => x.GetRelationTypeByAlias(It.IsAny<string>())).Returns(() => ModelMocks.SimpleMockedRelationType());
            mockRelationService.Setup(x => x.GetById(It.IsAny<int>())).Returns(() => ModelMocks.SimpleMockedRelation(1234,567,8910));
            mockRelationService.Setup(x => x.Relate( It.IsAny<IUmbracoEntity>(), It.IsAny<IUmbracoEntity>(), It.IsAny<IRelationType>() ) )
                .Returns(() => ModelMocks.SimpleMockedRelation(1234, 567, 8910 ));

            var mockServiceProvider = new Mock<IServiceProvider>();
            mockServiceProvider.Setup(x => x.GetService(It.IsAny<Type>())).Returns(new ModelMocks.SimplePropertyEditor());

            Func<IEnumerable<Type>> producerList = Enumerable.Empty<Type>;
            var mockPropertyEditorResolver = new Mock<PropertyEditorResolver>(
                Mock.Of<IServiceProvider>(),
                Mock.Of<ILogger>(),
                producerList);

        }
 public DataTypeConverterBase()
 {
     Services = ApplicationContext.Current.Services;
 }
 public ConversionResult(ServiceContext services, int sourceDataTypeId, int targetDataTypeId, bool updatePropertyTypes, bool publish, bool isTest)
 {
     Init(services, sourceDataTypeId, targetDataTypeId, updatePropertyTypes, publish, isTest);
 }
 public void Configure(string connectionString, string providerName, string baseDirectory)
 {
     Trace.WriteLine("Current AppDomain: " + AppDomain.CurrentDomain.FriendlyName);
     Trace.WriteLine("Current AppDomain: " + AppDomain.CurrentDomain.BaseDirectory);
     _manager = new ServiceContextManager(connectionString, providerName, baseDirectory);
     _serviceContext = _manager.Services;
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="dbContext"></param>
 /// <param name="serviceContext"></param>
 /// <param name="enableCache"></param>
 public ApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext, bool enableCache)
     : this(enableCache)
 {
     _databaseContext = dbContext;
     _services = serviceContext;		
 }
Ejemplo n.º 21
0
 public WithdrawManagerTreeController()
 {
     Services = ApplicationContext.Services;
     contentType_settings = Services.ContentTypeService.GetContentType("WithdrawElement");
 }
Ejemplo n.º 22
0
 private static Template ImportTemplate(ServiceContext svces, string filepath, string name, string alias, string text, ITemplate master = null)
 {
     var t = new Template(filepath, name, alias) { Content = text };
     if (master != null)
         t.SetMasterTemplate(master);
     svces.FileService.SaveTemplate(t);
     return t;
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FastTrackDataInstaller"/> class.
        /// </summary>
        public FastTrackDataInstaller()
        {
            _services = ApplicationContext.Current.Services;

            var templates = new[] { "Product", "Payment", "PaymentMethod", "BillingAddress", "ShipRateQuote", "ShippingAddress" };

            _templates = ApplicationContext.Current.Services.FileService.GetTemplates(templates);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This will dispose and reset all resources used to run the application
        /// </summary>
        /// <remarks>
        /// IMPORTANT: Never dispose this object if you require the Umbraco application to run, disposing this object
        /// is generally used for unit testing and when your application is shutting down after you have booted Umbraco.
        /// </remarks>
        void IDisposable.Dispose()
        {
            // Only operate if we haven't already disposed
            if (_disposed) return;

            using (new WriteLock(_disposalLocker))
            {
                // Check again now we're inside the lock
                if (_disposed) return;

                //clear the cache
                if (ApplicationCache != null)
                {
                    ApplicationCache.ClearAllCache();    
                }
                //reset all resolvers
                ResolverCollection.ResetAll();
                //reset resolution itself (though this should be taken care of by resetting any of the resolvers above)
                Resolution.Reset();
                
                //reset the instance objects
                this.ApplicationCache = null;
                if (_databaseContext != null) //need to check the internal field here
                {
                    if (DatabaseContext.IsDatabaseConfigured)
                    {
                        DatabaseContext.Database.Dispose();       
                    }                    
                }
                this.DatabaseContext = null;
                this.Services = null;
                this._isReady = false; //set the internal field
                
                // Indicate that the instance has been disposed.
                _disposed = true;
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BazaarDataInstaller"/> class.
 /// </summary>
 public BazaarDataInstaller()
 {
     _services = ApplicationContext.Current.Services;
 }
Ejemplo n.º 26
0
 	/// <summary>
     /// Constructor
     /// </summary>        
     internal ApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext)
         : this(dbContext, serviceContext, true)
 	{
 			
 	}
Ejemplo n.º 27
0
 public ArticulateDataInstaller(ServiceContext services)
 {
     if (services == null) throw new ArgumentNullException(nameof(services));
     _services = services;
 }
Ejemplo n.º 28
0
		public UmbracoMediaService(ServiceContext services)
		{
			_services = services;
		}
Ejemplo n.º 29
0
 /// <summary>
 /// Creates and assigns the application context singleton
 /// </summary>
 /// <param name="dbContext"></param>
 /// <param name="serviceContext"></param>
 protected virtual void CreateApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext)
 {
     //create the ApplicationContext
     ApplicationContext = ApplicationContext.Current = new ApplicationContext(dbContext, serviceContext);
 }
 protected abstract ApiController CreateController(Type controllerType, HttpRequestMessage msg, UmbracoHelper helper, ITypedPublishedContentQuery qry, ServiceContext serviceContext, BaseSearchProvider searchProvider);