Ejemplo n.º 1
0
        public RoleProvider()
        {
            var container = ContextScopeProvider.CreateChildContainer();

            modulesRegistration = container.Resolve <IModulesRegistration>();
            unitOfWork          = container.Resolve <IUnitOfWork>();
        }
Ejemplo n.º 2
0
 private void Instance_MediaFileDeleted(SingleItemEventArgs <MediaFile> args)
 {
     try
     {
         var lifetimeScope = ContextScopeProvider.CreateChildContainer();
         if (!lifetimeScope.IsRegistered <ICmsConfiguration>())
         {
             throw new CmsApiException(string.Format("A '{0}' is unknown type in the Better CMS scope.", typeof(ICmsConfiguration).FullName));
         }
         var cmsConfiguration = lifetimeScope.Resolve <ICmsConfiguration>();
         if (cmsConfiguration.Storage.MoveDeletedFilesToTrash)
         {
             if (!lifetimeScope.IsRegistered <IMediaFileService>())
             {
                 throw new CmsApiException(string.Format("A '{0}' is unknown type in the Better CMS scope.", typeof(IMediaFileService).FullName));
             }
             var mediaFileService = lifetimeScope.Resolve <IMediaFileService>();
             mediaFileService.MoveFilesToTrashFolder();
         }
     }
     catch (Exception ex)
     {
         Log.Error("Failed to start up deleted media trash collector.", ex);
     }
 }
Ejemplo n.º 3
0
 public EncryptableString()
 {
     using (var container = ContextScopeProvider.CreateChildContainer())
     {
         encryptor = container.Resolve <ITextEncryptor>();
     }
 }
Ejemplo n.º 4
0
        public void RunMigrations(List <ModuleDescriptor> descriptors, IVersionChecker versionChecker = null)
        {
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                var assemblyLoader = container.Resolve <IAssemblyLoader>();

                if (versionChecker == null)
                {
                    var mock = new Mock <IVersionChecker>();
                    mock
                    .Setup(vc => vc.VersionExists(It.IsAny <string>(), It.IsAny <long>()))
                    .Returns <string, long>((s, l) => false);
                    versionChecker = mock.Object;
                }

                var configuration = new Mock <IConfiguration>();
                configuration
                .Setup(c => c.Database)
                .Returns(() => new DatabaseConfigurationElement
                {
                    ConnectionString = connectionString
                });

                var migrationRunner = new DefaultMigrationRunner(assemblyLoader, configuration.Object, versionChecker);
                migrationRunner.MigrateStructure(descriptors);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Loads available assemblies.
        /// </summary>
        internal static void LoadAssemblies()
        {
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                if (container == null)
                {
                    throw new CmsException("Better CMS dependencies container is not initialized.");
                }

                if (HostingEnvironment.IsHosted)
                {
                    HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedResourcesVirtualPathProvider(container.Resolve <IEmbeddedResourcesProvider>()));
                }

                ControllerBuilder.Current.SetControllerFactory(container.Resolve <DefaultCmsControllerFactory>());
                ViewEngines.Engines.Insert(0, new EmbeddedResourcesViewEngine());

                IAssemblyManager assemblyManager = container.Resolve <IAssemblyManager>();

                // First add referenced modules...
                assemblyManager.AddReferencedModules();

                // ...then scan and register uploaded modules.
                assemblyManager.AddUploadedModules();

                var moduleRegistration = container.Resolve <IModulesRegistration>();
                moduleRegistration.InitializeModules();
            }
        }
Ejemplo n.º 6
0
        public void Should_Refresh_Entity()
        {
            // Create entity
            var model = DatabaseTestDataProvider.ProvideRandomTestItemModel();

            Repository.Save(model);
            UnitOfWork.Commit();

            var version = model.Version;

            // Load attached and detached version, touch multiple times
            var detachedModel = Repository.First <TestItemModel>(model.Id);

            // Open another session
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                var repository2 = container.Resolve <IRepository>();
                var unitOfWork2 = container.Resolve <IUnitOfWork>();

                var attachedModel = repository2.First <TestItemModel>(model.Id);
                attachedModel.Name = TestDataProvider.ProvideRandomString();
                unitOfWork2.Commit();
            }

            Assert.AreEqual(detachedModel.Version, version);

            // Refresh detached entity - version should be updated
            Repository.Refresh(detachedModel);
            Assert.AreNotEqual(detachedModel.Version, version);
        }
Ejemplo n.º 7
0
        private void HostAuthenticateRequest(SingleItemEventArgs <HttpApplication> args)
        {
            if (Configuration.Users != null)
            {
                if (Configuration.Users.CreateDefaultUserOnStart)
                {
                    CheckIfIsFirstUserRegistered();

                    if (!isFirstUserRegistered)
                    {
                        using (var container = ContextScopeProvider.CreateChildContainer())
                        {
                            var registrationService = container.Resolve <IRegistrationService>();
                            registrationService.NavigateToRegisterFirstUserPage();
                        }
                    }
                }

                if (Configuration.Users.EnableCmsFormsAuthentication)
                {
                    using (var container = ContextScopeProvider.CreateChildContainer())
                    {
                        var registrationService = container.Resolve <IAuthenticationService>();
                        registrationService.AuthenticateRequest(args.Item);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void ShouldRegisterAndRetrieveService()
        {
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                Assert.IsNotNull(container);

                // Service is not registered yet
                bool exceptionWasThrown = false;
                try
                {
                    container.Resolve <ITestInterface>();
                }
                catch (ComponentNotRegisteredException)
                {
                    exceptionWasThrown = true;
                }
                Assert.IsTrue(exceptionWasThrown);
            }

            // Registering service
            var builder = new ContainerBuilder();

            builder.RegisterType <TestInterfaceImplementation>().As <ITestInterface>().SingleInstance();
            ContextScopeProvider.RegisterTypes(builder);

            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                var service = container.Resolve <ITestInterface>();

                Assert.IsNotNull(service);
                Assert.IsTrue(service is TestInterfaceImplementation);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates the data API.
        /// </summary>
        /// <typeparam name="TApiContext">The type of the API content.</typeparam>
        /// <returns></returns>
        public static TApiContext CreateApiContextOf <TApiContext>(ApiContext parentApiContext = null) where TApiContext : ApiContext
        {
            ILifetimeScope lifetimeScope;

            if (parentApiContext == null)
            {
                lifetimeScope = ContextScopeProvider.CreateChildContainer();
            }
            else
            {
                lifetimeScope = parentApiContext.GetLifetimeScope();
            }

            if (!lifetimeScope.IsRegistered <TApiContext>())
            {
                throw new CmsApiException(string.Format("A '{0}' type is unknown as Better CMS API context.", typeof(TApiContext).Name));
            }

            var apiContext = lifetimeScope.Resolve <TApiContext>(new Parameter[] { new PositionalParameter(0, lifetimeScope) });

            if (parentApiContext != null)
            {
                apiContext.MarkParentLifetimeScope();
            }

            return(apiContext);
        }
Ejemplo n.º 10
0
 private void ApplicationStart(SingleItemEventArgs <HttpApplication> args)
 {
     using (var container = ContextScopeProvider.CreateChildContainer())
     {
         var containerProvider = container.Resolve <PerWebRequestContainerProvider>();
         new WebApiApplicationHost(() => containerProvider.CurrentScope).Init();
     }
 }
Ejemplo n.º 11
0
 private void OnEntityDelete(SingleItemEventArgs <IEntity> args)
 {
     using (var container = ContextScopeProvider.CreateChildContainer())
     {
         var tracker = container.Resolve <IEntityTrackingService>();
         tracker.OnEntityDelete(args.Item);
     }
 }
Ejemplo n.º 12
0
        public void RegisterModule(ModuleDescriptor moduleDescriptor)
        {
            ContainerBuilder containerBuilder = new ContainerBuilder();

            ModuleRegistrationContext registrationContext = new ModuleRegistrationContext(moduleDescriptor);

            moduleDescriptor.RegisterModuleTypes(registrationContext, containerBuilder);
            moduleDescriptor.RegisterModuleCommands(registrationContext, containerBuilder);
            moduleDescriptor.RegisterModuleApiContexts(registrationContext, containerBuilder);
            moduleDescriptor.RegisterModuleControllers(registrationContext, containerBuilder, controllerExtensions);
            moduleDescriptor.RegisterCustomRoutes(registrationContext, containerBuilder);

            ContextScopeProvider.RegisterTypes(containerBuilder);

            knownModules.Add(moduleDescriptor.AreaName.ToLowerInvariant(), registrationContext);

            var jsModules = moduleDescriptor.RegisterJsIncludes();

            if (jsModules != null)
            {
                foreach (var jsModuleDescriptor in jsModules)
                {
                    knownJavaScriptModules.Add(jsModuleDescriptor.Name, jsModuleDescriptor);
                }
            }

            var userRoles = moduleDescriptor.RegisterUserRoles(containerBuilder);

            UpdateConcurrentBagWithEnumerator(knownUserRoles, userRoles);

            var sidebarHeadProjections = moduleDescriptor.RegisterSidebarHeaderProjections(containerBuilder);

            UpdateConcurrentBagWithEnumerator(knownSidebarHeadContentItems, sidebarHeadProjections);

            var sidebarSideProjections = moduleDescriptor.RegisterSidebarSideProjections(containerBuilder);

            UpdateConcurrentBagWithEnumerator(knownSidebarContentItems, sidebarSideProjections);

            var sidebarBodyProjections = moduleDescriptor.RegisterSidebarMainProjections(containerBuilder);

            UpdateConcurrentBagWithEnumerator(knownSidebarBodyContentItems, sidebarBodyProjections);

            var siteSettingsProjections = moduleDescriptor.RegisterSiteSettingsProjections(containerBuilder);

            UpdateConcurrentBagWithEnumerator(knownSiteSettingsItems, siteSettingsProjections);

            var styleSheetFiles = moduleDescriptor.RegisterCssIncludes();

            if (styleSheetFiles != null)
            {
                foreach (var styleSheetFile in styleSheetFiles)
                {
                    knownStyleSheetIncludes.Add(styleSheetFile);
                }
            }
        }
Ejemplo n.º 13
0
        private void DemandReadWriteRule(IAccessSecuredObject item)
        {
            // Do not demand access, if user set SaveUnsecured to true explicilty
            if (item.SaveUnsecured)
            {
                return;
            }

            try
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    var  unitOfWork = container.Resolve <IUnitOfWork>();
                    Type itemType;

                    if (item is IProxy)
                    {
                        itemType = item.GetType().BaseType;
                    }
                    else
                    {
                        itemType = item.GetType();
                    }

                    object securedObject;
                    if (!cacheService.GetEntity(itemType, item.Id, out securedObject))
                    {
                        securedObject = unitOfWork.Session.Get(itemType, item.Id);
                        cacheService.AddEntity(itemType, item.Id, securedObject);
                    }

                    if (securedObject != null)
                    {
                        var accessControlService = container.Resolve <IAccessControlService>();
                        var securityService      = container.Resolve <ISecurityService>();

                        var principal = securityService.GetCurrentPrincipal();

                        if (accessControlService.GetAccessLevel((IAccessSecuredObject)securedObject, principal) != AccessLevel.ReadWrite)
                        {
                            throw new ValidationException(
                                      () => string.Format(RootGlobalization.Validation_CurrentUserHasNoRightsToUpdateOrDelete_Message, principal.Identity.Name, item.Title),
                                      string.Format("Current user {0} has no rights to update or delete secured object {1}.", principal.Identity.Name, item));
                        }
                    }
                }
            }
            catch (ValidationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CmsException(string.Format("Failed to check an access level of current user for the record {0}.", item), ex);
            }
        }
Ejemplo n.º 14
0
        public void Should_Return_Correct_Controller_Messages()
        {
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                var controller = container.Resolve <SampleWebController>() as ICommandContext;

                Assert.IsNotNull(controller);
                Assert.IsNotNull(controller.Messages);
            }
        }
Ejemplo n.º 15
0
        private void RegisterModule(ModuleDescriptor moduleDescriptor)
        {
            ContainerBuilder containerBuilder = new ContainerBuilder();

            var registrationContext = moduleDescriptor.CreateRegistrationContext();

            RegisterModuleDescriptor(registrationContext, containerBuilder);
            ContextScopeProvider.RegisterTypes(containerBuilder);

            knownModules.Add(registrationContext.GetRegistrationName(), registrationContext);
        }
Ejemplo n.º 16
0
 private void OnEntitySave(EntitySavingEventArgs args)
 {
     using (var container = ContextScopeProvider.CreateChildContainer())
     {
         if (args.Session == null || args.Session.IsDirtyEntity(args.Entity))
         {
             var tracker = container.Resolve <IEntityTrackingService>();
             tracker.OnEntityUpdate(args.Entity);
         }
     }
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets a list of the roles that a specified user is in for the configured applicationName.
        /// </summary>
        /// <param name="username">The user to return a list of roles for.</param>
        /// <returns>
        /// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
        /// </returns>
        public override string[] GetRolesForUser(string username)
        {
            if (repository == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(GetRolesForUser(container.Resolve <IRepository>(), username));
                }
            }

            return(GetRolesForUser(repository, username));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Gets a list of all the roles for the configured applicationName.
        /// </summary>
        /// <returns>
        /// A string array containing the names of all the roles stored in the data source for the configured applicationName.
        /// </returns>
        public override string[] GetAllRoles()
        {
            if (repository == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(GetAllRoles(container.Resolve <IRepository>()));
                }
            }

            return(GetAllRoles(repository));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Finds the users in role.
        /// </summary>
        /// <param name="roleName">Name of the role.</param>
        /// <param name="userNameToMatch">The user name to match.</param>
        /// <returns></returns>
        public override string[] FindUsersInRole(string roleName, string userNameToMatch)
        {
            if (repository == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(FindUsersInRole(container.Resolve <IRepository>(), roleName, userNameToMatch));
                }
            }

            return(FindUsersInRole(repository, roleName, userNameToMatch));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the user name associated with the specified e-mail address.
        /// </summary>
        /// <param name="email">The e-mail address to search for.</param>
        /// <returns>
        /// The user name associated with the specified e-mail address. If no match is found, return null.
        /// </returns>
        public override string GetUserNameByEmail(string email)
        {
            if (userService == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(GetUserNameByEmail(container.Resolve <IUserService>(), email));
                }
            }

            return(GetUserNameByEmail(userService, email));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Removes a role from the data source for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to delete.</param>
        /// <param name="throwOnPopulatedRole">If true, throw an exception if <paramref name="roleName" /> has one or more members and do not delete <paramref name="roleName" />.</param>
        /// <returns>
        /// true if the role was successfully deleted; otherwise, false.
        /// </returns>
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            if (roleService == null || unitOfWork == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(DeleteRole(container.Resolve <IRoleService>(), container.Resolve <IUnitOfWork>(), roleName, throwOnPopulatedRole));
                }
            }

            return(DeleteRole(roleService, unitOfWork, roleName, throwOnPopulatedRole));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        /// </summary>
        /// <param name="username">The user name to search for.</param>
        /// <param name="roleName">The role to search in.</param>
        /// <returns>
        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        /// </returns>
        public override bool IsUserInRole(string username, string roleName)
        {
            if (repository == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(IsUserInRole(container.Resolve <IRepository>(), username, roleName));
                }
            }

            return(IsUserInRole(repository, username, roleName));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Verifies that the specified user name and password exist in the data source.
        /// </summary>
        /// <param name="username">The name of the user to validate.</param>
        /// <param name="password">The password for the specified user.</param>
        /// <returns>
        /// true if the specified username and password are valid; otherwise, false.
        /// </returns>
        public override bool ValidateUser(string username, string password)
        {
            if (authenticationService == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(ValidateUser(container.Resolve <IAuthenticationService>(), username, password));
                }
            }

            return(ValidateUser(authenticationService, username, password));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
        /// </summary>
        /// <param name="emailToMatch">The e-mail address to search for.</param>
        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex" /> is zero-based.</param>
        /// <param name="pageSize">The size of the page of results to return.</param>
        /// <param name="totalRecords">The total number of matched users.</param>
        /// <returns>
        /// A <see cref="T:System.Web.Security.MembershipUserCollection" /> collection that contains a page of <paramref name="pageSize" /><see cref="T:System.Web.Security.MembershipUser" /> objects beginning at the page specified by <paramref name="pageIndex" />.
        /// </returns>
        public override System.Web.Security.MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            if (userService == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(FindUsersByEmail(container.Resolve <IUserService>(), emailToMatch, pageIndex, pageSize, out totalRecords));
                }
            }

            return(FindUsersByEmail(userService, emailToMatch, pageIndex, pageSize, out totalRecords));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets a collection of all the users in the data source in pages of data.
        /// </summary>
        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex" /> is zero-based.</param>
        /// <param name="pageSize">The size of the page of results to return.</param>
        /// <param name="totalRecords">The total number of matched users.</param>
        /// <returns>
        /// A <see cref="T:System.Web.Security.MembershipUserCollection" /> collection that contains a page of <paramref name="pageSize" /><see cref="T:System.Web.Security.MembershipUser" /> objects beginning at the page specified by <paramref name="pageIndex" />.
        /// </returns>
        public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            if (userService == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(GetAllUsers(container.Resolve <IUserService>(), pageIndex, pageSize, out totalRecords));
                }
            }

            return(GetAllUsers(userService, pageIndex, pageSize, out totalRecords));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to search for in the data source.</param>
        /// <returns>
        /// true if the role name already exists in the data source for the configured applicationName; otherwise, false.
        /// </returns>
        public override bool RoleExists(string roleName)
        {
            if (repository == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(RoleExists(container.Resolve <IRepository>(), roleName));
                }
            }

            return(RoleExists(repository, roleName));
        }
        private void ApplicationStart(SingleItemEventArgs <HttpApplication> args)
        {
            Logger.Info("OnHostStart: preparing web api...");

            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                var containerProvider = container.Resolve <PerWebRequestContainerProvider>();
                new WebApiApplicationHost(() => containerProvider.CurrentScope).Init();
            }

            Logger.Info("OnHostStart: preparing web api completed.");
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Gets a list of users in the specified role for the configured applicationName.
        /// </summary>
        /// <param name="roleName">The name of the role to get the list of users for.</param>
        /// <returns>
        /// A string array containing the names of all the users who are members of the specified role for the configured applicationName.
        /// </returns>
        public override string[] GetUsersInRole(string roleName)
        {
            if (repository == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(GetUsersInRole(container.Resolve <IRepository>(), roleName));
                }
            }

            return(GetUsersInRole(repository, roleName));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
        /// </summary>
        /// <param name="username">The name of the user to get information for.</param>
        /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
        /// <returns>
        /// A <see cref="T:System.Web.Security.MembershipUser" /> object populated with the specified user's information from the data source.
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
        {
            if (userService == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(GetUser(container.Resolve <IUserService>(), username));
                }
            }

            return(GetUser(userService, username));
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Processes a request to update the password for a membership user.
        /// </summary>
        /// <param name="username">The user to update the password for.</param>
        /// <param name="oldPassword">The current password for the specified user.</param>
        /// <param name="newPassword">The new password for the specified user.</param>
        /// <returns>
        /// true if the password was updated successfully; otherwise, false.
        /// </returns>
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (authenticationService == null || unitOfWork == null)
            {
                using (var container = ContextScopeProvider.CreateChildContainer())
                {
                    return(ChangePassword(container.Resolve <IAuthenticationService>(), container.Resolve <IUnitOfWork>(), username, oldPassword, newPassword));
                }
            }

            return(ChangePassword(authenticationService, unitOfWork, username, oldPassword, newPassword));
        }