protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            //if its the first level
            if (parentId == RootNodeId)
            {
                using (var uow = BackOfficeRequestContext.Application.Hive.OpenReader<IContentStore>())
                {
                    var items = uow.Repositories.Schemas.GetAll<AttributeType>()
                        .Where(x => !x.Id.IsSystem())
                        .OrderBy(x => x.Name.Value);

                    foreach (var treeNode in items.Select(dt =>
                                                          CreateTreeNode(
                                                              dt.Id,
                                                              queryStrings,
                                                              dt.Name,
                                                              Url.GetEditorUrl(dt.Id, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings),
                                                              false,
                                                              "tree-data-type")))
                    {
                        //add the menu items
                        treeNode.AddEditorMenuItem<Delete>(this, "deleteUrl", "Delete");

                        NodeCollection.Add(treeNode);
                    }
                }

            }
            else if (!AddRootNodeToCollection(parentId, queryStrings))
            {
                throw new NotSupportedException("The DataType tree does not support more than 1 level");
            }

            return UmbracoTree();
        }
        public void Content_LevelExtensionMethod()
        {
            // Arrange
            var newGuid = Guid.NewGuid();
            var newGuidRedHerring = Guid.NewGuid();
            var childGuid = new HiveId(Guid.NewGuid());
            var child1_1Guid = new HiveId(Guid.NewGuid());
            var child1_2Guid = new HiveId(Guid.NewGuid());
            var child1_3Guid = new HiveId(Guid.NewGuid());
            var child1_4Guid = new HiveId(Guid.NewGuid());
            var child1_1_1Guid = new HiveId(Guid.NewGuid());
            var child1_1_2Guid = new HiveId(Guid.NewGuid());
            var child2Guid = new HiveId(Guid.NewGuid());
            var parent = HiveModelCreationHelper.SetupTestData(newGuid, newGuidRedHerring, this.Setup.ProviderSetup);
            var child1 = this.AddChildNodeWithId(parent, childGuid, 1);
            var child1_1 = this.AddChildNodeWithId(child1, child1_1Guid, 1);
            var child1_2 = this.AddChildNodeWithId(child1, child1_2Guid, 2);
            var child1_3 = this.AddChildNodeWithId(child1, child1_3Guid, 3);
            var child1_4 = this.AddChildNodeWithId(child1, child1_4Guid, 4);
            var child1_1_1 = this.AddChildNodeWithId(child1_1, child1_1_1Guid, 1);
            var child1_1_2 = this.AddChildNodeWithId(child1_1, child1_1_2Guid, 1);
            var child2 = this.AddChildNodeWithId(parent, child2Guid, 2);

            var child1AsContent = this.HiveManager.FrameworkContext.TypeMappers.Map<Content>(child1);
            var child1_1_2AsContent = this.HiveManager.FrameworkContext.TypeMappers.Map<Content>(child1_1_2);

            var child1Path = child1AsContent.GetPath(this.HiveManager);
            Assert.That(child1Path.Count(), Is.EqualTo(2), "Path was: " + child1Path.ToString() + ", parent id is: " + parent.Id);
            Assert.That(child1Path.Level, Is.EqualTo(2));
            var child1_1_2Path = child1_1_2AsContent.GetPath(this.HiveManager);
            Assert.That(child1_1_2Path.Count(), Is.EqualTo(4), "Path was: " + child1_1_2Path.ToString() + ", parent id is: " + parent.Id);
        }
        //[UmbracoAuthorize(Permissions = new[] { FixedPermissionIds.Rollback })] 
        public virtual JsonResult RollbackForm(HiveId id, HiveId revisionId)
        {
            using (var uow = Hive.Create<IContentStore>())
            {
                var entity = uow.Repositories.Get<TypedEntity>(id);
                if (entity == null)
                    throw new NullReferenceException("Could not find entity with id " + id);

                var revision = uow.Repositories.Revisions.Get<TypedEntity>(id, revisionId);
                if (revision == null)
                    throw new NullReferenceException("Could not find revision with id " + revisionId);

                var newRevision = revision.CopyToNewRevision();

                uow.Repositories.Revisions.AddOrUpdate(newRevision);
                uow.Complete();

                var successMsg = "Rollback.Success.Message".Localize(this, new
                    {
                        Name = entity.GetAttributeValue(NodeNameAttributeDefinition.AliasValue, "Name")
                    });

                Notifications.Add(new NotificationMessage(
                                      successMsg,
                                      "Rollback.Title".Localize(this), NotificationType.Success));

                return new CustomJsonResult(new
                    {
                        success = true,
                        notifications = Notifications,
                        msg = successMsg
                    }.ToJsonString);
            }
        }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            using (var uow = BackOfficeRequestContext.Application.Hive.OpenReader<IContentStore>())
            {
                var items = uow.Repositories.Schemas.GetEntityByRelationType<EntitySchema>(FixedRelationTypes.DefaultRelationType, parentId)
                    //don't include the 'special' schemas
                    .Where(x => !x.Id.IsSystem())
                    .OrderBy(x => x.Name.Value);

                foreach (var treeNode in
                    items
                        .Select(dt =>
                                CreateTreeNode(
                                    dt.Id,
                                    queryStrings,
                                    dt.Name,
                                    Url.GetEditorUrl(dt.Id, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings),
                                    dt.RelationProxies.GetChildRelations(FixedRelationTypes.DefaultRelationType).Any(),
                                    "tree-data-type")))
                {

                    //add the menu items
                    treeNode.AddEditorMenuItem<CreateItem>(this, "createUrl", "CreateNew");
                    treeNode.AddEditorMenuItem<Delete>(this, "deleteUrl", "Delete");
                    treeNode.AddMenuItem<Reload>();

                    NodeCollection.Add(treeNode);
                }
            }

            return UmbracoTree();
        }
 /// <summary>
 /// Need to check if the node being requested is a file, if so, return the rules for it, otherwise process as per normal
 /// </summary>
 /// <param name="parentId"></param>
 /// <param name="queryStrings"></param>
 /// <returns></returns>
 protected override RebelTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
 {
     using (var uow = Hive.CreateReadonly())
     {
         var stylesheet = uow.Repositories.Get<File>(parentId);
         if (!stylesheet.IsContainer)
         {
             var rules = StylesheetHelper.ParseRules(stylesheet);
             if (rules.Any())
             {
                 foreach (var rule in rules)
                 {
                     var hiveId = new HiveId(new Uri(HiveUriRouteMatch), string.Empty, new HiveIdValue(parentId.Value + "/" + rule.Name.Replace(" ", "__s__")));
                     var node = CreateTreeNode(hiveId,
                         null,
                         rule.Name,
                         GetEditorUrl(hiveId, queryStrings),
                         false,
                         "tree-css-item");
                     node.AddEditorMenuItem<Delete>(this, "deleteUrl", "DeleteRule");
                     NodeCollection.Add(node);
                 }
             }
             return RebelTree();
         }
     }
     
     return base.GetTreeData(parentId, queryStrings);
 }
        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()
                });
            }
        }
        protected virtual void AddRecycleBin(HiveId parentId, FormCollection queryStrings)
        {
            //check if this node is the first node in the tree, if so, then append the recycle bin.
            //if the tree is in dialog mode then ignore
            if (RecycleBinId.IsNullValueOrEmpty() || (parentId != RootNodeId) || queryStrings.GetValue<bool>(TreeQueryStringParameters.DialogMode)) 
                return;

            var hiveProvider = GetHiveProvider(parentId, queryStrings);
            using (var uow = hiveProvider.CreateReadonly<IContentStore>())
            {
                var recycleBinEntity = uow.Repositories.Get(RecycleBinId);
                Mandate.That(recycleBinEntity != null, x => new NullReferenceException("Could not find the Recycle bin entity with Id" + RecycleBinId + " in the repository"));

                var recycleBinNode = CreateTreeNode(RecycleBinId, queryStrings, "Recycle bin", Url.GetCurrentDashboardUrl());
                //TODO: check if bin is empty, if so render the bin_empty.png icon
                recycleBinNode.Icon = Url.Content(BackOfficeRequestContext.Application.Settings.RebelFolders.DocTypeIconFolder + "/bin.png");
                
                //add the menu items
                recycleBinNode.AddMenuItem<EmptyRecycleBin>("emptyBinUrl", Url.GetEditorUrl("EmptyBin", null, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings));
                recycleBinNode.AddEditorMenuItem<Permissions>(this, "permissionsUrl", "Permissions");
                recycleBinNode.AddMenuItem<Reload>();

                recycleBinNode.Style.AddCustom("recycle-bin");

                //check if it has children
                recycleBinNode.HasChildren = recycleBinEntity.RelationProxies.GetChildRelations(FixedRelationTypes.DefaultRelationType).Any();

                NodeCollection.Add(recycleBinNode);
            }
            

            
        }
Example #8
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
            });
        }
 /// <summary>
 /// Clears the cache, removes domain cache items and content-url items
 /// </summary>
 /// <param name="clearDomains">true to clear all domain cache</param>
 /// <param name="clearForIds">will clear the URL</param>
 /// <param name="clearMappedUrls">will clear the cache for all URLs mapped to entities</param>
 /// <param name="clearGeneratedUrls">clears cache for all generated urls</param>
 /// <param name="clearAll">Clears all cache</param>
 public void ClearCache(bool clearDomains = false, HiveId[] clearForIds = null, bool clearMappedUrls = false, bool clearGeneratedUrls = false, bool clearAll = false)
 {
     if (clearAll)
     {
         ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(DomainListKey);
         ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(ContentUrlKey + ".+");
         ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(HostnameUrlKey + ".+");
         ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(EntityMappedKey + ".+");
     }
     else
     {
         if (clearMappedUrls)
         {
             ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(EntityMappedKey + ".+");
         }
         if (clearDomains)
         {
             ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(DomainListKey);
         }
         if (clearGeneratedUrls)
         {
             ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(ContentUrlKey + ".+");
             ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(HostnameUrlKey + ".+");
         }
         if (clearForIds != null && clearForIds.Any())
         {
             foreach (var id in clearForIds)
             {
                 ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(Regex.Escape(ContentUrlKey + id) + ".*");
                 ApplicationContext.FrameworkContext.ApplicationCache.InvalidateItems(Regex.Escape(HostnameUrlKey + id) + ".*");
             }
         }
     }
 }
        protected override RebelTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            //if its the first level
            if (parentId == RootNodeId)
            {
                var membershipService = BackOfficeRequestContext.Application.Security.Users;
                var users = membershipService.GetAll().OrderBy(x => x.Username).ToList();

                foreach (var treeNode in users.Select(user => 
                            (TreeNode)CreateTreeNode(
                                user.Id, 
                                queryStrings,
                                //user.Name.OrIfNullOrWhiteSpace(user.Username),
                                user.Username,
                                GetEditorUrl(user.Id, queryStrings))))
                {
                    treeNode.Icon = "tree-user";
                    treeNode.HasChildren = false;

                    //add the menu items
                    treeNode.AddEditorMenuItem<Delete>(this, "deleteUrl", "Delete");

                    NodeCollection.Add(treeNode);
                }
            }
            else
            {
                throw new NotSupportedException("The User tree does not support more than 1 level");
            }

            return RebelTree();
        }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            if (parentId == RootNodeId)
            {
                foreach (var node in PackageTreeNodes
                    .Select(x =>
                            CreateTreeNode(
                                x.Item1,
                                queryStrings,
                                x.Item2,
                                Url.GetEditorUrl(x.Item3, null, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings),
                                x.Item3,
                                false,
                                "tree-repository")))
                {
                    NodeCollection.Add(node);
                }
            }
            else
            {
                throw new NotImplementedException("The Packaging tree does not support more than 1 level");
            }

            return UmbracoTree();
        }
Example #12
0
 /// <summary>
 /// Gets the nices URL for .
 /// </summary>
 /// <param name="id">The id.</param>
 /// <returns></returns>
 public JsonResult NiceUrl(HiveId id)
 {
     return Json(new
         {
             niceUrl = BackOfficeRequestContext.RoutingEngine.GetUrl(id)
         });
 }
 public PublicAccessStatusResult(HiveId sourceId, bool canAccess, HiveId loginPageId, HiveId errorPageId)
 {
     SourceId = sourceId;
     CanAccess = canAccess;
     LoginPageId = loginPageId;
     ErrorPageId = errorPageId;
 }
 public HiveRelationCacheKey(RepositoryTypes repositoryType, HiveId entityId, Direction direction, RelationType relationType)
 {
     RepositoryType = repositoryType;
     EntityId = entityId;
     Direction = direction;
     RelationType = relationType;
 }
        public ActionResult SetParameters(HiveId contentId, string macroAlias, bool isNew, string inlineMacroId = "", string macroParameters = "")
        {
            var viewModel = new SetParametersModel
            {
                ContentId = contentId,
                IsNew = isNew,
                InlineMacroId = inlineMacroId
            };

            var macroEditorModel = GetMacroByAlias(macroAlias);

            BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map
                <MacroEditorModel, SetParametersModel>(macroEditorModel, viewModel);

            if (!string.IsNullOrEmpty(macroParameters))
            {
                var macroParamsDict = macroParameters.DecodeMacroParameters();

                foreach (var macroParam in viewModel.MacroParameters.Where(macroParam => macroParamsDict.ContainsKey(macroParam.Alias)))
                {
                    macroParam.ParameterEditorModel.SetModelValue(macroParamsDict[macroParam.Alias]);
                }
            }

            //return View(EmbeddedViewEngine.EmbeddedViewPath.Create("Umbraco.Cms.Web.PropertyEditors.RichTextBox.Views.InsertMacroDialog.cshtml", "Umbraco.Cms.Web.PropertyEditors"));
            return View(EmbeddedViewPath.Create("Umbraco.Cms.Web.PropertyEditors.RichTextBox.TinyMCE.Views.InsertMacro.SetParameters.cshtml, Umbraco.Cms.Web.PropertyEditors"), viewModel);
        }
        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);
            }
        }
        public virtual ActionResult Rollback(HiveId id)
        {
            var model = new RollbackModel { Id = id };

            using (var uow = Hive.Create<IContentStore>())
            {
                var entity = uow.Repositories.Revisions.GetLatestRevision<TypedEntity>(model.Id);
                if (entity == null)
                    throw new NullReferenceException("Could not find entity with id " + model.Id);

                model.LastRevision = entity;

                var nameAttr = model.LastRevision.Item.Attributes.FirstOrDefault(x => x.AttributeDefinition.Alias == NodeNameAttributeDefinition.AliasValue);
                model.Name = nameAttr != null ? nameAttr.GetValueAsString("Name") : "Unknown";
                model.CreateDate = model.LastRevision.Item.UtcStatusChanged.DateTime;

                var revisions = uow.Repositories.Revisions.GetAll<TypedEntity>(model.LastRevision.Item.Id);

                model.Versions = revisions
                    .OrderByDescending(x => x.MetaData.UtcStatusChanged)
                    .Skip(1) // Skip current revision
                    .Select(x =>
                        {
                            var name = x.MetaData.StatusType.Name.IfNull(y => new LocalizedString(x.MetaData.StatusType.Alias));

                            return new SelectListItem
                                         {
                                             Text = x.MetaData.UtcCreated.DateTime.ToShortDateString() + " " + x.MetaData.UtcCreated.DateTime.ToShortTimeString() + " - '" + name + "'", 
                                             Value = x.MetaData.Id.ToString()
                                         };
                        });
            }

            return View(model);
        }
 public JsonResult IsNodeSelectable(HiveId dataTypeId, HiveId nodeId, Guid treeId)
 {
     var ds = BackOfficeRequestContext.RegisteredComponents.TreeControllers.GetNodeSelectorDataSource(treeId);
     
     try
     {
         return Json(new
         {
             result = CSharpExpressionsUtility.GetNodeFilterResult(BackOfficeRequestContext, dataTypeId, ds, nodeId),
             success = true
         });
     }
     catch (Exception ex)
     {
         var errorMsg = "NodeSelector filter error (see rebel log for full details): " + ex.Message;
         LogHelper.Error<NodeSelectorUtilityController>("The filter executed on the node caused an error", ex);
         Notifications.Add(new NotificationMessage(errorMsg, "Compilation error", NotificationType.Error));
         return new CustomJsonResult(new
         {
             success = false,
             notifications = Notifications,
             errorMsg
         }.ToJsonString);                
     }              
     
 }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            //First node - get the root entities
            if (parentId == RootNodeId)
            {
                foreach (var node in SystemInfoNodes
                    .Select(x =>
                        CreateTreeNode(
                            x.Item1,
                            queryStrings,
                            x.Item2,
                            Url.GetEditorUrl(x.Item3, null, _editorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings),
                            x.Item3)))
                {
                    node.HasChildren = false;
                    NodeCollection.Add(node);
                }
            }
            else
            {
                throw new NotSupportedException("The SystemInfo tree does not support more than 1 level");    
            }

            return UmbracoTree();
        }
Example #20
0
 public void SerializedCommonValues_ContainNoInvalidPathChars(string input)
 {
     CheckInvalidPathChars(input);
     var hiveId = new HiveId(input);
     CheckInvalidPathChars(hiveId.ToString(HiveIdFormatStyle.AsUri));
     CheckInvalidPathChars(hiveId.ToString(HiveIdFormatStyle.UriSafe));
 }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            if (parentId == RootNodeId)
            {
                foreach (var node in BackOfficeRequestContext.Application.Settings.Languages
                    .OrderBy(x => x.Name)
                    .Select(x =>
                            CreateTreeNode(
                                new HiveId(x.IsoCode),
                                queryStrings,
                                x.Name,
                                GetEditorUrl(new HiveId(x.IsoCode), queryStrings),
                                "Edit",
                                false,
                                "tree-language")))
                {
                    node.AddEditorMenuItem<UnsecuredDelete>(this, "deleteUrl", "Delete");

                    NodeCollection.Add(node);
                }
            }
            else
            {
                throw new NotImplementedException("The Languages tree does not support more than 1 level");
            }

            return UmbracoTree();
        }
        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);
            });
        }
 /// <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);
 }
Example #24
0
        public void IsSystem_WhenCreatedFromSystemGuid()
        {
            // Arrange
            var id = new HiveId(Guid.Parse("10000000000000000000000000000100"));

            // Assert
            Assert.IsTrue(id.IsSystem());
        }
        public ActionResult Create(HiveId id)
        {
            var model = new PackageDefinitionEditorModel {ParentId = id};

            PopulateCollections(model);

            return View("Edit", model);
        }
Example #26
0
 public void CreateHiveIdFromRootValue(string input, string rootShouldBe, string providerShouldBe, string valueShouldBe, string toStringShouldBe)
 {
     var id = new HiveId(input);
     Assert.AreEqual(rootShouldBe, id.ProviderGroupRoot == null ? null : id.ProviderGroupRoot.ToString());
     Assert.AreEqual(providerShouldBe, id.ProviderId);
     Assert.AreEqual(valueShouldBe, id.Value.ToString());
     Assert.AreEqual(toStringShouldBe, id.ToUri().ToString());
     Assert.AreEqual(id.ToString(), new HiveId(id.ToString()).ToString());
 }
Example #27
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <remarks>
 /// The Id is a string serialized HiveId and contains the file name of the template
 /// </remarks>
 public TemplateFile(HiveId id)
 {
     Id = id;
     if (id.Value.Type != HiveIdValueTypes.String)
     {
         throw new NotSupportedException(
             "The HiveId for a template must be a string with the value of the template file name and extension");
     }
 }
        protected override RebelTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            using (var uow = Hive.CreateReadonly())
            {
                var repo = uow.Repositories;
                var files = repo.GetAll<File>().Where(x => !x.IsContainer);

                // Create map of files based upon Layout properties
                var fileMap = TemplateHelper.CreateLayoutFileMap(files);

                // Choose the tree depth to render
                var currentKey = "None";
                if (parentId != RootNodeId)
                {
                    var parentFile = files.SingleOrDefault(x => x.Id == parentId);
                    currentKey = Server.MapPath(parentFile.RootRelativePath);
                }

                // Construct tree nodes
                var treeNodes = fileMap[currentKey].Select(f => new
                {
                    treeNode = CreateTreeNode(
                        f.Id,
                        queryStrings,
                        f.GetFileNameForDisplay(),
                        GetEditorUrl(f.Id, queryStrings),
                        fileMap.ContainsKey(Server.MapPath(f.RootRelativePath)),
                        f.Name.ToLower().StartsWith("_viewstart.") 
                            ? "tree-viewstart-template" 
                            : f.Name.StartsWith("_") || f.RelationProxies.GetChildRelations(FixedRelationTypes.DefaultRelationType).Any()
                                ? "tree-master-template" 
                                : "tree-template"
                    ),
                    entity = f
                });

                foreach (var file in treeNodes)
                {
                    // Set menu items
                    file.treeNode.AddEditorMenuItem<CreateItem>(this, "createUrl", "CreateNew");
                    file.treeNode.AddEditorMenuItem<Delete>(this, "deleteUrl", "Delete");
                    file.treeNode.AddMenuItem<Reload>();

                    // Set tree expand url
                    if (file.treeNode.HasChildren)
                    {
                        file.treeNode.JsonUrl = Url.GetTreeUrl(GetType(), file.treeNode.HiveId, queryStrings);
                    }

                    // Add to node collection
                    NodeCollection.Add(file.treeNode);
                }
            }

            return RebelTree();   
        }
Example #29
0
        public PartialViewResult Register(string memberTypeAlias, HiveId memberGroupId, HiveId successRedirectId)
        {
            var viewModel = new RegisterModel
            {
                MemberTypeAlias = memberTypeAlias, 
                MemberGroupId = memberGroupId,
                SuccessRedirectId = successRedirectId,
                RequiresQuestionAndAnswer = _context.Application.Security.Members.MembershipProvider.RequiresQuestionAndAnswer
            };

            return PartialView("RegisterPartial", viewModel);
        }
Example #30
0
        /// <summary>
        /// Creates a data type
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="alias"></param>
        /// <param name="propertyEditor">The PropertyEditor associated with the DataType</param>
        /// <param name="preValues">The pre values stored in the repository for the DataType</param>
        public DataType(HiveId id, string name, string alias, dynamic propertyEditor, string preValues)
        {
            Mandate.ParameterNotEmpty(id, "id");
            Mandate.ParameterNotNullOrEmpty(name, "name");
            Mandate.ParameterNotNullOrEmpty(alias, "alias");
            //Mandate.ParameterNotNull(propertyEditor, "propertyEditor");

            Name = name;
            Alias = alias;
            InternalPropertyEditor = propertyEditor;
            Prevalues = preValues;
        }
        internal static Revision <T> GetLatestRevision <T>(this IEnumerable <IReadonlyProviderRevisionRepository <T> > readonlyRepositories, HiveId hiveId, Uri idRoot, RevisionStatusType revisionStatusType = null)
            where T : class, IVersionableEntity
        {
            Revision <T> returnValue = null;

            //TODO: Determine which repo is the primary one
            //TODO: Ensure population of the incoming queue is sorted by Ordinal
            foreach (var reader in readonlyRepositories)
            {
                returnValue = reader.GetLatestRevision <T>(hiveId, revisionStatusType);
                if (returnValue != null)
                {
                    break;
                }
            }
            return(GroupSessionHelper.MakeIdsAbsolute(returnValue, idRoot));
        }
 internal static void Delete <T>(this IEnumerable <ICoreRepository <T> > repositories, HiveId id)
     where T : class, IReferenceByHiveId
 {
     //TODO: Determine which repo is the primary one
     //TODO: Ensure population of the incoming queue is sorted by Ordinal
     foreach (var repository in repositories)
     {
         repository.Delete <T>(id);
     }
 }
Example #33
0
        public static void ChangeOrCreateRelationMetadata(this ICoreRelationsRepository session, HiveId withSourceId, HiveId withDestinationId, RelationType withRelationType, params RelationMetaDatum[] newMetadata)
        {
            var findRelation = session.FindRelation(withSourceId, withDestinationId, withRelationType) ??
                               new Relation(withRelationType, withSourceId, withDestinationId, 0, newMetadata);

            findRelation.MetaData.Clear();
            newMetadata.ForEach(x => findRelation.MetaData.Add(x));
            session.ChangeRelation(findRelation, findRelation.SourceId, findRelation.DestinationId);
        }
 internal static bool Exists <T>(this IEnumerable <IReadonlyProviderRepository <T> > readonlyRepositoryies, HiveId id)
     where T : class, IReferenceByHiveId
 {
     return(readonlyRepositoryies.Any(readonlyProviderRepository => readonlyProviderRepository.Exists <T>(id)));
 }
        public static IEnumerable <IReadonlyRelation <IRelatableEntity, IRelatableEntity> > GetLazyDescendentRelations <T>(this ICoreReadonlyRepository <T> readonlyRepository, HiveId ascendentId, RelationType relationType = null)
            where T : class, IRelatableEntity
        {
            var items = readonlyRepository.GetDescendentRelations(ascendentId, relationType);

            return(items
                   .Select(relationById => CreateLazyOrUseExistingRelation(readonlyRepository, relationById)));
        }
Example #36
0
 public static IEnumerable <HiveId> GetAncestorIds <T>(this ICoreReadonlyRepository <T> session, HiveId sourceId, RelationType relationType = null)
     where T : class, IRelatableEntity
 {
     return(GetAncestorRelationSourceIds(session, relationType, sourceId));
 }
Example #37
0
 private static HiveId[] GetAncestorRelationSourceIds(this ICoreReadonlyRelationsRepository session, RelationType relationType, HiveId sourceId)
 {
     return(session.GetAncestorRelations(sourceId, relationType).Select(x => x.SourceId).ToArray());
 }
Example #38
0
        public static CompositeEntitySchema GetComposite <TSchema>(this IReadonlyProviderRepository <AbstractSchemaPart> repo, HiveId id)
            where TSchema : EntitySchema
        {
            var schema = repo.Get <TSchema>(id);

            if (schema == null)
            {
                return(null);
            }
            var ancestors = repo.Get <TSchema>(true, repo.GetAncestorRelations(id, FixedRelationTypes.DefaultRelationType).Select(x => x.SourceId).ToArray());

            return(new CompositeEntitySchema(schema, ancestors));
        }
Example #39
0
        /// <summary>
        /// Returns the collection of ancestor ids
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mappingGroup"></param>
        /// <param name="id"></param>
        /// <param name="relationType"></param>
        /// <returns></returns>
        public static EntityPath GetEntityPath <T>(this ICoreReadonlyRepository <T> mappingGroup, HiveId id, RelationType relationType)
            where T : class, IRelatableEntity
        {
            var ancestorOrSelfIds = mappingGroup.GetAncestorsIdsOrSelf(id, relationType);

            return(new EntityPath(ancestorOrSelfIds.Reverse()));
        }
Example #40
0
 public override QueryTestDescription <TypedEntity> GetQueryById(HiveId value)
 {
     return(new QueryTestDescription <TypedEntity>(x => x.Id == value));
 }
 protected virtual void PopulateFileContentFromStub(FileEditorModel model, HiveId stubFileId)
 {
     PopulateFileContentFromStub(model, stubFileId, new Dictionary <string, string>());
 }
        internal static IRelationById FindRelation(this IEnumerable <IReadonlyProviderRelationsRepository> sessions, HiveId sourceId, HiveId destinationId, Uri idRoot, RelationType relationType = null)
        {
            IRelationById result = null;

            foreach (var readonlyRelationsRepository in sessions)
            {
                if (readonlyRelationsRepository.CanReadRelations)
                {
                    result = readonlyRelationsRepository.FindRelation(sourceId, destinationId, relationType);
                }
                if (result != null)
                {
                    break;
                }
            }
            return(GroupSessionHelper.CreateRelationByAbsoluteId(result, idRoot));
        }
Example #43
0
        public static IEnumerable <T> GetChildren <T>(this IProviderRepository <TypedEntity> repository, RelationType relationType, HiveId sourceId, params RelationMetaDatum[] metaDatum)
            where T : TypedEntity, new()
        {
            var relations      = repository.GetChildRelations(sourceId, relationType);
            var destinationIds = relations.Select(x => x.DestinationId).ToArray();

            return(!destinationIds.Any() ? Enumerable.Empty <T>() : repository.Get <T>(true, destinationIds));
        }
Example #44
0
 public static HiveId[] GetDescendantIds(this ICoreReadonlyRelationsRepository session, HiveId sourceId, RelationType relationType)
 {
     return(session.GetDescendentRelations(sourceId, relationType).Select(x => x.DestinationId).ToArray());
 }
Example #45
0
        public static IEnumerable <HiveId> GetAncestorsIdsOrSelf <T>(this ICoreReadonlyRepository <T> session, HiveId sourceId, RelationType relationType = null)
            where T : class, IRelatableEntity
        {
            var ancestorRelationSourceIds = GetAncestorRelationSourceIds(session, relationType, sourceId);

            return(new[] { sourceId }.Union(ancestorRelationSourceIds));
        }
Example #46
0
 public static void AddRelation(this ICoreRelationsRepository session, HiveId sourceId, HiveId destinationId, AbstractRelationType relationType, int ordinal, params RelationMetaDatum[] metaData)
 {
     session.AddRelation(new Relation(relationType, sourceId, destinationId, ordinal, metaData));
 }
        internal static IEnumerable <Revision <T> > GetAll <T>(this IEnumerable <IReadonlyProviderRevisionRepository <T> > readonlyRepositories, HiveId entityId, Uri idRoot, RevisionStatusType revisionStatusType = null)
            where T : class, IVersionableEntity
        {
            //TODO: Determine which repo is the primary one
            //TODO: Ensure population of the incoming queue is sorted by Ordinal
            var totalOutput = new HashSet <Revision <T> >();

            foreach (var reader in readonlyRepositories)
            {
                reader.GetAll <T>(entityId).SkipWhile(SkipAndMerge(reader, totalOutput)).ForEach(x => totalOutput.Add(x));
            }
            return(totalOutput.DistinctBy(x => x.MetaData.Id).Select(x => GroupSessionHelper.MakeIdsAbsolute(x, idRoot)));
        }
Example #48
0
 public static IEnumerable <T> GetEntityByRelationType <T>(this ICoreReadonlyRepository <AbstractSchemaPart> repository, RelationType relationType, HiveId sourceId, params RelationMetaDatum[] metaDatum)
     where T : AbstractSchemaPart, new()
 {
     return(GetChildren <T>(repository, relationType, sourceId, metaDatum));
 }
Example #49
0
        public static IEnumerable <IReadonlyRelation <IRelatableEntity, IRelatableEntity> > GetLazyRelations <T>(this ICoreReadonlyRepository <T> session, HiveId sourceId, Direction direction, RelationType relationType = null)
            where T : class, IRelatableEntity
        {
            switch (direction)
            {
            case Direction.Ancestors:
                return(session.GetLazyAncestorRelations(sourceId, relationType));

            case Direction.Children:
                return(session.GetLazyChildRelations(sourceId, relationType));

            case Direction.Descendents:
                return(session.GetLazyDescendentRelations(sourceId, relationType));

            case Direction.Parents:
                return(session.GetLazyParentRelations(sourceId, relationType));
            }
            return(Enumerable.Empty <IReadonlyRelation <IRelatableEntity, IRelatableEntity> >());
        }
        internal static IEnumerable <IRelationById> GetAncestorRelations(this IEnumerable <IReadonlyProviderRelationsRepository> allProviderRepositories, HiveId descendentId, Uri idRoot, RelationType relationType = null)
        {
            var totalOutput = new HashSet <IRelationById>();

            foreach (var relationsRepository in allProviderRepositories)
            {
                if (relationsRepository.CanReadRelations)
                {
                    var provider  = relationsRepository;
                    var relations = relationsRepository.RepositoryScopedCache.GetOrCreateTyped("rprr_GetAncestorRelations_" + descendentId + (relationType != null ? relationType.RelationName : "any_relationtype"),
                                                                                               () => provider.GetAncestorRelations(descendentId, relationType).ToArray());

                    relations
                    .SkipWhile(SkipAndMergeRelationsFromProviders(relationsRepository.ProviderMetadata, totalOutput))
                    .ForEach(x => totalOutput.Add(x));
                }
            }
            return(totalOutput.Distinct().Select(x => GroupSessionHelper.CreateRelationByAbsoluteId(x, idRoot)));
        }
Example #51
0
        public static IEnumerable <IRelationById> GetRelations(this ICoreReadonlyRelationsRepository session, HiveId sourceId, Direction direction, RelationType relationType = null)
        {
            switch (direction)
            {
            case Direction.Ancestors:
                return(session.GetAncestorRelations(sourceId, relationType));

            case Direction.Children:
                return(session.GetChildRelations(sourceId, relationType));

            case Direction.Descendents:
                return(session.GetDescendentRelations(sourceId, relationType));

            case Direction.Parents:
                return(session.GetParentRelations(sourceId, relationType));
            }
            return(Enumerable.Empty <IReadonlyRelation <IRelatableEntity, IRelatableEntity> >());
        }
Example #52
0
 public static IEnumerable <IRelationById> GetSiblingRelations(this ICoreReadonlyRelationsRepository session, HiveId siblingId, RelationType relationType = null)
 {
     Mandate.ParameterNotEmpty(siblingId, "siblingId");
     return(session.GetBranchRelations(siblingId, relationType).Where(x => !x.DestinationId.EqualsIgnoringProviderId(siblingId)));
 }
Example #53
0
        public static IEnumerable <IRelatableEntity> GetAncestors <T>(this ICoreReadonlyRepository <T> session, HiveId sourceId, RelationType relationType = null)
            where T : class, IRelatableEntity
        {
            var ancestorRelationSourceIds = GetAncestorRelationSourceIds(session, relationType, sourceId);
            var ancestors = session.Get <T>(true, ancestorRelationSourceIds);

            return(ancestors);
        }
Example #54
0
        /// <summary>
        /// Changes an existing relation's source, destination and ordinal
        /// </summary>
        /// <param name="session"></param>
        /// <param name="originalRelation"></param>
        /// <param name="newSourceId"></param>
        /// <param name="newDestinationId"></param>
        /// <param name="newOrdinal"></param>
        public static void ChangeRelation(this ICoreRelationsRepository session, IRelationById originalRelation, HiveId newSourceId, HiveId newDestinationId, int newOrdinal = int.MinValue)
        {
            session.RemoveRelation(originalRelation);
            var useOrdinal = newOrdinal == int.MinValue ? originalRelation.Ordinal : newOrdinal;

            session.AddRelation(new Relation(originalRelation.Type, newSourceId, newDestinationId, useOrdinal, originalRelation.MetaData.ToArray()));
        }
Example #55
0
        public static IEnumerable <T> GetChildren <T>(this ICoreReadonlyRepository <AbstractSchemaPart> repository, RelationType relationType, HiveId sourceId, params RelationMetaDatum[] metaDatum)
            where T : AbstractSchemaPart, new()
        {
            var relations      = repository.GetChildRelations(sourceId, relationType);
            var destinationIds = relations.Select(x => x.DestinationId).ToArray();

            return(!destinationIds.Any() ? Enumerable.Empty <T>() : repository.Get <T>(true, destinationIds));
        }
Example #56
0
        /// <summary>
        /// Changes an existing relation's source, destination and ordinal
        /// </summary>
        /// <param name="session"></param>
        /// <param name="originalSourceId"></param>
        /// <param name="originalDestinationId"></param>
        /// <param name="withRelationType"></param>
        /// <param name="newSourceId"></param>
        /// <param name="newDestinationId"></param>
        /// <param name="newOrdinal"></param>
        public static void ChangeRelation(this ICoreRelationsRepository session, HiveId originalSourceId, HiveId originalDestinationId, RelationType withRelationType, HiveId newSourceId, HiveId newDestinationId, int newOrdinal = int.MinValue)
        {
            var findRelation = session.FindRelation(originalSourceId, originalDestinationId, withRelationType);

            if (findRelation != null)
            {
                session.ChangeRelation(findRelation, newSourceId, newDestinationId, newOrdinal);
            }
        }
Example #57
0
        public static IQueryable <T> QueryChildEntitiesByRelationType <T>(this IEntityRepositoryGroup <IProviderTypeFilter> repository, RelationType relationType, HiveId sourceId)
            where T : TypedEntity, new()
        {
            var childIds = repository.GetChildRelations(sourceId, relationType).Select(x => x.DestinationId).ToArray();

            return(repository.Query <T>().InIds(childIds));
        }
        internal static IEnumerable <IRelationById> GetDescendentRelations(this IEnumerable <IReadonlyProviderRelationsRepository> session, HiveId ancestorId, Uri idRoot, RelationType relationType = null)
        {
            var totalOutput = new HashSet <IRelationById>();

            foreach (var readonlyRelationsRepository in session)
            {
                if (readonlyRelationsRepository.CanReadRelations)
                {
                    readonlyRelationsRepository.GetDescendentRelations(ancestorId, relationType)
                    .SkipWhile(SkipAndMergeRelationsFromProviders(readonlyRelationsRepository.ProviderMetadata, totalOutput))
                    .ForEach(x => totalOutput.Add(x));
                }
            }
            return(totalOutput.Distinct().Select(x => GroupSessionHelper.CreateRelationByAbsoluteId(x, idRoot)));
        }
Example #59
0
 public override IRelationById PerformFindRelation(HiveId sourceId, HiveId destinationId, RelationType relationType)
 {
     return(Helper.PerformFindRelation(sourceId, destinationId, relationType));
 }
Example #60
0
 public static IEnumerable <T> GetChildren <T>(this IQueryable <TypedEntity> repository, RelationType relationType, HiveId sourceId, params RelationMetaDatum[] metaDatum)
     where T : TypedEntity, new()
 {
     return(repository.WithParentIds(relationType, sourceId).Cast <T>().ToList());
 }