Exemple #1
0
        public void Delete <T>(T item)  where T : class
        {
            Guid guid = Guid.Empty;

            try
            {
                guid = InstanceContext.GetClassId(typeof(T), item);
            }
            catch (SitecoreIdException ex)
            {
                throw new MapperException("Failed to get item ID", ex);
            }

            if (guid == Guid.Empty)
            {
                throw new MapperException("Guid for item is empty");
            }

            Item scItem = _database.GetItem(new ID(guid));

            if (scItem == null)
            {
                throw new MapperException("Item not found");
            }

            scItem.Delete();
        }
Exemple #2
0
        /// <summary>
        /// Retrieves an item based on the passed in class based on the version and language properties on the class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <returns></returns>
        private Item GetItemFromSitecore <T>(T target)
        {
            Guid guid = InstanceContext.GetClassId(typeof(T), target);

            SitecoreClassConfig config   = InstanceContext.GetSitecoreClass(typeof(T));
            Language            language = null;
            int versionNumber            = -1;

            if (config.LanguageProperty != null)
            {
                language = config.LanguageProperty.Property.GetValue(target, null) as Language;
            }
            if (config.VersionProperty != null)
            {
                versionNumber = (int)config.VersionProperty.Property.GetValue(target, null);
            }
            if (language != null && versionNumber > 0)
            {
                return(_database.GetItem(new ID(guid), language, new global::Sitecore.Data.Version(versionNumber)));
            }
            else if (language != null)
            {
                return(_database.GetItem(new ID(guid), language));
            }
            else
            {
                return(_database.GetItem(new ID(guid)));
            }
        }
        private string MakeEditable <T>(Expression <Func <T, object> > field, Expression <Func <T, string> > standardOutput, T target, Database database)
        {
            if (IsInEditingMode)
            {
                if (field.Parameters.Count > 1)
                {
                    throw new MapperException("To many parameters in linq expression {0}".Formatted(field.Body));
                }

                var  site = global::Sitecore.Context.Site;
                Type type = typeof(T);

                InstanceContext context = Context.GetContext();

                Guid id = Guid.Empty;

                try
                {
                    id = context.GetClassId(type, target);
                }
                catch (SitecoreIdException ex)
                {
                    throw new MapperException("Page editting error. Type {0} can not be used for editing. Could not find property with SitecoreID attribute. See inner exception".Formatted(typeof(T).FullName), ex);
                }

                var scClass = context.GetSitecoreClass(typeof(T));

                var prop = Utility.GetPropertyInfo(type, field.Body);

                if (prop == null)
                {
                    throw new MapperException("Page editting error. Could not find property {0} on type {1}".Formatted(field.Body, type.FullName));
                }

                var dataHandler = scClass.DataHandlers.FirstOrDefault(x => x.Property == prop);

                var item = database.GetItem(new ID(id));

                using (new ContextItemSwitcher(item))
                {
                    FieldRenderer renderer = new FieldRenderer();
                    renderer.Item       = item;
                    renderer.FieldName  = ((AbstractSitecoreField)dataHandler).FieldName;
                    renderer.Parameters = "";
                    return(renderer.Render());
                }
            }
            else
            {
                if (standardOutput != null)
                {
                    return(standardOutput.Compile().Invoke(target));
                }
                else
                {
                    return(field.Compile().Invoke(target).ToString());
                }
            }
        }
        private string MakeEditable <T>(Expression <Func <T, object> > field, Expression <Func <T, string> > standardOutput, T target, Database database, string parameters)
        {
            if (standardOutput == null || IsInEditingMode)
            {
                if (field.Parameters.Count > 1)
                {
                    throw new MapperException("To many parameters in linq expression {0}".Formatted(field.Body));
                }



                MemberExpression memberExpression;

                if (field.Body is UnaryExpression)
                {
                    memberExpression = ((UnaryExpression)field.Body).Operand as MemberExpression;
                }
                else if (!(field.Body is MemberExpression))
                {
                    throw new MapperException("Expression doesn't evaluate to a member {0}".Formatted(field.Body));
                }
                else
                {
                    memberExpression = (MemberExpression)field.Body;
                }



                //we have to deconstruct the lambda expression to find the
                //correct target object
                //For example if we have the lambda expression x =>x.Children.First().Content
                //we have to evaluate what the first Child object is, then evaluate the field to edit from there.

                //this contains the expression that will evaluate to the object containing the property
                var objectExpression = memberExpression.Expression;

                var finalTarget = Expression.Lambda(objectExpression, field.Parameters).Compile().DynamicInvoke(target);

                var site = global::Sitecore.Context.Site;


                InstanceContext context = Context.GetContext();


                //if the class a proxy then we have to get it's base type
                Type type;
                if (finalTarget is IProxyTargetAccessor)
                {
                    //first try the base type
                    type = finalTarget.GetType().BaseType;

                    //if it doesn't contain the base type then we need to check the interfaces
                    if (!context.Classes.ContainsKey(type))
                    {
                        var interfaces = finalTarget.GetType().GetInterfaces();

                        string name = finalTarget.GetType().Name;
                        //be default castle will use the name of the class it is proxying for it's own name
                        foreach (var inter in interfaces)
                        {
                            if (name.StartsWith(inter.Name))
                            {
                                type = inter;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    type = finalTarget.GetType();
                }


                Guid id = Guid.Empty;

                try
                {
                    id = context.GetClassId(type, finalTarget);
                }
                catch (SitecoreIdException ex)
                {
                    throw new MapperException("Page editting error. Type {0} can not be used for editing. Could not find property with SitecoreID attribute. See inner exception".Formatted(typeof(T).FullName), ex);
                }

                var scClass = context.GetSitecoreClass(type);

                //lambda expression does not always return expected memberinfo when inheriting
                //c.f. http://stackoverflow.com/questions/6658669/lambda-expression-not-returning-expected-memberinfo
                var prop = type.GetProperty(memberExpression.Member.Name);

                //interfaces don't deal with inherited properties well
                if (prop == null && type.IsInterface)
                {
                    Func <Type, PropertyInfo> interfaceCheck = null;
                    interfaceCheck = (inter) =>
                    {
                        var interfaces = inter.GetInterfaces();
                        var properties =
                            interfaces.Select(x => x.GetProperty(memberExpression.Member.Name)).Where(
                                x => x != null);
                        if (properties.Any())
                        {
                            return(properties.First());
                        }
                        else
                        {
                            return(interfaces.Select(x => interfaceCheck(x)).FirstOrDefault(x => x != null));
                        }
                    };
                    prop = interfaceCheck(type);
                }

                if (prop != null && prop.DeclaringType != prop.ReflectedType)
                {
                    //properties mapped in data handlers are based on declaring type when field is inherited, make sure we match
                    prop = prop.DeclaringType.GetProperty(prop.Name);
                }

                if (prop == null)
                {
                    throw new MapperException("Page editting error. Could not find property {0} on type {1}".Formatted(memberExpression.Member.Name, type.FullName));
                }

                var dataHandler = scClass.DataHandlers.FirstOrDefault(x => x.Property == prop);
                if (dataHandler == null)
                {
                    throw new MapperException(
                              "Page editting error. Could not find data handler for property {2} {0}.{1}".Formatted(
                                  prop.DeclaringType, prop.Name, prop.MemberType));
                }

                var item = database.GetItem(new ID(id));

                using (new ContextItemSwitcher(item))
                {
                    FieldRenderer renderer = new FieldRenderer();
                    renderer.Item       = item;
                    renderer.FieldName  = ((AbstractSitecoreField)dataHandler).FieldName;
                    renderer.Parameters = parameters;
                    return(renderer.Render());
                }
            }
            else
            {
                return(standardOutput.Compile().Invoke(target));
            }
            //return field.Compile().Invoke(target).ToString();
        }
        private string MakeEditable <T>(Expression <Func <T, object> > field, Expression <Func <T, string> > standardOutput, T target, Database database, string parameters)
        {
            if (standardOutput == null || IsInEditingMode)
            {
                if (field.Parameters.Count > 1)
                {
                    throw new MapperException("To many parameters in linq expression {0}".Formatted(field.Body));
                }



                MemberExpression memberExpression;

                if (field.Body is UnaryExpression)
                {
                    memberExpression = ((UnaryExpression)field.Body).Operand as MemberExpression;
                }
                else if (!(field.Body is MemberExpression))
                {
                    throw new MapperException("Expression doesn't evaluate to a member {0}".Formatted(field.Body));
                }
                else
                {
                    memberExpression = (MemberExpression)field.Body;
                }



                //we have to deconstruct the lambda expression to find the
                //correct target object
                //For example if we have the lambda expression x =>x.Children.First().Content
                //we have to evaluate what the first Child object is, then evaluate the field to edit from there.

                //this contains the expression that will evaluate to the object containing the property
                var objectExpression = memberExpression.Expression;

                var finalTarget = Expression.Lambda(objectExpression, field.Parameters).Compile().DynamicInvoke(target);

                var site = global::Sitecore.Context.Site;


                //if the class a proxy then we have to get it's base type
                Type type = finalTarget is IProxyTargetAccessor?finalTarget.GetType().BaseType : finalTarget.GetType();

                InstanceContext context = Context.GetContext();

                Guid id = Guid.Empty;

                try
                {
                    id = context.GetClassId(type, finalTarget);
                }
                catch (SitecoreIdException ex)
                {
                    throw new MapperException("Page editting error. Type {0} can not be used for editing. Could not find property with SitecoreID attribute. See inner exception".Formatted(typeof(T).FullName), ex);
                }

                var scClass = context.GetSitecoreClass(type);

                var prop = memberExpression.Member;

                if (prop == null)
                {
                    throw new MapperException("Page editting error. Could not find property {0} on type {1}".Formatted(memberExpression.Member.Name, type.FullName));
                }

                var dataHandler = scClass.DataHandlers.FirstOrDefault(x => x.Property == prop);
                if (dataHandler == null)
                {
                    throw new MapperException(
                              "Page editting error. Could not find data handler for property {2} {0}.{1}".Formatted(
                                  prop.DeclaringType, prop.Name, prop.MemberType));
                }

                var item = database.GetItem(new ID(id));

                using (new ContextItemSwitcher(item))
                {
                    FieldRenderer renderer = new FieldRenderer();
                    renderer.Item       = item;
                    renderer.FieldName  = ((AbstractSitecoreField)dataHandler).FieldName;
                    renderer.Parameters = parameters;
                    return(renderer.Render());
                }
            }
            else
            {
                return(standardOutput.Compile().Invoke(target));
            }
            //return field.Compile().Invoke(target).ToString();
        }
Exemple #6
0
        public T Create <T, K>(K parent, string name, T data)  where T : class where K : class
        {
            //check that the data is not null and if it has an ID check that it is empty
            if (data != null)
            {
            }

            Guid guid = Guid.Empty;

            try
            {
                guid = InstanceContext.GetClassId(typeof(K), parent);
            }
            catch (SitecoreIdException ex)
            {
                throw new MapperException("Failed to get parent ID", ex);
            }


            if (guid == Guid.Empty)
            {
                throw new MapperException("Guid for parent is empty");
            }

            Item pItem = _database.GetItem(new ID(guid));

            if (pItem == null)
            {
                throw new MapperException("Could not find parent item");
            }

            SitecoreClassConfig scClass = InstanceContext.GetSitecoreClass(typeof(T));

            Guid templateId = scClass.TemplateId;
            Guid branchId   = scClass.BranchId;

            Item item = null;

            if (templateId != Guid.Empty)
            {
                item = pItem.Add(name, new TemplateID(new ID(templateId)));
            }
            else if (branchId != Guid.Empty)
            {
                item = pItem.Add(name, new BranchId(new ID(branchId)));
            }
            else
            {
                throw new MapperException("Type {0} does not have a Template ID or Branch ID".Formatted(typeof(T).FullName));
            }



            if (item == null)
            {
                throw new MapperException("Failed to create child with name {0} and parent {1}".Formatted(name, item.Paths.FullPath));
            }

            //if we have data save it to the item
            if (data != null)
            {
                item.Editing.BeginEdit();
                WriteToItem <T>(data, item);
                item.Editing.EndEdit();
            }
            return(CreateClass <T>(false, false, item));
        }
Exemple #7
0
        /// <summary>
        /// Creates a new Sitecore item.
        /// </summary>
        /// <typeparam name="T">The type of the new item to create. This type must have either a TemplateId or BranchId defined on the SitecoreClassAttribute or fluent equivalent</typeparam>
        /// <typeparam name="K">The type of the parent item</typeparam>
        /// <param name="parent">The parent of the new item to create. Must have the SitecoreIdAttribute or fluent equivalent</param>
        /// <param name="newItem">New item to create, must have the attribute SitecoreInfoAttribute of type SitecoreInfoType.Name or the fluent equivalent</param>
        /// <returns></returns>
        public T Create <T, K>(K parent, T newItem)
            where T : class
            where K : class
        {
            try
            {
                Guid id = InstanceContext.GetClassId(typeof(T), newItem);
                if (id != Guid.Empty)
                {
                    throw new MapperException("You are trying to create an item on a class that doesn't have an empty ID value");
                }
            }
            catch (SitecoreIdException ex)
            {
                //we can swallow this exception for now
                //should look to do this beeter
            }


            Guid parentId = Guid.Empty;

            try
            {
                parentId = InstanceContext.GetClassId(typeof(K), parent);
            }
            catch (SitecoreIdException ex)
            {
                throw new MapperException("Failed to get parent ID", ex);
            }


            if (parentId == Guid.Empty)
            {
                throw new MapperException("Guid for parent is empty");
            }

            Item pItem = GetItemFromSitecore <K>(parent);

            if (pItem == null)
            {
                throw new MapperException("Could not find parent item with ID {0}".Formatted(parentId));
            }

            SitecoreClassConfig scClass = InstanceContext.GetSitecoreClass(typeof(T));

            var nameProperty = scClass.Properties.Where(x => x.Attribute is SitecoreInfoAttribute)
                               .Cast <SitecoreProperty>().FirstOrDefault(x => x.Attribute.CastTo <SitecoreInfoAttribute>().Type == SitecoreInfoType.Name);

            if (nameProperty == null)
            {
                throw new MapperException("Type {0} does not have a property with SitecoreInfoType.Name".Formatted(typeof(T).FullName));
            }

            string name = string.Empty;

            try
            {
                name = nameProperty.Property.GetValue(newItem, null).ToString();
            }
            catch
            {
                throw new MapperException("Failed to get item name");
            }

            if (name.IsNullOrEmpty())
            {
                throw new MapperException("New class has no name");
            }


            Guid templateId = scClass.TemplateId;
            Guid branchId   = scClass.BranchId;

            Item item = null;

            if (templateId != Guid.Empty)
            {
                item = pItem.Add(name, new TemplateID(new ID(templateId)));
            }
            else if (branchId != Guid.Empty)
            {
                item = pItem.Add(name, new BranchId(new ID(branchId)));
            }
            else
            {
                throw new MapperException("Type {0} does not have a Template ID or Branch ID".Formatted(typeof(T).FullName));
            }

            if (item == null)
            {
                throw new MapperException("Failed to create item");
            }

            //write new data to the item

            item.Editing.BeginEdit();
            WriteToItem <T>(newItem, item);
            item.Editing.EndEdit();

            //then read it back
            ReadFromItem(newItem, item, scClass);
            return(newItem);
            //   return CreateClass<T>(false, false, item);
        }