Exemple #1
0
        /// <summary>
        /// Creates content type(s) associated with the specified type to the given site, and create list if any.
        /// </summary>
        /// <remarks>
        /// Children content types associated with derived types are also created. Content types and site columns are prosivioned on the root site.
        /// If a <see cref="SPListAttribute"/> is attributed to the specified type, a list with URL specified by <see cref="SPListAttribute.Url"/> will be created on the given site.
        /// However, if another <see cref="SPListAttribute"/> is attributed to derived types, lists will *not* be created.</remarks>
        /// <param name="type">A type that derives from <see cref="SPModel"/>.</param>
        /// <param name="targetWeb">Site object.</param>
        /// <returns>A collection of lists affected.</returns>
        public static ICollection <SPList> Provision(Type type, SPWeb targetWeb)
        {
            SPModelDescriptor      descriptor = SPModelDescriptor.Resolve(type);
            SPModelUsageCollection collection = descriptor.Provision(targetWeb);

            return(collection.GetListCollection());
        }
Exemple #2
0
        public CamlExpression GetContentTypeExpression(SPModelDescriptor other)
        {
            CommonHelper.ConfirmNotNull(other, "other");
            IEnumerable <SPContentTypeId> contentTypeIds = this == other ? this.ContentTypeIds : IntersectContentTypeIds(this.ContentTypeIds.ToArray(), other.ContentTypeIds.ToArray());

            return(contentTypeIds.Aggregate(Caml.False, (v, a) => v | Caml.OfContentType(a)));
        }
Exemple #3
0
        internal static SPModel TryCreate(ISPListItemAdapter adapter, SPModelCollection parentCollection)
        {
            CommonHelper.ConfirmNotNull(adapter, "adapter");
            CommonHelper.ConfirmNotNull(parentCollection, "parentCollection");

            SPModelDescriptor exactType;

            try {
                exactType = SPModelDescriptor.Resolve(adapter.ContentTypeId);
            } catch (ArgumentException) {
                return(null);
            }
            if (exactType.ModelType.IsGenericType)
            {
                throw new InvalidOperationException(String.Format("Cannot create object from generic type '{0}'. Consider adding SPModelManagerDefaultTypeAttribute to the model class.", exactType.ModelType.FullName));
            }
            try {
                calledByInternal = true;
                SPModel item = (SPModel)exactType.ModelInstanceType.CreateInstance();
                item.Adapter          = Intercept.ThroughProxy(adapter, new TransparentProxyInterceptor(), new[] { new SPListItemAdapterInterceptionBehavior(item, adapter, parentCollection) });
                item.ParentCollection = parentCollection;
                return(item);
            } finally {
                calledByInternal = false;
            }
        }
Exemple #4
0
        /// <summary>
        /// Creates content type(s) associated with the specified type to the given list.
        /// </summary>
        /// <remarks>
        /// Children content types associated with derived types are also created. Content types and site columns are prosivioned on the root site.
        /// If a <see cref="SPListAttribute"/> is attributed to the specified type, values specified on the attribute are copied to the given list.
        /// </remarks>
        /// <param name="type">A type that derives from <see cref="SPModel"/>.</param>
        /// <param name="targetList">A list object.</param>
        /// <returns>A collection of lists affected.</returns>
        public static ICollection <SPList> Provision(Type type, SPList targetList)
        {
            SPModelDescriptor      descriptor = SPModelDescriptor.Resolve(type);
            SPModelUsageCollection collection = descriptor.Provision(targetList.ParentWeb, new SPModelListProvisionOptions(targetList));

            return(collection.GetListCollection());
        }
Exemple #5
0
        /// <summary>
        /// Creates content type(s) associated with the specified type to the given site, and create list with the specified URL and title if any.
        /// </summary>
        /// <param name="type">A type that derives from <see cref="SPModel"/>.</param>
        /// <param name="targetWeb">Site object.</param>
        /// <param name="webRelativeUrl">List URL.</param>
        /// <param name="title">List title.</param>
        /// <returns>A collection of lists affected.</returns>
        public static ICollection <SPList> Provision(Type type, SPWeb targetWeb, string webRelativeUrl, string title)
        {
            SPModelDescriptor      descriptor = SPModelDescriptor.Resolve(type);
            SPModelUsageCollection collection = descriptor.Provision(targetWeb, new SPModelListProvisionOptions(webRelativeUrl, title));

            return(collection.GetListCollection());
        }
Exemple #6
0
        /// <summary>
        /// Gets the default manager instantiated with the specified site and an existing SharePoint object cache.
        /// Actual type of the created manager can be set through <see cref="SPModelManagerDefaultTypeAttribute"/> on the model type.
        /// If there is no <see cref="SPModelManagerDefaultTypeAttribute"/> specified, an <see cref="SPModelManager{T}"/> object is instantiated with <paramref name="type"/>.
        /// </summary>
        /// <param name="type">Model type.</param>
        /// <param name="contextWeb">A site object.</param>
        /// <param name="cache">An instance of SharePoint object cache.</param>
        /// <returns>A manager object.</returns>
        public static ISPModelManager GetDefaultManager(Type type, SPWeb contextWeb, SPObjectCache cache)
        {
            SPModelDescriptor       descriptor = SPModelDescriptor.Resolve(type);
            ISPModelManagerInternal manager    = descriptor.CreateManager(contextWeb);

            manager.ObjectCache = cache;
            return(manager);
        }
Exemple #7
0
        private static ReadOnlyCollection <string> GetAllSelectProperties(SPModelDescriptor descriptor)
        {
            List <string> viewFields = new List <string>();

            viewFields.AddRange(descriptor.RequiredViewFields);
            viewFields.AddRange(SPModel.RequiredViewFields);
            return(new ReadOnlyCollection <string>(viewFields));
        }
Exemple #8
0
 public SPModelQuery(ISPModelManagerInternal manager, Type modelType, CamlExpression expression, int limit, int startRow)
 {
     CommonHelper.ConfirmNotNull(manager, "manager");
     CommonHelper.ConfirmNotNull(modelType, "modelType");
     this.Manager    = manager;
     this.Descriptor = SPModelDescriptor.Resolve(modelType);
     this.ContentTypeFilterExpression = manager.Descriptor.GetContentTypeExpression(this.descriptor);
     this.Expression = expression;
     this.Offset     = startRow;
     this.Limit      = limit;
 }
 private SPModelMonitor(SPSite site)
 {
     this.siteId     = site.ID;
     this.descriptor = SPModelDescriptor.Resolve(typeof(T));
     foreach (SPModelUsage usage in descriptor.GetUsages(site.RootWeb))
     {
         monitoredLists.Add(usage.ListId);
     }
     Initialize(site.ID,
                new SPChangeMonitorFilter(SPChangeObjectType.List, SPChangeFlags.ListContentTypeAdd | SPChangeFlags.ListContentTypeDelete),
                new SPChangeMonitorFilter(SPChangeObjectType.Item, SPChangeFlags.Add | SPChangeFlags.Update | SPChangeFlags.Delete | SPChangeFlags.SystemUpdate));
 }
Exemple #10
0
        public CamlExpression GetContentTypeExpression(SPModelDescriptor other)
        {
            CommonHelper.ConfirmNotNull(other, "other");
            CamlExpression expression = Caml.False;

            foreach (SPContentTypeId contentTypeId in this.ContentTypeIds)
            {
                if (other == this || other.ContentTypeIds.Any(v => v.IsParentOf(contentTypeId)))
                {
                    expression |= Caml.OfContentType(contentTypeId);
                }
            }
            return(expression);
        }
Exemple #11
0
        public static SPModelDescriptor Resolve(SPContentTypeId contentTypeId, SPSite lookupSite)
        {
            CommonHelper.ConfirmNotNull(lookupSite, "lookupSite");
            try {
                SPModelDescriptor descriptor = Resolve(contentTypeId);
                if (descriptor.ContentTypeIds.Contains(contentTypeId))
                {
                    return(descriptor);
                }
            } catch (ArgumentException) { }

            RegisterReferencedAssemblies(lookupSite);
            return(Resolve(contentTypeId));
        }
Exemple #12
0
        /// <summary>
        /// Creates a model object representing the list item.
        /// </summary>
        /// <param name="adapter">A data access adapter of the list item.</param>
        /// <returns>A model object or *null* if there is no types associated with the content type of the list item.</returns>
        public static SPModel TryCreate(ISPListItemAdapter adapter)
        {
            CommonHelper.ConfirmNotNull(adapter, "adapter");
            SPContentTypeId contentTypeId;

            try {
                contentTypeId = adapter.ContentTypeId;
            } catch (MemberAccessException) {
                return(null);
            }
            SPModelDescriptor descriptor;

            try {
                descriptor = SPModelDescriptor.Resolve(contentTypeId, adapter.Site);
            } catch (ArgumentException) {
                return(null);
            }
            ISPModelManagerInternal manager = descriptor.CreateManager(adapter.Web);

            return(manager.TryCreateModel(adapter, false));
        }
Exemple #13
0
        public void AddImplementedType(SPModelDescriptor descriptor)
        {
            CommonHelper.ConfirmNotNull(descriptor, "descriptor");
            foreach (SPModelDescriptor otherType in base.Children)
            {
                if (otherType != descriptor)
                {
                    foreach (SPFieldAttribute attribute in otherType.Fields)
                    {
                        descriptor.AddInterfaceDepenedentField(attribute);
                    }
                    foreach (SPFieldAttribute attribute in descriptor.Fields)
                    {
                        otherType.AddInterfaceDepenedentField(attribute);
                    }
                }
            }
            foreach (SPFieldAttribute attribute in descriptor.Fields)
            {
                AddRequiredViewField(attribute);
            }
            SPContentTypeId contentTypeId = descriptor.ContentTypeIds.First();

            foreach (SPModelDescriptor otherType in base.Children)
            {
                if (contentTypeId.IsChildOf(otherType.ContentTypeIds.First()))
                {
                    return;
                }
            }
            if (!baseType.HasValue)
            {
                baseType = descriptor.BaseType;
            }
            else if (baseType != descriptor.BaseType)
            {
                baseType = SPBaseType.UnspecifiedBaseType;
            }
            base.Children.Add(descriptor);
        }
Exemple #14
0
 protected void CheckFieldConsistency(SPModelDescriptor other)
 {
     foreach (SPFieldAttribute definition in fieldAttributes)
     {
         SPFieldAttribute parentDefinition = other.fieldAttributes.FirstOrDefault(v => v.InternalName == definition.InternalName);
         if (parentDefinition != null)
         {
             if (definition.GetType() != parentDefinition.GetType())
             {
                 throw new SPModelProvisionException(String.Format("Definition for field '{0}' in content type '{1}' conflicts with parent content type.", definition.InternalName, contentTypeAttribute.Name));
             }
             foreach (PropertyInfo property in definition.GetType().GetProperties())
             {
                 object myValue = property.GetValue(definition, null);
                 object paValue = property.GetValue(parentDefinition, null);
                 if (!Object.Equals(myValue, paValue))
                 {
                     if (property.PropertyType == typeof(SPOption) && (SPOption)myValue == SPOption.Unspecified)
                     {
                         continue;
                     }
                     if (property.PropertyType == typeof(StringCollection))
                     {
                         StringCollection sourceCollection = (StringCollection)myValue;
                         StringCollection targetCollection = (StringCollection)paValue;
                         if (sourceCollection.Count == targetCollection.Count && !sourceCollection.Cast <string>().Except(targetCollection.Cast <string>()).Any())
                         {
                             continue;
                         }
                     }
                     throw new SPModelProvisionException(String.Format("Definition for field '{0}' in content type '{1}' conflicts with parent content type.", definition.InternalName, contentTypeAttribute.Name));
                 }
             }
         }
     }
 }
Exemple #15
0
        internal static Type BuildTypeFromAbstractBaseType(Type baseType)
        {
            Random      random         = new Random();
            string      chars          = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            string      randomTypeName = String.Concat(baseType.Name, "__", new String(Enumerable.Repeat(chars, 8).Select(s => s[random.Next(s.Length)]).ToArray()));
            TypeBuilder typeBuilder    = ModuleBuilder.DefineType(randomTypeName, TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit, baseType);

            MethodInfo spModelGetAdapterMethod           = typeof(SPModel).GetMethod("get_Adapter", true);
            MethodInfo spModelGetManagerMethod           = typeof(SPModel).GetMethod("get_Manager", true);
            MethodInfo spModelGetParentCollectionMethod  = typeof(SPModel).GetMethod("get_ParentCollection", true);
            MethodInfo ispModelManagerGetTermStoreMethod = typeof(ISPModelManager).GetMethod("get_TermStore");

            foreach (PropertyInfo sourceProperty in baseType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                MethodInfo sourceGetter = sourceProperty.GetGetMethod(true);
                MethodInfo sourceSetter = sourceProperty.GetSetMethod(true);
                if ((sourceGetter != null && sourceGetter.IsAbstract) || (sourceSetter != null && sourceSetter.IsAbstract))
                {
                    SPModelFieldAssociationCollection association = SPModelFieldAssociationCollection.GetByMember(sourceProperty);
                    if (!association.Queryable)
                    {
                        continue;
                    }
                    SPFieldAttribute field               = association.Fields.First();
                    MethodInfo       getterMethod        = null;
                    MethodInfo       setterMethod        = null;
                    MethodInfo       postGetterMethod    = null;
                    MethodInfo       preSetterMethod     = null;
                    Type             secondParameterType = null;

                    if (sourceProperty.PropertyType == typeof(bool))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetBoolean");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetBoolean");
                    }
                    else if (sourceProperty.PropertyType == typeof(int))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetInteger");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetInteger");
                    }
                    else if (sourceProperty.PropertyType == typeof(double))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetNumber");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetNumber");
                    }
                    else if (sourceProperty.PropertyType == typeof(string))
                    {
                        if (field.Type == SPFieldType.Lookup)
                        {
                            getterMethod = typeof(ISPListItemAdapter).GetMethod("GetLookupFieldValue");
                            setterMethod = typeof(ISPListItemAdapter).GetMethod("SetLookupFieldValue");
                        }
                        else if (field.Type == SPFieldType.URL)
                        {
                            getterMethod     = typeof(ISPListItemAdapter).GetMethod("GetUrlFieldValue");
                            setterMethod     = typeof(SPExtension).GetMethod("SetUrlFieldValue", new[] { typeof(ISPListItemAdapter), typeof(string), typeof(string) });
                            postGetterMethod = typeof(SPFieldUrlValue).GetProperty("Url").GetGetMethod();
                        }
                        else
                        {
                            getterMethod = typeof(ISPListItemAdapter).GetMethod("GetString");
                            setterMethod = typeof(ISPListItemAdapter).GetMethod("SetString");
                        }
                    }
                    else if (sourceProperty.PropertyType == typeof(Guid))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetGuid");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetGuid");
                    }
                    else if (sourceProperty.PropertyType == typeof(DateTime?))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetDateTime");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetDateTime");
                    }
                    else if (sourceProperty.PropertyType == typeof(DateTime))
                    {
                        getterMethod    = typeof(SPExtension).GetMethod("GetDateTimeOrMin");
                        setterMethod    = typeof(ISPListItemAdapter).GetMethod("SetDateTime");
                        preSetterMethod = typeof(DateTime?).GetMethod("op_Implicit");
                    }
                    else if (sourceProperty.PropertyType == typeof(Term))
                    {
                        getterMethod        = typeof(ISPListItemAdapter).GetMethod("GetTaxonomy");
                        setterMethod        = typeof(ISPListItemAdapter).GetMethod("SetTaxonomy");
                        secondParameterType = typeof(TermStore);
                    }
                    else if (sourceProperty.PropertyType == typeof(SPFieldUrlValue))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetUrlFieldValue");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetUrlFieldValue");
                    }
                    else if (sourceProperty.PropertyType == typeof(SPPrincipal))
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetUserFieldValue");
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetUserFieldValue");
                    }
                    else if (sourceProperty.PropertyType.IsOf <Enum>())
                    {
                        getterMethod = typeof(ISPListItemAdapter).GetMethod("GetEnum").MakeGenericMethod(sourceProperty.PropertyType);
                        setterMethod = typeof(ISPListItemAdapter).GetMethod("SetEnum").MakeGenericMethod(sourceProperty.PropertyType);
                    }
                    else if (sourceProperty.PropertyType.IsOf <SPModel>())
                    {
                        getterMethod        = typeof(ISPListItemAdapter).GetMethod("GetModel").MakeGenericMethod(sourceProperty.PropertyType);
                        setterMethod        = typeof(ISPListItemAdapter).GetMethod("SetModel").MakeGenericMethod(sourceProperty.PropertyType);
                        secondParameterType = typeof(SPModelCollection);
                    }
                    else
                    {
                        Type elementType;
                        if (sourceProperty.PropertyType.IsOf(typeof(IEnumerable <>), out elementType))
                        {
                            bool isReadOnly = sourceProperty.PropertyType.IsOf(typeof(ReadOnlyCollection <>));
                            if (elementType == typeof(Term))
                            {
                                getterMethod        = typeof(ISPListItemAdapter).GetMethod(isReadOnly ? "GetTaxonomyMultiReadOnly" : "GetTaxonomyMulti");
                                secondParameterType = typeof(TermStore);
                            }
                            else if (elementType == typeof(SPPrincipal))
                            {
                                getterMethod = typeof(ISPListItemAdapter).GetMethod(isReadOnly ? "GetMultiUserFieldValueReadOnly" : "GetMultiUserFieldValue");
                            }
                            else if (elementType == typeof(string))
                            {
                                if (field.Type == SPFieldType.MultiChoice)
                                {
                                    getterMethod = typeof(ISPListItemAdapter).GetMethod(isReadOnly ? "GetMultiChoiceFieldValueReadOnly" : "GetMultiChoiceFieldValue");
                                }
                                else
                                {
                                    getterMethod = typeof(ISPListItemAdapter).GetMethod(isReadOnly ? "GetMultiLookupFieldValueReadOnly" : "GetMultiLookupFieldValue");
                                }
                            }
                            else
                            {
                                try {
                                    SPModelDescriptor.Resolve(elementType);
                                    getterMethod        = typeof(ISPListItemAdapter).GetMethod(isReadOnly ? "GetModelCollectionReadOnly" : "GetModelCollection").MakeGenericMethod(elementType);
                                    secondParameterType = typeof(SPModelCollection);
                                } catch (ArgumentException) { }
                            }
                            if (sourceSetter != null)
                            {
                                throw new InvalidOperationException("Collection property cannot have setter.");
                            }
                        }
                    }
                    if ((sourceGetter != null && getterMethod == null) || (sourceSetter != null && setterMethod == null))
                    {
                        throw new InvalidOperationException(String.Format("Unable to find suitable method for '{0}.{1}'.", baseType.Name, sourceProperty.Name));
                    }

                    PropertyBuilder property = typeBuilder.DefineProperty(sourceProperty.Name, PropertyAttributes.HasDefault, sourceProperty.PropertyType, null);
                    if (sourceGetter != null)
                    {
                        MethodBuilder propertyGetter   = typeBuilder.DefineMethod(sourceGetter.Name, GetMethodVisibility(sourceGetter) | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.SpecialName | MethodAttributes.HideBySig, sourceProperty.PropertyType, Type.EmptyTypes);
                        ILGenerator   propertyGetterIL = propertyGetter.GetILGenerator();
                        propertyGetterIL.Emit(OpCodes.Ldarg_0);
                        propertyGetterIL.Emit(OpCodes.Call, spModelGetAdapterMethod);
                        propertyGetterIL.Emit(OpCodes.Ldstr, field.InternalName);
                        if (secondParameterType != null)
                        {
                            if (secondParameterType == typeof(TermStore))
                            {
                                propertyGetterIL.Emit(OpCodes.Ldarg_0);
                                propertyGetterIL.Emit(OpCodes.Call, spModelGetManagerMethod);
                                propertyGetterIL.Emit(OpCodes.Callvirt, ispModelManagerGetTermStoreMethod);
                            }
                            else if (secondParameterType == typeof(SPModelCollection))
                            {
                                propertyGetterIL.Emit(OpCodes.Ldarg_0);
                                propertyGetterIL.Emit(OpCodes.Call, spModelGetParentCollectionMethod);
                            }
                            else
                            {
                                throw new NotSupportedException();
                            }
                        }
                        if (getterMethod.DeclaringType.IsInterface || getterMethod.IsAbstract)
                        {
                            propertyGetterIL.Emit(OpCodes.Callvirt, getterMethod);
                        }
                        else
                        {
                            propertyGetterIL.Emit(OpCodes.Call, getterMethod);
                        }
                        if (postGetterMethod != null)
                        {
                            propertyGetterIL.Emit(OpCodes.Call, postGetterMethod);
                        }
                        propertyGetterIL.Emit(OpCodes.Ret);
                        property.SetGetMethod(propertyGetter);
                    }
                    if (sourceSetter != null)
                    {
                        MethodBuilder propertySetter   = typeBuilder.DefineMethod(sourceSetter.Name, GetMethodVisibility(sourceSetter) | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new Type[] { sourceProperty.PropertyType });
                        ILGenerator   propertySetterIL = propertySetter.GetILGenerator();
                        propertySetterIL.Emit(OpCodes.Ldarg_0);
                        propertySetterIL.Emit(OpCodes.Call, spModelGetAdapterMethod);
                        propertySetterIL.Emit(OpCodes.Ldstr, field.InternalName);
                        propertySetterIL.Emit(OpCodes.Ldarg_1);
                        if (preSetterMethod != null)
                        {
                            propertySetterIL.Emit(OpCodes.Call, preSetterMethod);
                        }
                        if (setterMethod.DeclaringType.IsInterface || setterMethod.IsAbstract)
                        {
                            propertySetterIL.Emit(OpCodes.Callvirt, setterMethod);
                        }
                        else
                        {
                            propertySetterIL.Emit(OpCodes.Call, setterMethod);
                        }
                        propertySetterIL.Emit(OpCodes.Nop);
                        propertySetterIL.Emit(OpCodes.Ret);
                        property.SetSetMethod(propertySetter);
                    }
                }
            }
            return(typeBuilder.CreateType());
        }
Exemple #16
0
 public bool Contains(SPModelDescriptor other)
 {
     return(this == other || this.Interfaces.Contains(other) || this.Children.Any(v => v.Contains(other)));
 }
Exemple #17
0
        /// <summary>
        /// Determines whether the specified list contains the content type associated with the model type.
        /// </summary>
        /// <param name="list">A list object.</param>
        /// <param name="type">Model type.</param>
        /// <exception cref="ArgumentException">The type <paramref name="type"/> does not associate with any content type.</exception>
        /// <returns>*true* if the specified list contains content type that is associated with the model type.</returns>
        public static bool DoesListContainsType(SPList list, Type type)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(type);

            return(descriptor.UsedInList(list));
        }
Exemple #18
0
        /// <summary>
        /// Gets all lists under the specified site and all its descendant sites which contains the content type associated with the model type.
        /// </summary>
        /// <param name="type">Model type.</param>
        /// <param name="contextWeb">A site object.</param>
        /// <exception cref="ArgumentException">The type <paramref name="type"/> does not associate with any content type.</exception>
        /// <returns>An enumerable of list objects.</returns>
        public static IEnumerable <SPList> EnumerateLists(Type type, SPWeb contextWeb)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(type);

            return(descriptor.GetUsages(contextWeb).GetListCollection());
        }
Exemple #19
0
        /// <summary>
        /// Gets the default manager instantiated with the specified site.
        /// Actual type of the created manager can be set through <see cref="SPModelManagerDefaultTypeAttribute"/> on the model type.
        /// If there is no <see cref="SPModelManagerDefaultTypeAttribute"/> specified, an <see cref="SPModelManager{T}"/> object is instantiated with <paramref name="type"/>.
        /// </summary>
        /// <param name="type">Model type.</param>
        /// <param name="contextWeb">A site object.</param>
        /// <returns>A manager object.</returns>
        public static ISPModelManager GetDefaultManager(Type type, SPWeb contextWeb)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(type);

            return(descriptor.CreateManager(contextWeb));
        }
Exemple #20
0
        private SPModelDescriptor(Type targetType, SPModelDefaultsAttribute defaultsAttribute)
        {
            this.ModelType = targetType;
            TargetTypeDictionary.TryAdd(targetType, this);
            TargetTypeDictionary.TryGetValue(targetType.BaseType, out this.Parent);
            if (this.Parent is SPModelInterfaceTypeDescriptor)
            {
                this.Parent = null;
            }

            this.contentTypeAttribute = targetType.GetCustomAttribute <SPContentTypeAttribute>(false);
            ResolveContentTypeId(contentTypeAttribute, targetType);
            ContentTypeDictionary.Add(contentTypeAttribute.ContentTypeId, this);

            this.defaultManagerType         = GetDefaultManagerType(targetType);
            this.provisionEventReceiverType = contentTypeAttribute.ProvisionEventReceiverType;
            this.hasExplicitListAttribute   = targetType.GetCustomAttribute <SPListAttribute>(false) != null;
            this.listAttribute   = targetType.GetCustomAttribute <SPListAttribute>(true) ?? new SPListAttribute();
            this.fieldAttributes = SPModelFieldAssociationCollection.EnumerateFieldAttributes(this, targetType).ToArray();

            if (contentTypeAttribute.Group == null && defaultsAttribute != null)
            {
                contentTypeAttribute.Group = defaultsAttribute.DefaultContentTypeGroup;
            }
            foreach (SPFieldAttribute attribute in fieldAttributes)
            {
                if (attribute.Group == null)
                {
                    if (this.Parent != null)
                    {
                        SPFieldAttribute baseAttribute = this.Parent.fieldAttributes.FirstOrDefault(v => v.InternalName == attribute.InternalName);
                        if (baseAttribute != null)
                        {
                            attribute.Group = baseAttribute.Group;
                            continue;
                        }
                    }
                    if (defaultsAttribute != null)
                    {
                        attribute.Group = defaultsAttribute.DefaultFieldGroup;
                    }
                }
            }

            if (contentTypeAttribute.ContentTypeId.IsChildOf(ContentTypeId.Page))
            {
                this.ItemType = SPModelItemType.PublishingPage;
            }
            else if (contentTypeAttribute.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.DocumentSet))
            {
                this.ItemType = SPModelItemType.DocumentSet;
            }
            else if (contentTypeAttribute.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Folder))
            {
                this.ItemType = SPModelItemType.Folder;
            }
            else if (contentTypeAttribute.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Document))
            {
                this.ItemType = SPModelItemType.File;
            }

            if (this.ItemType == SPModelItemType.GenericItem)
            {
                this.baseType = SPBaseType.GenericList;
            }
            else if (contentTypeAttribute.ContentTypeId.IsChildOf(SPBuiltInContentTypeId.Issue))
            {
                this.baseType = SPBaseType.Issue;
            }
            else
            {
                this.baseType = SPBaseType.DocumentLibrary;
            }

            if (this.Parent != null)
            {
                this.Parent.Children.Add(this);
                this.fieldAttributes = fieldAttributes.Concat(this.Parent.fieldAttributes).Distinct().ToArray();
                if (provisionEventReceiverType == null)
                {
                    this.provisionEventReceiverType = this.Parent.provisionEventReceiverType;
                }
            }

            foreach (SPFieldAttribute v in fieldAttributes)
            {
                AddRequiredViewField(v);
            }
            foreach (Type interfaceType in targetType.GetInterfaces())
            {
                if (!interfaceType.IsDefined(typeof(SPModelIgnoreAttribute), true))
                {
                    SPModelInterfaceTypeDescriptor interfaceDescriptor = (SPModelInterfaceTypeDescriptor)TargetTypeDictionary.EnsureKeyValue(interfaceType, SPModelInterfaceTypeDescriptor.Create);
                    interfaceDescriptor.AddImplementedType(this);
                    this.Interfaces.Add(interfaceDescriptor);
                }
            }
            if (targetType.BaseType != typeof(SPModel) && targetType.BaseType.GetCustomAttribute <SPContentTypeAttribute>(false) == null)
            {
                SPModelInterfaceTypeDescriptor interfaceDescriptor = (SPModelInterfaceTypeDescriptor)TargetTypeDictionary.EnsureKeyValue(targetType.BaseType, SPModelInterfaceTypeDescriptor.Create);
                interfaceDescriptor.AddImplementedType(this);
                this.Interfaces.Add(interfaceDescriptor);
            }
            if (!targetType.IsAbstract)
            {
                instanceType = new Lazy <Type>(() => targetType);
            }
            else
            {
                instanceType = new Lazy <Type>(() => SPModel.BuildTypeFromAbstractBaseType(targetType), LazyThreadSafetyMode.ExecutionAndPublication);
            }
        }
Exemple #21
0
        /// <summary>
        /// Resolves inherited <see cref="SPModel"/> type associated with the specified content type ID.
        /// For details of associating Content type ID for a given type, see <see cref="SPContentTypeAttribute"/>.
        /// </summary>
        /// <param name="contentTypeId">Content type ID.</param>
        /// <exception cref="System.ArgumentException">No types are found with the specified content type ID.</exception>
        /// <returns>A resolved type.</returns>
        public static Type ResolveType(SPContentTypeId contentTypeId)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(contentTypeId);

            return(descriptor.ModelType);
        }
Exemple #22
0
        /// <summary>
        /// Gets a list of field internal names needed when querying list item represented by the specified model type.
        /// </summary>
        /// <param name="type">A type that derives from <see cref="SPModel"/>.</param>
        /// <returns>A list of internal names.</returns>
        public static string[] GetRequiredViewFields(Type type)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(type);

            return(descriptor.RequiredViewFields);
        }
Exemple #23
0
        /// <summary>
        /// Gets a list of content type ID associated with the specified model type.
        /// </summary>
        /// <param name="type">A type that derives from <see cref="SPModel"/>.</param>
        /// <returns>A list of content type ID.</returns>
        public static SPContentTypeId[] ResolveContentTypeId(Type type)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(type);

            return(descriptor.ContentTypeIds.ToArray());
        }
Exemple #24
0
        internal void HandleEvent(SPModelEventArgs e)
        {
            SPModelDescriptor descriptor = SPModelDescriptor.Resolve(this.GetType());

            foreach (SPModelInterfaceTypeDescriptor d in descriptor.Interfaces)
            {
                if (d.EventHandlerType != null)
                {
                    ISPModelEventHandler handler = (ISPModelEventHandler)d.EventHandlerType.CreateInstance();
                    handler.HandleEvent(this, e);
                }
            }
            switch (e.EventType)
            {
            case SPModelEventType.Adding:
                OnAdding(e);
                OnAddingOrUpdating(e);
                return;

            case SPModelEventType.Added:
                OnAdded(e);
                OnAddedOrUpdated(e);
                return;

            case SPModelEventType.AddedAsync:
                OnAddedAsync(e);
                OnAddedOrUpdatedAsync(e);
                return;

            case SPModelEventType.Updating:
                OnUpdating(e);
                OnAddingOrUpdating(e);
                return;

            case SPModelEventType.Updated:
                OnUpdated(e);
                OnAddedOrUpdated(e);
                return;

            case SPModelEventType.UpdatedAsync:
                OnUpdatedAsync(e);
                OnAddedOrUpdatedAsync(e);
                return;

            case SPModelEventType.Deleting:
                OnDeleting(e);
                return;

            case SPModelEventType.Deleted:
                OnDeleted(e);
                return;

            case SPModelEventType.Publishing:
                OnPublishing(e);
                return;

            case SPModelEventType.Published:
                OnPublished(e);
                return;
            }
        }