示例#1
0
 public void SerializedCommonValues_ContainNoInvalidPathChars(string input)
 {
     CheckInvalidPathChars(input);
     var hiveId = new HiveId(input);
     CheckInvalidPathChars(hiveId.ToString(HiveIdFormatStyle.AsUri));
     CheckInvalidPathChars(hiveId.ToString(HiveIdFormatStyle.UriSafe));
 }
示例#2
0
        public void RelationSerializerTests_FromXml_Works()
        {
            //Arrange
            var sourceId      = new HiveId(Guid.NewGuid());
            var destinationId = new HiveId(Guid.NewGuid());
            var relationType  = new RelationType("TestRelationType");
            var xml           = string.Format(
                @"<relation type=""{0}"" sourceId=""{1}"" destinationId=""{2}"" ordinal=""0"">
                    <metaDatum key=""test1"" value=""value1"" />
                    <metaDatum key=""test2"" value=""value2"" />
                 </relation>",
                relationType.RelationName,
                sourceId.ToString(HiveIdFormatStyle.AsUri),
                destinationId.ToString(HiveIdFormatStyle.AsUri));

            //Act
            var relation = RelationSerializer.FromXml(xml);

            //Assert
            Assert.IsTrue(relation != null);
            Assert.IsTrue(relation.Type.RelationName == relationType.RelationName);
            Assert.IsTrue(relation.SourceId.ToString(HiveIdFormatStyle.AsUri) == sourceId.ToString(HiveIdFormatStyle.AsUri));
            Assert.IsTrue(relation.DestinationId.ToString(HiveIdFormatStyle.AsUri) == destinationId.ToString(HiveIdFormatStyle.AsUri));
            Assert.IsTrue(relation.Ordinal == 0);
            Assert.IsTrue(relation.MetaData.Count == 2);
            Assert.IsTrue(relation.MetaData.Single(x => x.Key == "test1").Value == "value1");
            Assert.IsTrue(relation.MetaData.Single(x => x.Key == "test2").Value == "value2");
        }
示例#3
0
        public void SerializedCommonValues_ContainNoInvalidPathChars(string input)
        {
            CheckInvalidPathChars(input);
            var hiveId = new HiveId(input);

            CheckInvalidPathChars(hiveId.ToString(HiveIdFormatStyle.AsUri));
            CheckInvalidPathChars(hiveId.ToString(HiveIdFormatStyle.UriSafe));
        }
示例#4
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());
 }
示例#5
0
        public void ToString_AsUriSafeFormat_FromPartialValue()
        {
            // Arrange
            var val1    = new HiveId("my-string-value");
            var uriSafe = "string$_my-string-value";

            // Assert
            Assert.AreNotEqual(uriSafe, val1.ToString(HiveIdFormatStyle.AsUri));
            Assert.AreEqual(uriSafe, val1.ToString(HiveIdFormatStyle.UriSafe));
        }
示例#6
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());
        }
示例#7
0
        public void ToString_AsUriFormat_FromFullValue()
        {
            // Arrange
            var val1 = new HiveId(new Uri("storage://stylesheets/"), "test-provider", new HiveIdValue("my-string-value"));
            var uri  = "storage://stylesheets/p__test-provider/v__string/my-string-value";

            // Assert
            Assert.AreNotEqual(uri, val1.ToString());
            Assert.AreEqual(uri, val1.ToString(HiveIdFormatStyle.AsUri));
        }
示例#8
0
        public void ToString_AsUriSafeFormat_FromFullValue()
        {
            // Arrange
            var val1    = new HiveId(new Uri("storage://stylesheets/"), "test-provider", new HiveIdValue("my-string-value"));
            var uriSafe = "storage$net_root$stylesheets$_p__test-provider$_v__string$_my-string-value";

            // Assert
            Assert.AreEqual(uriSafe, val1.ToString());
            Assert.AreEqual(uriSafe, val1.ToString(HiveIdFormatStyle.UriSafe));
            Assert.AreNotEqual(uriSafe, val1.ToString(HiveIdFormatStyle.AsUri));
        }
示例#9
0
 private static void AssertCompareHiveIds(HiveId hiveId, HiveId compareTo)
 {
     Assert.AreEqual(hiveId.ProviderGroupRoot, compareTo.ProviderGroupRoot);
     Assert.AreEqual(hiveId.ProviderId, compareTo.ProviderId);
     Assert.AreEqual(hiveId.Value, compareTo.Value);
     Assert.AreEqual(hiveId.Value.Type, compareTo.Value.Type);
     Assert.AreEqual(hiveId, compareTo);
     Assert.AreEqual(hiveId.ToString(), compareTo.ToString());
     Assert.AreEqual(hiveId.ToUri(), compareTo.ToUri());
     Assert.AreEqual(hiveId.ToString(HiveIdFormatStyle.AsUri), compareTo.ToString(HiveIdFormatStyle.AsUri));
     Assert.AreEqual(hiveId.ToString(HiveIdFormatStyle.UriSafe), compareTo.ToString(HiveIdFormatStyle.UriSafe));
     Assert.AreEqual(hiveId.ToString(HiveIdFormatStyle.AutoSingleValue), compareTo.ToString(HiveIdFormatStyle.AutoSingleValue));
 }
示例#10
0
        public void DocumentTypeEditorControllerTests_DocumentType_Saved()
        {
            //Arrange

            var schema  = CreateNewSchema();
            var schema1 = CreateNewSchema(alias: "schema1");
            var schema2 = CreateNewSchema(alias: "schema2");

            var template1 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("home-page.cshtml"));
            var template2 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("faq-page.cshtml"));

            var controller = new DocumentTypeEditorController(GetBackOfficeRequestContext());

            controller.InjectDependencies(new Dictionary <string, string>(), new Dictionary <string, string>
            {
                { "Name", "Hello" },
                { "Alias", "hello" },
                { "Icon", "myicon" },
                { "Thumbnail", "mythumbnail" },
                { "Description", "my description" },
                { "DefaultTemplateId", template1.ToString() },
                { "AllowedTemplates", string.Concat(template1.ToString(), ",", template2.ToString()) },
                { "AllowedChildren", string.Concat(schema1.Id.ToString(), ",", schema2.Id.ToString()) }
            }, GetBackOfficeRequestContext(), false);

            //Act

            var result = controller.EditForm(schema.Id);

            //Assert

            Assert.IsTrue(result is RedirectToRouteResult);

            using (var uow = UmbracoApplicationContext.Hive.OpenReader <IContentStore>())
            {
                var entity = uow.Repositories.Schemas.Get <EntitySchema>(schema.Id);
                if (entity == null)
                {
                    Assert.Fail("no entity found");
                }

                Assert.AreEqual(schema.UtcCreated, entity.UtcCreated);
                Assert.IsTrue(schema.UtcModified < entity.UtcModified);
                Assert.AreEqual("hello", entity.Alias);
                Assert.AreEqual("Hello", entity.Name.Value);
                Assert.AreEqual("myicon", entity.GetXmlConfigProperty("icon"));
                Assert.AreEqual("mythumbnail", entity.GetXmlConfigProperty("thumb"));
                Assert.AreEqual("my description", entity.GetXmlConfigProperty("description"));
                Assert.AreEqual(template1.ToString(), entity.GetXmlConfigProperty("default-template"));
            }
        }
        public void DocumentTypeEditorControllerTests_DocumentType_Saved()
        {
            //Arrange

            var schema = CreateNewSchema();
            var schema1 = CreateNewSchema(alias: "schema1");
            var schema2 = CreateNewSchema(alias: "schema2");

            var template1 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("home-page.cshtml"));
            var template2 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("faq-page.cshtml"));

            var controller = new DocumentTypeEditorController(GetBackOfficeRequestContext());
            controller.InjectDependencies(new Dictionary<string, string>(), new Dictionary<string, string>
                                              {
                                                  {"Name", "Hello"},
                                                  {"Alias", "hello"},
                                                  {"Icon", "myicon"},
                                                  {"Thumbnail", "mythumbnail"},
                                                  {"Description", "my description"},
                                                  {"DefaultTemplateId", template1.ToString()},
                                                  {"AllowedTemplates", string.Concat(template1.ToString(),",", template2.ToString()) },
                                                  {"AllowedChildren", string.Concat(schema1.Id.ToString(),",", schema2.Id.ToString())}
                                              }, GetBackOfficeRequestContext(), false);

            //Act

            var result = controller.EditForm(schema.Id);

            //Assert

            Assert.IsTrue(result is RedirectToRouteResult);

            using (var uow = RebelApplicationContext.Hive.OpenReader<IContentStore>())
            {
                var entity = uow.Repositories.Schemas.Get<EntitySchema>(schema.Id);
                if (entity == null)
                    Assert.Fail("no entity found");

                Assert.AreEqual(schema.UtcCreated, entity.UtcCreated);
                Assert.IsTrue(schema.UtcModified < entity.UtcModified);
                Assert.AreEqual("hello", entity.Alias);
                Assert.AreEqual("Hello", entity.Name.Value);
                Assert.AreEqual("myicon", entity.GetXmlConfigProperty("icon"));
                Assert.AreEqual("mythumbnail", entity.GetXmlConfigProperty("thumb"));
                Assert.AreEqual("my description", entity.GetXmlConfigProperty("description"));
                Assert.AreEqual(template1.ToString(), entity.GetXmlConfigProperty("default-template"));
            }
        }
示例#12
0
        public void Delete <T>(HiveId entityId)
        {
            Mandate.ParameterNotEmpty(entityId, "entityId");

            var file = GetEntity <File>(entityId);

            if (file == null)
            {
                throw new IOException(
                          string.Format("File with id '{0}' does not exist in this providers storage location", entityId));
            }

            if (!file.IsContainer)
            {
                System.IO.File.Delete(file.Location);
            }
            else
            {
                System.IO.Directory.Delete(file.Location, true);
            }

            // Delete any relations
            var entityMd5     = entityId.ToString().ToMd5();
            var searchPattern = "*" + entityMd5 + "*.xml";

            if (Directory.Exists(_relationsFolder))
            {
                var files = Directory.GetFiles(_relationsFolder, searchPattern);
                foreach (var filePath in files)
                {
                    System.IO.File.Delete(filePath);
                }
            }
        }
示例#13
0
        public void DocumentTypeEditorControllerTests_All_Standard_Values_Bound()
        {
            var schema  = CreateNewSchema();
            var schema1 = CreateNewSchema(alias: "schema1");
            var schema2 = CreateNewSchema(alias: "schema2");

            var template1 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("home-page.cshtml"));
            var template2 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("faq-page.cshtml"));

            var controller = new DocumentTypeEditorController(GetBackOfficeRequestContext());

            controller.InjectDependencies(new Dictionary <string, string>(), new Dictionary <string, string>
            {
                { "Name", "Hello" },
                { "Alias", "hello" },
                { "Icon", "myicon" },
                { "Thumbnail", "mythumbnail" },
                { "Description", "my description" },
                { "DefaultTemplateId", template1.ToString() },
                { "AllowedTemplates", string.Concat(template1.ToString(), ",", template2.ToString()) },
                { "AllowedChildren", string.Concat(schema1.Id.ToString(), ",", schema2.Id.ToString()) }
            }, GetBackOfficeRequestContext());

            //Act

            var result = (ViewResult)controller.EditForm(schema.Id);
            var model  = (DocumentTypeEditorModel)result.Model;

            //Assert

            Assert.AreEqual("Hello", model.Name);
            Assert.AreEqual("hello", model.Alias);
            Assert.AreEqual("myicon", model.Icon);
            Assert.AreEqual("mythumbnail", model.Thumbnail);
            Assert.AreEqual("my description", model.Description);
            Assert.AreEqual(template1, model.DefaultTemplateId);

            Assert.AreEqual(2, model.AllowedTemplates.Where(x => x.Selected).Count());
            Assert.AreEqual(template2.ToString(), model.AllowedTemplates.ElementAt(0).Value);
            Assert.AreEqual(template1.ToString(), model.AllowedTemplates.ElementAt(1).Value);

            var allowedChildren = model.AllowedChildren.Where(x => x.Selected).ToArray();

            Assert.AreEqual(2, allowedChildren.Count());
            Assert.AreEqual(schema1.Id.ToString(), allowedChildren.First().Value);
            Assert.AreEqual(schema2.Id.ToString(), allowedChildren.Last().Value);
        }
示例#14
0
        public void CreateFromValues_WithShortProviderGroup()
        {
            // Arrange
            var val1 = new HiveId(new Uri("storage://"), "provider-id", new HiveIdValue(1));

            // Assert
            Assert.AreEqual("storage://p__provider-id/v__int32/1", val1.ToString(HiveIdFormatStyle.AsUri));
        }
示例#15
0
        private static void AssertEntityIdIsRooted(Uri idRoot, HiveId hiveId)
        {
            var message = "For: " + hiveId.ToFriendlyString();

            Assert.NotNull(hiveId.ProviderGroupRoot, message);
            Assert.That(hiveId.ToString(HiveIdFormatStyle.AsUri), Is.StringStarting(idRoot.ToString()), message);
            Assert.AreEqual(hiveId.ProviderGroupRoot, idRoot, message);
            Assert.NotNull(hiveId.ProviderId, message);
        }
示例#16
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());
        }
示例#17
0
        public void ExtensionMethod_ToJsonObject()
        {
            var hiveId = new HiveId("content", "my-provider", new HiveIdValue(Guid.NewGuid()));

            var json = hiveId.ToJsonObject();

            Assert.AreEqual(json["htmlId"].ToString(), hiveId.GetHtmlId());
            Assert.AreEqual(json["rawValue"].ToString(), hiveId.ToString());
            Assert.AreEqual(json["value"].ToString(), hiveId.Value.Value.ToString());
            Assert.AreEqual(json["valueType"].ToString(), ((int)hiveId.Value.Type).ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(json["provider"].ToString(), hiveId.ProviderId);
            Assert.AreEqual(json["scheme"].ToString(), hiveId.ProviderGroupRoot.ToString());
        }
        /// <summary>
        /// Resolves the url for the specified id.
        /// </summary>
        /// <param name="routingEngine"></param>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public static string GetUrl(this IRoutingEngine routingEngine, HiveId id)
        {
            Mandate.ParameterNotEmpty(id, "id");

            var applicationContext = DependencyResolver.Current.GetService <IRebelApplicationContext>();

            var hive = applicationContext.Hive.GetReader <IContentStore>(id.ToUri());

            if (hive != null)
            {
                var key  = CacheKey.Create(new UrlCacheKey(id));
                var item = hive.HiveContext.GenerationScopedCache.GetOrCreate(key, () =>
                {
                    using (var uow = hive.CreateReadonly())
                    {
                        //var entity = uow.Repositories.Get<TypedEntity>(id);
                        var entity = uow.Repositories.OfRevisionType(FixedStatusTypes.Published).InIds(id).FirstOrDefault();
                        if (entity == null)
                        {
                            throw new NullReferenceException("Could not find a TypedEntity in the repository for a content item with id " + id.ToFriendlyString());
                        }

                        return(routingEngine.GetUrlForEntity(entity));
                    }
                });

                var urlResult = item.Value.Item;

                ////return from scoped cache so we don't have to lookup in the same session
                //var urlResult = applicationContext.FrameworkContext.ScopedCache.GetOrCreateTyped<UrlResolutionResult>("nice-url-" + id, () =>
                //    {
                //        using (var uow = hive.CreateReadonly())
                //        {
                //            var entity = uow.Repositories.Get<TypedEntity>(id);
                //            if (entity == null)
                //                throw new NullReferenceException("Could not find a TypedEntity in the repository for a content item with id " + id.ToFriendlyString());

                //            return routingEngine.GetUrlForEntity(entity);
                //        }
                //    });
                if (urlResult.IsSuccess())
                {
                    return(urlResult.Url);
                }

                //return a hashed url with the status
                return("#" + urlResult.Status);
            }

            return(id.ToString());
        }
示例#19
0
        public void PerformDelete <T>(HiveId id)
        {
            // Delete any relations to this id
            GetRelationsTable().RemoveAll(x => x.SourceId.EqualsIgnoringProviderId(id) || x.DestinationId.EqualsIgnoringProviderId(id));
            // Delete any revisions of this id
            var revisions = PerformGetAllRevisions <TypedEntity>()
                            .Where(x => x.Item.Id.EqualsIgnoringProviderId(id));

            foreach (var revision in revisions)
            {
                Cache.Remove(revision.MetaData.Id.ToString());
            }
            Cache.Remove(id.ToString());
        }
示例#20
0
        public void RelationById_Setting_Ids_In_Constructor_Works()
        {
            //Arrange
            var sourceId      = new HiveId(1);
            var destinationId = new HiveId(2);
            var relationType  = new RelationType("TestRelationType");

            //Act
            var relation = new RelationById(sourceId, destinationId, relationType, 0);

            //Assert
            Assert.IsTrue(relation.SourceId.ToString(HiveIdFormatStyle.AsUri) == sourceId.ToString(HiveIdFormatStyle.AsUri));
            Assert.IsTrue(relation.DestinationId.ToString(HiveIdFormatStyle.AsUri) == destinationId.ToString(HiveIdFormatStyle.AsUri));
        }
示例#21
0
        public void ParsingDynamicLazyStringWorks()
        {
            var realId = new HiveId(Guid.NewGuid());
            var lazyHiveId = new Lazy<object>(() => realId.ToString());
            var hiveId = lazyHiveId.Value;
            var myBendy = new BendyObject();
            myBendy["Item"] = new BendyObject();
            myBendy["Item"].Value = new BendyObject(lazyHiveId);

            var asDynamic = (dynamic)myBendy;

            var result = HiveId.Parse(asDynamic.Item.Value);

            Assert.That(result, Is.EqualTo(realId));
        }
        /// <summary>
        /// Resolves the url for the specified id.
        /// </summary>
        /// <param name="routingEngine"></param>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public static string GetUrl(this IRoutingEngine routingEngine, HiveId id)
        {
            Mandate.ParameterNotEmpty(id, "id");

            var applicationContext = DependencyResolver.Current.GetService<IRebelApplicationContext>();

            var hive = applicationContext.Hive.GetReader<IContentStore>(id.ToUri());
            if (hive != null)
            {
                var key = CacheKey.Create(new UrlCacheKey(id));
                var item = hive.HiveContext.GenerationScopedCache.GetOrCreate(key, () =>
                    {
                        using (var uow = hive.CreateReadonly())
                        {
                            //var entity = uow.Repositories.Get<TypedEntity>(id);
                            var entity = uow.Repositories.OfRevisionType(FixedStatusTypes.Published).InIds(id).FirstOrDefault();
                            if (entity == null)
                                throw new NullReferenceException("Could not find a TypedEntity in the repository for a content item with id " + id.ToFriendlyString());

                            return routingEngine.GetUrlForEntity(entity);
                        }
                    });

                var urlResult = item.Value.Item;

                ////return from scoped cache so we don't have to lookup in the same session
                //var urlResult = applicationContext.FrameworkContext.ScopedCache.GetOrCreateTyped<UrlResolutionResult>("nice-url-" + id, () =>
                //    {
                //        using (var uow = hive.CreateReadonly())
                //        {
                //            var entity = uow.Repositories.Get<TypedEntity>(id);
                //            if (entity == null)
                //                throw new NullReferenceException("Could not find a TypedEntity in the repository for a content item with id " + id.ToFriendlyString());

                //            return routingEngine.GetUrlForEntity(entity);
                //        }
                //    });
                if (urlResult.IsSuccess())
                {
                    return urlResult.Url;
                }

                //return a hashed url with the status
                return "#" + urlResult.Status;
            }

            return id.ToString();
        }
示例#23
0
        public void ParsingDynamicLazyStringWorks()
        {
            var realId     = new HiveId(Guid.NewGuid());
            var lazyHiveId = new Lazy <object>(() => realId.ToString());
            var hiveId     = lazyHiveId.Value;
            var myBendy    = new BendyObject();

            myBendy["Item"]       = new BendyObject();
            myBendy["Item"].Value = new BendyObject(lazyHiveId);

            var asDynamic = (dynamic)myBendy;

            var result = HiveId.Parse(asDynamic.Item.Value);

            Assert.That(result, Is.EqualTo(realId));
        }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            //if its the first level
            if (parentId == RootNodeId)
            {
                var hive = BackOfficeRequestContext.Application.Hive.GetReader<ISecurityStore>(
                    //BUG: this check is only a work around because the way that Hive currently works cannot return the 'real' id of the entity. SD.
                    parentId == RootNodeId
                        ? new Uri(ProviderGroupRoot)
                        : parentId.ToUri());

                Mandate.That(hive != null, x => new NotSupportedException("Could not find a hive provider for route: " + parentId.ToString(HiveIdFormatStyle.AsUri)));

                using (var uow = hive.CreateReadonly())
                {
                    //TODO: not sure how this is supposed to be casted to UserGroup
                    var items = uow.Repositories.GetChildren<UserGroup>(FixedRelationTypes.DefaultRelationType, VirtualRoot)
                        .OrderBy(x => x.Name)
                        .ToArray();

                    foreach (var treeNode in items.Select(userGroup =>
                                (TreeNode)CreateTreeNode(
                                    userGroup.Id,
                                    queryStrings,
                                    userGroup.Name,
                                    GetEditorUrl(userGroup.Id, queryStrings))))
                    {
                        treeNode.Icon = "tree-user-type";
                        treeNode.HasChildren = false;

                        //add the menu items
                        if (treeNode.Title != "Administrator")
                            treeNode.AddEditorMenuItem<Delete>(this, "deleteUrl", "Delete");

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

            return UmbracoTree();
        }
        public void Converts_From_Int()
        {
            //Arrange

            var id = new HiveId(1234);
            var converter = TypeDescriptor.GetConverter(typeof(HiveId));
            var encodedId = id.ToString();

            //Assert

            Assert.IsTrue(converter.CanConvertFrom(typeof(int)));
            Assert.IsTrue(converter.CanConvertTo(typeof(string)));
            Assert.AreEqual(1234, converter.ConvertTo(id, typeof(int)));
            Assert.IsTrue(id.Equals(converter.ConvertFrom(1234)));
            Assert.IsTrue(id.Equals(converter.ConvertFrom(encodedId)));
            Assert.AreEqual(id, converter.ConvertFrom(1234));
            Assert.AreEqual(id, converter.ConvertFrom(encodedId));
        }
        public void Converts_From_String()
        {
            //Arrange
            var rawId     = new HiveId("My-Test-Template.cshtml");
            var encodedId = rawId.ToString();
            var converter = TypeDescriptor.GetConverter(typeof(HiveId));

            //Act


            //Assert

            Assert.IsTrue(converter.CanConvertFrom(typeof(string)));
            Assert.IsTrue(converter.CanConvertTo(typeof(string)));
            Assert.AreEqual(encodedId, converter.ConvertTo(rawId, typeof(string)));
            Assert.IsTrue(rawId.Equals(converter.ConvertFrom(encodedId)));
            Assert.AreEqual(rawId, converter.ConvertFrom(encodedId));
        }
        public void Converts_From_String()
        {
            //Arrange
            var rawId = new HiveId("My-Test-Template.cshtml");
            var encodedId = rawId.ToString();
            var converter = TypeDescriptor.GetConverter(typeof(HiveId));

            //Act


            //Assert

            Assert.IsTrue(converter.CanConvertFrom(typeof(string)));
            Assert.IsTrue(converter.CanConvertTo(typeof(string)));
            Assert.AreEqual(encodedId, converter.ConvertTo(rawId, typeof(string)));
            Assert.IsTrue(rawId.Equals(converter.ConvertFrom(encodedId)));
            Assert.AreEqual(rawId, converter.ConvertFrom(encodedId));
        }
        public void Converts_From_Int()
        {
            //Arrange

            var id        = new HiveId(1234);
            var converter = TypeDescriptor.GetConverter(typeof(HiveId));
            var encodedId = id.ToString();

            //Assert

            Assert.IsTrue(converter.CanConvertFrom(typeof(int)));
            Assert.IsTrue(converter.CanConvertTo(typeof(string)));
            Assert.AreEqual(1234, converter.ConvertTo(id, typeof(int)));
            Assert.IsTrue(id.Equals(converter.ConvertFrom(1234)));
            Assert.IsTrue(id.Equals(converter.ConvertFrom(encodedId)));
            Assert.AreEqual(id, converter.ConvertFrom(1234));
            Assert.AreEqual(id, converter.ConvertFrom(encodedId));
        }
        public void ContentEditorControllerTests_Create_New_Wizard_Step_Bound_And_Validated()
        {
            //Arrange

            var selectedDocTypeId = new HiveId("content", "", new HiveIdValue(Guid.NewGuid()));
            var createModel       = new CreateContentModel {
                Name = "test", SelectedDocumentTypeId = selectedDocTypeId
            };

            // Get the parent content schema
            using (var writer = RebelApplicationContext.Hive.OpenWriter <IContentStore>())
            {
                var contentSchemaRoot = writer.Repositories.Schemas.Get <EntitySchema>(FixedHiveIds.ContentRootSchema);
                //create doc type in persistence layer
                var schema = HiveModelCreationHelper.CreateEntitySchema("test", "Test", new AttributeDefinition[] { });
                schema.Id = selectedDocTypeId;
                schema.RelationProxies.EnlistParent(contentSchemaRoot, FixedRelationTypes.DefaultRelationType);
                writer.Repositories.Schemas.AddOrUpdate(schema);
                writer.Complete();
            }

            var controller = new ContentEditorController(GetBackOfficeRequestContext());

            controller.InjectDependencies(new Dictionary <string, string>(), new Dictionary <string, string>
            {
                { "Name", "test" },
                { "SelectedDocumentTypeId", selectedDocTypeId.ToString() }
            }, GetBackOfficeRequestContext());

            //Act

            var result = (ViewResult)controller.CreateNewForm(createModel);
            var model  = (CreateContentModel)result.Model;

            //Assert

            Assert.IsTrue(controller.ModelState.IsValidField("Name"),
                          string.Join("; ", controller.ModelState["Name"].Errors.Select(x => x.ErrorMessage)));
            Assert.IsTrue(controller.ModelState.IsValidField("SelectedDocumentTypeId"),
                          string.Join("; ", controller.ModelState["SelectedDocumentTypeId"].Errors.Select(x => x.ErrorMessage)));

            Assert.AreEqual("test", model.Name);
            Assert.AreEqual((Guid)selectedDocTypeId.Value, (Guid)model.SelectedDocumentTypeId.Value);
        }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            //if its the first level
            if (parentId == RootNodeId)
            {
                var hive = BackOfficeRequestContext.Application.Hive.GetReader<ISecurityStore>(
                    //BUG: this check is only a work around because the way that Hive currently works cannot return the 'real' id of the entity. SD.
                    (parentId == RootNodeId)
                        ? new Uri("security://users")
                        : parentId.ToUri());

                Mandate.That(hive != null, x => new NotSupportedException("Could not find a hive provider for route: " + parentId.ToString(HiveIdFormatStyle.AsUri)));

                using (var uow = hive.CreateReadonly())
                {
                    var items = uow.Repositories.GetEntityByRelationType<User>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserVirtualRoot)
                        .OrderBy(x => x.Name)
                        .ToArray();

                    foreach (var treeNode in items.Select(user =>
                                (TreeNode)CreateTreeNode(
                                    user.Id,
                                    queryStrings,
                                    user.Name,
                                    Url.GetEditorUrl(user.Id, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings))))
                    {
                        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 UmbracoTree();
        }
        public void ContentEditorControllerTests_Create_New_Wizard_Step_Bound_And_Validated()
        {
            //Arrange

            var selectedDocTypeId = new HiveId("content", "", new HiveIdValue(Guid.NewGuid()));
            var createModel = new CreateContentModel { Name = "test", SelectedDocumentTypeId = selectedDocTypeId };
            // Get the parent content schema
            using (var writer = UmbracoApplicationContext.Hive.OpenWriter<IContentStore>())
            {
                var contentSchemaRoot = writer.Repositories.Schemas.Get<EntitySchema>(FixedHiveIds.ContentRootSchema);
                //create doc type in persistence layer
                var schema = HiveModelCreationHelper.CreateEntitySchema("test", "Test", new AttributeDefinition[] { });
                schema.Id = selectedDocTypeId;
                schema.RelationProxies.EnlistParent(contentSchemaRoot, FixedRelationTypes.DefaultRelationType);
                writer.Repositories.Schemas.AddOrUpdate(schema);
                writer.Complete();
            }
            
            var controller = new ContentEditorController(GetBackOfficeRequestContext());
            controller.InjectDependencies(new Dictionary<string, string>(), new Dictionary<string, string>
                                              {
                                                  { "Name", "test" },
                                                  { "SelectedDocumentTypeId", selectedDocTypeId.ToString() }
                                              }, GetBackOfficeRequestContext());

            //Act

            var result = (ViewResult)controller.CreateNewForm(createModel);
            var model = (CreateContentModel)result.Model;

            //Assert

            Assert.IsTrue(controller.ModelState.IsValidField("Name"),
                string.Join("; ", controller.ModelState["Name"].Errors.Select(x => x.ErrorMessage)));
            Assert.IsTrue(controller.ModelState.IsValidField("SelectedDocumentTypeId"), 
                string.Join("; ", controller.ModelState["SelectedDocumentTypeId"].Errors.Select(x => x.ErrorMessage)));

            Assert.AreEqual("test", model.Name);
            Assert.AreEqual((Guid)selectedDocTypeId.Value, (Guid)model.SelectedDocumentTypeId.Value);
        }
 public SelectedTemplateAttribute(HiveId templateId, AttributeGroup group)
     : base(new SelectedTemplateAttributeDefinition(group), templateId.IsNullValueOrEmpty() ? "" : templateId.ToString())
 {
 }
        protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
        {
            //if its the first level
            if (parentId == RootNodeId)
            {
                var hive = BackOfficeRequestContext.Application.Hive.GetReader <ISecurityStore>(
                    //BUG: this check is only a work around because the way that Hive currently works cannot return the 'real' id of the entity. SD.
                    parentId == RootNodeId
                        ? new Uri("security://user-groups/")
                        : parentId.ToUri());

                Mandate.That(hive != null, x => new NotSupportedException("Could not find a hive provider for route: " + parentId.ToString(HiveIdFormatStyle.AsUri)));

                using (var uow = hive.CreateReadonly())
                {
                    //TODO: not sure how this is supposed to be casted to UserGroup
                    var items = uow.Repositories.GetEntityByRelationType <UserGroup>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserGroupVirtualRoot)
                                .OrderBy(x => x.Name)
                                .ToArray();

                    foreach (var treeNode in items.Select(user =>
                                                          (TreeNode)CreateTreeNode(
                                                              user.Id,
                                                              queryStrings,
                                                              user.Name,
                                                              Url.GetEditorUrl(user.Id, EditorControllerId, BackOfficeRequestContext.RegisteredComponents, BackOfficeRequestContext.Application.Settings))))
                    {
                        treeNode.Icon        = "tree-user-type";
                        treeNode.HasChildren = false;

                        //add the menu items
                        if (treeNode.Title != "Administrator")
                        {
                            treeNode.AddEditorMenuItem <Delete>(this, "deleteUrl", "Delete");
                        }

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

            return(UmbracoTree());
        }
示例#34
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));
        }
 private string GetUmbracoUserCacheKeyForId(HiveId id)
 {
     return "hmp_GetUmbracoUser_" + VirtualRootId.ToString().ToMd5() + "_" + id.ToString();
 }
        public void Initialize()
        {
            #region Vars

            IReadonlyEntityRepositoryGroup <IContentStore> readonlyContentStoreRepository;
            IReadonlySchemaRepositoryGroup <IContentStore> readonlyContentStoreSchemaRepository;
            IEntityRepositoryGroup <IContentStore>         contentStoreRepository;
            ISchemaRepositoryGroup <IContentStore>         contentStoreSchemaRepository;

            IReadonlyEntityRepositoryGroup <IFileStore> readonlyFileStoreRepository;
            IReadonlySchemaRepositoryGroup <IFileStore> readonlyFileStoreSchemaRepository;
            IEntityRepositoryGroup <IFileStore>         fileStoreRepository;
            ISchemaRepositoryGroup <IFileStore>         fileStoreSchemaRepository;

            #endregion

            var hive = MockHiveManager.GetManager()
                       .MockContentStore(out readonlyContentStoreRepository, out readonlyContentStoreSchemaRepository, out contentStoreRepository, out contentStoreSchemaRepository)
                       .MockFileStore(out readonlyFileStoreRepository, out readonlyFileStoreSchemaRepository, out fileStoreRepository, out fileStoreSchemaRepository);

            //Setup file store
            var fileId = new HiveId("storage", "file-uploader", new HiveIdValue("test.jpg"));
            var file   = new File
            {
                Id           = fileId,
                Name         = "test.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test")
            };

            readonlyFileStoreRepository
            .Get <File>(true, Arg.Any <HiveId[]>())
            .Returns(new[] { file });

            var thumbnailId = new HiveId("storage", "file-uploader", new HiveIdValue("test_100.jpg"));
            var thumbnail   = new File
            {
                Id           = thumbnailId,
                Name         = "test_100.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test_100")
            };

            var relation = Substitute.For <IReadonlyRelation <IRelatableEntity, IRelatableEntity> >();
            relation.MetaData.Returns(new RelationMetaDataCollection(new[] { new RelationMetaDatum("size", "100") }));
            relation.Source.Returns(file);
            relation.SourceId.Returns(fileId);
            relation.Destination.Returns(thumbnail);
            relation.DestinationId.Returns(thumbnailId);

            readonlyFileStoreRepository.GetLazyChildRelations(fileId, FixedRelationTypes.ThumbnailRelationType)
            .Returns(new[] { relation });

            //Setup media store
            var mediaPickerAttributeDefType = new AttributeType {
                RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId
            };
            var mediaPickerAttributeDef = new AttributeDefinition("umbracoFile", "")
            {
                Id = FixedHiveIds.FileUploadAttributeType, AttributeType = mediaPickerAttributeDefType
            };
            var mediaPickerProperty = new TypedAttribute(mediaPickerAttributeDef, fileId.ToString());

            var mediaId     = new HiveId("0A647849-BF5C-413B-9420-7AB4C9521505");
            var mediaEntity = new TypedEntity {
                Id = mediaId
            };
            mediaEntity.Attributes.Add(mediaPickerProperty);

            //readonlyContentStoreRepository
            //    .Get<TypedEntity>(true, Arg.Any<HiveId[]>())
            //    .Returns(new[] { mediaEntity });

            //readonlyContentStoreRepository
            //    .SingleOrDefault<TypedEntity>(Arg.Any<Expression<Func<TypedEntity, bool>>>())
            //    .Returns(mediaEntity);

            var mediaEntityList = new List <TypedEntity> {
                mediaEntity
            };
            readonlyContentStoreRepository
            .Provider
            .Returns(mediaEntityList.AsQueryable().Provider);

            // Setup application
            var appContext = Substitute.For <IUmbracoApplicationContext>();
            appContext.Hive.Returns(hive);

            // Setup back office request
            _backOfficeRequestContext = Substitute.For <IBackOfficeRequestContext>();
            _backOfficeRequestContext.Application.Returns(appContext);
        }
示例#37
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());
 }
示例#38
0
        public void ToString_AsUriSafeFormat_FromPartialValue()
        {
            // Arrange
            var val1 = new HiveId("my-string-value");
            var uriSafe = "string$_my-string-value";

            // Assert
            Assert.AreNotEqual(uriSafe, val1.ToString(HiveIdFormatStyle.AsUri));
            Assert.AreEqual(uriSafe, val1.ToString(HiveIdFormatStyle.UriSafe));
        }
示例#39
0
 private static void AssertEntityIdIsRooted(Uri idRoot, HiveId hiveId)
 {
     var message = "For: " + hiveId.ToFriendlyString();
     Assert.NotNull(hiveId.ProviderGroupRoot, message);
     Assert.That(hiveId.ToString(HiveIdFormatStyle.AsUri), Is.StringStarting(idRoot.ToString()), message);
     Assert.AreEqual(hiveId.ProviderGroupRoot, idRoot, message);
     Assert.NotNull(hiveId.ProviderId, message);
 }
 /// <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;
 }
示例#41
0
        public void CreateFromValues_WithShortProviderGroup()
        {
            // Arrange
            var val1 = new HiveId(new Uri("storage://"), "provider-id", new HiveIdValue(1));

            // Assert
            Assert.AreEqual("storage://p__provider-id/v__int32/1", val1.ToString(HiveIdFormatStyle.AsUri));
        }
示例#42
0
 private static void AssertCompareHiveIds(HiveId hiveId, HiveId compareTo)
 {
     Assert.AreEqual(hiveId.ProviderGroupRoot, compareTo.ProviderGroupRoot);
     Assert.AreEqual(hiveId.ProviderId, compareTo.ProviderId);
     Assert.AreEqual(hiveId.Value, compareTo.Value);
     Assert.AreEqual(hiveId.Value.Type, compareTo.Value.Type);
     Assert.AreEqual(hiveId, compareTo);
     Assert.AreEqual(hiveId.ToString(), compareTo.ToString());
     Assert.AreEqual(hiveId.ToUri(), compareTo.ToUri());
     Assert.AreEqual(hiveId.ToString(HiveIdFormatStyle.AsUri), compareTo.ToString(HiveIdFormatStyle.AsUri));
     Assert.AreEqual(hiveId.ToString(HiveIdFormatStyle.UriSafe), compareTo.ToString(HiveIdFormatStyle.UriSafe));
     Assert.AreEqual(hiveId.ToString(HiveIdFormatStyle.AutoSingleValue), compareTo.ToString(HiveIdFormatStyle.AutoSingleValue));
 }
示例#43
0
        public void ToString_AsUriSafeFormat_FromFullValue()
        {
            // Arrange
            var val1 = new HiveId(new Uri("storage://stylesheets/"), "test-provider", new HiveIdValue("my-string-value"));
            var uriSafe = "storage$net_root$stylesheets$_p__test-provider$_v__string$_my-string-value";

            // Assert
            Assert.AreEqual(uriSafe, val1.ToString());
            Assert.AreEqual(uriSafe, val1.ToString(HiveIdFormatStyle.UriSafe));
            Assert.AreNotEqual(uriSafe, val1.ToString(HiveIdFormatStyle.AsUri));
        }
示例#44
0
        public void ToString_AsUriFormat_FromFullValue()
        {
            // Arrange
            var val1 = new HiveId(new Uri("storage://stylesheets/"), "test-provider", new HiveIdValue("my-string-value"));
            var uri = "storage://stylesheets/p__test-provider/v__string/my-string-value";

            // Assert
            Assert.AreNotEqual(uri, val1.ToString());
            Assert.AreEqual(uri, val1.ToString(HiveIdFormatStyle.AsUri));
        }
示例#45
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
            });
        }
示例#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);
        }
示例#47
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
            }));
        }
示例#48
0
 private string GetRebelUserCacheKeyForId(HiveId id)
 {
     return("hmp_GetRebelUser_" + VirtualRootId.ToString().ToMd5() + "_" + id.ToString());
 }
        public void Initialize()
        {
            #region Vars

            IReadonlyEntityRepositoryGroup <IContentStore> readonlyContentStoreRepository;
            IReadonlySchemaRepositoryGroup <IContentStore> readonlyContentStoreSchemaRepository;
            IEntityRepositoryGroup <IContentStore>         contentStoreRepository;
            ISchemaRepositoryGroup <IContentStore>         contentStoreSchemaRepository;

            IReadonlyEntityRepositoryGroup <IFileStore> readonlyFileStoreRepository;
            IReadonlySchemaRepositoryGroup <IFileStore> readonlyFileStoreSchemaRepository;
            IEntityRepositoryGroup <IFileStore>         fileStoreRepository;
            ISchemaRepositoryGroup <IFileStore>         fileStoreSchemaRepository;

            #endregion

            var hive = MockHiveManager.GetManager()
                       .MockContentStore(out readonlyContentStoreRepository, out readonlyContentStoreSchemaRepository, out contentStoreRepository, out contentStoreSchemaRepository)
                       .MockFileStore(out readonlyFileStoreRepository, out readonlyFileStoreSchemaRepository, out fileStoreRepository, out fileStoreSchemaRepository);

            //Setup file store
            var fileId = new HiveId("storage", "file-uploader", new HiveIdValue("test.jpg"));
            var file   = new File
            {
                Id           = fileId,
                Name         = "test.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test")
            };

            readonlyFileStoreRepository
            .Get <File>(true, Arg.Any <HiveId[]>())
            .Returns(new[] { file });

            var thumbnailId = new HiveId("storage", "file-uploader", new HiveIdValue("test_100.jpg"));
            var thumbnail   = new File
            {
                Id           = thumbnailId,
                Name         = "test_100.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test_100")
            };

            var relation = Substitute.For <IReadonlyRelation <IRelatableEntity, IRelatableEntity> >();
            relation.MetaData.Returns(new RelationMetaDataCollection(new[] { new RelationMetaDatum("size", "100") }));
            relation.Source.Returns(file);
            relation.SourceId.Returns(fileId);
            relation.Destination.Returns(thumbnail);
            relation.DestinationId.Returns(thumbnailId);

            readonlyFileStoreRepository.GetLazyChildRelations(fileId, FixedRelationTypes.ThumbnailRelationType)
            .Returns(new[] { relation });

            //Setup media store
            var mediaPickerAttributeDefType = new AttributeType {
                RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId
            };
            var mediaPickerAttributeDef = new AttributeDefinition("rebelFile", "")
            {
                Id = FixedHiveIds.FileUploadAttributeType, AttributeType = mediaPickerAttributeDefType
            };
            var mediaPickerProperty = new TypedAttribute(mediaPickerAttributeDef, fileId.ToString());

            var mediaId     = new HiveId("0A647849-BF5C-413B-9420-7AB4C9521505");
            var mediaEntity = new TypedEntity {
                Id = mediaId
            };
            //mediaEntity.SetupFromSchema(FixedSchemas.MediaImageSchema);
            mediaEntity.Attributes.Add(mediaPickerProperty);
            mediaEntity.Attributes["rebelFile"].Values["MediaId"] = "0A647849-BF5C-413B-9420-7AB4C9521505";

            //readonlyContentStoreRepository
            //    .Get<TypedEntity>(true, Arg.Any<HiveId[]>())
            //    .Returns(new[] { mediaEntity });

            //readonlyContentStoreRepository
            //    .SingleOrDefault<TypedEntity>(Arg.Any<Expression<Func<TypedEntity, bool>>>())
            //    .Returns(mediaEntity);

            var mediaEntityList = new List <TypedEntity> {
                mediaEntity
            };
            readonlyContentStoreRepository
            .Query()
            .Returns(mediaEntityList.AsQueryable());

            // Setup application
            var appContext = Substitute.For <IRebelApplicationContext>();
            appContext.Hive.Returns(hive);

            // Setup back office request
            _backOfficeRequestContext = Substitute.For <IBackOfficeRequestContext>();
            _backOfficeRequestContext.Application.Returns(appContext);

            var member = new Member {
                Id = new HiveId("0285372B-AB14-45B6-943A-8709476AB655"), Username = "******"
            };

            // Setup fake HttpContext (Just needed to fake current member)
            var identity = new GenericIdentity(member.Username);
            var user     = new GenericPrincipal(identity, new string[0]);
            var wp       = new SimpleWorkerRequest("/virtual", "c:\\inetpub\\wwwroot\\physical\\", "page.aspx", "query", new StringWriter());
            HttpContext.Current = new HttpContext(wp)
            {
                User = user
            };

            appContext.Security.Members.GetByUsername(member.Username).Returns(member);

            appContext.Security.PublicAccess.GetPublicAccessStatus(member.Id, mediaEntity.Id)
            .Returns(new PublicAccessStatusResult(mediaEntity.Id, true));
        }
 public SelectedTemplateAttribute(HiveId templateId, AttributeGroup group)
     : base(new SelectedTemplateAttributeDefinition(group), templateId.IsNullValueOrEmpty() ? "" : templateId.ToString())
 { }
        public void DocumentTypeEditorControllerTests_All_Standard_Values_Bound()
        {

            var schema = CreateNewSchema();
            var schema1 = CreateNewSchema(alias: "schema1");
            var schema2 = CreateNewSchema(alias: "schema2");

            var template1 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("home-page.cshtml"));
            var template2 = new HiveId(new Uri("storage://templates"), "templates", new HiveIdValue("faq-page.cshtml"));

            var controller = new DocumentTypeEditorController(GetBackOfficeRequestContext());
            controller.InjectDependencies(new Dictionary<string, string>(), new Dictionary<string, string>
                                              {
                                                  {"Name", "Hello"},
                                                  {"Alias", "hello"},
                                                  {"Icon", "myicon"},
                                                  {"Thumbnail", "mythumbnail"},
                                                  {"Description", "my description"},
                                                  {"DefaultTemplateId", template1.ToString()},
                                                  {"AllowedTemplates", string.Concat(template1.ToString(),",", template2.ToString()) },
                                                  {"AllowedChildren", string.Concat(schema1.Id.ToString(),",", schema2.Id.ToString())}
                                              }, GetBackOfficeRequestContext());

            //Act

            var result = (ViewResult)controller.EditForm(schema.Id);
            var model = (DocumentTypeEditorModel)result.Model;

            //Assert

            Assert.AreEqual("Hello", model.Name);
            Assert.AreEqual("hello", model.Alias);
            Assert.AreEqual("myicon", model.Icon);
            Assert.AreEqual("mythumbnail", model.Thumbnail);
            Assert.AreEqual("my description", model.Description);
            Assert.AreEqual(template1, model.DefaultTemplateId);

            Assert.AreEqual(2, model.AllowedTemplates.Where(x => x.Selected).Count());
            Assert.AreEqual(template2.ToString(), model.AllowedTemplates.ElementAt(0).Value);
            Assert.AreEqual(template1.ToString(), model.AllowedTemplates.ElementAt(1).Value);

            var allowedChildren = model.AllowedChildren.Where(x => x.Selected).ToArray();
            Assert.AreEqual(2, allowedChildren.Count());
            Assert.AreEqual(schema1.Id.ToString(), allowedChildren.First().Value);
            Assert.AreEqual(schema2.Id.ToString(), allowedChildren.Last().Value);
        }
示例#52
0
        public void ExtensionMethod_ToJsonObject()
        {
            var hiveId = new HiveId("content", "my-provider", new HiveIdValue(Guid.NewGuid()));

            var json = hiveId.ToJsonObject();

            Assert.AreEqual(json["htmlId"].ToString(), hiveId.GetHtmlId());
            Assert.AreEqual(json["rawValue"].ToString(), hiveId.ToString());
            Assert.AreEqual(json["value"].ToString(), hiveId.Value.Value.ToString());
            Assert.AreEqual(json["valueType"].ToString(), ((int)hiveId.Value.Type).ToString(CultureInfo.InvariantCulture));
            Assert.AreEqual(json["provider"].ToString(), hiveId.ProviderId);
            Assert.AreEqual(json["scheme"].ToString(), hiveId.ProviderGroupRoot.ToString());
        }
        public void Initialize()
        {
            #region Vars

            IReadonlyEntityRepositoryGroup<IContentStore> readonlyContentStoreRepository;
            IReadonlySchemaRepositoryGroup<IContentStore> readonlyContentStoreSchemaRepository;
            IEntityRepositoryGroup<IContentStore> contentStoreRepository;
            ISchemaRepositoryGroup<IContentStore> contentStoreSchemaRepository;

            IReadonlyEntityRepositoryGroup<IFileStore> readonlyFileStoreRepository;
            IReadonlySchemaRepositoryGroup<IFileStore> readonlyFileStoreSchemaRepository;
            IEntityRepositoryGroup<IFileStore> fileStoreRepository;
            ISchemaRepositoryGroup<IFileStore> fileStoreSchemaRepository;

            #endregion

            var hive = MockHiveManager.GetManager()
                .MockContentStore(out readonlyContentStoreRepository, out readonlyContentStoreSchemaRepository, out contentStoreRepository, out contentStoreSchemaRepository)
                .MockFileStore(out readonlyFileStoreRepository, out readonlyFileStoreSchemaRepository, out fileStoreRepository, out fileStoreSchemaRepository);

            //Setup file store
            var fileId = new HiveId("storage", "file-uploader", new HiveIdValue("test.jpg"));
            var file = new File
            {
                Id = fileId,
                Name = "test.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test")
            };

            readonlyFileStoreRepository
                .Get<File>(true, Arg.Any<HiveId[]>())
                .Returns(new[] { file });

            var thumbnailId = new HiveId("storage", "file-uploader", new HiveIdValue("test_100.jpg"));
            var thumbnail = new File
            {
                Id = thumbnailId,
                Name = "test_100.jpg",
                ContentBytes = Encoding.UTF8.GetBytes("test_100")
            };

            var relation = Substitute.For<IReadonlyRelation<IRelatableEntity, IRelatableEntity>>();
            relation.MetaData.Returns(new RelationMetaDataCollection(new[] { new RelationMetaDatum("size", "100") }));
            relation.Source.Returns(file);
            relation.SourceId.Returns(fileId);
            relation.Destination.Returns(thumbnail);
            relation.DestinationId.Returns(thumbnailId);

            readonlyFileStoreRepository.GetLazyChildRelations(fileId, FixedRelationTypes.ThumbnailRelationType)
                .Returns(new[]{ relation });

            //Setup media store
            var mediaPickerAttributeDefType = new AttributeType { RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId };
            var mediaPickerAttributeDef = new AttributeDefinition("umbracoFile", "") { Id = FixedHiveIds.FileUploadAttributeType, AttributeType = mediaPickerAttributeDefType };
            var mediaPickerProperty = new TypedAttribute(mediaPickerAttributeDef, fileId.ToString());

            var mediaId = new HiveId("0A647849-BF5C-413B-9420-7AB4C9521505");
            var mediaEntity = new TypedEntity { Id = mediaId };
            //mediaEntity.SetupFromSchema(FixedSchemas.MediaImageSchema);
            mediaEntity.Attributes.Add(mediaPickerProperty);
            mediaEntity.Attributes["umbracoFile"].Values["MediaId"] = "0A647849-BF5C-413B-9420-7AB4C9521505";

            //readonlyContentStoreRepository
            //    .Get<TypedEntity>(true, Arg.Any<HiveId[]>())
            //    .Returns(new[] { mediaEntity });

            //readonlyContentStoreRepository
            //    .SingleOrDefault<TypedEntity>(Arg.Any<Expression<Func<TypedEntity, bool>>>())
            //    .Returns(mediaEntity);

            var mediaEntityList = new List<TypedEntity> { mediaEntity };
            readonlyContentStoreRepository
                .Query()
                .Returns(mediaEntityList.AsQueryable());

            // Setup application
            var appContext = Substitute.For<IUmbracoApplicationContext>();
            appContext.Hive.Returns(hive);

            // Setup back office request
            _backOfficeRequestContext = Substitute.For<IBackOfficeRequestContext>();
            _backOfficeRequestContext.Application.Returns(appContext);

            var member = new Member {Id = new HiveId("0285372B-AB14-45B6-943A-8709476AB655"), Username = "******"};

            // Setup fake HttpContext (Just needed to fake current member)
            var identity = new GenericIdentity(member.Username);
            var user = new GenericPrincipal(identity, new string[0]);
            var wp = new SimpleWorkerRequest("/virtual", "c:\\inetpub\\wwwroot\\physical\\", "page.aspx", "query", new StringWriter());
            HttpContext.Current = new HttpContext(wp) {User = user};

            appContext.Security.Members.GetByUsername(member.Username).Returns(member);

            appContext.Security.PublicAccess.GetPublicAccessStatus(member.Id, mediaEntity.Id)
                .Returns(new PublicAccessStatusResult(mediaEntity.Id, true));
        }