public static TypedEntity MapTypedEntity(XElement xElement) { Mandate.ParameterNotNull(xElement, "xElement"); var attribs = new HashSet<TypedAttribute>(); var ordinal = 0; foreach (var childElement in xElement.Elements().Where(x => !x.HasAttributes)) { var typedAttribute = new TypedAttribute(new AttributeDefinition() { Alias = childElement.Name.LocalName, Name = childElement.Name.LocalName, Ordinal = ordinal, Id = HiveId.Empty }, childElement.Value) { Id = HiveId.Empty }; attribs.Add(typedAttribute); ordinal++; } var nodeId = (int)xElement.Attribute("id"); var returnValue = new TypedEntity { // TODO: Replace provider id with injected value inside UoWFactory Id = new HiveId("content", "r-xmlstore-01", new HiveIdValue(nodeId)) }; returnValue.Attributes.Reset(attribs); return returnValue; }
private Revision<TypedEntity> CreateDictionatyItem(string key, Dictionary<string, string> translations) { var schema = FixedSchemas.DictionaryItemSchema; var nameAttributeDefinition = schema.AttributeDefinitions.SingleOrDefault(x => x.Alias == NodeNameAttributeDefinition.AliasValue); var translationAttributeDefinition = schema.AttributeDefinitions.SingleOrDefault(x => x.Alias == DictionaryItemSchema.TranslationsAlias); var entity = new TypedEntity { Id = new HiveId(new Uri("dictionary://"), null, new HiveIdValue(Guid.NewGuid())), EntitySchema = FixedSchemas.DictionaryItemSchema, UtcCreated = DateTime.Now, UtcModified = DateTime.Now, UtcStatusChanged = DateTime.Now }; var nameAttribute = new TypedAttribute(nameAttributeDefinition); nameAttribute.Values.Add("UrlName", key); nameAttribute.Values.Add("Name", key); entity.Attributes.Add(nameAttribute); var translationAttribute = new TypedAttribute(translationAttributeDefinition); foreach (var translation in translations) translationAttribute.Values.Add(translation.Key, translation.Value); entity.Attributes.Add(translationAttribute); var revision = new Revision<TypedEntity>(entity) { MetaData = { StatusType = FixedStatusTypes.Published } }; return revision; }
public static TypedEntity MapTypedEntity(XElement xElement) { Mandate.ParameterNotNull(xElement, "xElement"); var attribs = new HashSet <TypedAttribute>(); var ordinal = 0; foreach (var childElement in xElement.Elements().Where(x => !x.HasAttributes)) { var typedAttribute = new TypedAttribute(new AttributeDefinition() { Alias = childElement.Name.LocalName, Name = childElement.Name.LocalName, Ordinal = ordinal, Id = HiveId.Empty }, childElement.Value) { Id = HiveId.Empty }; attribs.Add(typedAttribute); ordinal++; } var nodeId = (int)xElement.Attribute("id"); var returnValue = new TypedEntity { // TODO: Replace provider id with injected value inside UoWFactory Id = new HiveId("content", "r-xmlstore-01", new HiveIdValue(nodeId)) }; returnValue.Attributes.Reset(attribs); return(returnValue); }
private static void ChangeValue(TypedAttribute nodeNameAttr, IQueryable <TypedEntity> parentQuery, TypedEntity item, string potentialValue, string valueKey, string existsSuffixCheck, string defaultSuffix, string dupeFormat) { var iterationCount = 0; var itExists = false; var originalValue = potentialValue; var valueCheck = potentialValue; do { iterationCount++; itExists = parentQuery.Any(x => x.InnerAttribute <string>(NodeNameAttributeDefinition.AliasValue, valueKey) == valueCheck && x.Id != item.Id); if (itExists) { // Don't concatenate (1) (2) etc. just use the original value plus a count valueCheck = originalValue + string.Format(dupeFormat, iterationCount); } } while (itExists); if (iterationCount > 1) { nodeNameAttr.Values[valueKey] = valueCheck; } //var exists = parentQuery // .Any(x => x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey) == potentialValue && x.Id != item.Id); //if (exists) //{ // // Get the count of items matching potentialValue + "(" // var dupeName = potentialValue + existsSuffixCheck; // var items = parentQuery // .Where( // x => // x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey).StartsWith(dupeName) && // x.Id != item.Id) // .ToList(); // var itemsDebug = items.Select(x => new // { // x.Id, // x.Attributes, // ValueKey = x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey) // }).ToArray(); // var count = items.Count; // if (count == 0) // { // potentialValue = potentialValue + defaultSuffix; // } // else // { // var newCount = (count + 1); // var format = string.Format(dupeFormat, newCount); // potentialValue = potentialValue + format; // } //} //nodeNameAttr.Values[valueKey] = potentialValue; }
public void ShallowCopyAttribute_ThrowsException_IfEntityIsNull() { // Arrange TypedAttribute nullTest = null; // Easy assert Assert.Throws <ArgumentNullException>(() => nullTest.CreateShallowCopy()); }
public TypedAttribute MapAttribute(Attribute attribute, AbstractLookupHelper lookupHelper, AbstractMappingEngine masterMapper) { //TODO: //- Remove Dates //- Add Ordinal to Rdbms for sorting within a tab var mapped = new TypedAttribute(); MapAttribute(attribute, mapped, lookupHelper, masterMapper); return(mapped); }
public static Attribute MapAttribute(TypedAttribute attribute, AbstractLookupHelper lookupHelper, AbstractMappingEngine masterMapper) { //TODO: //- Remove Dates //- Add Ordinal to Rdbms for sorting within a tab var mapped = GetObjectReference(attribute.Id, lookupHelper, () => new Attribute()); MapAttribute(attribute, mapped, lookupHelper, masterMapper); return(mapped); }
public static IEnumerable <dynamic> SelectedMedia(this TypedAttribute attribute, bool includeUnpublished, bool includeRecycled) { //BUG: we are returning content currently since there is no AsDynamic method for Media. // this should still work but may cause problems if people try to access content specific stuff dynamically. // http://issues.rebelcms.com/issue/U5-959 // Also, because of this we cannot validate the media tree type!! return(GetItems <Content, IContentStore>(attribute.SelectedNodeIds().ToArray(), includeUnpublished, includeRecycled, FixedHiveIds.MediaRecylceBin) .AsDynamic()); }
public void SetUp() { var assemblies = new[] { typeof(Umbraco.Tests.Extensions.TestDynamicExtensions).Assembly }; var supportedDynamicTypes = new[] { typeof(Content), typeof(BendyObject) }; var supportedDynamicFieldTypes = new[] { typeof(Content), typeof(TypedAttribute), typeof(BendyObject) }; var bendyMethods = DynamicExtensionsHelper.GetExtensions(assemblies, supportedDynamicTypes); var subBendyMethods = DynamicExtensionsHelper.GetExtensions<DynamicFieldExtensionAttribute>(assemblies, supportedDynamicFieldTypes); var bendy = new BendyObject(); BendyObjectExtensionsHelper.ApplyDynamicExtensions<Content>(bendy, bendyMethods); var content = new Content(); _bendy = bendy; _bendy["__OriginalItem"] = content; var attrType1 = new AttributeType {RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId}; var attrDef1 = new AttributeDefinition {AttributeType = attrType1}; var attr1 = new TypedAttribute(attrDef1); var subBendy1 = new BendyObject(); subBendy1["__OriginalItem"] = attr1; subBendy1.AddLazy("__Parent", () => bendy); subBendy1["__ParentKey"] = "Test"; BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.FileUploadPropertyEditorId, subBendy1, subBendyMethods); _bendy["Test"] = subBendy1; var attrType2 = new AttributeType { RenderTypeProvider = CorePluginConstants.TreeNodePickerPropertyEditorId }; var attrDef2 = new AttributeDefinition { AttributeType = attrType2 }; var attr2 = new TypedAttribute(attrDef2); var subBendy2 = new BendyObject(); subBendy2["__OriginalItem"] = attr2; subBendy2.AddLazy("__Parent", () => bendy); subBendy2["__ParentKey"] = "Test2"; BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.TreeNodePickerPropertyEditorId, subBendy2, subBendyMethods); _bendy["Test2"] = subBendy2; }
public static IEnumerable <Content> SelectedMediaEntities(this TypedAttribute attribute, bool includeUnpublished, bool includeRecycled) { Mandate.ParameterNotNull(attribute, "attribute"); var nodeSelector = ValidateNodeSelectorPropertyEditor(attribute); return(GetItemsWithValidation <Content, IContentStore>( attribute, nodeSelector, Guid.Parse(FixedTreeIds.NodeSelectorMediaTreeId), () => "This method can only be used when the attribute is defined by a NodeSelector PropertyEditor that is configured to use the Media tree", includeUnpublished, includeRecycled, FixedHiveIds.ContentRecylceBin)); }
private static void Add(this TypedAttributeCollection attributeCollection, TypedAttribute typedAttribute) { //NOTE: Here we need to generate an id for this item. // Though Id generation should generally be performed by Hive providers, a TypedAttribute can exist without an // id in the repository when a AttributeDefinition is created on the Schema and there are no TypeEntity revisions // for that schema with the updated AttributeDefinition. if (typedAttribute.Id.IsNullValueOrEmpty()) { typedAttribute.Id = new HiveId(Guid.NewGuid()); } attributeCollection.Add(typedAttribute); }
public void CanSerializeThenDeserializeTypedAttribute() { var att = new TypedAttribute(new NodeNameAttributeDefinition(new AttributeGroup("tab1", "My Group", 5)), "some value"); var result = SerializationService.ToStream(att); Assert.That(result.Success, Is.True); Assert.That(result.ResultStream, Is.Not.Null); var resultJson = result.ResultStream.ToJsonString(); var reHydrated = SerializationService.FromJson <TypedAttribute>(resultJson); Assert.That(reHydrated, Is.Not.Null); }
public static TypedAttribute CreateShallowCopy(this TypedAttribute attribute) { Mandate.ParameterNotNull(attribute, "attribute"); var copied = new TypedAttribute(attribute.AttributeDefinition); foreach (var v in attribute.Values) { copied.Values.Add(v); } copied.Id = HiveId.Empty; copied.UtcCreated = DateTimeOffset.UtcNow; copied.UtcModified = attribute.UtcModified; copied.UtcStatusChanged = attribute.UtcStatusChanged; return(copied); }
/// <summary> /// Ensures that the attribute is defined by a NodeSelector /// </summary> /// <param name="attribute"></param> /// <returns></returns> private static NodeSelectorEditor ValidateNodeSelectorPropertyEditor(TypedAttribute attribute) { Action throwException = () => { throw new NotSupportedException("This extension method can only be used with an attribute that is defined by a property editor of type NodeSelector"); }; var propEditorFactory = DependencyResolver.Current.GetService <IPropertyEditorFactory>(); var propEditor = propEditorFactory.GetPropertyEditor(attribute.AttributeDefinition.AttributeType.RenderTypeProvider); if (propEditor == null) { throwException(); } var nodeSelector = propEditor.Value as NodeSelectorEditor; if (nodeSelector == null) { throwException(); } return(nodeSelector); }
/// <summary> /// Adds a property to the collection if it doesn't exist and returns true, otherwise returns false /// </summary> /// <param name="attributeCollection"></param> /// <param name="typedAttribute"></param> /// <returns></returns> public static bool TryAdd(this TypedAttributeCollection attributeCollection, TypedAttribute typedAttribute) { // First try to find an existing attribute by alias var existing = attributeCollection.FirstOrDefault(x => x.AttributeDefinition.Alias == typedAttribute.AttributeDefinition.Alias); // If it's null, add it if (existing == null) { Add(attributeCollection, typedAttribute); return(true); } // If the attribute exists, but its definition doesn't have an id, but the incoming one does, we should replace it // This is for scenarios where, for example, an entity has been "setup" from a schema that didn't have ids set, and is then // later re-setup from a schema that had ids for its definitions if (existing.AttributeDefinition.Id == HiveId.Empty && typedAttribute.AttributeDefinition.Id != HiveId.Empty) { existing.AttributeDefinition = typedAttribute.AttributeDefinition; } return(false); }
public static IEnumerable <HiveId> SelectedNodeIds(this TypedAttribute attribute) { Mandate.ParameterNotNull(attribute, "attribute"); ValidateNodeSelectorPropertyEditor(attribute); return(attribute.Values //need to ensure they are sorted! .OrderBy(x => { var index = x.Key.Substring(3, x.Key.Length - 3); int i; return int.TryParse(index, out i) ? i : 0; }) .Select(x => { //ensure the value is parsable, this shouldn't happen but we'll be sure to check. var hiveId = HiveId.TryParse(x.Value.ToString()); return hiveId.Success ? hiveId.Result : HiveId.Empty; }) .Where(x => !x.IsNullValueOrEmpty())); //if it didn't parse, don't return it }
/// <summary> /// Returns the items for either the requested Media or Content /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TStore"></typeparam> /// <param name="attribute"></param> /// <param name="nodeSelector"></param> /// <param name="treeId"></param> /// <param name="errMsg"></param> /// <param name="includeUnpublished"></param> /// <param name="includeRecycled"></param> /// <param name="recycleBinId"></param> /// <returns></returns> private static IEnumerable <T> GetItemsWithValidation <T, TStore>( TypedAttribute attribute, NodeSelectorEditor nodeSelector, Guid treeId, Func <string> errMsg, bool includeUnpublished, bool includeRecycled, HiveId recycleBinId) where T : TypedEntity where TStore : class, IProviderTypeFilter { var preVals = nodeSelector.CreatePreValueEditorModel(); preVals.SetModelValues(attribute.AttributeDefinition.AttributeType.RenderTypeProviderConfig); //now we can check if it is set to a content tree if (preVals.SelectedTree != treeId) { throw new InvalidOperationException(errMsg()); } return(GetItems <T, TStore>(attribute.SelectedNodeIds().ToArray(), includeUnpublished, includeRecycled, recycleBinId)); }
public void attrSet( StringI name, TypedAttribute v ) { throw new NotImplementedException(); }
public static IEnumerable <dynamic> SelectedContent(this TypedAttribute attribute, bool includeUnpublished, bool includeRecycled) { return(attribute.SelectedContentEntities(includeUnpublished, includeRecycled) .Select(x => x.AsDynamic())); }
public static TypedEntity CreateTypedEntity(EntitySchema schema, TypedAttribute[] attribs, bool assignId = false) { var entity = new TypedEntity { EntitySchema = schema }; entity.Attributes.Reset(attribs); if (assignId) entity.Id = new HiveId(Guid.NewGuid()); return entity; }
public static Revision<TypedEntity> CreateVersionedTypedEntity(EntitySchema schema, TypedAttribute[] attribs) { var entity = new Revision<TypedEntity> { Item = new TypedEntity { EntitySchema = schema } }; entity.Item.Attributes.Reset(attribs); entity.MetaData = new RevisionData(); return entity; }
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)); }
public void attrSet( StringI name, TypedAttribute v ) { }
/// <summary> /// Returns the value of the key value based on the key, if the key is not found, a null value is returned /// </summary> /// <param name="a"></param> /// <param name="key"></param> /// <returns></returns> public static object GetValue(this TypedAttribute a, string key) { return(a.Values.GetValue(key)); }
public void CanSerializeThenDeserializeTypedAttribute() { var att = new TypedAttribute(new NodeNameAttributeDefinition(new AttributeGroup("tab1", "My Group", 5)), "some value"); var result = SerializationService.ToStream(att); Assert.That(result.Success, Is.True); Assert.That(result.ResultStream, Is.Not.Null); var resultJson = result.ResultStream.ToJsonString(); var reHydrated = SerializationService.FromJson<TypedAttribute>(resultJson); Assert.That(reHydrated, Is.Not.Null); }
/// <summary> /// Adds the attribute alias. /// </summary> /// <param name="d">The d.</param> /// <param name="ta">The ta.</param> public static void AddAttributeAlias(LazyDictionary <string, ItemField> d, TypedAttribute ta) { d.Add(CreateAttributeAliasField(ta.AttributeDefinition.Alias), new ItemField(ta.AttributeDefinition.Alias)); }
/// <summary> /// Returns the value of the key value based on the key as it's string value, if the key is not found, then an empty string is returned /// </summary> /// <param name="a"></param> /// <param name="key"></param> /// <returns></returns> public static string GetValueAsString(this TypedAttribute a, string key) { return(a.Values.GetValueAsString(key)); }
/// <summary> /// Serializes the specified value. /// </summary> /// <param name="value">The value.</param> public dynamic Serialize(TypedAttribute value) { return((dynamic)value.DynamicValue); }
public void MapAttribute(Attribute source, TypedAttribute destination, AbstractLookupHelper lookupHelper, AbstractMappingEngine masterMapper) { destination.AttributeDefinition = MapAttributeDefinition(source.AttributeDefinition, lookupHelper, masterMapper); destination.Id = (HiveId)source.Id; destination.Values.Clear(); foreach (var value in source.AttributeStringValues) { destination.Values.Add(value.ValueKey, value.Value); } foreach (var value in source.AttributeIntegerValues) { destination.Values.Add(value.ValueKey, value.Value); } foreach (var value in source.AttributeDecimalValues) { destination.Values.Add(value.ValueKey, value.Value); } foreach (var value in source.AttributeDateValues) { destination.Values.Add(value.ValueKey, value.Value); } foreach (var value in source.AttributeLongStringValues) { destination.Values.Add(value.ValueKey, value.Value); } //// TODO: Add LanguageInfo to the Values in the persistence (not rdbms) model //destination.Values.LazyLoadFactory = () => //{ // // Using ConcurrentDictionary as it has a handy AddOrUpdate method meaning a quick // // way of using the last-inserted version, should we hit any ValueKey clashes // var items = new ConcurrentDictionary<string, Lazy<object>>(); // foreach (var attributeStringValue in source.AttributeStringValues) // { // var attribValue = attributeStringValue; // var lazyProxyCall = new Lazy<object>(() => attribValue.Value); // items.AddOrUpdate(attribValue.ValueKey, lazyProxyCall, (x,y) => lazyProxyCall); // } // foreach (var attributeIntegerValue in source.AttributeIntegerValues) // { // var attribValue = attributeIntegerValue; // var lazyProxyCall = new Lazy<object>(() => attribValue.Value); // items.AddOrUpdate(attribValue.ValueKey, lazyProxyCall, (x, y) => lazyProxyCall); // } // foreach (var value in source.AttributeDecimalValues) // { // var attribValue = value; // var lazyProxyCall = new Lazy<object>(() => attribValue.Value); // items.AddOrUpdate(attribValue.ValueKey, lazyProxyCall, (x, y) => lazyProxyCall); // } // foreach (var attributeDateValue in source.AttributeDateValues) // { // var attribValue = attributeDateValue; // var lazyProxyCall = new Lazy<object>(() => attribValue.Value); // items.AddOrUpdate(attribValue.ValueKey, lazyProxyCall, (x, y) => lazyProxyCall); // } // foreach (var attributeLongStringValue in source.AttributeLongStringValues) // { // var attribValue = attributeLongStringValue; // var lazyProxyCall = new Lazy<object>(() => attribValue.Value); // items.AddOrUpdate(attribValue.ValueKey, lazyProxyCall, (x, y) => lazyProxyCall); // } // return items; //}; }
protected override void PerformMap(SearchResult source, TypedEntity target, MappingExecutionScope scope) { base.PerformMap(source, target, scope); //lookup the document type from examine var entitySchema = _helper.PerformGet <EntitySchema>(true, LuceneIndexer.IndexNodeIdFieldName, new HiveId(source.Fields[FixedIndexedFields.SchemaId])).ToArray(); if (!entitySchema.Any()) { throw new DataException("Could not find an item in the index with id " + source.Fields[FixedIndexedFields.SchemaId]); } target.EntitySchema = entitySchema.SingleOrDefault(); var ancestorSchemaIds = _helper.PeformGetParentRelations(target.EntitySchema.Id, FixedRelationTypes.DefaultRelationType). SelectRecursive( x => _helper.PeformGetParentRelations(x.SourceId, FixedRelationTypes.DefaultRelationType)). ToArray(); if (ancestorSchemaIds.Any()) { var ancestorSchemas = _helper.PerformGet <EntitySchema>(true, LuceneIndexer.IndexNodeIdFieldName, ancestorSchemaIds.Select(x => x.SourceId).ToArray()).ToArray(); target.EntitySchema = new CompositeEntitySchema(target.EntitySchema, ancestorSchemas); } // We'll check this later if an attribute definition doesn't exist on the current schema so we can check parents var compositeSchema = target.EntitySchema as CompositeEntitySchema; //now we need to build up the attributes, get all attribute aliases and go from there foreach (var f in source.Fields.Where(x => x.Key.StartsWith(FixedAttributeIndexFields.AttributePrefix) && x.Key.EndsWith(FixedAttributeIndexFields.AttributeAlias))) { //get the alias for the attribute var alias = f.Value; //now we can use this alias to find the rest of the attributes values //var nameKey = FixedAttributeIndexFields.AttributePrefix + alias + "." + FixedAttributeIndexFields.AttributeName; var valueKey = FixedAttributeIndexFields.AttributePrefix + alias; var idKey = FixedAttributeIndexFields.AttributePrefix + alias + "." + FixedAttributeIndexFields.AttributeId; //find the associated definition in the schema and set it var def = target.EntitySchema.AttributeDefinitions.SingleOrDefault(x => x.Alias == alias); // Check if the definition is "inherited" because it exists on a parent schema if (def == null) { if (compositeSchema != null) { def = compositeSchema.AllAttributeDefinitions.SingleOrDefault(x => x.Alias == alias); } } if (def != null) { //get all values for the current value (as some attributes can store multiple named values, not just one) var values = source.Fields .Where(k => k.Key.StartsWith(valueKey) //&& !k.Key.EndsWith(FixedAttributeIndexFields.AttributeName) && !k.Key.EndsWith(FixedAttributeIndexFields.AttributeAlias) && !k.Key.EndsWith(FixedAttributeIndexFields.AttributeId)); var attribute = new TypedAttribute(def) { Id = HiveId.Parse(source.Fields[idKey]) }; foreach (var v in values) { //get the value name, it could be blank if this attribute is only storing one value var valueName = v.Key.Substring(valueKey.Length, v.Key.Length - valueKey.Length); if (valueName.IsNullOrWhiteSpace()) { //if its a null value name, then set the dynamic value attribute.DynamicValue = GetRealValueFromField(def.AttributeType.SerializationType, v.Value); } else { //if its a named value, then set it by name attribute.Values.Add(valueName.TrimStart('.'), GetRealValueFromField(def.AttributeType.SerializationType, v.Value)); } } target.Attributes.SetValueOrAdd(attribute); } } }
public static IEnumerable <dynamic> SelectedMedia(this TypedAttribute attribute) { return(attribute.SelectedMedia(false, false)); }
public void SetUp() { var assemblies = new[] { typeof(Rebel.Tests.Extensions.TestDynamicExtensions).Assembly }; var supportedDynamicTypes = new[] { typeof(Content), typeof(BendyObject) }; var supportedDynamicFieldTypes = new[] { typeof(Content), typeof(TypedAttribute), typeof(BendyObject) }; var bendyMethods = DynamicExtensionsHelper.GetExtensions(assemblies, supportedDynamicTypes); var subBendyMethods = DynamicExtensionsHelper.GetExtensions <DynamicFieldExtensionAttribute>(assemblies, supportedDynamicFieldTypes); var bendy = new BendyObject(); BendyObjectExtensionsHelper.ApplyDynamicExtensions <Content>(bendy, bendyMethods); var content = new Content(); _bendy = bendy; _bendy["__OriginalItem"] = content; var attrType1 = new AttributeType { RenderTypeProvider = CorePluginConstants.FileUploadPropertyEditorId }; var attrDef1 = new AttributeDefinition { AttributeType = attrType1 }; var attr1 = new TypedAttribute(attrDef1); var subBendy1 = new BendyObject(); subBendy1["__OriginalItem"] = attr1; subBendy1.AddLazy("__Parent", () => bendy); subBendy1["__ParentKey"] = "Test"; BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.FileUploadPropertyEditorId, subBendy1, subBendyMethods); _bendy["Test"] = subBendy1; var attrType2 = new AttributeType { RenderTypeProvider = CorePluginConstants.TreeNodePickerPropertyEditorId }; var attrDef2 = new AttributeDefinition { AttributeType = attrType2 }; var attr2 = new TypedAttribute(attrDef2); var subBendy2 = new BendyObject(); subBendy2["__OriginalItem"] = attr2; subBendy2.AddLazy("__Parent", () => bendy); subBendy2["__ParentKey"] = "Test2"; BendyObjectExtensionsHelper.ApplyDynamicFieldExtensions(content, CorePluginConstants.TreeNodePickerPropertyEditorId, subBendy2, subBendyMethods); _bendy["Test2"] = subBendy2; }
public static string TestTypedAttributeFieldStringMethodNoArgs(this TypedAttribute attr) { return("Hello Attribute Field World"); }
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)); }
private dynamic SetPropertyValue(CustomTypedEntity <Content> typedEntity, string key, TypedAttribute attribute, LocalizedString type) { dynamic value = attribute.DynamicValue; if (type == UploaderType) { value = _url.GetMediaUrl(typedEntity, key); } else if (type == MediaPickerType) { string id = string.Concat(string.Empty, value); if (!string.IsNullOrEmpty(id)) { value = _url.GetMediaUrl(id, "uploadedFile"); } } return(value); }
/// <summary> /// Adds the attribute alias. /// </summary> /// <param name="d">The d.</param> /// <param name="ta">The ta.</param> public static void AddAttributeAlias(LazyDictionary<string, ItemField> d, TypedAttribute ta) { d.Add(CreateAttributeAliasField(ta.AttributeDefinition.Alias), new ItemField(ta.AttributeDefinition.Alias)); }
public static IEnumerable <Content> SelectedMediaEntities(this TypedAttribute attribute) { return(attribute.SelectedMediaEntities(false, false)); }
//public static void AddAttributeName(LazyDictionary<string, ItemField> d, TypedAttribute ta) //{ // d.Add( // AttributePrefix + ta.AttributeDefinition.Alias + "." + AttributeName, // new ItemField(ta.AttributeDefinition.Name)); //} public static void AddAttributeId(LazyDictionary<string, ItemField> d, TypedAttribute ta) { d.Add(CreateAttributeIdField(ta.AttributeDefinition.Alias), new Lazy<ItemField>(() => new ItemField(ta.Id.Value.ToString()))); //lazy load this id as it might not be set }
public dynamic Serialize(TypedAttribute value) { return (dynamic)value.DynamicValue; }
public AttrProxy(TypedAttribute attr, Player player) { _attr = new SourcedItem<TypedAttribute>(null, "<anon>", attr); _player = player; }
private static void ChangeValue(TypedAttribute nodeNameAttr, IQueryable<TypedEntity> parentQuery, TypedEntity item, string potentialValue, string valueKey, string existsSuffixCheck, string defaultSuffix, string dupeFormat) { var iterationCount = 0; var itExists = false; var originalValue = potentialValue; var valueCheck = potentialValue; do { iterationCount++; itExists = parentQuery.Any(x => x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey) == valueCheck && x.Id != item.Id); if (itExists) { // Don't concatenate (1) (2) etc. just use the original value plus a count valueCheck = originalValue + string.Format(dupeFormat, iterationCount); } } while (itExists); if (iterationCount > 1) { nodeNameAttr.Values[valueKey] = valueCheck; } //var exists = parentQuery // .Any(x => x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey) == potentialValue && x.Id != item.Id); //if (exists) //{ // // Get the count of items matching potentialValue + "(" // var dupeName = potentialValue + existsSuffixCheck; // var items = parentQuery // .Where( // x => // x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey).StartsWith(dupeName) && // x.Id != item.Id) // .ToList(); // var itemsDebug = items.Select(x => new // { // x.Id, // x.Attributes, // ValueKey = x.InnerAttribute<string>(NodeNameAttributeDefinition.AliasValue, valueKey) // }).ToArray(); // var count = items.Count; // if (count == 0) // { // potentialValue = potentialValue + defaultSuffix; // } // else // { // var newCount = (count + 1); // var format = string.Format(dupeFormat, newCount); // potentialValue = potentialValue + format; // } //} //nodeNameAttr.Values[valueKey] = potentialValue; }
public static void MapAttribute(TypedAttribute source, Attribute destination, AbstractLookupHelper lookupHelper, AbstractMappingEngine masterMapper) { destination.AttributeDefinition = MapAttributeDefinition(source.AttributeDefinition, lookupHelper, masterMapper); destination.Id = (Guid)source.Id.Value; var mapLanguageToLocale = MapLanguageToLocale(FixedLocales.Default, lookupHelper, masterMapper); Func <string, bool> keyNotFoundPredicate = x => source.Values.All(y => y.Key != x); destination.AttributeStringValues.RemoveAll(x => keyNotFoundPredicate.Invoke(x.ValueKey)); destination.AttributeDecimalValues.RemoveAll(x => keyNotFoundPredicate.Invoke(x.ValueKey)); destination.AttributeLongStringValues.RemoveAll(x => keyNotFoundPredicate.Invoke(x.ValueKey)); destination.AttributeIntegerValues.RemoveAll(x => keyNotFoundPredicate.Invoke(x.ValueKey)); destination.AttributeDateValues.RemoveAll(x => keyNotFoundPredicate.Invoke(x.ValueKey)); foreach (var value in source.Values) { switch (source.AttributeDefinition.AttributeType.SerializationType.DataSerializationType) { case DataSerializationTypes.LongString: var longString = destination.AttributeLongStringValues.FirstOrDefault(x => x.ValueKey == value.Key) ?? new AttributeLongStringValue() { Locale = mapLanguageToLocale, ValueKey = value.Key, Attribute = destination }; if (value.Value != null) { longString.Value = value.Value.ToString(); } destination.AttributeLongStringValues.Add(longString); break; case DataSerializationTypes.Boolean: case DataSerializationTypes.SmallInt: case DataSerializationTypes.LargeInt: var intVal = destination.AttributeIntegerValues.FirstOrDefault(x => x.ValueKey == value.Key) ?? new AttributeIntegerValue() { Locale = mapLanguageToLocale, ValueKey = value.Key, Attribute = destination }; if (value.Value != null) { intVal.Value = Convert.ToInt32(value.Value); } destination.AttributeIntegerValues.Add(intVal); break; case DataSerializationTypes.Decimal: var decimalValue = destination.AttributeDecimalValues.FirstOrDefault(x => x.ValueKey == value.Key) ?? new AttributeDecimalValue() { Locale = mapLanguageToLocale, ValueKey = value.Key, Attribute = destination }; if (value.Value != null) { decimalValue.Value = (int)value.Value; } destination.AttributeDecimalValues.Add(decimalValue); break; case DataSerializationTypes.Date: var dateVal = destination.AttributeDateValues.FirstOrDefault(x => x.ValueKey == value.Key) ?? new AttributeDateValue() { Locale = mapLanguageToLocale, ValueKey = value.Key, Attribute = destination }; if (value.Value != null) { if (value.Value is DateTimeOffset) { dateVal.Value = (DateTimeOffset)value.Value; } else if (value.Value is DateTime) { dateVal.Value = new DateTimeOffset((DateTime)value.Value); } } destination.AttributeDateValues.Add(dateVal); break; case DataSerializationTypes.String: default: var shortString = destination.AttributeStringValues.FirstOrDefault(x => x.ValueKey == value.Key) ?? new AttributeStringValue() { Locale = mapLanguageToLocale, ValueKey = value.Key, Attribute = destination }; if (value.Value != null) { shortString.Value = value.Value.ToString(); } destination.AttributeStringValues.Add(shortString); break; } } }
//public static void AddAttributeName(LazyDictionary<string, ItemField> d, TypedAttribute ta) //{ // d.Add( // AttributePrefix + ta.AttributeDefinition.Alias + "." + AttributeName, // new ItemField(ta.AttributeDefinition.Name)); //} public static void AddAttributeId(LazyDictionary <string, ItemField> d, TypedAttribute ta) { d.Add(CreateAttributeIdField(ta.AttributeDefinition.Alias), new Lazy <ItemField>(() => new ItemField(ta.Id.Value.ToString()))); //lazy load this id as it might not be set }
public void attrSet( StringI name, TypedAttribute v ) { _attrs[name] = v; }