public void GetField_FieldContainsId_ReturnsConcreteType()
        {
            //Assign
            var item     = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldTypeMapper/GetField");
            var targetId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
            var mapper   = new SitecoreFieldTypeMapper();
            var field    = item.Fields[FieldName];
            var config   = new SitecoreFieldConfiguration();

            config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");

            var context = Context.Create(Utilities.CreateStandardResolver());

            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
            var service = new SitecoreService(Database, context);


            var scContext = new SitecoreDataMappingContext(null, item, service);

            using (new ItemEditing(item, true))
            {
                field.Value = targetId.ToString();
            }

            //Act
            var result = mapper.GetField(field, config, scContext) as Stub;

            //Assert
            Assert.AreEqual(targetId, result.Id);
        }
        public void SetField_ClassContainsIdButItemMissing_ThrowsException()
        {
            //Assign
            var item     = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldTypeMapper/SetField");
            var targetId = Guid.Parse("{11111111-A3F0-410E-8A6D-07FF3A1E78C3}");
            var mapper   = new SitecoreFieldTypeMapper();
            var field    = item.Fields[FieldName];

            var config = new SitecoreFieldConfiguration();

            config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");

            var context = Context.Create(Utilities.CreateStandardResolver());

            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
            var service = new SitecoreService(Database, context);

            var propertyValue = new Stub();

            propertyValue.Id = targetId;

            var scContext = new SitecoreDataMappingContext(null, item, service);

            using (new ItemEditing(item, true))
            {
                field.Value = string.Empty;
            }

            //Act
            using (new ItemEditing(item, true))
            {
                mapper.SetField(field, propertyValue, config, scContext);
            }
        }
        public void GetField_FieldRandomText_ReturnsNull()
        {
            //Assign
            var item     = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreFieldTypeMapper/GetField");
            var targetId = "some random text";
            var mapper   = new SitecoreFieldTypeMapper();
            var field    = item.Fields[FieldName];
            var config   = new SitecoreFieldConfiguration();

            config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");

            var context = Context.Create(Utilities.CreateStandardResolver());

            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));
            var service = new SitecoreService(Database, context);


            var scContext = new SitecoreDataMappingContext(null, item, service);

            using (new ItemEditing(item, true))
            {
                field.Value = targetId.ToString();
            }

            //Act
            var result = mapper.GetField(field, config, scContext) as Stub;

            //Assert
            Assert.IsNull(result);
        }
        public void GetField_FieldIsNull_ReturnsNullImageObject()
        {
            //Assign
            string fieldValue = null;

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
                {
                    new DbField(FieldName)
                    {
                        Value = fieldValue
                    }
                }
            })
            {
                var item    = database.GetItem("/sitecore/content/TestItem");
                var field   = item.Fields[FieldName];
                var mapper  = new SitecoreFieldImageMapper();
                var options = new GetItemOptionsParams();

                var service = Substitute.For <ISitecoreService>();
                service.Config = new Config();

                var context = new SitecoreDataMappingContext(null, null, service, options);


                //Act
                var result = mapper.GetField(field, null, context) as Image;

                //Assert
                Assert.IsNull(result);
            }
        }
Esempio n. 5
0
        public void MapToProperty_GetsValueByFieldId_ReturnsFieldValue()
        {
            //Assign
            var fieldValue = "test value";
            var fieldId    = new ID("{6B43481F-F129-4F53-BEEE-EA84F9B1A6D4}");
            var database   = Sitecore.Configuration.Factory.GetDatabase("master");
            var item       = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToProperty");

            var config = new SitecoreFieldConfiguration();

            config.FieldId = fieldId;

            var mapper = new StubMapper(null);

            mapper.Setup(new DataMapperResolverArgs(null, config));
            mapper.Value = fieldValue;

            var context = new SitecoreDataMappingContext(null, item, null);

            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                item[fieldId] = fieldValue;
                item.Editing.EndEdit();
            }

            //Act
            var result = mapper.MapToProperty(context);

            //Assert
            Assert.AreEqual(fieldValue, result);
        }
        /// <summary>
        /// Sets the field value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.NullReferenceException">Could not find item to save value {0}.Formatted(Configuration)</exception>
        public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context", "The context was incorrectly set");
            
            if(context.Service == null)
                throw new NullReferenceException("The context's service property was null");

            if (context.Service.GlassContext == null)
                throw new NullReferenceException("The service glass context is null");
            
            if (context.Service.Database == null)
                throw new NullReferenceException("The database is not set for the service");

            if (value == null)
                return string.Empty;

            var type = value.GetType();

            var typeConfig = context.Service.GlassContext.GetTypeConfiguration<SitecoreTypeConfiguration>(value);

            if(typeConfig == null)
                throw new NullReferenceException("The type {0} has not been loaded into context {1}".Formatted(type.FullName, context.Service.GlassContext.Name));

            var item = typeConfig.ResolveItem(value, context.Service.Database);
            if(item == null)
                throw new NullReferenceException("Could not find item to save value {0}".Formatted(Configuration));

            return item.ID.ToString();
        }
        public void MapCmsToProperty_DoesNotAlterObject()
        {
            //Assign
            var fieldValue = "hello world";
            var propertyValue = "goodbye world";

            var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreIgnoreMapper/Target");
            var field = item.Fields["Field"];

            var mapper = new SitecoreIgnoreMapper();
            var config = new SitecoreIgnoreMapper();

            using (new ItemEditing(item, true))
            {
                field.Value = fieldValue;
            }

            var stub = new StubClass();
            stub.Field = propertyValue;
            var context = new SitecoreDataMappingContext(stub, item, null);

            //Act
            mapper.MapCmsToProperty(context);


            //Assert
            Assert.AreEqual(stub.Field, propertyValue);
        }
        public void MapToProperty_SitecoreInfoTypeTemplateId_ReturnsTemplateIdAsID()
        {
            //Assign
            var type = SitecoreInfoType.TemplateId;

            var mapper = new SitecoreInfoMapper();
            var config = new SitecoreInfoConfiguration();

            config.Type         = type;
            config.PropertyInfo = typeof(Stub).GetProperty("TemplateId");

            mapper.Setup(new DataMapperResolverArgs(null, config));

            var item     = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");
            var expected = item.TemplateID;

            Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
            var dataContext = new SitecoreDataMappingContext(null, item, null);

            //Act
            var value = mapper.MapToProperty(dataContext);

            //Assert
            Assert.AreEqual(expected, value);
        }
        public void MapToProperty_GetItemByID_ReturnsItem()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var context = Context.Create(Utilities.CreateStandardResolver());
            var mapper = new SitecoreNodeMapper();
            var language = LanguageManager.GetLanguage("en");
            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));

            mapper.Setup(new DataMapperResolverArgs(context, config));

            var obj = new Stub();
            var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Source", language);
            var target = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Target", language);
            var service = Substitute.For<ISitecoreService>();
            var expected = new StubMapped();

            config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
            config.Id = "{EC4351CE-C5F1-4F01-B354-3D26DC7A66CD}";

            service.CreateType(
                typeof(StubMapped),
                Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                false,
                false, null).Returns(expected);

            var mappingContext = new SitecoreDataMappingContext(obj, source, service);

            //Act
            var result = mapper.MapToProperty(mappingContext);

            //Assert
            Assert.AreEqual(expected, result);

        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {

            Image img = new Image();
            ImageField scImg = new ImageField(field);

            int height = 0;
            int.TryParse(scImg.Height, out height);
            int width = 0;
            int.TryParse(scImg.Width, out width);
            int hSpace = 0;
            int.TryParse(scImg.HSpace, out hSpace);
            int vSpace = 0;
            int.TryParse(scImg.VSpace, out vSpace);

            img.Alt = scImg.Alt;
            img.Border = scImg.Border;
            img.Class = scImg.Class;
            img.Height = height;
            img.HSpace = hSpace;
            img.MediaId = scImg.MediaID.Guid;
            if (scImg.MediaItem != null)
                img.Src = MediaManager.GetMediaUrl(scImg.MediaItem);
            img.VSpace = vSpace;
            img.Width = width;

            return img;
        }
        public void MapToProperty_SitecoreInfoTypeTemplateId_ReturnsTemplateIdAsID()
        {
            //Assign

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
            })
            {
                var type = SitecoreInfoType.TemplateId;

                var mapper  = new SitecoreInfoMapper();
                var options = new GetItemOptionsParams();
                var config  = new SitecoreInfoConfiguration();
                config.Type         = type;
                config.PropertyInfo = typeof(Stub).GetProperty("TemplateId");

                mapper.Setup(new DataMapperResolverArgs(null, config));

                var item     = database.GetItem("/sitecore/Content/TestItem");
                var expected = item.TemplateID;

                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
                var dataContext = new SitecoreDataMappingContext(null, item, null, options);

                //Act
                var value = mapper.MapToProperty(dataContext);

                //Assert
                Assert.AreEqual(expected, value);
            }
        }
        public void MapToProperty_ItemHasNoChildren_NoObjectsCreated()
        {
            //Assign
            var database = Sitecore.Configuration.Factory.GetDatabase("master");

            var item   = database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreChildrenMapper/Parent/Child1");
            var mapper = new SitecoreChildrenMapper();

            var config = new SitecoreChildrenConfiguration();

            config.InferType    = false;
            config.IsLazy       = false;
            config.PropertyInfo = typeof(Stub).GetProperty("Children");

            var service   = Substitute.For <ISitecoreService>();
            var predicate = Arg.Is <Item>(x => item.Children.Any(y => x.ID == y.ID));

            //ME - Although this looks correct I am not sure it is
            service.CreateType(typeof(StubChild), predicate, false, false, null).ReturnsForAnyArgs(info => new StubChild()
            {
                Id = info.Arg <Item>().ID
            });
            service.Config = new Config();

            var context = new SitecoreDataMappingContext(null, item, service);

            mapper.Setup(new DataMapperResolverArgs(null, config));

            //Act
            var result = mapper.MapToProperty(context) as IEnumerable <StubChild>;

            //Assert

            Assert.AreEqual(0, result.Count());
        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            if (field == null)
                return string.Empty;

            if (config.Setting == SitecoreFieldSettings.RichTextRaw)
            {
                return field.Value;
            }

            Guid fieldGuid = field.ID.Guid;

            // shortest route - we know whether or not its rich text
            if (isRichTextDictionary.ContainsKey(fieldGuid))
            {
                return GetResult(field, isRichTextDictionary[fieldGuid]);
            }

            // we don't know - it might still be rich text
            bool isRichText = field.TypeKey == _richTextKey;
            isRichTextDictionary.TryAdd(fieldGuid, isRichText);

            // now we know it isn't rich text - return the raw result.
            return GetResult(field, isRichText);
        }
        public void MapToProperty_ConfigurationSetupCorrectly_CallsCreateClassOnService()
        {
            //Assign
            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
            })
            {
                var item = database.GetItem("/sitecore/content/TestItem");
                var service = Substitute.For<ISitecoreService>();
                var scContext = new SitecoreDataMappingContext(null, item, service);

                var config = new SitecoreParentConfiguration();
                config.PropertyInfo = typeof(Stub).GetProperty("Property");

                var mapper = new SitecoreParentMapper();
                mapper.Setup(new DataMapperResolverArgs(null, config));

                //Act
                var result = mapper.MapToProperty(scContext);

                //Assert

                //ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails.
                service.Received()
                    .CreateType(config.PropertyInfo.PropertyType, Arg.Is<Item>(x => x.ID == item.Parent.ID), true, false,
                        null);
            }
        }
        public void MapToProperty_ConfigurationIsLazy_CallsCreateClassOnServiceWithIsLazy()
        {
            //Assign
            var db        = Sitecore.Configuration.Factory.GetDatabase("master");
            var item      = db.GetItem("/sitecore/content/Tests/DataMappers/SitecoreParentMapperFixture/EmptyItem");
            var service   = Substitute.For <ISitecoreService>();
            var scContext = new SitecoreDataMappingContext(null, item, service);

            var config = new SitecoreParentConfiguration();

            config.PropertyInfo = typeof(Stub).GetProperty("Property");
            config.IsLazy       = true;

            var mapper = new SitecoreParentMapper();

            mapper.Setup(new DataMapperResolverArgs(null, config));

            //Act
            var result = mapper.MapToProperty(scContext);

            //Assert

            //ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails.
            service.Received().CreateType(config.PropertyInfo.PropertyType, Arg.Is <Item>(x => x.ID == item.Parent.ID), true, false);
        }
Esempio n. 16
0
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config,
                                        SitecoreDataMappingContext context)
        {
            if (field == null || field.Value.Trim().IsNullOrEmpty())
            {
                return(null);
            }

            Guid fieldGuid = field.ID.Guid;

            // shortest route - we know whether or not its rich text
            var isInternalLink =
                _isInternalLinkFieldDictionary.GetOrAdd(fieldGuid, (id) => field.TypeKey == InternalLinkKey);


            Link link = new Link();

            if (isInternalLink)
            {
                InternalLinkField internalLinkField = new Sitecore.Data.Fields.InternalLinkField(field);
                MapToLinkModel(link, internalLinkField, config, context.Options as GetOptionsSc);
            }
            else
            {
                LinkField linkField = new LinkField(field);

                MapToLinkModel(link, linkField, config, context.Options as GetOptionsSc);
            }


            return(link);
        }
        /// <summary>
        /// Sets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="Glass.Mapper.MapperException">No item with ID {0}. Can not update File Item field.Formatted(newId)</exception>
        public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            File file = value as File;

            var item = field.Item;

            FileField fileField = new FileField(field);

            if (file == null)
            {
                fileField.Clear();
                return;
            }

            if (fileField.MediaID.Guid != file.Id)
            {
                if (file.Id == Guid.Empty)
                {
                    ItemLink link = new ItemLink(item.Database.Name, item.ID, fileField.InnerField.ID, fileField.MediaItem.Database.Name, fileField.MediaID, fileField.MediaItem.Paths.FullPath);
                    fileField.RemoveLink(link);
                }
                else
                {
                    ID newId = new ID(file.Id);
                    Item target = item.Database.GetItem(newId);
                    if (target != null)
                    {
                        fileField.MediaID = newId;
                        ItemLink link = new ItemLink(item.Database.Name, item.ID, fileField.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                        fileField.UpdateLink(link);
                    }
                    else throw new MapperException("No item with ID {0}. Can not update File Item field".Formatted(newId));
                }
            }
        }
        public void MapToProperty_SitecoreInfoTypeLanguage_ReturnsEnLanguageType()
        {
            //Assign

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
            })
            {
                var type = SitecoreInfoType.Language;

                var mapper = new SitecoreInfoMapper();
                var config = new SitecoreInfoConfiguration();
                config.Type = type;
                mapper.Setup(new DataMapperResolverArgs(null, config));

                var item = database.GetItem("/sitecore/Content/TestItem");

                var expected = item.Language;

                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
                var dataContext = new SitecoreDataMappingContext(null, item, null);

                //Act
                var value = mapper.MapToProperty(dataContext);

                //Assert
                Assert.AreEqual(expected, value);
            }
        }
        public void MapToProperty_SitecoreInfoTypeBaseTemplateIds_ReturnsBaseTemplateIds()
        {
            //Assign
            var type = SitecoreInfoType.BaseTemplateIds;

            var mapper = new SitecoreInfoMapper();
            var config = new SitecoreInfoConfiguration();

            config.Type         = type;
            config.PropertyInfo = typeof(Stub).GetProperty("BaseTemplateIds");

            mapper.Setup(new DataMapperResolverArgs(null, config));

            var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");

            Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
            var dataContext = new SitecoreDataMappingContext(null, item, null);

            //Act
            IEnumerable <ID> results;

            using (new SecurityDisabler())
            {
                results = mapper.MapToProperty(dataContext) as IEnumerable <ID>;
            }

            //Assert
            Assert.Greater(results.Count(), 10);
            Assert.IsTrue(results.All(x => x != item.TemplateID));
        }
        public void MapToProperty_SitecoreInfoTypeLanguage_ReturnsEnStringType()
        {
            //Assign
            var type = SitecoreInfoType.Language;

            var mapper = new SitecoreInfoMapper();
            var config = new SitecoreInfoConfiguration();

            config.Type         = type;
            config.PropertyInfo = new FakePropertyInfo(typeof(string), "StringField", typeof(Stub));
            mapper.Setup(new DataMapperResolverArgs(null, config));

            var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");

            var expected = item.Language.Name;


            Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
            var dataContext = new SitecoreDataMappingContext(null, item, null);

            //Act
            var value = mapper.MapToProperty(dataContext);

            //Assert
            Assert.AreEqual(expected, value);
        }
        public void MapToProperty_MediaUrlWithFlag_ReturnsModifiedUrl(
            SitecoreInfoMediaUrlOptions option,
            string expected
            )
        {
            //Assign
            var mapper = new SitecoreInfoMapper();
            var config = new SitecoreInfoConfiguration();

            config.Type            = SitecoreInfoType.MediaUrl;
            config.MediaUrlOptions = option;
            mapper.Setup(new DataMapperResolverArgs(null, config));

            Sitecore.Context.Site = null;

            var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");

            Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
            var dataContext = new SitecoreDataMappingContext(null, item, null);

            //Act
            var value = mapper.MapToProperty(dataContext);

            //Assert
            Assert.AreEqual(expected, value);
        }
        public void MapToCms_SavingName_UpdatesTheItemName()
        {
            //Assign
            var type     = SitecoreInfoType.Name;
            var expected = "new  name";

            var mapper = new SitecoreInfoMapper();
            var config = new SitecoreInfoConfiguration();

            config.Type = type;
            mapper.Setup(new DataMapperResolverArgs(null, config));

            var item = _db.GetItem("/sitecore/Content/Tests/DataMappers/SitecoreInfoMapper/DataMappersEmptyItem");

            Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");


            var dataContext = new SitecoreDataMappingContext(null, item, null);

            dataContext.PropertyValue = expected;

            string actual = string.Empty;

            //Act
            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                mapper.MapToCms(dataContext);
                actual = item.Name;
                item.Editing.CancelEdit();
            }

            //Assert
            Assert.AreEqual(expected, actual);
        }
        public void MapToProperty_SitecoreInfoTypeNotSet_ThrowsException()
        {
            //Assign
            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
            })
            {
                SitecoreInfoType type = SitecoreInfoType.NotSet;

                var mapper = new SitecoreInfoMapper();
                var config = new SitecoreInfoConfiguration();
                config.Type = type;

                var item    = database.GetItem("/sitecore/Content/TestItem");
                var options = new GetItemOptionsParams();

                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
                var dataContext = new SitecoreDataMappingContext(null, item, null, options);

                //Act
                Assert.Throws <MapperException>(() => mapper.Setup(new DataMapperResolverArgs(null, config)));

                //Assert
                //No asserts expect exception
            }
        }
        public void MapToProperty_ItemIdAsID_ReturnsIdAsID()
        {
            //Assign
            string targetPath = "/sitecore/content/target";

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Target")
            })
            {
                var mapper   = new SitecoreIdMapper();
                var config   = new SitecoreIdConfiguration();
                var property = typeof(Stub).GetProperty("IDId");
                var options  = new GetItemOptionsParams();

                config.PropertyInfo = property;

                mapper.Setup(new DataMapperResolverArgs(null, config));

                var item = database.GetItem("/sitecore/content/Target");

                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
                var dataContext = new SitecoreDataMappingContext(null, item, null, options);
                var expected    = item.ID;

                //Act
                var value = mapper.MapToProperty(dataContext);

                //Assert
                Assert.AreEqual(expected, value);
            }
        }
        public void MapToProperty_SitecoreInfoTypeItemuri_ReturnsFullItemUri()
        {
            //Assign
            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
            })
            {
                var type    = SitecoreInfoType.ItemUri;
                var options = new GetItemOptionsParams();

                var mapper = new SitecoreInfoMapper();
                var config = new SitecoreInfoConfiguration();
                config.Type         = type;
                config.PropertyInfo = new FakePropertyInfo(typeof(string), "StringField", typeof(Stub));
                mapper.Setup(new DataMapperResolverArgs(null, config));

                var item = database.GetItem("/sitecore/Content/TestItem");

                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
                var dataContext = new SitecoreDataMappingContext(null, item, null, options);

                //Act
                var value = mapper.MapToProperty(dataContext) as ItemUri;

                //Assert
                Assert.AreEqual(item.ID, value.ItemID);
                Assert.AreEqual(item.Language, value.Language);
                Assert.AreEqual(item.Database.Name, value.DatabaseName);
                Assert.AreEqual(item.Version, value.Version);
            }
        }
        /// <summary>
        /// Gets the field value.
        /// </summary>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            Type type = config.PropertyInfo.PropertyType;
            //Get generic type
            Type pType = Glass.Mapper.Utilities.GetGenericArgument(type);

            //The enumerator only works with piped lists
            IEnumerable<string> parts = fieldValue.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            //replace any pipe encoding with an actual pipe
            parts = parts.Select(x => x.Replace(Global.PipeEncoding, "|")).ToArray();
            
            
            
            IEnumerable<object> items = parts.Select(x => Mapper.GetFieldValue(x, Mapper.Configuration as SitecoreFieldConfiguration, context)).ToArray();
            var list = Utilities.CreateGenericType(typeof (List<>), new Type[] {pType}) as IList;
            
            foreach (var item in items)
            {
                if(item != null)
                    list.Add(item);
            }

            return list;
        }
        public void MapToProperty_GetItemByIdDifferentLanguageTargetDoesNotExistInLanguage_ReturnsNull()
        {
            //Assign
            var config = new SitecoreNodeConfiguration();
            var context = Context.Create(Utilities.CreateStandardResolver());
            var mapper = new SitecoreNodeMapper();
            var language = LanguageManager.GetLanguage("af-ZA");
            context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration"));

            mapper.Setup(new DataMapperResolverArgs(context, config));

            var obj = new Stub();
            var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/Source", language);
            var target = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreNodeMapper/TargetOneLanguage", language);
            var service = Substitute.For<ISitecoreService>();
            var expected = new StubMapped();

            config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
            config.Id = "{03CDE6B5-B2A2-40D6-A944-53D66DDD2CA4}";

            service.CreateType(
                typeof(StubMapped),
                Arg.Is<Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                false,
                false, null).Returns(expected);

            var mappingContext = new SitecoreDataMappingContext(obj, source, service);

            //Act
            var result = mapper.MapToProperty(mappingContext);

            //Assert
            Assert.IsNull(result);
        }
        public void MapToProperty_ItemIdAsGuid_ReturnsIdAsGuid()
        {
            //Assign
            string targetPath = "/sitecore/content/target";

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Target")
            })
            {
                var mapper = new SitecoreIdMapper();
                var config = new SitecoreIdConfiguration();
                var property = typeof(Stub).GetProperty("GuidId");
                var item = database.GetItem("/sitecore/content/target");

                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");

                config.PropertyInfo = property;

                mapper.Setup(new DataMapperResolverArgs(null, config));

                var dataContext = new SitecoreDataMappingContext(null, item, null);
                var expected = item.ID.Guid;

                //Act
                var value = mapper.MapToProperty(dataContext);

                //Assert
                Assert.AreEqual(expected, value);
            }
        }
        public void MapToProperty_ParentDoesNotHaveLanguageVersion_ReturnsNull()
        {
            //Assign
            var db       = Sitecore.Configuration.Factory.GetDatabase("master");
            var language = LanguageManager.GetLanguage("af-ZA");
            var item     = db.GetItem("/sitecore/content/Tests/DataMappers/SitecoreParentMapperFixture/EmptyItem", language);

            //parent mustn't have a version
            Assert.AreEqual(0, item.Parent.Versions.Count);

            var service   = Substitute.For <ISitecoreService>();
            var scContext = new SitecoreDataMappingContext(null, item, service);

            var config = new SitecoreParentConfiguration();

            config.PropertyInfo = typeof(Stub).GetProperty("Property");
            config.InferType    = true;

            var mapper = new SitecoreParentMapper();

            mapper.Setup(new DataMapperResolverArgs(null, config));

            //Act
            var result = mapper.MapToProperty(scContext);

            //Assert

            //ME - I am not sure why I have to use the Arg.Is but just using item.Parent as the argument fails.
            service.Received().CreateType(config.PropertyInfo.PropertyType, Arg.Is <Item>(x => x.ID == item.Parent.ID), true, true, null);
            Assert.IsNull(result);
        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            var data = field.GetBlobStream();

            MemoryStream stream = null;

            if (data.CanRead)
            {
                 stream = new MemoryStream();

                byte[] buffer = new byte[2048];
                int bytesRead;


                while ((bytesRead = data.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }

                data.Close();

                stream.Seek(0, SeekOrigin.Begin);
            }
            return stream;
        }
 /// <summary>
 /// Gets the field value.
 /// </summary>
 /// <param name="fieldValue">The field value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.Object.</returns>
 /// <exception cref="Glass.Mapper.MapperException">Could not convert value to double</exception>
 public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config,
                                      SitecoreDataMappingContext context)
 {
     if (fieldValue.IsNullOrEmpty()) return 0f;
     float dValue = 0f;
     if (float.TryParse(fieldValue, NumberStyles.Any, CultureInfo.InvariantCulture, out dValue)) return dValue;
     else throw new MapperException("Could not convert value to double");
 }
 /// <summary>
 /// Gets the field value.
 /// </summary>
 /// <param name="fieldValue">The field value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.Object.</returns>
 /// <exception cref="Glass.Mapper.MapperException">Could not convert value to double</exception>
 public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config,
                                      SitecoreDataMappingContext context)
 {
     if (fieldValue.IsNullOrEmpty()) return 0;
     int dValue = 0;
     if (int.TryParse(fieldValue, NumberStyles.Any, CultureInfo.InvariantCulture, out dValue)) return dValue;
     else throw new MapperException("Could not convert value to Integer");
 }
        /// <summary>
        /// Gets the field value.
        /// </summary>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config,
                                             SitecoreDataMappingContext context)
        {
            if (fieldValue.IsNullOrEmpty()) return Guid.Empty;


            return Guid.Parse(fieldValue);
        }
 /// <summary>
 /// Sets the field value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.String.</returns>
 /// <exception cref="Glass.Mapper.MapperException">The value is not of type System.Guid</exception>
 public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     if (value is ID)
     {
         return ((ID)value).ToString();
     }
     else throw new MapperException("The value is not of type Sitecore.Data.ID");
 }
 /// <summary>
 /// Sets the field value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.String.</returns>
 /// <exception cref="Glass.Mapper.MapperException">The value is not of type System.Guid</exception>
 public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     if (value is Guid)
     {
         return ((Guid)value).ToString("B").ToUpper();
     }
     else throw new MapperException("The value is not of type System.Guid");
 }
        /// <summary>
        /// Sets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        public override void SetField(Sitecore.Data.Fields.Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {

            if (value == null)
            {
                return;
            }
            field.SetBlobStream(value as Stream);
        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            if (string.IsNullOrWhiteSpace(field.Value))
            {
                return null;
            }

            return base.GetField(field, config, context);
        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            Image img = new Image();
            ImageField scImg = new ImageField(field);

            MapToImage(img, scImg);

            return img;
        }
Esempio n. 39
0
        public void MapCmsToProperty_PageEditorOnly_FieldNotUpdated()
        {
            //Assign
            var templateId = ID.NewID;
            var fieldId    = ID.NewID;
            var targetId   = ID.NewID;

            using (Db database = new Db
            {
                new DbTemplate(templateId)
                {
                    { "Field", "" }
                },
                new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
            })
            {
                var fieldValue = "test value set";
                var preValue   = "some other value";
                var fieldName  = "Field";
                var item       = database.GetItem("/sitecore/content/Target");
                var options    = new GetItemOptionsParams();

                var config = new SitecoreFieldConfiguration();
                config.FieldName    = fieldName;
                config.PropertyInfo = typeof(Stub).GetProperty("Property");
                config.ReadOnly     = false;
                config.Setting      = SitecoreFieldSettings.PageEditorOnly;

                var mapper = new StubMapper(null);
                mapper.Setup(new DataMapperResolverArgs(null, config));
                mapper.Value = preValue;

                Assert.IsFalse(mapper.ReadOnly);

                var context = new SitecoreDataMappingContext(new Stub(), item, null, options);

                using (new SecurityDisabler())
                {
                    item.Editing.BeginEdit();
                    item[fieldName] = fieldValue;
                    item.Editing.EndEdit();
                }

                //Act
                using (new SecurityDisabler())
                {
                    item.Editing.BeginEdit();
                    mapper.MapCmsToProperty(context);
                    item.Editing.EndEdit();
                }
                //Assert
                var itemAfter =
                    database.GetItem("/sitecore/content/Target");
                Assert.AreEqual(mapper.Value, preValue);
                Assert.AreEqual(fieldValue, itemAfter[fieldName]);
            }
        }
 /// <summary>
 /// Sets the field value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.String.</returns>
 /// <exception cref="System.NotSupportedException">The value is not of type System.Decimal</exception>
 public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     if (value is decimal)
     {
         return value.ToString();
     }
     else
         throw new NotSupportedException("The value is not of type System.Decimal");
 }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            FileField fileField = new FileField(field);
            File file = new File();
            if (fileField.MediaItem != null)
                file.Src = MediaManager.GetMediaUrl(fileField.MediaItem);
            file.Id = fileField.MediaID.Guid;

            return file;
        }
        /// <summary>
        /// Sets the field value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.NotSupportedException">The value is not of type System.Double</exception>
        public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            double? doubleValue = value as double?;
            if (doubleValue.HasValue)
            {
                return doubleValue.Value.ToString(CultureInfo.InvariantCulture);
            }

            throw new NotSupportedException("The value is not of type System.Double");
        }
 /// <summary>
 /// Sets the field value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.String.</returns>
 /// <exception cref="System.NotSupportedException">The value is not of type System.DateTime</exception>
 public override string SetFieldValue(object value, Configuration.SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     if (value is DateTime)
     {
         DateTime date = (DateTime)value;
         return global::Sitecore.DateUtil.ToIsoDate(date);
     }
     else
         throw new NotSupportedException("The value is not of type System.DateTime");
 }
        /// <summary>
        /// Sets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        public override void SetField(Sitecore.Data.Fields.Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            if (value == null)
            {
                field.Value = null;
                return;
            }

            base.SetField(field, value, config, context);
        }
 /// <summary>
 /// Sets the field value.
 /// </summary>
 /// <param name="value">The value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.String.</returns>
 public override string SetFieldValue( object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     if (value is bool)
     {
         bool actual = (bool)value;
         return actual ? "1" : "0";
     }
     else
         throw new NotSupportedException("The value is not of type System.Boolean");
 }
        public void SetField_ClassContainsNoIdProperty_ThrowsException()
        {
            //Assign
            var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");

            using (Db database = new Db
            {
                new DbTemplate(new ID(templateId))
                {
                    new DbField("Field")
                    {
                        Type = "text"
                    }
                },

                new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
            })
            {
                var item     = database.GetItem("/sitecore/content/Target");
                var targetId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
                var mapper   = new SitecoreFieldTypeMapper();
                var field    = item.Fields["Field"];
                var options  = new GetItemOptionsParams();

                var config = new SitecoreFieldConfiguration();
                config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyNoId");

                var context = Context.Create(Utilities.CreateStandardResolver());
                context.Load(new OnDemandLoader <SitecoreTypeConfiguration>(typeof(StubContaining)));

                var service = new SitecoreService(database.Database, context);

                var propertyValue = new StubNoId();

                var scContext = new SitecoreDataMappingContext(null, item, service, options);

                using (new ItemEditing(item, true))
                {
                    field.Value = string.Empty;
                }

                //Act
                using (new ItemEditing(item, true))
                {
                    Assert.Throws <NotSupportedException>(() =>
                    {
                        mapper.SetField(field, propertyValue, config,
                                        scContext);
                    });
                }

                //Assert
                Assert.AreEqual(string.Empty, item["Field"]);
            }
        }
Esempio n. 47
0
        public void MapToProperty_SitecoreInfoType_GetsExpectedValueFromSitecore(
            SitecoreInfoType type, object expected
            )
        {
            //Assign
            var mapper = new SitecoreInfoMapper();
            var config = new SitecoreInfoConfiguration();

            config.Type = type;
            mapper.Setup(new DataMapperResolverArgs(null, config));

            Sitecore.Context.Site = null;
            var templateId = ID.NewID;
            var itemId     = new ID("031501A9C7F24596BD659276DA3A627A");
            var options    = new GetItemOptionsParams();

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbTemplate("TestTemplate", templateId),
                new Sitecore.FakeDb.DbItem("TestItem", itemId)
                {
                    Fields = { new FakeDbField(new ID("{B5E02AD9-D56F-4C41-A065-A133DB87BDEB}"), "DataMappersEmptyItem DisplayName") },
                    TemplateID = templateId,
                }
            })
            {
#if SC90 || SC91 || SC92
                var mediaUrlProvider = Substitute.For <BaseMediaManager>();

                SitecoreVersionAbstractions.MediaManager = new LazyResetable <BaseMediaManager>(() => mediaUrlProvider);

                mediaUrlProvider
                .GetMediaUrl(Arg.Is <Sitecore.Data.Items.MediaItem>(i => i.ID == itemId), Arg.Any <MediaUrlOptions>())
                .Returns("/~/media/Test.ashx");
#else
                Sitecore.Resources.Media.MediaProvider mediaProvider = Substitute.For <Sitecore.Resources.Media.MediaProvider>();
                mediaProvider
                .GetMediaUrl(Arg.Is <Sitecore.Data.Items.MediaItem>(i => i.ID == itemId), Arg.Any <MediaUrlOptions>())
                .Returns("/~/media/Test.ashx");

                new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider);
#endif

                var item = database.GetItem("/sitecore/content/TestItem");
                Assert.IsNotNull(item, "Item is null, check in Sitecore that item exists");
                var dataContext = new SitecoreDataMappingContext(null, item, null, options);

                //Act
                var value = mapper.MapToProperty(dataContext);

                //Assert
                Assert.AreEqual(expected, value);
            }
        }
        /// <summary>
        /// Gets the field value.
        /// </summary>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetFieldValue(string fieldValue, Configuration.SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            var isoDate = Sitecore.DateUtil.IsoDateToDateTime(fieldValue);
#if (SC80 || SC81)
            return fieldValue.EndsWith("Z", StringComparison.OrdinalIgnoreCase) 
                ? Sitecore.DateUtil.ToServerTime(isoDate) 
                : isoDate;
#else
            return isoDate;
#endif
        }
        /// <summary>
        /// Gets the field value.
        /// </summary>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config,
                                             SitecoreDataMappingContext context)
        {
            if (fieldValue.IsNullOrEmpty())
            {
                return(Guid.Empty);
            }


            return(Guid.Parse(fieldValue));
        }
        /// <summary>
        /// Sets the field value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.String.</returns>
        public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            NameValueCollection collection = value as NameValueCollection;

            if (collection != null)
            {
                return Utilities.ConstructQueryString(collection);
            }
            else return string.Empty;

        }
        public void MapToProperty_GetItemByPathDifferentLanguage_ReturnsItem()
        {
            //Assign

            var language = LanguageManager.GetLanguage("af-ZA");

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Source")
                {
                    new Sitecore.FakeDb.DbField("Title")
                    {
                        { language.Name, language.Name }
                    }
                },
                new Sitecore.FakeDb.DbItem("Target")
                {
                    new Sitecore.FakeDb.DbField("Title")
                    {
                        { language.Name, language.Name }
                    }
                },
            })
            {
                var config = new SitecoreNodeConfiguration();
                var mapper = new SitecoreNodeMapper();

                mapper.Setup(new DataMapperResolverArgs(null, config));

                var obj      = new Stub();
                var source   = database.Database.GetItem("/sitecore/content/Source", language);
                var target   = database.Database.GetItem("/sitecore/content/Target", language);
                var service  = Substitute.For <ISitecoreService>();
                var expected = new StubMapped();

                config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
                config.Path         = "/sitecore/content/Target";

                service.CreateType(
                    typeof(StubMapped),
                    Arg.Is <Item>(x => x.Paths.FullPath == target.Paths.FullPath && x.Language == language),
                    false,
                    false, null).Returns(expected);
                service.ItemVersionHandler.VersionCountEnabledAndHasVersions(target).Returns(true);

                var mappingContext = new SitecoreDataMappingContext(obj, source, service);

                //Act
                var result = mapper.MapToProperty(mappingContext);

                //Assert
                Assert.AreEqual(expected, result);
            }
        }
Esempio n. 52
0
        public void MapPropertyToCms_FieldReadOnly_FieldNotUpdated()
        {
            //Assign
            var templateId = ID.NewID;
            var fieldId    = ID.NewID;
            var targetId   = ID.NewID;

            using (Db database = new Db
            {
                new DbTemplate(templateId)
                {
                    { "Field", "" }
                },
                new Sitecore.FakeDb.DbItem("Target", targetId, templateId),
            })
            {
                var fieldValue = "test value set";
                var fieldName  = "Field";
                var item       = database.GetItem("/sitecore/content/Target");

                var config = new SitecoreFieldConfiguration();
                config.FieldName    = fieldName;
                config.PropertyInfo = typeof(Stub).GetProperty("Property");
                config.ReadOnly     = true;

                var mapper = new StubMapper(null);
                mapper.Setup(new DataMapperResolverArgs(null, config));
                mapper.Value = fieldValue;

                Assert.IsTrue(mapper.ReadOnly);

                var context = new SitecoreDataMappingContext(new Stub(), item, null);

                using (new SecurityDisabler())
                {
                    item.Editing.BeginEdit();
                    item[fieldName] = string.Empty;
                    item.Editing.EndEdit();
                }

                //Act
                using (new SecurityDisabler())
                {
                    item.Editing.BeginEdit();
                    mapper.MapPropertyToCms(context);
                    item.Editing.EndEdit();
                }
                //Assert
                var itemAfter =
                    database.GetItem("/sitecore/content/Target");
                Assert.AreNotEqual(mapper.Value, itemAfter[fieldName]);
                Assert.AreEqual(item[fieldName], itemAfter[fieldName]);
            }
        }
        public void GetField_RichText_ValueGoesByRenderFieldPipeline()
        {
            //Assign
            var fieldBase =
                "<p>Test with <a href=\"~/link.aspx?_id=BFD7975DF42F41E19DDA9A38E971555F&amp;_z=z\">link</a></p>";
            var fieldValue = SimpleRenderField.ReplacementKey + fieldBase;

            ;
            var expected = SimpleRenderField.ReplacementValue + fieldBase;

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
                {
                    new DbField(FieldName)
                    {
                        Value = fieldValue,
                        Type = "Rich Text"
                    }
                }
            })
            {
                using (new FakeSite())
                {
                    var item =
                        database.GetItem("/sitecore/content/TestItem");
                    var field = item.Fields[FieldName];

                    var mapper = new SitecoreFieldStringMapper();
                    var config = new SitecoreFieldConfiguration();

                    Sitecore.Context.Site = Sitecore.Configuration.Factory.GetSite("website");
                    Sitecore.Context.Site.SetDisplayMode(DisplayMode.Preview, DisplayModeDuration.Remember);

                    using (new ItemEditing(item, true))
                    {
                        field.Value = fieldValue;
                    }


                    var context = new SitecoreDataMappingContext(null, item, null, new GetItemByPathOptions());


                    //Act
                    var result = mapper.GetField(field, config, context) as string;

                    Sitecore.Context.Site = null;

                    //Assert
                    Assert.AreEqual(expected, result);
                }
            }
        }
Esempio n. 54
0
        public void MapToProperty_GetItemByPathDifferentLanguage_ReturnsItem()
        {
            //Assign

            var language = LanguageManager.GetLanguage("af-ZA");

            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("Source")
                {
                    new Sitecore.FakeDb.DbField("Title")
                    {
                        { language.Name, language.Name }
                    }
                },
                new Sitecore.FakeDb.DbItem("Target")
                {
                    new Sitecore.FakeDb.DbField("Title")
                    {
                        { language.Name, language.Name }
                    }
                },
            })
            {
                var config = new SitecoreNodeConfiguration();
                var mapper = new SitecoreNodeMapper();

                mapper.Setup(new DataMapperResolverArgs(null, config));

                var obj      = new Stub();
                var source   = database.Database.GetItem("/sitecore/content/Source", language);
                var target   = database.Database.GetItem("/sitecore/content/Target", language);
                var service  = Substitute.For <ISitecoreService>();
                var expected = new StubMapped();
                var options  = new GetItemOptionsParams();

                config.PropertyInfo = typeof(Stub).GetProperty("StubMapped");
                config.Path         = "/sitecore/content/Target";


                service.GetItem(Arg.Is <GetItemByItemOptions>(x => x.Item.Uri == target.Uri)).Returns(expected);


                var mappingContext = new SitecoreDataMappingContext(obj, source, service, options);

                //Act
                var result = mapper.MapToProperty(mappingContext);

                //Assert
                Assert.AreEqual(expected, result);
            }
        }
        public void MapToProperty_ItemHasThreeChildren_ThreeObjectAreCreated()
        {
            //Assign
            using (Db database = new Db
            {
                new Sitecore.FakeDb.DbItem("TestItem")
                {
                    new Sitecore.FakeDb.DbItem("Child1"),
                    new Sitecore.FakeDb.DbItem("Child2"),
                    new Sitecore.FakeDb.DbItem("Child3")

                }
            })
            {

                var item = database.GetItem("/sitecore/content/TestItem");
                var mapper = new SitecoreChildrenMapper();

                var config = new SitecoreChildrenConfiguration();
                config.InferType = false;
                config.IsLazy = false;
                config.PropertyInfo = typeof(Stub).GetProperty("Children");

                var service = Substitute.For<ISitecoreService>();
                var predicate = Arg.Is<Item>(x => item.Children.Any(y => x.ID == y.ID));

                //ME - Although this looks correct I am not sure it is
                service.CreateType(typeof(StubChild), predicate, false, false, null)
                    .ReturnsForAnyArgs(info => new StubChild()
                    {
                        Id = info.Arg<Item>().ID
                    });
                service.Config.Returns(new Config());

                var context = new SitecoreDataMappingContext(null, item, service);

                mapper.Setup(new DataMapperResolverArgs(null, config));

                //Act
                var result = mapper.MapToProperty(context) as IEnumerable<StubChild>;

                //Assert

                Assert.AreEqual(item.Children.Count, result.Count());

                foreach (Item child in item.Children)
                {
                    Assert.IsTrue(result.Any(x => x.Id == child.ID));
                }
            }

        }
 /// <summary>
 /// Gets the field.
 /// </summary>
 /// <param name="field">The field.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <returns>System.Object.</returns>
 public override object GetField(Sitecore.Data.Fields.Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     Type ruleFactory = typeof(RuleFactory);
     var method = ruleFactory.GetMethod("GetRules",
                                         System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static,
                                         null,
                                         new Type[] { typeof(global::Sitecore.Data.Fields.Field) },
                                         null);
     Type[] genericArgs = Configuration.PropertyInfo.PropertyType.GetGenericArguments();
     method = method.MakeGenericMethod(genericArgs);
     object rules = method.Invoke(null, new object[] { field });
     return rules;
 }
 /// <summary>
 /// Sets the field.
 /// </summary>
 /// <param name="field">The field.</param>
 /// <param name="value">The value.</param>
 /// <param name="config">The config.</param>
 /// <param name="context">The context.</param>
 /// <exception cref="System.NotSupportedException">It is not possible to save data from a rich text field when the data isn't raw.
 ///                     + Set the SitecoreFieldAttribute setting property to SitecoreFieldSettings.RichTextRaw for property {0} on type {1}.Formatted(config.PropertyInfo.Name, config.PropertyInfo.ReflectedType.FullName)</exception>
 public override void SetField(Sitecore.Data.Fields.Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
 {
     if (field == null)
     {
         return;
     }
     
     if (field.Type.StartsWith("Rich Text") && config.Setting != SitecoreFieldSettings.RichTextRaw)
     {
         throw new NotSupportedException("It is not possible to save data from a rich text field when the data isn't raw."
             + "Set the SitecoreFieldAttribute setting property to SitecoreFieldSettings.RichTextRaw for property {0} on type {1}".Formatted(config.PropertyInfo.Name, config.PropertyInfo.ReflectedType.FullName));
     }
     
     field.Value = value != null ? value.ToString() : null;
 }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {

            if (field.Value.IsNullOrEmpty())
            {
                return null;
            }

            Image img = new Image();
            ImageField scImg = new ImageField(field);

            MapToImage(img, scImg);

            return img;
        }
        /// <summary>
        /// Sets the field value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.NullReferenceException">Could not find item to save value {0}.Formatted(Configuration)</exception>
        public override string  SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {

            if (value == null)
                return string.Empty;
            else
            {
                var typeConfig = context.Service.GlassContext[value.GetType()] as SitecoreTypeConfiguration;

                var item = typeConfig.ResolveItem(value, context.Service.Database);
                if(item == null)
                    throw new NullReferenceException("Could not find item to save value {0}".Formatted(Configuration));

               return item.ID.ToString();
            }
        }
        public void MapToProperty_MapsItemToProperty()
        {
            //Arrange
            var database = Sitecore.Configuration.Factory.GetDatabase("master");
            var item = database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreItemMapper/Target");
            var mapper = new SitecoreItemMapper();
            var obj = new StubClass();

            var mappingContext = new SitecoreDataMappingContext(obj, item, null);
            
            //Act
           var result = mapper.MapToProperty(mappingContext);
            
            //Assign
            Assert.AreEqual(item, result);

        }