protected override void PopulateFileContentFromStub(FileEditorModel model, HiveId stubFileId, IDictionary <string, string> replacements)
        {
            var parentId = model.ParentId;

            model.ParentId = FixedHiveIds.SystemRoot;

            replacements = new Dictionary <string, string> {
                { "$layout$", "" }, { "$sections$", "" }
            };

            if (!stubFileId.IsNullValueOrEmpty())
            {
                if (!parentId.IsNullValueOrEmpty() && parentId != FixedHiveIds.SystemRoot)
                {
                    using (var uow = Hive.Create())
                    {
                        var parentFile = uow.Repositories.Get <File>(parentId);
                        if (parentFile == null)
                        {
                            throw new ArgumentException("No file could be found for the parent id specified");
                        }

                        replacements["$layout$"]   = parentFile.Name;
                        replacements["$sections$"] = new TemplateParser().Parse(parentFile).Sections.Where(x => x != "Body")
                                                     .Aggregate("", (current, section) => current + ("\n@section " + section + "\n{\n\n}\n"));
                    }
                }
            }

            base.PopulateFileContentFromStub(model, stubFileId, replacements);
        }
Ejemplo n.º 2
0
        public IEnumerable <PermissionStatusResult> GetPermissionStatuses(IEnumerable <HiveId> userGroupIds, HiveId entityId, params Guid[] permissionIds)
        {
            var entityHive = Hive.GetReader <ISecurityStore>(new Uri("security://user-groups"));

            using (var uow = entityHive.CreateReadonly())
            {
                foreach (var permissionId in permissionIds)
                {
                    // Get the permission reference
                    if (!_permissions.Exists(permissionId))
                    {
                        throw new InvalidOperationException("Unable to find a Permission with the id '" + permissionId + "'");
                    }

                    // If value is null, or permission is not an entity permission, just use the system root
                    if (entityId.IsNullValueOrEmpty() || _permissions.Single(x => x.Metadata.Id == permissionId).Metadata.Type != FixedPermissionTypes.EntityAction)
                    {
                        entityId = FixedHiveIds.SystemRoot;
                    }

                    var source = HiveId.Empty;
                    var result = GetPermissionStatus(permissionId, userGroupIds, entityId, out source, uow);
                    yield return(new PermissionStatusResult(source, result, permissionId));
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets a list of UserGroup ids that the specified User belongs to.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        protected IEnumerable <HiveId> GetUserGroupIdsForUser(HiveId userId)
        {
            return(Hive.FrameworkContext.ScopedCache.GetOrCreateTyped("ss_GetUserGroupIdsForUser_" + userId,
                                                                      () =>
            {
                var hive = Hive.GetReader <ISecurityStore>(new Uri("security://user-groups"));
                using (var uow = hive.CreateReadonly())
                {
                    if (!userId.IsNullValueOrEmpty())
                    {
                        // Valid hive id, so go find any related user groups
                        return uow.Repositories.GetParentRelations(userId, FixedRelationTypes.UserGroupRelationType)
                        .Select(x => x.SourceId)
                        .ToList();
                    }

                    // Empty hive id, so assume anonymous user
                    var id = uow.Repositories.QueryContext.Query <UserGroup>()
                             .Where(x => x.Name == "Anonymous")
                             .ToList() // Currently have to call ToList before select, as QueryContext can't handly the type change right now (2011/10/28)
                             .Select(x => x.Id);

                    return id;
                }
            }));
        }
Ejemplo n.º 4
0
        public PermissionResult GetExplicitPermission(Guid permissionId, IEnumerable <HiveId> userGroupIds, IReadonlyGroupUnit <ISecurityStore> securityUow, HiveId entityId = default(HiveId))
        {
            Mandate.ParameterNotNull(userGroupIds, "userGroupIds");

            //get/store the result in scoped cache

            var ids = userGroupIds.ToList();

            ids.Sort((id1, id2) => id1.ToString().CompareTo(id2.ToString())); // Sort the list of ids so that the cache key is the same regardless of order of passed in collection

            var key = "explicit-permission-" + (permissionId.ToString("N") + string.Join("", ids.Select(x => x.ToString())) + entityId).ToMd5();

            return(Hive.FrameworkContext.ScopedCache.GetOrCreateTyped <PermissionResult>(key, () =>
            {
                // Get the permission reference
                if (!_permissions.Exists(permissionId))
                {
                    throw new InvalidOperationException("Unable to find a Permission with the id '" + permissionId + "'");
                }

                // If value is null, or permission is not an entity permission, just use the system root
                if (entityId.IsNullValueOrEmpty() || _permissions.Single(x => x.Metadata.Id == permissionId).Metadata.Type != FixedPermissionTypes.EntityAction)
                {
                    entityId = FixedHiveIds.SystemRoot;
                }

                HiveId source;
                var status = GetPermissionStatus(permissionId, ids, entityId, out source, securityUow);
                return new PermissionResult(_permissions.Get(permissionId).Value, source, status);
            }));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets the parent relations
        /// </summary>
        /// <param name="childId"></param>
        /// <param name="relationType"></param>
        /// <returns></returns>
        public IEnumerable <IRelationById> PeformGetParentRelations(HiveId childId, RelationType relationType = null)
        {
            var key = ScopedCacheKey + "PeformGetParentRelations-" +
                      (childId.Value + (relationType != null ? relationType.RelationName : "")).ToMd5();

            return(GetOrCreateFromScopedCache <IEnumerable <IRelationById> >(key, () =>
            {
                if (childId.IsNullValueOrEmpty())
                {
                    return Enumerable.Empty <RelationById>();
                }

                //lookup all relations with this destination
                var criteria = ExamineManager.CreateSearchCriteria()
                               .Must().Field(LuceneIndexer.IndexCategoryFieldName, "Relation".Escape())
                               .Must().HiveId(childId, FixedRelationIndexFields.DestinationId);

                if (relationType != null)
                {
                    criteria = criteria
                               .Must().Field(FixedRelationIndexFields.RelationType, relationType.RelationName.Escape());
                }

                var result = ExamineManager.Search(criteria.Compile());
                //NOTE: This isn't lazy since we need to store a real object in cache but with Lucene, we already have the results
                return result.Select(x => _frameworkContext.TypeMappers.Map <SearchResult, IRelationById>(x)).ToArray();
            }));
        }
Ejemplo n.º 6
0
        public PermissionResult GetExplicitPermission(Guid permissionId, IEnumerable<HiveId> userGroupIds, IReadonlyGroupUnit<ISecurityStore> securityUow, HiveId entityId = default(HiveId))
        {
            Mandate.ParameterNotNull(userGroupIds, "userGroupIds");

            //get/store the result in scoped cache

            var ids = userGroupIds.ToList();
            ids.Sort((id1, id2) => id1.ToString().CompareTo(id2.ToString())); // Sort the list of ids so that the cache key is the same regardless of order of passed in collection

            var key = "explicit-permission-" + (permissionId.ToString("N") + string.Join("", ids.Select(x => x.ToString())) + entityId).ToMd5();

            return Hive.FrameworkContext.ScopedCache.GetOrCreateTyped<PermissionResult>(key, () =>
            {
                // Get the permission reference
                if (!_permissions.Exists(permissionId))
                    throw new InvalidOperationException("Unable to find a Permission with the id '" + permissionId + "'");

                // If value is null, or permission is not an entity permission, just use the system root
                if (entityId.IsNullValueOrEmpty() || _permissions.Single(x => x.Metadata.Id == permissionId).Metadata.Type != FixedPermissionTypes.EntityAction)
                    entityId = FixedHiveIds.SystemRoot;

                HiveId source;
                var status = GetPermissionStatus(permissionId, ids, entityId, out source, securityUow);
                return new PermissionResult(_permissions.Get(permissionId).Value, source, status);
            });
        }
Ejemplo n.º 7
0
        public virtual ActionResult Sort(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create<IContentStore>())
            {
                var exists = uow.Repositories.Exists<TypedEntity>(id.Value);
                if (!exists)
                    throw new ArgumentException(string.Format("No entity found for id: {0} on action Sort", id));

                var model = new SortModel { ParentId = id.Value };

                var items = uow.Repositories.GetLazyChildRelations(id.Value, FixedRelationTypes.DefaultRelationType);

                model.Items = items.Select(
                    x => new SortItem
                        {
                            UtcCreated = x.Destination.UtcCreated,
                            Id = x.Destination.Id,
                            SortIndex = x.Ordinal,
                            //TODO: Casting the relation as a TPE here but the item may be related to something else, not a TPE: need a helper method for returning the name
                            Name =
                                ((TypedEntity)x.Destination).Attributes[NodeNameAttributeDefinition.AliasValue].Values[
                                    "Name"].ToString()
                        })
                    .OrderBy(x => x.SortIndex)
                    .ToArray();

                return View(model);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Validates the email.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="excludeId">The exclude id.</param>
        /// <returns></returns>
        private bool ValidateEmail(string email, HiveId excludeId)
        {
            if (RequiresUniqueEmail)
            {
                using (var uow = Hive.Create())
                {
                    Expression <Func <RebelMembershipUser, bool> > predicate;

                    if (excludeId.IsNullValueOrEmpty())
                    {
                        predicate = x => x.Email == email;
                    }
                    else
                    {
                        predicate = x => x.Email == email && x.Id != excludeId;
                    }

                    var exists = uow.Repositories
                                 .Query <RebelMembershipUser>()
                                 .WithParentIds(VirtualRootId)
                                 .Any(predicate);

                    return(!exists);
                }
            }

            return(true);
        }
Ejemplo n.º 9
0
        public virtual ActionResult Language(HiveId? id)
        {
            if (id.IsNullValueOrEmpty())
                return HttpNotFound();

            // TODO: Check for a current language
            using (var uow = Hive.Create<IContentStore>())
            {
                //get the typed/content entity for which to assign hostnames
                var entity = uow.Repositories.Get<TypedEntity>(id.Value);
                if (entity == null)
                    throw new ArgumentException("Could not find entity with id " + id);

                //get the assigned hostnames
                var languageRelations = uow.Repositories.GetParentRelations(id.Value, FixedRelationTypes.LanguageRelationType);
                var language = languageRelations.Any() ? languageRelations.Single().MetaData.SingleOrDefault(x => x.Key == "IsoCode").Value : null;

                return View(new LanguageModel
                {
                    Id = id.Value,
                    IsoCode = language,
                    InstalledLanguages = BackOfficeRequestContext.Application.Settings.Languages
                        .Where(x => x.IsoCode != id.Value.ToString())
                        .OrderBy(x => x.Name)
                        .Select(x => new SelectListItem
                        {
                            Text = x.Name,
                            Value = x.IsoCode
                        }).ToList()
                });
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Filters the with public access.
 /// </summary>
 /// <param name="entityIds">The entity ids.</param>
 /// <param name="memberId">The member id.</param>
 /// <param name="publicAccessService">The public access service.</param>
 /// <returns></returns>
 public static IEnumerable<HiveId> FilterWithPublicAccess(this IEnumerable<HiveId> entityIds,
     HiveId memberId ,
     IPublicAccessService publicAccessService)
 {
     return memberId.IsNullValueOrEmpty()
         ? entityIds.Where(id => !publicAccessService.IsProtected(id))
         : entityIds.Where(id => publicAccessService.GetPublicAccessStatus(memberId, id).CanAccess);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Filters the with public access.
 /// </summary>
 /// <param name="entityIds">The entity ids.</param>
 /// <param name="memberId">The member id.</param>
 /// <param name="publicAccessService">The public access service.</param>
 /// <returns></returns>
 public static IEnumerable <HiveId> FilterWithPublicAccess(this IEnumerable <HiveId> entityIds,
                                                           HiveId memberId,
                                                           IPublicAccessService publicAccessService)
 {
     return(memberId.IsNullValueOrEmpty()
         ? entityIds.Where(id => !publicAccessService.IsProtected(id))
         : entityIds.Where(id => publicAccessService.GetPublicAccessStatus(memberId, id).CanAccess));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Check if an entity exists
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="id">The id.</param>
        /// <param name="idField"></param>
        /// <returns></returns>
        public bool Exists <TEntity>(HiveId id, string idField)
        {
            if (id.IsNullValueOrEmpty())
            {
                return(false);
            }

            return(PerformGet <TEntity>(true, idField, id).Any());
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets a reference to an object if it already exists in the set maintained by the lookup helper, otherwise calls a factory to create a new instance.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id">The id.</param>
        /// <param name="lookupHelper">The lookup helper.</param>
        /// <param name="factory">The factory.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        private static T GetObjectReference <T>(HiveId id, AbstractLookupHelper lookupHelper, Func <T> factory) where T : class, IReferenceByGuid
        {
            T output = null;

            if (!id.IsNullValueOrEmpty())
            {
                output = lookupHelper.Lookup <T>(id);
            }
            return(output ?? factory.Invoke());
        }
Ejemplo n.º 14
0
        public void NullConversion_EqualTo_Empty()
        {
            HiveId myItem             = new HiveId((string)null);
            string serialized         = myItem.ToString();
            var    myDeserializedItem = HiveId.Parse(serialized);

            Assert.AreEqual(myItem, HiveId.Empty);
            Assert.AreEqual(myDeserializedItem, HiveId.Empty);
            Assert.IsTrue(myItem.IsNullValueOrEmpty());
        }
Ejemplo n.º 15
0
        public PermissionResult GetInheritedPermission(Guid permissionId, IEnumerable <HiveId> userGroupIds, IReadonlyGroupUnit <IContentStore> uow, HiveId entityId = default(HiveId))
        {
            Mandate.ParameterNotNull(userGroupIds, "userGroupIds");

            //get/store the result in scoped cache

            var ids = userGroupIds.ToList();

            ids.Sort((id1, id2) => id1.ToString().CompareTo(id2.ToString())); // Sort the list of ids so that the cache key is the same regardless of order of passed in collection

            var key = "inherited-permission-" + (permissionId.ToString("N") + string.Join("", ids.Select(x => x.ToString())) + entityId).ToMd5();

            return(Hive.FrameworkContext.ScopedCache.GetOrCreateTyped <PermissionResult>(key, () =>
            {
                // Get the permission reference
                if (!_permissions.Exists(permissionId))
                {
                    throw new InvalidOperationException("Unable to find a Permission with the id '" + permissionId + "'");
                }

                if (entityId.IsNullValueOrEmpty())
                {
                    entityId = FixedHiveIds.SystemRoot;
                }

                // Loop through entities ancestors
                var ancestorsIds = uow.Repositories.GetAncestorRelations(entityId, FixedRelationTypes.DefaultRelationType)
                                   .Select(x => x.SourceId).ToArray();

                foreach (var ancestorId in ancestorsIds)
                {
                    HiveId source;
                    var status = GetPermissionStatus(permissionId, ids, ancestorId, out source);

                    // We are not interested in inherit permissions, so if we find one, move on
                    if (status != PermissionStatus.Inherit)
                    {
                        return new PermissionResult(_permissions.Get(permissionId).Value, source, status);
                    }

                    // If the ancester is system root, we've reached then end, in which case return a deny result
                    //BUG: We shouldn't have to compare the system root value but NH is returning content:// for the system root
                    if (ancestorId == FixedHiveIds.SystemRoot || ancestorId.Value == FixedHiveIds.SystemRoot.Value)
                    {
                        return new PermissionResult(_permissions.Get(permissionId).Value, source, PermissionStatus.Deny);
                    }
                }

                // We shouldn't get this far, as the last node in ancestors should always be SystemRoot, but we need to supply a fallback
                return new PermissionResult(_permissions.Get(permissionId).Value, HiveId.Empty, PermissionStatus.Deny);
            }));
        }
Ejemplo n.º 16
0
        public virtual RebelTreeResult Index(HiveId id, FormCollection querystrings)
        {
            //if the id is empty, then set it as the root node/self id
            if (id.IsNullValueOrEmpty())
            {
                id = new HiveId(TreeId);
            }

            //if its the root node, render it otherwise render normal nodes
            return(AddRootNodeToCollection(id, querystrings)
                ? RebelTree()
                : GetTreeData(id, querystrings));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the inherited permission.
        /// </summary>
        /// <param name="permissionId">The permission id.</param>
        /// <param name="userGroupIds">The user group ids.</param>
        /// <param name="entityId">The entity id.</param>
        /// <returns></returns>
        public PermissionResult GetInheritedPermission(Guid permissionId, IEnumerable <HiveId> userGroupIds, HiveId entityId = default(HiveId))
        {
            // Get the permission reference
            if (entityId.IsNullValueOrEmpty())
            {
                entityId = FixedHiveIds.SystemRoot;
            }

            var entityHive = Hive.GetReader <IContentStore>(entityId.ToUri());

            using (var uow = entityHive.CreateReadonly())
                return(GetInheritedPermission(permissionId, userGroupIds, uow, entityId));
        }
        /// <summary>
        /// Validates the username.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="excludeId">The exclude id.</param>
        /// <returns></returns>
        private bool ValidateUserName(string userName, HiveId excludeId)
        {
            if (userName.IsNullOrWhiteSpace())
            {
                return(false);
            }

            using (var uow = _hive.Create())
            {
                return(!uow.Repositories.GetAll <User>().Any(
                           x => x.Attribute <string>(UserSchema.UsernameAlias).InvariantEquals(userName) &&
                           (excludeId.IsNullValueOrEmpty() || excludeId != x.Id)));
            }
        }
        public override ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create<ISecurityStore>())
            {
                var userEntity = uow.Repositories.Get<Member>(id.Value);
                if (userEntity == null)
                    throw new ArgumentException(string.Format("No member found for id: {0} on action Edit", id));

                var userViewModel = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<Member, MemberEditorModel>(userEntity);
                return View(userViewModel);
            }
        }
        /// <summary>
        /// Validates the email.
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="excludeId">The exclude id.</param>
        /// <returns></returns>
        private bool ValidateEmail(string email, HiveId excludeId)
        {
            if (RequiresUniqueEmail)
            {
                using (var uow = _hive.Create())
                {
                    return(!uow.Repositories.GetAll <User>().Any(
                               x => x.Attribute <string>(UserSchema.EmailAlias).InvariantEquals(email) &&
                               (excludeId.IsNullValueOrEmpty() || excludeId != x.Id)));
                }
            }

            return(true);
        }
Ejemplo n.º 21
0
        public void ExtensionMethod_IsNullOrEmpty()
        {
            // Arrange
            var nullValue  = new HiveId((string)null);
            var nullValue2 = new HiveId((Uri)null);
            var validValue = new HiveId(Guid.NewGuid());

            // Assert
            Assert.IsTrue(default(HiveId).IsNullValueOrEmpty());
            Assert.IsTrue(new HiveId().IsNullValueOrEmpty());
            Assert.IsTrue(HiveId.Empty.IsNullValueOrEmpty());
            Assert.IsTrue(nullValue.IsNullValueOrEmpty());
            Assert.IsTrue(nullValue2.IsNullValueOrEmpty());
            Assert.IsFalse(validValue.IsNullValueOrEmpty());
        }
        public ActionResult EditForm(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();
            
            using (var uow = BackOfficeRequestContext.Application.Hive.OpenWriter<IContentStore>())
            {
                var dataTypeEntity = uow.Repositories.Schemas.Get<AttributeType>(id.Value);
                if (dataTypeEntity == null)
                    throw new ArgumentException(string.Format("No AttributeType found for id: {0} on action EditForm", id));

                var dataTypeViewModel = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<AttributeType, DataTypeEditorModel>(dataTypeEntity);

                return ProcessSubmit(dataTypeViewModel, dataTypeEntity);
            }           
        }
        /// <summary>
        /// Displays the edit language form.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            var isoCode = id.Value.Value.ToString();
            var language = BackOfficeRequestContext.Application.Settings.Languages.SingleOrDefault(x => x.IsoCode == isoCode);
            if (language == null)
                throw new ArgumentException(string.Format("No language found for iso code: {0} on action Edit", isoCode));

            var model = CreateLanguageEditorModel(id.Value);

            BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map(language, model);

            return View("Edit", model);
        }
        /// <summary>
        /// Displays the editor
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create())
            {
                var file = uow.Repositories.Get<File>(id.Value);
                if (file != null)
                {
                    var model = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<FileEditorModel>(file);
                    EnsureViewData(model, file);
                    return View(model);
                }
            }

            return HttpNotFound();
        }
        /// <summary>
        /// Action to render the editor
        /// </summary>
        /// <returns></returns>        
        public override ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create())
            {
                var userEntity = uow.Repositories.Get<UserGroup>(id.Value);
                if (userEntity == null)
                    throw new ArgumentException(string.Format("No user group found for id: {0} on action Edit", id));

                var userViewModel = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<UserGroup, UserGroupEditorModel>(userEntity);

                PopulatePermissions(userViewModel);

                return View(userViewModel);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets a list of UserGroup ids that the specified User belongs to.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        protected IEnumerable <HiveId> GetUserGroupIdsForUser(HiveId userId)
        {
            return(Hive.FrameworkContext.ScopedCache.GetOrCreateTyped("ss_GetUserGroupIdsForUser_" + userId,
                                                                      () =>
            {
                if (userId != null && !userId.IsNullValueOrEmpty())
                {
                    var user = _users.GetById(userId, true);
                    if (user != null)
                    {
                        return user.Groups;
                    }
                }

                return Enumerable.Empty <HiveId>();
            }));
        }
Ejemplo n.º 27
0
        public ActionResult Publish(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create<IContentStore>())
            {
                var contentEntity = uow.Repositories.Revisions.GetLatestRevision<TypedEntity>(id.Value);
                if (contentEntity == null)
                    throw new ArgumentException(string.Format("No entity found for id: {0} on action Publish", id));

                return View(new PublishModel
                    {
                        Id = contentEntity.Item.Id,
                        Name = contentEntity.Item.GetAttributeValueAsString(NodeNameAttributeDefinition.AliasValue, "UrlName")
                    });
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Checks if the node Id is the root node and if so creates the root node and appends it to the
        /// NodeCollection based on the standard tree parameters
        /// </summary>
        /// <param name="id"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        /// <remarks>
        /// This method ensure that all of the correct meta data is set for the root node so that the Rebel application works
        /// as expected. Meta data such as 'treeId' and 'searchable'
        /// </remarks>
        protected bool AddRootNodeToCollection(HiveId id, FormCollection queryStrings)
        {
            Mandate.ParameterNotEmpty(id, "id");
            Mandate.ParameterCondition(!id.IsNullValueOrEmpty(), "id");

            //if its the root model
            if (id.Equals(TreeId))
            {
                //get the root model
                var rootNode = CreateRootNode(queryStrings);

                NodeCollection.Add(rootNode);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 29
0
        public override ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create())
            {
                var macroFile = uow.Repositories.Get<File>(id.Value);
                if (macroFile != null)
                {
                    var model = MacroSerializer.FromFile(macroFile);
                    EnsureModelListData(model);                    

                    return View(model);
                }
            }

            return HttpNotFound();
        }
Ejemplo n.º 30
0
        public PermissionResults GetInheritedPermissions(IEnumerable <HiveId> userGroupIds, HiveId entityId = default(HiveId), params Guid[] permissionIds)
        {
            var results = new List <PermissionResult>();

            // Get the permission reference
            if (entityId.IsNullValueOrEmpty())
            {
                entityId = FixedHiveIds.SystemRoot;
            }

            var entityHive = Hive.GetReader <IContentStore>(entityId.ToUri());

            using (var uow = entityHive.CreateReadonly())
            {
                results.AddRange(permissionIds.Select(permissionId => GetInheritedPermission(permissionId, userGroupIds, uow, entityId)));
            }

            return(new PermissionResults(results.ToArray()));
        }
        public virtual ActionResult CreateNew(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            var currentFolderPath = "/";
            if (id != FixedHiveIds.SystemRoot)
            {
                using (var uow = Hive.Create())
                {
                    var parentFile = uow.Repositories.Get<File>(id.Value);
                    if (parentFile == null)
                        throw new ArgumentException("No folder could be found for the id specified");
                    currentFolderPath = "/" + parentFile.GetFilePathForDisplay();
                }
            }
            var model = new CreateFileModel { ParentId = id.Value, CurrentFolderPath = currentFolderPath };
            EnsureViewData(model);
            return View(model);
        }
        /// <summary>
        /// Action to render the editor
        /// </summary>
        /// <returns></returns>        
        public override ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = Hive.Create<ISecurityStore>())
            {
                var userEntity = uow.Repositories.Get<User>(id.Value);
                if (userEntity == null)
                    throw new ArgumentException(string.Format("No user found for id: {0} on action Edit", id));

                var userViewModel = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map<User, UserEditorModel>(userEntity);
                //TODO: Shouldn't this be done in the mappings ?
                userViewModel.UserGroups = uow.Repositories.GetParentRelations(userEntity.Id, FixedRelationTypes.UserGroupRelationType)
                    .Select(x => x.SourceId).ToArray();

                EnsureViewBagData();

                return View(userViewModel);
            }
        }
Ejemplo n.º 33
0
        public virtual ActionResult Hostname(HiveId? id)
        {
            if (id.IsNullValueOrEmpty())
                return HttpNotFound();

            using (var uow = Hive.Create<IContentStore>())
            {
                //get the typed/content entity for which to assign hostnames
                var entity = uow.Repositories.Get<TypedEntity>(id.Value);
                if (entity == null)
                    throw new ArgumentException("Could not find entity with id " + id);

                //get the assigned hostnames
                var assignedHostnames = uow.Repositories.GetChildren<Hostname>(FixedRelationTypes.HostnameRelationType, id.Value);

                //get the hostname relations (so there's only one query)
                var hostnameRelations = uow.Repositories.GetChildRelations(id.Value, FixedRelationTypes.HostnameRelationType).ToArray();

                return View(new HostnamesModel
                {
                    Id = id.Value,
                    VirtualDirectory = HttpContext.Request.ApplicationPath.TrimEnd('/'),
                    AssignedHostnames = assignedHostnames
                        .Select(x =>
                        {
                            //BUG: This should never be null but currently the call to GetRelations is doing some weird caching!
                            var sortOrder = hostnameRelations.Where(r => r.DestinationId == x.Id).SingleOrDefault();
                            var h = new HostnameEntryModel
                            {
                                Id = x.Id,
                                Hostname = x.Attribute<string>(HostnameSchema.HostnameAlias),
                                SortOrder = sortOrder == null ? 0 : sortOrder.Ordinal
                            };
                            return h;
                        })
                        .ToList()
                });
            }
        }
Ejemplo n.º 34
0
        public JsonResult MacroContents(HiveId currentNodeId, string macroAlias,
                                        //custom model binder for this json dictionary
                                        [ModelBinder(typeof(JsonDictionaryModelBinder))]
                                        IDictionary <string, object> macroParams)
        {
            if (macroParams == null)
            {
                macroParams = new Dictionary <string, object>();
            }

            var stringOutput = _macroRenderer.RenderMacroAsString(
                macroAlias, macroParams.ToDictionary(x => x.Key, x => x.Value.ToString()), ControllerContext, true,
                () =>
            {
                if (currentNodeId.IsNullValueOrEmpty())
                {
                    return(null);
                }

                using (var uow = RoutableRequestContext.Application.Hive.OpenReader <IContentStore>(currentNodeId.ToUri()))
                {
                    var entity = uow.Repositories.Get <TypedEntity>(currentNodeId);
                    if (entity == null)
                    {
                        throw new NullReferenceException("Could not find entity with id " + currentNodeId.ToString());
                    }

                    return(RoutableRequestContext.Application.FrameworkContext.TypeMappers.Map <Content>(entity));
                }
            });

            return(Json(new
            {
                macroContent = stringOutput
            }));
        }
Ejemplo n.º 35
0
        //TODO: We need to add an internal cache to this lookup as it gets called quite a few times when dealing with relations
        private FileSystemInfo GetFile(HiveId id)
        {
            //Console.WriteLine("GetFile " + id.ToString(HiveIdFormatStyle.AsUri));

            //if there is an empty id, then we need to return our root
            if (!id.IsNullValueOrEmpty() && (((string)id.Value.Value).IsNullOrWhiteSpace() || ((string)id.Value.Value) == "/") || ((string)id.Value.Value) == "\\")
            {
                return(_directory);
            }

            //NOTE: If we don't trim the trailing '\\' we will end up in an infinite loop with the logic
            // below because with '\\' on the end it will find all files and the folder, whereas we want to
            // only find the file or the folder.
            // We also need to trim the start because it can't start with \\ otherwise the system thinks were querying a UNC path.
            var stringId = ((string)id.Value.Value).TrimEnd(Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar);

            var file = _directory
                       .GetFiles(stringId, SearchOption.TopDirectoryOnly)
                       .OfType <FileSystemInfo>()
                       .Concat(_directory.GetDirectories(stringId, SearchOption.TopDirectoryOnly))
                       .FirstOrDefault();

            return(file);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Gets the inherited permission.
        /// </summary>
        /// <param name="permissionId">The permission id.</param>
        /// <param name="userGroupIds">The user group ids.</param>
        /// <param name="entityId">The entity id.</param>
        /// <returns></returns>
        public PermissionResult GetInheritedPermission(Guid permissionId, IEnumerable<HiveId> userGroupIds, HiveId entityId = default(HiveId))
        {
            // Get the permission reference
            if (entityId.IsNullValueOrEmpty())
                entityId = FixedHiveIds.SystemRoot;

            var entityHive = Hive.GetReader<IContentStore>(entityId.ToUri());
            using (var uow = entityHive.CreateReadonly())
                return GetInheritedPermission(permissionId, userGroupIds, uow, entityId);
        }
Ejemplo n.º 37
0
        public PermissionResult GetInheritedPermission(Guid permissionId, IEnumerable<HiveId> userGroupIds, IReadonlyGroupUnit<IContentStore> uow, HiveId entityId = default(HiveId))
        {

            Mandate.ParameterNotNull(userGroupIds, "userGroupIds");

            //get/store the result in scoped cache

            var ids = userGroupIds.ToList();
            ids.Sort((id1, id2) => id1.ToString().CompareTo(id2.ToString())); // Sort the list of ids so that the cache key is the same regardless of order of passed in collection

            var key = "inherited-permission-" + (permissionId.ToString("N") + string.Join("", ids.Select(x => x.ToString())) + entityId).ToMd5();

            return Hive.FrameworkContext.ScopedCache.GetOrCreateTyped<PermissionResult>(key, () =>
            {
                // Get the permission reference
                if (!_permissions.Exists(permissionId))
                    throw new InvalidOperationException("Unable to find a Permission with the id '" + permissionId + "'");

                if (entityId.IsNullValueOrEmpty())
                    entityId = FixedHiveIds.SystemRoot;

                // Loop through entities ancestors
                var ancestorsIds = uow.Repositories.GetAncestorRelations(entityId, FixedRelationTypes.DefaultRelationType)
                    .Select(x => x.SourceId).ToArray();

                foreach (var ancestorId in ancestorsIds)
                {
                    HiveId source;
                    var status = GetPermissionStatus(permissionId, ids, ancestorId, out source);

                    // We are not interested in inherit permissions, so if we find one, move on
                    if (status != PermissionStatus.Inherit)
                    {
                        return new PermissionResult(_permissions.Get(permissionId).Value, source, status);
                    }

                    // If the ancester is system root, we've reached then end, in which case return a deny result
                    //BUG: We shouldn't have to compare the system root value but NH is returning content:// for the system root
                    if (ancestorId == FixedHiveIds.SystemRoot || ancestorId.Value == FixedHiveIds.SystemRoot.Value)
                    {
                        return new PermissionResult(_permissions.Get(permissionId).Value, source, PermissionStatus.Deny);
                    }
                }

                // We shouldn't get this far, as the last node in ancestors should always be SystemRoot, but we need to supply a fallback
                return new PermissionResult(_permissions.Get(permissionId).Value, HiveId.Empty, PermissionStatus.Deny);
            });
        }
 /// <summary>
 /// Create selected template content property.
 /// </summary>
 /// <param name="docType"></param>
 /// <param name="selectedTemplateId"> </param>
 /// <returns></returns>
 private ContentProperty CreateSelectedTemplateContentProperty(DocumentTypeEditorModel docType, HiveId selectedTemplateId)
 {
     var prop = new ContentProperty((HiveId)Guid.NewGuid(),
                                                docType.Properties.Single(x => x.Alias == SelectedTemplateAttributeDefinition.AliasValue),
                                                selectedTemplateId.IsNullValueOrEmpty() ? new Dictionary<string, object>() : new Dictionary<string, object> { { "TemplateId", selectedTemplateId.ToString() } })
     {
         Name = SelectedTemplateAttributeDefinition.AliasValue,
         Alias = SelectedTemplateAttributeDefinition.AliasValue,
         TabId = docType.DefinedTabs.Single(x => x.Alias == FixedGroupDefinitions.GeneralGroup.Alias).Id
     };
     return prop;
 }
Ejemplo n.º 39
0
        public PermissionResults GetInheritedPermissions(IEnumerable<HiveId> userGroupIds, HiveId entityId = default(HiveId), params Guid[] permissionIds)
        {
            var results = new List<PermissionResult>();

            // Get the permission reference
            if (entityId.IsNullValueOrEmpty())
                entityId = FixedHiveIds.SystemRoot;

            var entityHive = Hive.GetReader<IContentStore>(entityId.ToUri());
            using (var uow = entityHive.CreateReadonly())
            {
                results.AddRange(permissionIds.Select(permissionId => GetInheritedPermission(permissionId, userGroupIds, uow, entityId)));
            }

            return new PermissionResults(results.ToArray());
        }
Ejemplo n.º 40
0
 public void NullConversion_EqualTo_Empty()
 {
     HiveId myItem = new HiveId((string)null);
     string serialized = myItem.ToString();
     var myDeserializedItem = HiveId.Parse(serialized);
     Assert.AreEqual(myItem, HiveId.Empty);
     Assert.AreEqual(myDeserializedItem, HiveId.Empty);
     Assert.IsTrue(myItem.IsNullValueOrEmpty());
 }
 public SelectedTemplateAttribute(HiveId templateId, AttributeGroup group)
     : base(new SelectedTemplateAttributeDefinition(group), templateId.IsNullValueOrEmpty() ? "" : templateId.ToString())
 {
 }
Ejemplo n.º 42
0
        public override void ConfigureMappings()
        {
            #region TypedEntity -> Content

            this.CreateMap<TypedEntity, Content>()
                .CreateUsing(x => new Content(x.Id, x.Attributes))
                //.ForMember(x => x.Attributes, opt => opt.MapFrom(x => x.Attributes))
                //.ForMember(x => x.ContentType, opt => opt.MapFrom(x => x.EntitySchema))
                .AfterMap((source, dest) =>
                    {
                        var appContext = DependencyResolver.Current.GetService<IRebelApplicationContext>();
                        if (appContext != null)
                        {
                            using (var uow = _resolverContext.Hive.OpenReader<IContentStore>())
                            {
                                // Sort order
                                var siblings = uow.Repositories.GetBranchRelations(dest.Id, FixedRelationTypes.DefaultRelationType);
                                var currentPlace = siblings.FirstOrDefault(x => x.DestinationId == dest.Id);
                                if (currentPlace != null) dest.SortOrder = currentPlace.Ordinal;

                                // Created by
                                var cRelation =
                                    uow.Repositories.GetParentRelations(source.Id, FixedRelationTypes.CreatedByRelationType).FirstOrDefault();
                                if (cRelation != null)
                                {
                                    dest.CreatedBy =
                                        appContext.Security.Users.GetByProfileId(cRelation.SourceId).Username;
                                }

                                // Modified by
                                var mRelation =
                                    uow.Repositories.GetParentRelations(source.Id, FixedRelationTypes.ModifiedByRelationType).FirstOrDefault();
                                if (mRelation != null)
                                {
                                    dest.ModifiedBy =
                                        appContext.Security.Users.GetByProfileId(mRelation.SourceId).Username;
                                }
                            }
                        }

                    var fileHive = _resolverContext.Hive.TryGetReader<IFileStore>(new Uri("storage://templates"));
                    if (fileHive == null) return;
                    using (var uow = fileHive.CreateReadonly())
                    {
                        //selected template
                        var templateVal = source.Attribute<string>(SelectedTemplateAttributeDefinition.AliasValue);
                        if (!templateVal.IsNullOrWhiteSpace())
                        {
                            var selectedTemplateId = new HiveId(source.Attribute<string>(SelectedTemplateAttributeDefinition.AliasValue));
                            if (!selectedTemplateId.IsNullValueOrEmpty())
                            {
                                var selectedTemplate = uow.Repositories.Get<File>(selectedTemplateId);
                                if (selectedTemplate != null)
                                {
                                    dest.CurrentTemplate = FrameworkContext.TypeMappers.Map<Template>(selectedTemplate);
                                }
                            }
                        }
                        
                        //alternative templates
                        var altTemplateIds = source.EntitySchema.GetXmlPropertyAsList<HiveId>("allowed-templates") ?? new List<HiveId>();
                        var altTemplates = uow.Repositories.Get<File>(true, altTemplateIds.ToArray());
                        dest.AlternativeTemplates = altTemplates.Select(x => FrameworkContext.TypeMappers.Map<Template>(x));
                    }
                });

            #endregion

            #region File -> Template

            this.CreateMap<File, Template>()
                .CreateUsing(x => new Template(x.Id))
                .ForMember(x => x.Name, x => x.MapFrom(y => y.Name))
                .ForMember(x => x.Alias, x => x.MapFrom(y => y.GetFileNameWithoutExtension()));

            #endregion

            #region TypedAttributeCollection > IEnumerable<Field>

            this.CreateMap<TypedAttributeCollection, IEnumerable<Field>>()
                .CreateUsing(x =>
                {
                    var output = new HashSet<Field>();
                    foreach (var attrib in x)
                    {
                        output.Add(Map<TypedAttribute, Field>(attrib));
                    }
                    return output;
                });

            #endregion

            #region TypedAttribute > Field

            this.CreateMap<TypedAttribute, Field>()
                .CreateUsing(x => new Field(Map<AttributeDefinition, FieldDefinition>(x.AttributeDefinition)))
                .ForMember(x => x.Values, opt => opt.MapFrom(x => x.Values));

            #endregion



            #region TypedAttributeValueCollection > IEnumerable<KeyedFieldValue>)

            this.CreateMap<KeyValuePair<string, object>, KeyedFieldValue>()
                .CreateUsing(x => new KeyedFieldValue(x.Key, x.Value));

            this.CreateMap<TypedAttributeValueCollection, IEnumerable<KeyedFieldValue>>()
                .CreateUsing(x => new HashSet<KeyedFieldValue>());

            #endregion

            #region AttributeDefinition > FieldDefinition

            this.CreateMap<AttributeDefinition, FieldDefinition>();

            #endregion

            #region EntitySchema > ContentType

            this.CreateMap<EntitySchema, ContentType>()
                .CreateUsing(x => new ContentType(x.Alias, x.Name, Map<IEnumerable<AttributeDefinition>, IEnumerable<FieldDefinition>>(x.AttributeDefinitions)));

            #endregion
        }
Ejemplo n.º 43
0
        public static bool HasValue(this TypedAttribute attr)
        {
            HiveId value = HiveId.Parse(attr.DynamicValue);

            return(!value.IsNullValueOrEmpty());
        }
Ejemplo n.º 44
0
        public override void ConfigureMappings()
        {
            #region TypedEntity -> Content

            this.CreateMap <TypedEntity, Content>()
            .CreateUsing(x => new Content(x.Id, x.Attributes))
            //.ForMember(x => x.Attributes, opt => opt.MapFrom(x => x.Attributes))
            //.ForMember(x => x.ContentType, opt => opt.MapFrom(x => x.EntitySchema))
            .AfterMap((source, dest) =>
            {
                var appContext = DependencyResolver.Current.GetService <IRebelApplicationContext>();
                if (appContext != null)
                {
                    using (var uow = _resolverContext.Hive.OpenReader <IContentStore>())
                    {
                        // Sort order
                        var siblings     = uow.Repositories.GetBranchRelations(dest.Id, FixedRelationTypes.DefaultRelationType);
                        var currentPlace = siblings.FirstOrDefault(x => x.DestinationId == dest.Id);
                        if (currentPlace != null)
                        {
                            dest.SortOrder = currentPlace.Ordinal;
                        }

                        // Created by
                        var cRelation =
                            uow.Repositories.GetParentRelations(source.Id, FixedRelationTypes.CreatedByRelationType).FirstOrDefault();
                        if (cRelation != null)
                        {
                            dest.CreatedBy =
                                appContext.Security.Users.GetByProfileId(cRelation.SourceId).Username;
                        }

                        // Modified by
                        var mRelation =
                            uow.Repositories.GetParentRelations(source.Id, FixedRelationTypes.ModifiedByRelationType).FirstOrDefault();
                        if (mRelation != null)
                        {
                            dest.ModifiedBy =
                                appContext.Security.Users.GetByProfileId(mRelation.SourceId).Username;
                        }
                    }
                }

                var fileHive = _resolverContext.Hive.TryGetReader <IFileStore>(new Uri("storage://templates"));
                if (fileHive == null)
                {
                    return;
                }
                using (var uow = fileHive.CreateReadonly())
                {
                    //selected template
                    var templateVal = source.Attribute <string>(SelectedTemplateAttributeDefinition.AliasValue);
                    if (!templateVal.IsNullOrWhiteSpace())
                    {
                        var selectedTemplateId = new HiveId(source.Attribute <string>(SelectedTemplateAttributeDefinition.AliasValue));
                        if (!selectedTemplateId.IsNullValueOrEmpty())
                        {
                            var selectedTemplate = uow.Repositories.Get <File>(selectedTemplateId);
                            if (selectedTemplate != null)
                            {
                                dest.CurrentTemplate = FrameworkContext.TypeMappers.Map <Template>(selectedTemplate);
                            }
                        }
                    }

                    //alternative templates
                    var altTemplateIds        = source.EntitySchema.GetXmlPropertyAsList <HiveId>("allowed-templates") ?? new List <HiveId>();
                    var altTemplates          = uow.Repositories.Get <File>(true, altTemplateIds.ToArray());
                    dest.AlternativeTemplates = altTemplates.Select(x => FrameworkContext.TypeMappers.Map <Template>(x));
                }
            });

            #endregion

            #region File -> Template

            this.CreateMap <File, Template>()
            .CreateUsing(x => new Template(x.Id))
            .ForMember(x => x.Name, x => x.MapFrom(y => y.Name))
            .ForMember(x => x.Alias, x => x.MapFrom(y => y.GetFileNameWithoutExtension()));

            #endregion

            #region TypedAttributeCollection > IEnumerable<Field>

            this.CreateMap <TypedAttributeCollection, IEnumerable <Field> >()
            .CreateUsing(x =>
            {
                var output = new HashSet <Field>();
                foreach (var attrib in x)
                {
                    output.Add(Map <TypedAttribute, Field>(attrib));
                }
                return(output);
            });

            #endregion

            #region TypedAttribute > Field

            this.CreateMap <TypedAttribute, Field>()
            .CreateUsing(x => new Field(Map <AttributeDefinition, FieldDefinition>(x.AttributeDefinition)))
            .ForMember(x => x.Values, opt => opt.MapFrom(x => x.Values));

            #endregion



            #region TypedAttributeValueCollection > IEnumerable<KeyedFieldValue>)

            this.CreateMap <KeyValuePair <string, object>, KeyedFieldValue>()
            .CreateUsing(x => new KeyedFieldValue(x.Key, x.Value));

            this.CreateMap <TypedAttributeValueCollection, IEnumerable <KeyedFieldValue> >()
            .CreateUsing(x => new HashSet <KeyedFieldValue>());

            #endregion

            #region AttributeDefinition > FieldDefinition

            this.CreateMap <AttributeDefinition, FieldDefinition>();

            #endregion

            #region EntitySchema > ContentType

            this.CreateMap <EntitySchema, ContentType>()
            .CreateUsing(x => new ContentType(x.Alias, x.Name, Map <IEnumerable <AttributeDefinition>, IEnumerable <FieldDefinition> >(x.AttributeDefinitions)));

            #endregion
        }
Ejemplo n.º 45
0
        internal static IDictionary<string, object> WriteUploadedFile(Guid mediaId, bool removeExistingFile, HttpPostedFileBase httpFile, IGroupUnitFactory<IFileStore> groupUnitFactory, HiveId existingFileId = default(HiveId), string thumbSizes = null)
        {
            var val = new Dictionary<string, object>();

            //add the media id to be saved
            val.Add("MediaId", mediaId.ToString("N"));

            // Check to see if we should delete the current file
            // either becuase remove file is checked, or we have a replacement file
            if (existingFileId != HiveId.Empty && (removeExistingFile || HasFile(httpFile)))
            {
                if (!existingFileId.IsNullValueOrEmpty())
                {
                    // delete entire property folder (deletes image and any thumbnails stored)
                    //var folderHiveId = HiveId.Parse("storage://file-uploader/string/" + MediaId.ToString("N"));
                    var folderHiveId = new HiveId("storage", "file-uploader", new HiveIdValue(mediaId.ToString("N")));

                    using (var uow = groupUnitFactory.Create())
                    {
                        try
                        {
                            uow.Repositories.Delete<File>(existingFileId); // Must delete file entity so that relations are deleted
                            uow.Repositories.Delete<File>(folderHiveId);
                            uow.Complete();
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Warn(typeof(ContentExtensions), "Could not delete previous file and/or container", ex);
                        }
                    }
                }
            }

            // If we've received a File from the binding, we need to save it
            if (HasFile(httpFile))
            {
                // Open a new unit of work to write the file
                using (var uow = groupUnitFactory.Create())
                {
                    // Create main file
                    var file = new File
                                   {
                                       RootedPath =
                                           mediaId.ToString("N") + "/" + Path.GetFileName(httpFile.FileName)
                                                .Replace(" ", "").Replace(",", "")
                                   };

                    var stream = httpFile.InputStream;
                    if (stream.CanRead && stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        using (var mem = new MemoryStream())
                        {
                            stream.CopyTo(mem);
                            file.ContentBytes = mem.ToArray();
                        }
                    }

                    uow.Repositories.AddOrUpdate(file);

                    // Create thumbnails (TODO: Need to encapsulate this so it can be reused in other places?)
                    CreateThumbnails(uow, file, mediaId.ToString("N"), thumbSizes);

                    uow.Complete();

                    val.Add("Value", file.Id);
                }
            }
            else if (!existingFileId.IsNullValueOrEmpty() && !removeExistingFile)
            {
                val.Add("Value", existingFileId);
            }
            else
            {
                val.Add("Value", HiveId.Empty);
            }

            return val;
        }
Ejemplo n.º 46
0
        private HashSet <ContentProperty> GetNodeProperties(int id, HiveId selectedTemplateId)
        {
            var customProperties = new List <ContentProperty>();
            var tabIds           = _docTypes.SelectMany(tabs => tabs.DefinedTabs).Select(x => x.Id).ToList();
            var currTab          = 0;

            var node = XmlData.Root.Descendants()
                       .Where(x => (string)x.Attribute("id") == id.ToString())
                       .Single();

            var docTypeArray = _docTypes.ToArray();
            //get the corresponding doc type for this node
            var docType = docTypeArray
                          .Where(x => x.Id == HiveId.ConvertIntToGuid(int.Parse((string)node.Attribute("nodeType"))))
                          .Single();

            //add node name
            var nodeName = new ContentProperty((HiveId)Guid.NewGuid(),
                                               docType.Properties.Where(x => x.Alias == NodeNameAttributeDefinition.AliasValue).Single(),
                                               new Dictionary <string, object> {
                { "Name", (string)node.Attribute("nodeName") }
            })
            {
                Name  = NodeNameAttributeDefinition.AliasValue,
                Alias = NodeNameAttributeDefinition.AliasValue,
                TabId = docType.DefinedTabs.Where(x => x.Alias == _generalGroup.Alias).Single().Id
            };

            customProperties.Add(nodeName);

            //add selected template (empty)
            var selectedTemplate = new ContentProperty((HiveId)Guid.NewGuid(),
                                                       docType.Properties.Where(x => x.Alias == SelectedTemplateAttributeDefinition.AliasValue).Single(),
                                                       selectedTemplateId.IsNullValueOrEmpty() ? new Dictionary <string, object>() : new Dictionary <string, object> {
                { "TemplateId", selectedTemplateId.ToString() }
            })
            {
                Name  = SelectedTemplateAttributeDefinition.AliasValue,
                Alias = SelectedTemplateAttributeDefinition.AliasValue,
                TabId = docType.DefinedTabs.Where(x => x.Alias == _generalGroup.Alias).Single().Id
            };

            customProperties.Add(selectedTemplate);

            customProperties.AddRange(
                node.Elements()
                .Where(e => e.Attribute("isDoc") == null)
                .Select(e =>
            {
                //Assigning the doc type properties is completely arbitrary here, all I'm doing is
                //aligning a DocumentTypeProperty that contains the DataType that I want to render

                ContentProperty np;
                DocumentTypeProperty dp;
                switch (e.Name.LocalName)
                {
                case "bodyText":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0]);
                    dp = docType.Properties.Where(x => x.Alias == "bodyText").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "colorSwatchPicker":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[2]);
                    dp = docType.Properties.Where(x => x.Alias == "colorSwatchPicker").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "tags":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[3]);
                    dp = docType.Properties.Where(x => x.Alias == "tags").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "textBox":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp = docType.Properties.Where(x => x.Alias == "textBox").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "publisher":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp = docType.Properties.Where(x => x.Alias == "publisher").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "numberOfPages":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp = docType.Properties.Where(x => x.Alias == "numberOfPages").Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;

                case "image":
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                    dp         = docType.Properties.Where(x => x.Alias == "image").Single();
                    var values = e.Value.Split(',');
                    np         = new ContentProperty((HiveId)GetNodeProperty(e), dp, new Dictionary <string, object> {
                        { "MediaId", values[0] }, { "Value", values[1] }
                    });
                    break;

                default:
                    //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1]);
                    dp = docType.Properties.Where(x => x.Alias == e.Name.LocalName).Single();
                    np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                    break;
                }

                //need to set the data type model for this property

                np.Alias = e.Name.LocalName;
                np.Name  = e.Name.LocalName;

                //add to a random tab
                currTab  = 0;        // currTab == 2 ? 0 : ++currTab;
                np.TabId = tabIds[currTab];

                return(np);
            }).ToList());

            return(new HashSet <ContentProperty>(customProperties));
        }
        public ActionResult Download(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = _hive.Create())
            {
                var def = PackageBuilderHelper.GetPackageDefinitionById(uow, id.Value);
                if(def == null)
                    return HttpNotFound();

                var pkg = PackageBuilderHelper.GetPackageFileById(uow, id.Value);
                if (pkg == null)
                    return HttpNotFound();

                return File(pkg.ContentBytes, "application/zip", def.Alias +"."+ def.Version + ".nupkg");
            }
        }
        public ActionResult Edit(HiveId? id)
        {
            if (id.IsNullValueOrEmpty()) return HttpNotFound();

            using (var uow = _hive.Create())
            {
                var def = PackageBuilderHelper.GetPackageDefinitionById(uow, id.Value);
                if(def == null)
                    return HttpNotFound();

                var pkg = PackageBuilderHelper.GetPackageFileById(uow, id.Value);

                var model = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers
                    .Map<PackageDefinition, PackageDefinitionEditorModel>(def);
                model.Id = id.Value;
                model.IsPublished = pkg != null;

                PopulateCollections(model);

                return View(model);
            }
        }
Ejemplo n.º 49
0
        public IEnumerable<PermissionStatusResult> GetPermissionStatuses(IEnumerable<HiveId> userGroupIds, HiveId entityId, params Guid[] permissionIds)
        {
            using (var uow = Hive.OpenReader<ISecurityStore>())
            {
                foreach (var permissionId in permissionIds)
                {
                    // Get the permission reference
                    if (!_permissions.Exists(permissionId))
                        throw new InvalidOperationException("Unable to find a Permission with the id '" + permissionId + "'");

                    // If value is null, or permission is not an entity permission, just use the system root
                    if (entityId.IsNullValueOrEmpty() || _permissions.Single(x => x.Metadata.Id == permissionId).Metadata.Type != FixedPermissionTypes.EntityAction)
                        entityId = FixedHiveIds.SystemRoot;

                    var source = HiveId.Empty;
                    var result = GetPermissionStatus(permissionId, userGroupIds, entityId, out source, uow);
                    yield return new PermissionStatusResult(source, result, permissionId);
                }
            }
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Checks if the node Id is the root node and if so creates the root node and appends it to the 
        /// NodeCollection based on the standard tree parameters
        /// </summary>
        /// <param name="id"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        /// <remarks>
        /// This method ensure that all of the correct meta data is set for the root node so that the Umbraco application works
        /// as expected. Meta data such as 'treeId' and 'searchable'
        /// </remarks>
        protected bool AddRootNodeToCollection(HiveId id, FormCollection queryStrings)
        {
            Mandate.ParameterNotEmpty(id, "id");
            Mandate.ParameterCondition(!id.IsNullValueOrEmpty(), "id");
            
            //if its the root model
            if (id.Equals(TreeId))
            {
                //get the root model
                var rootNode = CreateRootNode(queryStrings);
             
                NodeCollection.Add(rootNode);

                return true;
            }

            return false;
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Gets a list of UserGroup ids that the specified User belongs to.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns></returns>
        protected IEnumerable<HiveId> GetUserGroupIdsForUser(HiveId userId)
        {
            return Hive.FrameworkContext.ScopedCache.GetOrCreateTyped("ss_GetUserGroupIdsForUser_" + userId,
                () =>
                {
                    if (userId != null && !userId.IsNullValueOrEmpty())
                    {
                        var user = _users.GetById(userId, true);
                        if (user != null)
                            return user.Groups;
                    }

                    return Enumerable.Empty<HiveId>();
                });
        }
Ejemplo n.º 52
0
        public virtual UmbracoTreeResult Index(HiveId id, FormCollection querystrings)
        {
            //if the id is empty, then set it as the root node/self id
            if (id.IsNullValueOrEmpty())
            {
                id = new HiveId(TreeId);
            }

            //if its the root node, render it otherwise render normal nodes
            return AddRootNodeToCollection(id, querystrings)
                ? UmbracoTree() 
                : GetTreeData(id, querystrings);
        }
 public SelectedTemplateAttribute(HiveId templateId, AttributeGroup group)
     : base(new SelectedTemplateAttributeDefinition(group), templateId.IsNullValueOrEmpty() ? "" : templateId.ToString())
 { }
Ejemplo n.º 54
0
        internal static IDictionary <string, object> WriteUploadedFile(Guid mediaId, bool removeExistingFile, HttpPostedFileBase httpFile, IGroupUnitFactory <IFileStore> groupUnitFactory, HiveId existingFileId = default(HiveId), string thumbSizes = null)
        {
            var val = new Dictionary <string, object>();

            //add the media id to be saved
            val.Add("MediaId", mediaId.ToString("N"));

            // Check to see if we should delete the current file
            // either becuase remove file is checked, or we have a replacement file
            if (existingFileId != HiveId.Empty && (removeExistingFile || HasFile(httpFile)))
            {
                if (!existingFileId.IsNullValueOrEmpty())
                {
                    // delete entire property folder (deletes image and any thumbnails stored)
                    //var folderHiveId = HiveId.Parse("storage://file-uploader/string/" + MediaId.ToString("N"));
                    var folderHiveId = new HiveId("storage", "file-uploader", new HiveIdValue(mediaId.ToString("N")));

                    using (var uow = groupUnitFactory.Create())
                    {
                        try
                        {
                            uow.Repositories.Delete <File>(existingFileId); // Must delete file entity so that relations are deleted
                            uow.Repositories.Delete <File>(folderHiveId);
                            uow.Complete();
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Warn(typeof(ContentExtensions), "Could not delete previous file and/or container", ex);
                        }
                    }
                }
            }

            // If we've received a File from the binding, we need to save it
            if (HasFile(httpFile))
            {
                // Open a new unit of work to write the file
                using (var uow = groupUnitFactory.Create())
                {
                    // Create main file
                    var file = new File
                    {
                        RootedPath =
                            mediaId.ToString("N") + "/" + Path.GetFileName(httpFile.FileName)
                            .Replace(" ", "").Replace(",", "")
                    };

                    var stream = httpFile.InputStream;
                    if (stream.CanRead && stream.CanSeek)
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        using (var mem = new MemoryStream())
                        {
                            stream.CopyTo(mem);
                            file.ContentBytes = mem.ToArray();
                        }
                    }

                    uow.Repositories.AddOrUpdate(file);

                    // Create thumbnails (TODO: Need to encapsulate this so it can be reused in other places?)
                    CreateThumbnails(uow, file, mediaId.ToString("N"), thumbSizes);

                    uow.Complete();

                    val.Add("Value", file.Id);
                }
            }
            else if (!existingFileId.IsNullValueOrEmpty() && !removeExistingFile)
            {
                val.Add("Value", existingFileId);
            }
            else
            {
                val.Add("Value", HiveId.Empty);
            }

            return(val);
        }
        protected override void PopulateFileContentFromStub(FileEditorModel model, HiveId stubFileId, IDictionary<string, string> replacements)
        {
            var parentId = model.ParentId;

            model.ParentId = FixedHiveIds.SystemRoot;

            replacements = new Dictionary<string, string> { { "$layout$", "" }, { "$sections$", "" } };

            if (!stubFileId.IsNullValueOrEmpty())
            {
                if (!parentId.IsNullValueOrEmpty() && parentId != FixedHiveIds.SystemRoot)
                {
                    using (var uow = Hive.Create())
                    {
                        var parentFile = uow.Repositories.Get<File>(parentId);
                        if (parentFile == null)
                            throw new ArgumentException("No file could be found for the parent id specified");

                        replacements["$layout$"] = parentFile.Name;
                        replacements["$sections$"] = new TemplateParser().Parse(parentFile).Sections.Where(x => x != "Body")
                            .Aggregate("", (current, section) => current + ("\n@section " + section + "\n{\n\n}\n"));
                    }
                }
            }
            
            base.PopulateFileContentFromStub(model, stubFileId, replacements);
        }
Ejemplo n.º 56
0
        private HashSet<ContentProperty> GetNodeProperties(int id, HiveId selectedTemplateId)
        {

            var customProperties = new List<ContentProperty>();
            var tabIds = _docTypes.SelectMany(tabs => tabs.DefinedTabs).Select(x => x.Id).ToList();
            var currTab = 0;

            var node = XmlData.Root.Descendants()
                .Where(x => (string)x.Attribute("id") == id.ToString())
                .Single();

            var docTypeArray = _docTypes.ToArray();
            //get the corresponding doc type for this node
            var docType = docTypeArray
                .Where(x => x.Id == HiveId.ConvertIntToGuid(int.Parse((string)node.Attribute("nodeType"))))
                .Single();

            //add node name
            var nodeName = new ContentProperty((HiveId)Guid.NewGuid(),
                                               docType.Properties.Where(x => x.Alias == NodeNameAttributeDefinition.AliasValue).Single(),
                                               new Dictionary<string, object> { { "Name", (string)node.Attribute("nodeName") } })
                {
                    Name = NodeNameAttributeDefinition.AliasValue,
                    Alias = NodeNameAttributeDefinition.AliasValue,
                    TabId = docType.DefinedTabs.Where(x => x.Alias == _generalGroup.Alias).Single().Id
                    
                };
            customProperties.Add(nodeName);

            //add selected template (empty)
            var selectedTemplate = new ContentProperty((HiveId)Guid.NewGuid(),
                                                       docType.Properties.Where(x => x.Alias == SelectedTemplateAttributeDefinition.AliasValue).Single(),
                                                       selectedTemplateId.IsNullValueOrEmpty() ? new Dictionary<string, object>() : new Dictionary<string, object> { { "TemplateId", selectedTemplateId.ToString() } })
                {
                    Name = SelectedTemplateAttributeDefinition.AliasValue,
                    Alias = SelectedTemplateAttributeDefinition.AliasValue,
                    TabId = docType.DefinedTabs.Where(x => x.Alias == _generalGroup.Alias).Single().Id
                };
            customProperties.Add(selectedTemplate);

            customProperties.AddRange(
                node.Elements()
                    .Where(e => e.Attribute("isDoc") == null)
                    .Select(e =>
                    {

                        //Assigning the doc type properties is completely arbitrary here, all I'm doing is 
                        //aligning a DocumentTypeProperty that contains the DataType that I want to render

                        ContentProperty np;
                        DocumentTypeProperty dp;
                        switch (e.Name.LocalName)
                        {
                            case "bodyText":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[0]);
                                dp = docType.Properties.Where(x => x.Alias == "bodyText").Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                            case "colorSwatchPicker":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[2]);
                                dp = docType.Properties.Where(x => x.Alias == "colorSwatchPicker").Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                            case "tags":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[3]);
                                dp = docType.Properties.Where(x => x.Alias == "tags").Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                            case "textBox":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                                dp = docType.Properties.Where(x => x.Alias == "textBox").Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                            case "publisher":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                                dp = docType.Properties.Where(x => x.Alias == "publisher").Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                            case "numberOfPages":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                                dp = docType.Properties.Where(x => x.Alias == "numberOfPages").Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                            case "image":
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[4]) { OverriddenPreValues = overridenPreVals };
                                dp = docType.Properties.Where(x => x.Alias == "image").Single();
                                var values = e.Value.Split(',');
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, new Dictionary<string, object> { { "MediaId", values[0] }, { "Value", values[1] } });
                                break;
                            default:
                                //dp = new DocumentTypeProperty(new HiveId(Guid.NewGuid()), _dataTypes[1]);
                                dp = docType.Properties.Where(x => x.Alias == e.Name.LocalName).Single();
                                np = new ContentProperty((HiveId)GetNodeProperty(e), dp, e.Value);
                                break;
                        }

                        //need to set the data type model for this property

                        np.Alias = e.Name.LocalName;
                        np.Name = e.Name.LocalName;

                        //add to a random tab
                        currTab = 0; // currTab == 2 ? 0 : ++currTab;
                        np.TabId = tabIds[currTab];

                        return np;
                    }).ToList());

            return new HashSet<ContentProperty>(customProperties);
        }