private ListInstance ProcessListItems(Web web,
                                              List siteList,
                                              ListInstance listInstance,
                                              ProvisioningTemplateCreationInformation creationInfo,
                                              Model.Configuration.Lists.Lists.ExtractListsListsConfiguration extractionConfig,
                                              Model.Configuration.Lists.Lists.ExtractListsQueryConfiguration queryConfig,
                                              Uri baseUri,
                                              ListItemCollection items,
                                              PnPMonitoredScope scope)
        {
            if (!string.IsNullOrEmpty(extractionConfig.KeyColumn))
            {
                listInstance.DataRows.KeyColumn      = extractionConfig.KeyColumn;
                listInstance.DataRows.UpdateBehavior = extractionConfig.UpdateBehavior;
            }

            var itemCount = 1;

            foreach (var item in items)
            {
                WriteSubProgress("List", listInstance.Title, itemCount, items.Count);

                var dataRow = ProcessDataRow(web, siteList, item, listInstance, extractionConfig, queryConfig, baseUri, creationInfo, scope);

                listInstance.DataRows.Add(dataRow);
                itemCount++;
            }
            return(listInstance);
        }
        /// <summary>
        ///     对数组列表逆序排序
        /// </summary>
        public void ReverseSort()
        {
            switch (BaseType)
            {
            case StructType.NormalArray:
                Array.Sort(NormalArray);
                Array.Reverse(NormalArray);
                break;

            case StructType.Array:
                Array.Sort(ArrayInstance);
                Array.Reverse(ArrayInstance);

                break;

            case StructType.ArrayList:
                ArrayListInstance.Sort();
                ArrayListInstance.Reverse();
                break;

            case StructType.List:
                ListInstance.Sort();
                ListInstance.Reverse();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #3
0
        public ListAssignmentFrame(ListInstance <T> instance, Variable[] elements) : base(false)
        {
            ElementType = typeof(T);
            Variable    = new ServiceVariable(instance, this);

            Elements = elements;
        }
        public void CanExtractCalculatedField()
        {
            var template          = new ProvisioningTemplate();
            var listInstance      = new ListInstance();
            var extractedTemplate = new ProvisioningTemplate();

            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field()
            {
                SchemaXml = ElementSchema
            });
            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field()
            {
                SchemaXml = TokenizedCalculatedFieldElementSchema
            });

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var f = ctx.Web.GetFieldById <FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldCalculated));
                Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly");

                var provisioningTemplateCreationInformation = new ProvisioningTemplateCreationInformation(ctx.Web);
                new ObjectField().ExtractObjects(ctx.Web, extractedTemplate, provisioningTemplateCreationInformation);

                XElement fieldElement = XElement.Parse(extractedTemplate.SiteFields.First(cf => Guid.Parse(XElement.Parse(cf.SchemaXml).Attribute("ID").Value).Equals(calculatedFieldId)).SchemaXml);
                var      formula      = fieldElement.Descendants("Formula").FirstOrDefault();

                Assert.AreEqual(@"=[{fieldtitle:DemoField}]&""DemoField""", formula.Value, true, "Calculated field formula is not extracted properly");
            }
        }
예제 #5
0
        public void DataRowsAreBeingSkippedIfAlreadyInplace()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                var template = new ProvisioningTemplate();
                template.TemplateCultureInfo = "1033";
                var listinstance = new ListInstance()
                {
                    Title        = datarowListName,
                    Url          = $"lists/{datarowListName}",
                    TemplateType = 100,
                };
                listinstance.Fields.Add(new Core.Framework.Provisioning.Model.Field()
                {
                    SchemaXml = $@"<Field Type=""Text"" DisplayName=""Key"" Required=""FALSE"" EnforceUniqueValues=""FALSE"" Indexed=""FALSE"" MaxLength=""255"" ID=""{(Guid.NewGuid().ToString("B"))}"" StaticName=""Key"" Name=""Key"" />"
                });

                var datarows = new List <DataRow>()
                {
                    new DataRow(new Dictionary <string, string> {
                        { "Title", "Test -1-" }, { "Key", "1" }
                    }, "1"),
                    new DataRow(new Dictionary <string, string> {
                        { "Title", "Test -2-" }, { "Key", "2" }
                    }, "2"),
                    new DataRow(new Dictionary <string, string> {
                        { "Title", "Test -3-" }, { "Key", "3" }
                    }, "3")
                };
                listinstance.DataRows.AddRange(datarows);
                template.Lists.Add(listinstance);
                ctx.Web.ApplyProvisioningTemplate(template);


                var rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount;
                Assert.IsTrue(rowCount == 3, "Row count not equals 3");

                listinstance.DataRows.KeyColumn      = "Key";
                listinstance.DataRows.UpdateBehavior = UpdateBehavior.Skip;
                ctx.Web.ApplyProvisioningTemplate(template);

                rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount;
                Assert.IsTrue(rowCount == 3, "Row count not equals 3");

                listinstance.DataRows.UpdateBehavior = UpdateBehavior.Overwrite;
                ctx.Web.ApplyProvisioningTemplate(template);

                rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount;
                Assert.IsTrue(rowCount == 3, "Row count not equals 3");

                listinstance.DataRows.Add(new DataRow(new Dictionary <string, string> {
                    { "Title", "Test -4-" }, { "Key", "4" }
                }, "4"));
                ctx.Web.ApplyProvisioningTemplate(template);

                rowCount = ctx.Web.GetListByTitle(datarowListName).ItemCount;
                Assert.IsTrue(rowCount == 4, "Row count not equals 4");
            }
        }
예제 #6
0
        public void CanUpdateCalculatedFieldRefInListInstance()
        {
            var template = new ProvisioningTemplate();

            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field()
            {
                SchemaXml = ElementSchema
            });
            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field()
            {
                SchemaXml = TokenizedCalculatedFieldElementSchema
            });

            var listInstance = new ListInstance();

            listInstance.Url          = string.Format("lists/{0}", listName);
            listInstance.Title        = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;

            var referencedField = new FieldRef();

            referencedField.Id = fieldId;
            listInstance.FieldRefs.Add(referencedField);

            var calculatedFieldRef = new FieldRef();

            calculatedFieldRef.Id = calculatedFieldId;
            listInstance.FieldRefs.Add(calculatedFieldRef);
            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var rf = list.GetFieldById <FieldText>(fieldId);
                var f1 = list.GetFieldById <FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(rf, "Referenced field not added");
                Assert.IsNotNull(f1);
                Assert.IsInstanceOfType(f1, typeof(FieldCalculated));
                Assert.IsFalse(f1.Formula.Contains('#') || f1.Formula.Contains('?'), "Calculated field was not provisioned properly the first time");

                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var f2 = list.GetFieldById <FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(f2);
                Assert.IsInstanceOfType(f2, typeof(FieldCalculated));
                Assert.IsFalse(f2.Formula.Contains('#') || f2.Formula.Contains('?'), "Calculated field was not provisioned properly the second time");
            }
        }
예제 #7
0
        public ListAssignmentFrame(ListInstance <T> instance, Variable[] elements) : base(false)
        {
            ElementType = typeof(T);
            Variable    = new ServiceVariable(instance, this);

            if (ElementType.MustBeBuiltWithFunc())
            {
                Variable.OverrideType(typeof(object[]));
            }

            Elements = elements;
        }
예제 #8
0
        public void CanExtractCalculatedFieldFromListInstance()
        {
            var template     = new ProvisioningTemplate();
            var listInstance = new ListInstance();

            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field()
            {
                SchemaXml = ElementSchema
            });

            listInstance.Url          = string.Format("lists/{0}", listName);
            listInstance.Title        = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;

            var referencedField = new FieldRef();

            referencedField.Id = fieldId;
            listInstance.FieldRefs.Add(referencedField);

            var calculatedField = new Core.Framework.Provisioning.Model.Field();

            calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema;
            listInstance.Fields.Add(calculatedField);
            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var rf = list.GetFieldById <FieldText>(fieldId);
                var f  = list.GetFieldById <FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(rf, "Referenced field not added");
                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldCalculated));
                Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly");

                var extractedTemplate = new ProvisioningTemplate();
                var provisioningTemplateCreationInformation = new ProvisioningTemplateCreationInformation(ctx.Web);
                new ObjectListInstance().ExtractObjects(ctx.Web, extractedTemplate, provisioningTemplateCreationInformation);

                XElement fieldElement = XElement.Parse(extractedTemplate.Lists.First(l => l.Title == listName).Fields.First(cf => Guid.Parse(XElement.Parse(cf.SchemaXml).Attribute("ID").Value).Equals(calculatedFieldId)).SchemaXml);
                var      formula      = fieldElement.Descendants("Formula").FirstOrDefault();

                Assert.AreEqual(@"=[{fieldtitle:DemoField}]&""DemoField""", formula.Value, true, "Calculated field formula is not extracted properly");
            }
        }
        private Model.DataRow ProcessDataRow(Web web, List siteList, ListItem item, ListInstance listInstance, Model.Configuration.Lists.Lists.ExtractListsListsConfiguration extractionConfig, Model.Configuration.Lists.Lists.ExtractListsQueryConfiguration queryConfig, Uri baseUri, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope)
        {
            var dataRow             = new Model.DataRow();
            var filteredFieldValues = item.FieldValues.ToList();

            if (queryConfig != null && queryConfig.ViewFields != null && queryConfig.ViewFields.Count > 0)
            {
                filteredFieldValues = item.FieldValues.Where(f => queryConfig.ViewFields.Contains(f.Key)).ToList();
            }
            if (queryConfig != null && queryConfig.IncludeAttachments)
            {
                filteredFieldValues = filteredFieldValues.Where(f => !f.Key.Equals("Attachments", StringComparison.InvariantCultureIgnoreCase)).ToList();
            }
            foreach (var fieldValue in filteredFieldValues)
            {
                var value = item.FieldValuesAsText[fieldValue.Key];
                var skip  = extractionConfig.SkipEmptyFields && string.IsNullOrEmpty(value);
                if (!skip)
                {
                    dataRow.Values.Add(fieldValue.Key, TokenizeValue(web, siteList.Fields.FirstOrDefault(f => f.InternalName == fieldValue.Key).TypeAsString, fieldValue, value));
                }
            }
            if (queryConfig != null && queryConfig.IncludeAttachments && siteList.EnableAttachments && (bool)item["Attachments"])
            {
#if !SP2013 && !SP2016
                item.Context.Load(item, i => i.AttachmentFiles.Include(a => a.FileName, a => a.FileNameAsPath, a => a.ServerRelativePath));
#else
                item.Context.Load(item, i => i.AttachmentFiles.Include(a => a.FileName, a => a.FileName, a => a.ServerRelativeUrl));
#endif
                item.Context.ExecuteQueryRetry();
                foreach (var attachmentFile in item.AttachmentFiles)
                {
#if !SP2013 && !SP2016
                    var fullUri = new Uri(baseUri, attachmentFile.ServerRelativePath.DecodedUrl);
#else
                    var fullUri = new Uri(baseUri, attachmentFile.ServerRelativeUrl);
#endif
                    var folderPath   = HttpUtility.UrlDecode(fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'));
                    var targetFolder = $"ListData/SITE_{web.Id.ToString("N")}/LIST_{siteList.Id.ToString("N")}/Attachments/{item.Id}";
                    dataRow.Attachments.Add(new Model.SharePoint.InformationArchitecture.DataRowAttachment()
                    {
#if !SP2013 && !SP2016
                        Name = attachmentFile.FileNameAsPath.DecodedUrl,
                        Src  = $"{targetFolder}/{attachmentFile.FileNameAsPath.DecodedUrl}"
#else
                        Name = attachmentFile.FileName,
                        Src  = $"{targetFolder}/{attachmentFile.FileName}"
#endif
                    });
        public void CanExtractCalculatedFieldFromListInstance()
        {
            var template = new ProvisioningTemplate();
            var listInstance = new ListInstance();

            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema });

            listInstance.Url = string.Format("lists/{0}", listName);
            listInstance.Title = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;

            var referencedField = new FieldRef();
            referencedField.Id = fieldId;
            listInstance.FieldRefs.Add(referencedField);

            var calculatedField = new Core.Framework.Provisioning.Model.Field();
            calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema;
            listInstance.Fields.Add(calculatedField);
            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var rf = list.GetFieldById<FieldText>(fieldId);
                var f = list.GetFieldById<FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(rf, "Referenced field not added");
                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldCalculated));
                Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly");

                var extractedTemplate = new ProvisioningTemplate();
                var provisioningTemplateCreationInformation = new ProvisioningTemplateCreationInformation(ctx.Web);
                new ObjectListInstance().ExtractObjects(ctx.Web, extractedTemplate, provisioningTemplateCreationInformation);

                XElement fieldElement = XElement.Parse(extractedTemplate.Lists.First(l => l.Title == listName).Fields.First(cf => Guid.Parse(XElement.Parse(cf.SchemaXml).Attribute("ID").Value).Equals(calculatedFieldId)).SchemaXml);
                var formula = fieldElement.Descendants("Formula").FirstOrDefault();

                Assert.AreEqual(@"=[{fieldtitle:DemoField}]&""DemoField""", formula.Value, true, "Calculated field formula is not extracted properly");
            }
        }
        private ProvisioningTemplate ProcessLibraryItems(Web web,
                                                         List siteList,
                                                         ProvisioningTemplate template,
                                                         ListInstance listInstance,
                                                         Model.Configuration.Lists.Lists.ExtractListsListsConfiguration extractionConfig,
                                                         Model.Configuration.Lists.Lists.ExtractListsQueryConfiguration queryConfig,
                                                         ProvisioningTemplateCreationInformation creationInfo,
                                                         PnPMonitoredScope scope,
                                                         ListItemCollection items,
                                                         Uri baseUri,
                                                         string defaultContentTypeId)
        {
            var itemCount = 1;

            foreach (var item in items)
            {
                switch (item.FileSystemObjectType)
                {
                case FileSystemObjectType.File:
                {
                    //PnP:File
                    ProcessDocumentRow(web, siteList, baseUri, item, listInstance, template, creationInfo, scope, itemCount, items.Count, defaultContentTypeId);
                    break;
                }

                case FileSystemObjectType.Folder:
                {
                    //PnP:Folder
                    ProcessFolderRow(web, item, siteList, listInstance, queryConfig, template, scope);
                    break;
                }

                default:
                {
                    //PnP:DataRow
                    ProcessDataRow(web, siteList, item, listInstance, extractionConfig, queryConfig, baseUri, creationInfo, scope);
                    break;
                }
                }
                itemCount++;
            }
            return(template);
        }
예제 #12
0
        public void shoule_get_instance_with_inline_dependencies()
        {
            ListInstance <string> instance = new ListInstance <string>(typeof(IList <string>));

            instance.AddInline(new ObjectInstance(typeof(string), "a"));
            instance.AddInline(new ObjectInstance(typeof(string), "b"));

            ConstructorInstance @object = new ConstructorInstance(typeof(ITestInstance), typeof(TestInstance), ServiceLifetime.Transient);

            @object.AddInline(instance);

            IContainer container = new Container(p =>
            {
                p.For <ITestInstance>().Use(@object);
            });


            ITestInstance value = container.GetInstance <ITestInstance>();

            value.Data.ShouldHaveTheSameElementsAs(new string[] { "a", "b" });
        }
        private ListInstance ProcessListItems(Web web,
                                              List siteList,
                                              ListInstance listInstance,
                                              ProvisioningTemplateCreationInformation creationInfo,
                                              Model.Configuration.Lists.Lists.ExtractConfiguration extractionConfig,
                                              Model.Configuration.Lists.Lists.ExtractQueryConfiguration queryConfig,
                                              Uri baseUri,
                                              ListItemCollection items,
                                              PnPMonitoredScope scope)
        {
            var itemCount = 1;

            foreach (var item in items)
            {
                WriteMessage($"List|{listInstance.Title}|{itemCount}|{items.Count}", ProvisioningMessageType.Progress);

                var dataRow = ProcessDataRow(web, siteList, item, listInstance, extractionConfig, queryConfig, baseUri, creationInfo, scope);

                listInstance.DataRows.Add(dataRow);
                itemCount++;
            }
            return(listInstance);
        }
        private void ProcessFolderRow(Web web, ListItem listItem, List siteList, ListInstance listInstance, Model.Configuration.Lists.Lists.ExtractQueryConfiguration queryConfig, ProvisioningTemplate template, PnPMonitoredScope scope)
        {
            listItem.EnsureProperties(it => it.ParentList.RootFolder.ServerRelativeUrl);
            string serverRelativeListUrl = listItem.ParentList.RootFolder.ServerRelativeUrl;
            string folderPath            = listItem.FieldValuesAsText["FileRef"].Substring(serverRelativeListUrl.Length).TrimStart(new char[] { '/' });

            if (!string.IsNullOrWhiteSpace(folderPath))
            {
                //listItem.EnsureProperties(it => it.Folder.UniqueId);
                string[]     folderSegments = folderPath.Split('/');
                Model.Folder pnpFolder      = null;
                for (int i = 0; i < folderSegments.Length; i++)
                {
                    if (i == 0)
                    {
                        pnpFolder = listInstance.Folders.FirstOrDefault(f => f.Name.Equals(folderSegments[i], StringComparison.CurrentCultureIgnoreCase));
                        if (pnpFolder == null)
                        {
                            string pathToCurrentFolder = string.Format("{0}/{1}", serverRelativeListUrl, string.Join("/", folderSegments.Take(i + 1)));
                            pnpFolder = ExtractFolderSettings(web, siteList, pathToCurrentFolder, scope, queryConfig);
                            listInstance.Folders.Add(pnpFolder);
                        }
                    }
                    else
                    {
                        var childFolder = pnpFolder.Folders.FirstOrDefault(f => f.Name.Equals(folderSegments[i], StringComparison.CurrentCultureIgnoreCase));
                        if (childFolder == null)
                        {
                            string pathToCurrentFolder = string.Format("{0}/{1}", serverRelativeListUrl, string.Join("/", folderSegments.Take(i + 1)));
                            childFolder = ExtractFolderSettings(web, siteList, pathToCurrentFolder, scope, queryConfig);
                            pnpFolder.Folders.Add(childFolder);
                        }
                        pnpFolder = childFolder;
                    }
                }
            }
        }
예제 #15
0
        public void CanProvisionCalculatedFieldLocallyInListInstance()
        {
            //This test will fail as tokens does not support this scenario.
            //The test serves as a reminder that this is not supported and needs to be fixed in a future release.
            var template     = new ProvisioningTemplate();
            var listInstance = new ListInstance();

            listInstance.Url          = string.Format("lists/{0}", listName);
            listInstance.Title        = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;
            var referencedField = new Core.Framework.Provisioning.Model.Field();

            referencedField.SchemaXml = ElementSchema;
            listInstance.Fields.Add(referencedField);
            var calculatedField = new Core.Framework.Provisioning.Model.Field();

            calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema;
            listInstance.Fields.Add(calculatedField);
            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var rf = list.GetFieldById <FieldText>(fieldId);
                var f  = list.GetFieldById <FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(rf, "Referenced field not added");
                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldCalculated));
                Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly");
            }
        }
        /// <summary>
        ///     数组集合结构的添加
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public void Add(TItemType item)
        {
            switch (BaseType)
            {
            case StructType.NormalArray:
                NormalArray[++ArrayCount] = item;
                break;

            case StructType.Array:
                ArrayInstance.SetValue(item, ++ArrayCount);
                break;

            case StructType.ArrayList:
                ArrayListInstance.Add(item);
                break;

            case StructType.List:
                ListInstance.Add(item);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #17
0
 public ListContent(List owner, int instanceIndex)
     : base(owner, ((AspNetCore.ReportingServices.ReportProcessing.List)owner.ReportItemDef).Grouping, owner.ReportItemDef.Visibility)
 {
     if (owner.ReportItemInstance != null)
     {
         ListInstance            listInstance = (ListInstance)owner.ReportItemInstance;
         ListContentInstanceList listContents = listInstance.ListContents;
         if (listContents != null)
         {
             if (instanceIndex < listContents.Count)
             {
                 this.m_listContentInstance = listContents[instanceIndex];
                 if (this.m_listContentInstance != null)
                 {
                     base.m_uniqueName = this.m_listContentInstance.UniqueName;
                 }
             }
             else
             {
                 Global.Tracer.Assert(0 == listContents.Count);
             }
         }
     }
 }
        public void ObjectListInstance_ProvisionObjects()
        {
            ObjectListInstance   handler  = new ObjectListInstance(FieldAndListProvisioningStepHelper.Step.ListAndStandardFields);
            ProvisioningTemplate template = new ProvisioningTemplate();
            string listName     = "PnP Unit Test List";
            var    listInstance = new ListInstance
            {
                Url          = string.Format("lists/{0}", listName),
                Title        = listName,
                TemplateType = (int)ListTemplateType.GenericList
            };

            listInstance.FieldRefs.Add(new FieldRef()
            {
                Id = new Guid("23f27201-bee3-471e-b2e7-b64fd8b7ca38")
            });
            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateTestClientContext(false))
            {
                TokenParser parser = new TokenParser(ctx.Web, template);
                handler.ProvisionObjects(ctx.Web, template, parser, null);
            }
        }
예제 #19
0
        public static ReportItem CreateItem(string uniqueName, AspNetCore.ReportingServices.ReportProcessing.ReportItem reportItemDef, ReportItemInstance reportItemInstance, RenderingContext renderingContext, NonComputedUniqueNames nonComputedUniqueNames)
        {
            if (reportItemDef == null)
            {
                return(null);
            }
            Global.Tracer.Assert(null != renderingContext);
            ReportItem reportItem    = null;
            int        intUniqueName = 0;

            NonComputedUniqueNames[] childrenNonComputedUniqueNames = null;
            if (reportItemInstance != null)
            {
                intUniqueName = reportItemInstance.UniqueName;
            }
            else if (nonComputedUniqueNames != null)
            {
                intUniqueName = nonComputedUniqueNames.UniqueName;
                childrenNonComputedUniqueNames = nonComputedUniqueNames.ChildrenUniqueNames;
            }
            if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.Line)
            {
                AspNetCore.ReportingServices.ReportProcessing.Line reportItemDef2 = (AspNetCore.ReportingServices.ReportProcessing.Line)reportItemDef;
                LineInstance reportItemInstance2 = (LineInstance)reportItemInstance;
                reportItem = new Line(uniqueName, intUniqueName, reportItemDef2, reportItemInstance2, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.CheckBox)
            {
                AspNetCore.ReportingServices.ReportProcessing.CheckBox reportItemDef3 = (AspNetCore.ReportingServices.ReportProcessing.CheckBox)reportItemDef;
                CheckBoxInstance reportItemInstance3 = (CheckBoxInstance)reportItemInstance;
                reportItem = new CheckBox(uniqueName, intUniqueName, reportItemDef3, reportItemInstance3, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.Image)
            {
                AspNetCore.ReportingServices.ReportProcessing.Image reportItemDef4 = (AspNetCore.ReportingServices.ReportProcessing.Image)reportItemDef;
                ImageInstance reportItemInstance4 = (ImageInstance)reportItemInstance;
                reportItem = new Image(uniqueName, intUniqueName, reportItemDef4, reportItemInstance4, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.TextBox)
            {
                AspNetCore.ReportingServices.ReportProcessing.TextBox reportItemDef5 = (AspNetCore.ReportingServices.ReportProcessing.TextBox)reportItemDef;
                TextBoxInstance reportItemInstance5 = (TextBoxInstance)reportItemInstance;
                reportItem = new TextBox(uniqueName, intUniqueName, reportItemDef5, reportItemInstance5, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.Rectangle)
            {
                AspNetCore.ReportingServices.ReportProcessing.Rectangle reportItemDef6 = (AspNetCore.ReportingServices.ReportProcessing.Rectangle)reportItemDef;
                RectangleInstance reportItemInstance6 = (RectangleInstance)reportItemInstance;
                reportItem = new Rectangle(uniqueName, intUniqueName, reportItemDef6, reportItemInstance6, renderingContext, childrenNonComputedUniqueNames);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.ActiveXControl)
            {
                AspNetCore.ReportingServices.ReportProcessing.ActiveXControl reportItemDef7 = (AspNetCore.ReportingServices.ReportProcessing.ActiveXControl)reportItemDef;
                ActiveXControlInstance reportItemInstance7 = (ActiveXControlInstance)reportItemInstance;
                reportItem = new ActiveXControl(uniqueName, intUniqueName, reportItemDef7, reportItemInstance7, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.SubReport)
            {
                AspNetCore.ReportingServices.ReportProcessing.SubReport subReport = (AspNetCore.ReportingServices.ReportProcessing.SubReport)reportItemDef;
                SubReportInstance subReportInstance = (SubReportInstance)reportItemInstance;
                bool   processedWithError           = false;
                Report innerReport;
                if (AspNetCore.ReportingServices.ReportProcessing.SubReport.Status.Retrieved != subReport.RetrievalStatus)
                {
                    innerReport        = null;
                    processedWithError = true;
                }
                else
                {
                    if (subReport.ReportContext == null && renderingContext.CurrentReportContext != null)
                    {
                        subReport.ReportContext = renderingContext.CurrentReportContext.GetSubreportContext(subReport.ReportPath);
                    }
                    ICatalogItemContext reportContext     = subReport.ReportContext;
                    RenderingContext    renderingContext2 = new RenderingContext(renderingContext, subReport.Uri, subReport.Report.EmbeddedImages, subReport.Report.ImageStreamNames, reportContext);
                    if (subReportInstance == null)
                    {
                        innerReport = new Report(subReport.Report, null, renderingContext2, subReport.ReportName, subReport.Description, null);
                    }
                    else if (subReportInstance.ReportInstance == null)
                    {
                        processedWithError = true;
                        innerReport        = new Report(subReport.Report, null, renderingContext2, subReport.ReportName, subReport.Description, null);
                    }
                    else
                    {
                        innerReport = new Report(subReport.Report, subReportInstance.ReportInstance, renderingContext2, subReport.ReportName, subReport.Description, null);
                    }
                }
                reportItem = new SubReport(intUniqueName, subReport, subReportInstance, renderingContext, innerReport, processedWithError);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.List)
            {
                AspNetCore.ReportingServices.ReportProcessing.List reportItemDef8 = (AspNetCore.ReportingServices.ReportProcessing.List)reportItemDef;
                ListInstance reportItemInstance8 = (ListInstance)reportItemInstance;
                reportItem = new List(intUniqueName, reportItemDef8, reportItemInstance8, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.Matrix)
            {
                AspNetCore.ReportingServices.ReportProcessing.Matrix reportItemDef9 = (AspNetCore.ReportingServices.ReportProcessing.Matrix)reportItemDef;
                MatrixInstance reportItemInstance9 = (MatrixInstance)reportItemInstance;
                reportItem = new Matrix(intUniqueName, reportItemDef9, reportItemInstance9, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.Table)
            {
                AspNetCore.ReportingServices.ReportProcessing.Table reportItemDef10 = (AspNetCore.ReportingServices.ReportProcessing.Table)reportItemDef;
                TableInstance reportItemInstance10 = (TableInstance)reportItemInstance;
                reportItem = new Table(intUniqueName, reportItemDef10, reportItemInstance10, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.OWCChart)
            {
                AspNetCore.ReportingServices.ReportProcessing.OWCChart reportItemDef11 = (AspNetCore.ReportingServices.ReportProcessing.OWCChart)reportItemDef;
                OWCChartInstance reportItemInstance11 = (OWCChartInstance)reportItemInstance;
                reportItem = new OWCChart(intUniqueName, reportItemDef11, reportItemInstance11, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.Chart)
            {
                AspNetCore.ReportingServices.ReportProcessing.Chart reportItemDef12 = (AspNetCore.ReportingServices.ReportProcessing.Chart)reportItemDef;
                ChartInstance reportItemInstance12 = (ChartInstance)reportItemInstance;
                reportItem = new Chart(intUniqueName, reportItemDef12, reportItemInstance12, renderingContext);
            }
            else if (reportItemDef is AspNetCore.ReportingServices.ReportProcessing.CustomReportItem)
            {
                AspNetCore.ReportingServices.ReportProcessing.CustomReportItem reportItemDef13 = (AspNetCore.ReportingServices.ReportProcessing.CustomReportItem)reportItemDef;
                CustomReportItemInstance reportItemInstance13 = (CustomReportItemInstance)reportItemInstance;
                reportItem = new CustomReportItem(uniqueName, intUniqueName, reportItemDef13, reportItemInstance13, renderingContext, childrenNonComputedUniqueNames);
                if (!renderingContext.NativeAllCRITypes && (renderingContext.NativeCRITypes == null || !renderingContext.NativeCRITypes.ContainsKey(((CustomReportItem)reportItem).Type)))
                {
                    reportItem = ((CustomReportItem)reportItem).AltReportItem;
                }
            }
            return(reportItem);
        }
예제 #20
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            var propertyLoadRequired = false;
            if (!web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                propertyLoadRequired = true;
            }
            if (!web.IsPropertyAvailable("Url"))
            {
                web.Context.Load(web, w => w.Url);
                propertyLoadRequired = true;
            }
            if (propertyLoadRequired)
            {
                web.Context.ExecuteQueryRetry();
            }

            var serverRelativeUrl = web.ServerRelativeUrl;

            // For each list in the site
            ListCollection lists = web.Lists;

            web.Context.Load(lists,
                lc => lc.IncludeWithDefaultProperties(
                    l => l.ContentTypes,
                    l => l.Views,
                    l => l.OnQuickLaunch,
                    l => l.RootFolder.ServerRelativeUrl,
                    l => l.Fields.IncludeWithDefaultProperties(
                        f => f.Id,
                        f => f.Title,
                        f => f.Hidden,
                        f => f.InternalName,
                        f => f.Required)));

            web.Context.ExecuteQuery();
            foreach (var item in lists)
            {
                // Do not export system lists
                if (!item.Hidden)
                {

                    int index = -1;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
                        index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
                                                                  f.TemplateType.Equals(item.BaseTemplate));
                    }

                    if (index == -1)
                    {
                        var contentTypeFields = new List<FieldRef>();
                        ListInstance list = new ListInstance();
                        list.Description = item.Description;
                        list.EnableVersioning = item.EnableVersioning;
                        list.TemplateType = item.BaseTemplate;
                        list.Title = item.Title;
                        list.Hidden = item.Hidden;
                        list.EnableFolderCreation = item.EnableFolderCreation;
                        list.DocumentTemplate = Tokenize(item.DocumentTemplateUrl, web.Url);
                        list.ContentTypesEnabled = item.ContentTypesEnabled;
                        list.Url = item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/');
                        list.TemplateFeatureID = item.TemplateFeatureId;
                        list.EnableAttachments = item.EnableAttachments;
                        list.OnQuickLaunch = item.OnQuickLaunch;
                        list.MaxVersionLimit = item.IsObjectPropertyInstantiated("MajorVersionLimit") ? item.MajorVersionLimit : 0;
                        list.EnableMinorVersions = item.EnableMinorVersions;
                        list.MinorVersionLimit = item.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit") ? item.MajorWithMinorVersionsLimit : 0;
                        int count = 0;

                        foreach (var ct in item.ContentTypes)
                        {
                            web.Context.Load(ct, c => c.Parent);
                            web.Context.ExecuteQuery();
                            if (ct.Parent != null)
                            {
                                // Add the parent to the list of content types
                                if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                                {
                                    list.ContentTypeBindings.Add(new ContentTypeBinding() { ContentTypeId = ct.Parent.StringId, Default = count == 0 ? true : false });
                                }
                            }
                            else
                            {
                                list.ContentTypeBindings.Add(new ContentTypeBinding() { ContentTypeId = ct.StringId, Default = count == 0 });
                            }

                            web.Context.Load(ct.FieldLinks);
                            web.Context.ExecuteQueryRetry();
                            foreach (var fieldLink in ct.FieldLinks)
                            {
                                if (!fieldLink.Hidden)
                                {
                                    contentTypeFields.Add(new FieldRef() { Id = fieldLink.Id });
                                }
                            }
                            count++;
                        }

                        foreach (var view in item.Views)
                        {
                            if (!view.Hidden)
                            {
                                list.Views.Add(new View() { SchemaXml = view.ListViewXml });
                            }
                        }

                        var siteColumns = web.Fields;
                        web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
                        web.Context.ExecuteQueryRetry();

                        foreach (var field in item.Fields)
                        {
                            if (!field.Hidden)
                            {
                                if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                                {
                                    bool addField = true;
                                    if (item.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                                    {
                                        if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                                        {
                                            addField = false;
                                        }
                                    }

                                    XElement fieldElement = XElement.Parse(field.SchemaXml);
                                    var sourceId = fieldElement.Attribute("SourceID") != null ? fieldElement.Attribute("SourceID").Value : null;

                                    if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3")
                                    {
                                        if (field.InternalName == "Editor" ||
                                            field.InternalName == "Author" ||
                                            field.InternalName == "Title" ||
                                            field.InternalName == "ID" ||
                                            field.InternalName == "Created" ||
                                            field.InternalName == "Modified" ||
                                            field.InternalName == "Attachments" ||
                                            field.InternalName == "_UIVersionString" ||
                                            field.InternalName == "DocIcon" ||
                                            field.InternalName == "LinkTitleNoMenu" ||
                                            field.InternalName == "LinkTitle" ||
                                            field.InternalName == "Edit" ||
                                            field.InternalName == "AppAuthor" ||
                                            field.InternalName == "AppEditor" ||
                                            field.InternalName == "ContentType" ||
                                            field.InternalName == "ItemChildCount" ||
                                            field.InternalName == "FolderChildCount" ||
                                            field.InternalName == "LinkFilenameNoMenu" ||
                                            field.InternalName == "LinkFilename" ||
                                            field.InternalName == "_CopySource" ||
                                            field.InternalName == "ParentVersionString" ||
                                            field.InternalName == "ParentLeafName" ||
                                            field.InternalName == "_CheckinComment" ||
                                            field.InternalName == "FileLeafRef" ||
                                            field.InternalName == "FileSizeDisplay" ||
                                            field.InternalName == "Preview" ||
                                            field.InternalName == "ThumbnailOnForm")
                                        {
                                            addField = false;
                                        }
                                    }
                                    if (addField)
                                    {

                                        list.FieldRefs.Add(new FieldRef(field.InternalName)
                                        {
                                            Id = field.Id,
                                            DisplayName = field.Title,
                                            Required = field.Required,
                                            Hidden = field.Hidden,
                                        });
                                    }
                                }
                                else
                                {
                                    list.Fields.Add((new Model.Field() { SchemaXml = field.SchemaXml }));
                                }
                            }
                        }
                        template.Lists.Add(list);
                    }
                }
            }

            return template;
        }
        protected override void ExecuteCmdlet()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }
            // Load the template
            var template = ProvisioningHelper.LoadSiteTemplateFromFile(Path, TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file.");
            }


            List spList = List.GetList(CurrentWeb);

            ClientContext.Load(spList, l => l.RootFolder, l => l.HasUniqueRoleAssignments);
            ClientContext.ExecuteQueryRetry();

            //We will remove a list if it's found so we can get the list
            ListInstance listInstance = template.Lists.Find(l => l.Title == spList.Title);

            if (listInstance == null)
            {
                throw new ApplicationException("List does not exist in the template file.");
            }


            Microsoft.SharePoint.Client.Folder listFolder = spList.RootFolder;
            ClientContext.Load(listFolder);
            ClientContext.ExecuteQueryRetry();

            IList <PnP.Framework.Provisioning.Model.Folder> folders = GetChildFolders(listFolder);

            template.Lists.Remove(listInstance);
            listInstance.Folders.AddRange(folders);
            template.Lists.Add(listInstance);

            // Determine the output file name and path
            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(Path, fileSystemConnector));
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }
예제 #22
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            var propertyLoadRequired = false;

            if (!web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                propertyLoadRequired = true;
            }
            if (!web.IsPropertyAvailable("Url"))
            {
                web.Context.Load(web, w => w.Url);
                propertyLoadRequired = true;
            }
            if (propertyLoadRequired)
            {
                web.Context.ExecuteQueryRetry();
            }

            var serverRelativeUrl = web.ServerRelativeUrl;

            // For each list in the site
            ListCollection lists = web.Lists;

            web.Context.Load(lists,
                             lc => lc.IncludeWithDefaultProperties(
                                 l => l.ContentTypes,
                                 l => l.Views,
                                 l => l.RootFolder.ServerRelativeUrl,
                                 l => l.Fields.IncludeWithDefaultProperties(
                                     f => f.Id,
                                     f => f.Title,
                                     f => f.Hidden,
                                     f => f.InternalName,
                                     f => f.Required)));

            web.Context.ExecuteQuery();
            foreach (var item in lists)
            {
                // Do not export system lists
                if (!item.Hidden)
                {
                    int index = -1;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves perf
                        index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length)) &&
                                                                          f.TemplateType.Equals(item.BaseTemplate));
                    }

                    if (index == -1)
                    {
                        var          contentTypeFields = new List <FieldRef>();
                        ListInstance list = new ListInstance();
                        list.Description         = item.Description;
                        list.EnableVersioning    = item.EnableVersioning;
                        list.TemplateType        = item.BaseTemplate;
                        list.Title               = item.Title;
                        list.Hidden              = item.Hidden;
                        list.DocumentTemplate    = Tokenize(item.DocumentTemplateUrl, web.Url);
                        list.ContentTypesEnabled = item.ContentTypesEnabled;
                        list.Url = item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/');
                        list.TemplateFeatureID   = item.TemplateFeatureId;
                        list.EnableAttachments   = item.EnableAttachments;
                        list.MaxVersionLimit     = item.IsObjectPropertyInstantiated("MajorVersionLimit") ? item.MajorVersionLimit : 0;
                        list.EnableMinorVersions = item.EnableMinorVersions;
                        list.MinorVersionLimit   = item.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit") ? item.MajorWithMinorVersionsLimit : 0;
                        int count = 0;

                        foreach (var ct in item.ContentTypes)
                        {
                            web.Context.Load(ct, c => c.Parent);
                            web.Context.ExecuteQuery();
                            if (ct.Parent != null)
                            {
                                // Add the parent to the list of content types
                                if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                                {
                                    list.ContentTypeBindings.Add(new ContentTypeBinding()
                                    {
                                        ContentTypeId = ct.Parent.StringId, Default = count == 0 ? true : false
                                    });
                                }
                            }
                            else
                            {
                                list.ContentTypeBindings.Add(new ContentTypeBinding()
                                {
                                    ContentTypeId = ct.StringId, Default = count == 0
                                });
                            }

                            web.Context.Load(ct.FieldLinks);
                            web.Context.ExecuteQueryRetry();
                            foreach (var fieldLink in ct.FieldLinks)
                            {
                                if (!fieldLink.Hidden)
                                {
                                    contentTypeFields.Add(new FieldRef()
                                    {
                                        Id = fieldLink.Id
                                    });
                                }
                            }
                            count++;
                        }

                        foreach (var view in item.Views)
                        {
                            if (!view.Hidden)
                            {
                                list.Views.Add(new View()
                                {
                                    SchemaXml = view.ListViewXml
                                });
                            }
                        }

                        var siteColumns = web.Fields;
                        web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
                        web.Context.ExecuteQueryRetry();

                        foreach (var field in item.Fields)
                        {
                            if (!field.Hidden)
                            {
                                if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                                {
                                    bool addField = true;
                                    if (item.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                                    {
                                        if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                                        {
                                            addField = false;
                                        }
                                    }

                                    XElement fieldElement = XElement.Parse(field.SchemaXml);
                                    var      sourceId     = fieldElement.Attribute("SourceID") != null?fieldElement.Attribute("SourceID").Value : null;

                                    if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3")
                                    {
                                        if (field.InternalName == "Editor" ||
                                            field.InternalName == "Author" ||
                                            field.InternalName == "Title" ||
                                            field.InternalName == "ID" ||
                                            field.InternalName == "Created" ||
                                            field.InternalName == "Modified" ||
                                            field.InternalName == "Attachments" ||
                                            field.InternalName == "_UIVersionString" ||
                                            field.InternalName == "DocIcon" ||
                                            field.InternalName == "LinkTitleNoMenu" ||
                                            field.InternalName == "LinkTitle" ||
                                            field.InternalName == "Edit" ||
                                            field.InternalName == "AppAuthor" ||
                                            field.InternalName == "AppEditor" ||
                                            field.InternalName == "ContentType" ||
                                            field.InternalName == "ItemChildCount" ||
                                            field.InternalName == "FolderChildCount" ||
                                            field.InternalName == "LinkFilenameNoMenu" ||
                                            field.InternalName == "LinkFilename" ||
                                            field.InternalName == "_CopySource" ||
                                            field.InternalName == "ParentVersionString" ||
                                            field.InternalName == "ParentLeafName" ||
                                            field.InternalName == "_CheckinComment" ||
                                            field.InternalName == "FileLeafRef" ||
                                            field.InternalName == "FileSizeDisplay" ||
                                            field.InternalName == "Preview" ||
                                            field.InternalName == "ThumbnailOnForm")
                                        {
                                            addField = false;
                                        }
                                    }
                                    if (addField)
                                    {
                                        list.FieldRefs.Add(new FieldRef(field.InternalName)
                                        {
                                            Id          = field.Id,
                                            DisplayName = field.Title,
                                            Required    = field.Required,
                                            Hidden      = field.Hidden,
                                        });
                                    }
                                }
                                else
                                {
                                    list.Fields.Add((new Model.Field()
                                    {
                                        SchemaXml = field.SchemaXml
                                    }));
                                }
                            }
                        }
                        template.Lists.Add(list);
                    }
                }
            }

            return(template);
        }
예제 #23
0
        private List UpdateList(Web web, List existingList, ListInstance templateList)
        {
            web.Context.Load(existingList,
                             l => l.Title,
                             l => l.Description,
                             l => l.OnQuickLaunch,
                             l => l.Hidden,
                             l => l.ContentTypesEnabled,
                             l => l.EnableAttachments,
                             l => l.EnableFolderCreation,
                             l => l.EnableMinorVersions,
                             l => l.DraftVersionVisibility
#if !CLIENTSDKV15
                             , l => l.MajorWithMinorVersionsLimit
#endif
                             );
            web.Context.ExecuteQueryRetry();

            if (existingList.BaseTemplate == templateList.TemplateType)
            {
                var isDirty = false;
                if (templateList.Title != existingList.Title)
                {
                    existingList.Title = templateList.Title;
                    isDirty            = true;
                }
                if (!string.IsNullOrEmpty(templateList.DocumentTemplate))
                {
                    if (existingList.DocumentTemplateUrl != templateList.DocumentTemplate.ToParsedString())
                    {
                        existingList.DocumentTemplateUrl = templateList.DocumentTemplate.ToParsedString();
                        isDirty = true;
                    }
                }
                if (!string.IsNullOrEmpty(templateList.Description) && templateList.Description != existingList.Description)
                {
                    existingList.Description = templateList.Description;
                    isDirty = true;
                }
                if (templateList.Hidden != existingList.Hidden)
                {
                    existingList.Hidden = templateList.Hidden;
                    isDirty             = true;
                }
                if (templateList.OnQuickLaunch != existingList.OnQuickLaunch)
                {
                    existingList.OnQuickLaunch = templateList.OnQuickLaunch;
                    isDirty = true;
                }
                if (templateList.ContentTypesEnabled != existingList.ContentTypesEnabled)
                {
                    existingList.ContentTypesEnabled = templateList.ContentTypesEnabled;
                    isDirty = true;
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.Survey && existingList.BaseTemplate != (int)ListTemplateType.DocumentLibrary)
                {
                    // https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.splist.enableattachments.aspx
                    // The EnableAttachments property does not apply to any list that has a base type of Survey or DocumentLibrary.
                    // If you set this property to true for either type of list, it throws an SPException.
                    if (templateList.EnableAttachments != existingList.EnableAttachments)
                    {
                        existingList.EnableAttachments = templateList.EnableAttachments;
                        isDirty = true;
                    }
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
                {
                    if (templateList.EnableFolderCreation != existingList.EnableFolderCreation)
                    {
                        existingList.EnableFolderCreation = templateList.EnableFolderCreation;
                        isDirty = true;
                    }
                }
                if (templateList.EnableVersioning)
                {
                    if (existingList.EnableVersioning != templateList.EnableVersioning)
                    {
                        existingList.EnableVersioning = templateList.EnableVersioning;
                        isDirty = true;
                    }
                    if (existingList.MajorVersionLimit != templateList.MaxVersionLimit)
                    {
                        existingList.MajorVersionLimit = templateList.MaxVersionLimit;
                        isDirty = true;
                    }
                    if (existingList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        if (templateList.EnableMinorVersions != existingList.EnableMinorVersions)
                        {
                            existingList.EnableMinorVersions = templateList.EnableMinorVersions;
                            isDirty = true;
                        }
                        if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                        {
                            existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                            isDirty = true;
                        }

                        if (templateList.EnableMinorVersions)
                        {
                            if (templateList.MinorVersionLimit != existingList.MajorWithMinorVersionsLimit)
                            {
                                existingList.MajorWithMinorVersionsLimit = templateList.MinorVersionLimit;
                            }

                            if (DraftVisibilityType.Approver ==
                                (DraftVisibilityType)templateList.DraftVersionVisibility)
                            {
                                if (templateList.EnableModeration)
                                {
                                    if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                    {
                                        existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                        isDirty = true;
                                    }
                                }
                            }
                            else
                            {
                                if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                {
                                    existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                    isDirty = true;
                                }
                            }
                        }
                    }
                }
                if (isDirty)
                {
                    existingList.Update();
                    web.Context.ExecuteQueryRetry();
                }


                if (existingList.ContentTypesEnabled)
                {
                    // Check if we need to add a content type

                    var existingContentTypes = existingList.ContentTypes;
                    web.Context.Load(existingContentTypes, cts => cts.Include(ct => ct.StringId));
                    web.Context.ExecuteQueryRetry();

                    var bindingsToAdd    = templateList.ContentTypeBindings.Where(ctb => existingContentTypes.All(ct => !ctb.ContentTypeId.Equals(ct.StringId, StringComparison.InvariantCultureIgnoreCase))).ToList();
                    var defaultCtBinding = templateList.ContentTypeBindings.FirstOrDefault(ctb => ctb.Default == true);
                    foreach (var ctb in bindingsToAdd)
                    {
                        existingList.AddContentTypeToListById(ctb.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                    }

                    // default ContentTypeBinding should be set last because
                    // list extension .SetDefaultContentTypeToList() re-sets
                    // the list.RootFolder UniqueContentTypeOrder property
                    // which may cause missing CTs from the "New Button"
                    if (defaultCtBinding != null)
                    {
                        existingList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                    }
                }
                return(existingList);
            }
            else
            {
                WriteWarning(string.Format("List {0} ({1}, {2}) exists but is of a different type. Skipping list.", templateList.Title, templateList.Url, existingList.Id), ProvisioningMessageType.Warning);
                return(null);
            }
        }
예제 #24
0
        private static ListInstance ExtractViews(List siteList, ListInstance list)
        {
            foreach (var listView in siteList.Views.AsEnumerable().Where(view => !view.Hidden && view.ServerRelativeUrl.StartsWith(siteList.RootFolder.ServerRelativeUrl)))
            {
                View view = ExtractView(listView);
                if (null != view)
                {
                    list.Views.Add(view);
                }
            }

            return list;
        }
예제 #25
0
        private List CreateList(Web web, ListInstance list)
        {
            var listCreate = new ListCreationInformation();

            listCreate.Description  = list.Description;
            listCreate.TemplateType = list.TemplateType;
            listCreate.Title        = list.Title;

            // the line of code below doesn't add the list to QuickLaunch
            // the OnQuickLaunch property is re-set on the Created List object
            listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off;

            listCreate.Url = list.Url.ToParsedString();
            listCreate.TemplateFeatureId = list.TemplateFeatureID;

            var createdList = web.Lists.Add(listCreate);

            createdList.Update();
            web.Context.Load(createdList, l => l.BaseTemplate);
            web.Context.ExecuteQueryRetry();

            if (!String.IsNullOrEmpty(list.DocumentTemplate))
            {
                createdList.DocumentTemplateUrl = list.DocumentTemplate.ToParsedString();
            }

            // EnableAttachments are not supported for DocumentLibraries and Surveys
            // TODO: the user should be warned
            if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableAttachments = list.EnableAttachments;
            }

            createdList.EnableModeration = list.EnableModeration;

            createdList.EnableVersioning = list.EnableVersioning;
            if (list.EnableVersioning)
            {
                createdList.MajorVersionLimit = list.MaxVersionLimit;

                if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                {
                    // Only supported on Document Libraries
                    createdList.EnableMinorVersions    = list.EnableMinorVersions;
                    createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;

                    if (list.EnableMinorVersions)
                    {
                        createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero.

                        // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true
                        if (DraftVisibilityType.Approver ==
                            (DraftVisibilityType)list.DraftVersionVisibility)
                        {
                            if (list.EnableModeration)
                            {
                                createdList.DraftVersionVisibility =
                                    (DraftVisibilityType)list.DraftVersionVisibility;
                            }
                            else
                            {
                                WriteWarning("DraftVersionVisibility not applied because EnableModeration is not set to true", ProvisioningMessageType.Warning);
                            }
                        }
                        else
                        {
                            createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;
                        }
                    }
                }
            }

            createdList.OnQuickLaunch = list.OnQuickLaunch;
            if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
            {
                createdList.EnableFolderCreation = list.EnableFolderCreation;
            }
            createdList.Hidden = list.Hidden;
            createdList.ContentTypesEnabled = list.ContentTypesEnabled;

            createdList.Update();

            web.Context.Load(createdList.Views);
            web.Context.Load(createdList, l => l.Id);
            web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl);
            web.Context.Load(createdList.ContentTypes);
            web.Context.ExecuteQueryRetry();

            // Remove existing content types only if there are custom content type bindings
            var contentTypesToRemove = new List <ContentType>();

            if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0)
            {
                contentTypesToRemove.AddRange(createdList.ContentTypes);
            }

            ContentTypeBinding defaultCtBinding = null;

            foreach (var ctBinding in list.ContentTypeBindings)
            {
                createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                if (ctBinding.Default)
                {
                    defaultCtBinding = ctBinding;
                }
            }

            // default ContentTypeBinding should be set last because
            // list extension .SetDefaultContentTypeToList() re-sets
            // the list.RootFolder UniqueContentTypeOrder property
            // which may cause missing CTs from the "New Button"
            if (defaultCtBinding != null)
            {
                createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
            }

            // Effectively remove existing content types, if any
            foreach (var ct in contentTypesToRemove)
            {
                ct.DeleteObject();
                web.Context.ExecuteQueryRetry();
            }

            return(createdList);
        }
        public void CanProvisionCalculatedFieldLocallyInListInstance()
        {
            //This test will fail as tokens does not support this scenario.
            //The test serves as a reminder that this is not supported and needs to be fixed in a future release.
            var template = new ProvisioningTemplate();
            var listInstance = new ListInstance();

            listInstance.Url = string.Format("lists/{0}", listName);
            listInstance.Title = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;
            var referencedField = new Core.Framework.Provisioning.Model.Field();
            referencedField.SchemaXml = ElementSchema;
            listInstance.Fields.Add(referencedField);
            var calculatedField = new Core.Framework.Provisioning.Model.Field();
            calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema;
            listInstance.Fields.Add(calculatedField);
            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var rf = list.GetFieldById<FieldText>(fieldId);
                var f = list.GetFieldById<FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(rf, "Referenced field not added");
                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldCalculated));
                Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly");
            }
        }
        private static DeclarationList CreateCurrentDeclarations()
        {
            DeclarationList declarationList = new DeclarationList();
            int             num             = 1;

            declarationList[num++] = IDOwner.GetDeclaration();
            declarationList[num++] = ReportItem.GetDeclaration();
            num++;
            declarationList[num++] = Report.GetDeclaration();
            declarationList[num++] = PageSection.GetDeclaration();
            declarationList[num++] = Line.GetDeclaration();
            declarationList[num++] = Rectangle.GetDeclaration();
            declarationList[num++] = Image.GetDeclaration();
            num++;
            declarationList[num++] = CheckBox.GetDeclaration();
            declarationList[num++] = TextBox.GetDeclaration();
            declarationList[num++] = SubReport.GetDeclaration();
            declarationList[num++] = ActiveXControl.GetDeclaration();
            declarationList[num++] = DataRegion.GetDeclaration();
            num++;
            declarationList[num++] = ReportHierarchyNode.GetDeclaration();
            declarationList[num++] = Grouping.GetDeclaration();
            declarationList[num++] = Sorting.GetDeclaration();
            declarationList[num++] = List.GetDeclaration();
            declarationList[num++] = Pivot.GetDeclaration();
            declarationList[num++] = Matrix.GetDeclaration();
            declarationList[num++] = PivotHeading.GetDeclaration();
            declarationList[num++] = MatrixHeading.GetDeclaration();
            declarationList[num++] = MatrixColumn.GetDeclaration();
            num++;
            declarationList[num++] = MatrixRow.GetDeclaration();
            num++;
            declarationList[num++] = Subtotal.GetDeclaration();
            declarationList[num++] = Table.GetDeclaration();
            declarationList[num++] = TableColumn.GetDeclaration();
            num++;
            declarationList[num++] = TableGroup.GetDeclaration();
            declarationList[num++] = TableRow.GetDeclaration();
            num++;
            declarationList[num++] = OWCChart.GetDeclaration();
            declarationList[num++] = ChartColumn.GetDeclaration();
            num++;
            declarationList[num++] = ReportItemCollection.GetDeclaration();
            declarationList[num++] = ReportItemIndexer.GetDeclaration();
            num++;
            declarationList[num++] = Style.GetDeclaration();
            num++;
            declarationList[num++] = AttributeInfo.GetDeclaration();
            declarationList[num++] = Visibility.GetDeclaration();
            declarationList[num++] = ExpressionInfo.GetDeclaration();
            num++;
            declarationList[num++] = DataAggregateInfo.GetDeclaration();
            num++;
            declarationList[num++] = RunningValueInfo.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = Filter.GetDeclaration();
            num++;
            declarationList[num++] = DataSource.GetDeclaration();
            num++;
            declarationList[num++] = DataSet.GetDeclaration();
            num++;
            declarationList[num++] = ReportQuery.GetDeclaration();
            declarationList[num++] = Field.GetDeclaration();
            num++;
            declarationList[num++] = ParameterValue.GetDeclaration();
            num++;
            num++;
            num++;
            num++;
            declarationList[num++] = ReportSnapshot.GetDeclaration();
            declarationList[num++] = SenderInformation.GetDeclaration();
            declarationList[num++] = InstanceInfo.GetDeclaration();
            declarationList[num++] = ReceiverInformation.GetDeclaration();
            declarationList[num++] = InstanceInfo.GetDeclaration();
            declarationList[num++] = DocumentMapNode.GetDeclaration();
            declarationList[num++] = InfoBase.GetDeclaration();
            declarationList[num++] = OffsetInfo.GetDeclaration();
            declarationList[num++] = InstanceInfo.GetDeclaration();
            declarationList[num++] = ReportItemInstanceInfo.GetDeclaration();
            declarationList[num++] = ReportInstanceInfo.GetDeclaration();
            declarationList[num++] = ReportItemColInstanceInfo.GetDeclaration();
            declarationList[num++] = LineInstanceInfo.GetDeclaration();
            declarationList[num++] = TextBoxInstanceInfo.GetDeclaration();
            declarationList[num++] = RectangleInstanceInfo.GetDeclaration();
            declarationList[num++] = CheckBoxInstanceInfo.GetDeclaration();
            declarationList[num++] = ImageInstanceInfo.GetDeclaration();
            declarationList[num++] = SubReportInstanceInfo.GetDeclaration();
            declarationList[num++] = ActiveXControlInstanceInfo.GetDeclaration();
            declarationList[num++] = ListInstanceInfo.GetDeclaration();
            declarationList[num++] = ListContentInstanceInfo.GetDeclaration();
            declarationList[num++] = MatrixInstanceInfo.GetDeclaration();
            declarationList[num++] = MatrixHeadingInstanceInfo.GetDeclaration();
            declarationList[num++] = MatrixCellInstanceInfo.GetDeclaration();
            declarationList[num++] = TableInstanceInfo.GetDeclaration();
            declarationList[num++] = TableGroupInstanceInfo.GetDeclaration();
            declarationList[num++] = TableRowInstanceInfo.GetDeclaration();
            declarationList[num++] = OWCChartInstanceInfo.GetDeclaration();
            declarationList[num++] = ChartInstanceInfo.GetDeclaration();
            declarationList[num++] = NonComputedUniqueNames.GetDeclaration();
            declarationList[num++] = InstanceInfoOwner.GetDeclaration();
            declarationList[num++] = ReportItemInstance.GetDeclaration();
            num++;
            declarationList[num++] = ReportInstance.GetDeclaration();
            declarationList[num++] = ReportItemColInstance.GetDeclaration();
            declarationList[num++] = LineInstance.GetDeclaration();
            declarationList[num++] = TextBoxInstance.GetDeclaration();
            declarationList[num++] = RectangleInstance.GetDeclaration();
            declarationList[num++] = CheckBoxInstance.GetDeclaration();
            declarationList[num++] = ImageInstance.GetDeclaration();
            declarationList[num++] = SubReportInstance.GetDeclaration();
            declarationList[num++] = ActiveXControlInstance.GetDeclaration();
            declarationList[num++] = ListInstance.GetDeclaration();
            declarationList[num++] = ListContentInstance.GetDeclaration();
            num++;
            declarationList[num++] = MatrixInstance.GetDeclaration();
            declarationList[num++] = MatrixHeadingInstance.GetDeclaration();
            num++;
            declarationList[num++] = MatrixCellInstance.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = TableInstance.GetDeclaration();
            declarationList[num++] = TableRowInstance.GetDeclaration();
            declarationList[num++] = TableColumnInstance.GetDeclaration();
            declarationList[num++] = TableGroupInstance.GetDeclaration();
            num++;
            declarationList[num++] = OWCChartInstance.GetDeclaration();
            declarationList[num++] = ParameterInfo.GetDeclaration();
            num++;
            num++;
            num++;
            declarationList[num++] = InstanceInfo.GetDeclaration();
            num++;
            declarationList[num++] = RecordSetInfo.GetDeclaration();
            declarationList[num++] = RecordRow.GetDeclaration();
            declarationList[num++] = RecordField.GetDeclaration();
            declarationList[num++] = ValidValue.GetDeclaration();
            num++;
            declarationList[num++] = ParameterDataSource.GetDeclaration();
            declarationList[num++] = ParameterDef.GetDeclaration();
            num++;
            declarationList[num++] = ParameterBase.GetDeclaration();
            num++;
            declarationList[num++] = ProcessingMessage.GetDeclaration();
            declarationList[num++] = MatrixSubtotalHeadingInstanceInfo.GetDeclaration();
            declarationList[num++] = MatrixSubtotalCellInstance.GetDeclaration();
            declarationList[num++] = CodeClass.GetDeclaration();
            num++;
            declarationList[num++] = TableDetail.GetDeclaration();
            declarationList[num++] = TableDetailInstance.GetDeclaration();
            num++;
            declarationList[num++] = TableDetailInstanceInfo.GetDeclaration();
            num++;
            declarationList[num++] = Action.GetDeclaration();
            declarationList[num++] = ActionInstance.GetDeclaration();
            declarationList[num++] = Chart.GetDeclaration();
            declarationList[num++] = ChartHeading.GetDeclaration();
            declarationList[num++] = ChartDataPoint.GetDeclaration();
            num++;
            declarationList[num++] = MultiChart.GetDeclaration();
            declarationList[num++] = MultiChartInstance.GetDeclaration();
            num++;
            declarationList[num++] = Axis.GetDeclaration();
            declarationList[num++] = AxisInstance.GetDeclaration();
            declarationList[num++] = ChartTitle.GetDeclaration();
            declarationList[num++] = ChartTitleInstance.GetDeclaration();
            declarationList[num++] = ThreeDProperties.GetDeclaration();
            declarationList[num++] = PlotArea.GetDeclaration();
            declarationList[num++] = Legend.GetDeclaration();
            declarationList[num++] = GridLines.GetDeclaration();
            declarationList[num++] = ChartDataLabel.GetDeclaration();
            declarationList[num++] = ChartInstance.GetDeclaration();
            declarationList[num++] = ChartHeadingInstance.GetDeclaration();
            declarationList[num++] = ChartHeadingInstanceInfo.GetDeclaration();
            num++;
            declarationList[num++] = ChartDataPointInstance.GetDeclaration();
            declarationList[num++] = ChartDataPointInstanceInfo.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = RenderingPagesRanges.GetDeclaration();
            num++;
            declarationList[num++] = IntermediateFormatVersion.GetDeclaration();
            declarationList[num++] = ImageInfo.GetDeclaration();
            declarationList[num++] = ActionItem.GetDeclaration();
            declarationList[num++] = ActionItemInstance.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = DataValue.GetDeclaration();
            declarationList[num++] = DataValueInstance.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = Tablix.GetDeclaration();
            declarationList[num++] = TablixHeading.GetDeclaration();
            declarationList[num++] = CustomReportItem.GetDeclaration();
            declarationList[num++] = CustomReportItemInstance.GetDeclaration();
            declarationList[num++] = CustomReportItemHeading.GetDeclaration();
            declarationList[num++] = CustomReportItemHeadingInstance.GetDeclaration();
            num++;
            num++;
            num++;
            num++;
            declarationList[num++] = CustomReportItemCellInstance.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = DataValueCRIList.GetDeclaration();
            declarationList[num++] = BookmarkInformation.GetDeclaration();
            declarationList[num++] = InstanceInfo.GetDeclaration();
            declarationList[num++] = DrillthroughInformation.GetDeclaration();
            declarationList[num++] = InstanceInfo.GetDeclaration();
            num++;
            declarationList[num++] = CustomReportItemInstanceInfo.GetDeclaration();
            declarationList[num++] = ImageMapAreaInstanceList.GetDeclaration();
            declarationList[num++] = ImageMapAreaInstance.GetDeclaration();
            num++;
            declarationList[num++] = InstanceInfo.GetDeclaration();
            declarationList[num++] = SortFilterEventInfo.GetDeclaration();
            declarationList[num++] = EndUserSort.GetDeclaration();
            num++;
            num++;
            declarationList[num++] = RecordSetPropertyNames.GetDeclaration();
            num++;
            num++;
            num++;
            declarationList[num++] = PageSectionInstance.GetDeclaration();
            num++;
            declarationList[num++] = PageSectionInstanceInfo.GetDeclaration();
            declarationList[num++] = SimpleTextBoxInstanceInfo.GetDeclaration();
            declarationList[num++] = ScopeLookupTable.GetDeclaration();
            num++;
            declarationList[num++] = ReportDrillthroughInfo.GetDeclaration();
            declarationList[num++] = InstanceInfo.GetDeclaration();
            Global.Tracer.Assert(declarationList.Count == num, "(current.Count == index)");
            return(declarationList);
        }
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                var serverRelativeUrl = web.ServerRelativeUrl;

                // For each list in the site
                var lists = web.Lists;

                web.Context.Load(lists,
                    lc => lc.IncludeWithDefaultProperties(
                        l => l.ContentTypes,
                        l => l.Views,
                        l => l.BaseTemplate,
                        l => l.OnQuickLaunch,
                        l => l.RootFolder.ServerRelativeUrl,
                        l => l.Fields.IncludeWithDefaultProperties(
                            f => f.Id,
                            f => f.Title,
                            f => f.Hidden,
                            f => f.InternalName,
                            f => f.Required)));

                web.Context.ExecuteQueryRetry();

                // Let's see if there are workflow subscriptions
                Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription[] workflowSubscriptions = null;
                try
                {
                    workflowSubscriptions = web.GetWorkflowSubscriptions();
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                // Retrieve all not hidden lists and the Workflow History Lists, just in case there are active workflow subscriptions
                foreach (var siteList in lists.AsEnumerable().Where(l => (l.Hidden == false || ((workflowSubscriptions != null && workflowSubscriptions.Length > 0) && l.BaseTemplate == 140))))
                {
                    ListInstance baseTemplateList = null;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
                        var index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
                                                                                   f.TemplateType.Equals(siteList.BaseTemplate));
                        if (index != -1)
                        {
                            baseTemplateList = creationInfo.BaseTemplate.Lists[index];
                        }
                    }

                    var contentTypeFields = new List<FieldRef>();
                    var list = new ListInstance
                    {
                        Description = siteList.Description,
                        EnableVersioning = siteList.EnableVersioning,
                        TemplateType = siteList.BaseTemplate,
                        Title = siteList.Title,
                        Hidden = siteList.Hidden,
                        EnableFolderCreation = siteList.EnableFolderCreation,
                        DocumentTemplate = Tokenize(siteList.DocumentTemplateUrl, web.Url),
                        ContentTypesEnabled = siteList.ContentTypesEnabled,
                        Url = siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/'),
                        TemplateFeatureID = siteList.TemplateFeatureId,
                        EnableAttachments = siteList.EnableAttachments,
                        OnQuickLaunch = siteList.OnQuickLaunch,
                        MaxVersionLimit =
                            siteList.IsObjectPropertyInstantiated("MajorVersionLimit") ? siteList.MajorVersionLimit : 0,
                        EnableMinorVersions = siteList.EnableMinorVersions,
                        MinorVersionLimit =
                            siteList.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit")
                                ? siteList.MajorWithMinorVersionsLimit
                                : 0
                    };
                    var count = 0;

                    foreach (var ct in siteList.ContentTypes)
                    {
                        web.Context.Load(ct, c => c.Parent);
                        web.Context.ExecuteQueryRetry();

                        list.ContentTypeBindings.Add(new ContentTypeBinding
                        {
                            ContentTypeId = ct.Parent != null ? ct.Parent.StringId : ct.StringId,
                            Default = count == 0
                        });

                        //if (ct.Parent != null)
                        //{
                        //    //Add the parent to the list of content types
                        //    if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                        //    {
                        //    list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.Parent.StringId, Default = count == 0 });
                        //    }
                        //}
                        //else
                        //{
                        //    list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.StringId, Default = count == 0 });
                        //}

                        web.Context.Load(ct.FieldLinks);
                        web.Context.ExecuteQueryRetry();
                        foreach (var fieldLink in ct.FieldLinks)
                        {
                            if (!fieldLink.Hidden)
                            {
                                contentTypeFields.Add(new FieldRef() { Id = fieldLink.Id });
                            }
                        }
                        count++;
                    }

                    foreach (var view in siteList.Views.AsEnumerable().Where(view => !view.Hidden))
                    {
                        var schemaElement = XElement.Parse(view.ListViewXml);

                        // Toolbar is not supported

                        var toolbarElement = schemaElement.Descendants("Toolbar").FirstOrDefault();
                        if (toolbarElement != null)
                        {
                            toolbarElement.Remove();
                        }

                        // XslLink is not supported
                        var xslLinkElement = schemaElement.Descendants("XslLink").FirstOrDefault();
                        if (xslLinkElement != null)
                        {
                            xslLinkElement.Remove();
                        }

                        list.Views.Add(new View { SchemaXml = schemaElement.ToString() });
                    }

                    var siteColumns = web.Fields;
                    web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
                    web.Context.ExecuteQueryRetry();

                    foreach (var field in siteList.Fields.AsEnumerable().Where(field => !field.Hidden))
                    {
                        if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                        {
                            var addField = true;
                            if (siteList.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                            {
                                if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                                {
                                    addField = false;
                                }
                            }

                            var fieldElement = XElement.Parse(field.SchemaXml);
                            var sourceId = fieldElement.Attribute("SourceID") != null ? fieldElement.Attribute("SourceID").Value : null;

                            if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3")
                            {
                                if (field.InternalName == "Editor" ||
                                    field.InternalName == "Author" ||
                                    field.InternalName == "Title" ||
                                    field.InternalName == "ID" ||
                                    field.InternalName == "Created" ||
                                    field.InternalName == "Modified" ||
                                    field.InternalName == "Attachments" ||
                                    field.InternalName == "_UIVersionString" ||
                                    field.InternalName == "DocIcon" ||
                                    field.InternalName == "LinkTitleNoMenu" ||
                                    field.InternalName == "LinkTitle" ||
                                    field.InternalName == "Edit" ||
                                    field.InternalName == "AppAuthor" ||
                                    field.InternalName == "AppEditor" ||
                                    field.InternalName == "ContentType" ||
                                    field.InternalName == "ItemChildCount" ||
                                    field.InternalName == "FolderChildCount" ||
                                    field.InternalName == "LinkFilenameNoMenu" ||
                                    field.InternalName == "LinkFilename" ||
                                    field.InternalName == "_CopySource" ||
                                    field.InternalName == "ParentVersionString" ||
                                    field.InternalName == "ParentLeafName" ||
                                    field.InternalName == "_CheckinComment" ||
                                    field.InternalName == "FileLeafRef" ||
                                    field.InternalName == "FileSizeDisplay" ||
                                    field.InternalName == "Preview" ||
                                    field.InternalName == "ThumbnailOnForm")
                                {
                                    addField = false;
                                }
                            }
                            if (addField)
                            {
                                list.FieldRefs.Add(new FieldRef(field.InternalName)
                                {
                                    Id = field.Id,
                                    DisplayName = field.Title,
                                    Required = field.Required,
                                    Hidden = field.Hidden,
                                });
                            }
                        }
                        else
                        {
                            list.Fields.Add((new Model.Field { SchemaXml = field.SchemaXml }));
                        }

                        list.Security = siteList.GetSecurity();
                    }
                    var logCTWarning = false;
                    if (baseTemplateList != null)
                    {
                        if (!baseTemplateList.Equals(list))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                            template.Lists.Add(list);
                            if (list.ContentTypesEnabled && list.ContentTypeBindings.Any() && web.IsSubSite())
                            {
                                logCTWarning = true;
                            }
                        }
                    }
                    else
                    {
                        scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                        template.Lists.Add(list);
                        if (list.ContentTypesEnabled && list.ContentTypeBindings.Any() && web.IsSubSite())
                        {
                            logCTWarning = true;
                        }

                    }
                    if (logCTWarning)
                    {
                        scope.LogWarning("You are extracting a template from a subweb. List '{0}' refers to content types. Content types are not exported when extracting a template from a subweb", list.Title);
                        WriteWarning(string.Format("You are extracting a template from a subweb. List '{0}' refers to content types. Content types are not exported when extracting a template from a subweb", list.Title), ProvisioningMessageType.Warning);
                    }
                }

            }
            return template;
        }
        // 删除数组集合元素
        public void Remove(TItemType item)
        {
            try
            {
                switch (BaseType)
                {
                case StructType.NormalArray:
                    if (Array.IndexOf(NormalArray, item) != -1)
                    {
                        NormalArray[Array.IndexOf(NormalArray, item)] = default(TItemType);
                        // for (var i = Array.IndexOf(NormalArray, item); i < ArrayCount - 1; i++)
                        //     NormalArray[i] = NormalArray[i + 1];
                        ArrayCount--;
                    }
                    else
                    {
                        var e = new StructShowControllerException("找不到元素!");
                        throw e;
                    }

                    break;

                case StructType.Array:
                    if (Array.IndexOf(ArrayInstance, item) != -1)
                    {
                        ArrayInstance.SetValue(null, Array.IndexOf(ArrayInstance, item));
                        // for (var i = Array.IndexOf(ArrayInstance, item); i < ArrayCount - 1; i++)
                        //     ArrayInstance.SetValue(ArrayInstance.GetValue(i + 1), i);
                        ArrayCount--;
                    }
                    else
                    {
                        var e = new StructShowControllerException("找不到元素!");
                        throw e;
                    }

                    break;

                case StructType.ArrayList:
                    if (ArrayListInstance.Contains(item))
                    {
                        ArrayListInstance.Remove(item);
                    }
                    else
                    {
                        var e = new StructShowControllerException("找不到元素!");
                        throw e;
                    }

                    break;

                case StructType.List:
                    if (ListInstance.Contains(item))
                    {
                        ListInstance.Remove(item);
                    }
                    else
                    {
                        var e = new StructShowControllerException("找不到元素!");
                        throw e;
                    }

                    break;

                case StructType.Dictionary:
                    if (DictionaryInstance.ContainsValue(item))
                    {
                        foreach (var comparable in DictionaryInstance)
                        {
                            if (comparable.Value.Equals(item))
                            {
                                DictionaryInstance.Remove(comparable.Key);
                            }
                        }
                    }
                    else
                    {
                        var e = new StructShowControllerException("找不到元素!");
                        throw e;
                    }

                    break;

                case StructType.HashTable:
                    if (HashTableInstance.ContainsValue(item))
                    {
                        foreach (DictionaryEntry entry in HashTableInstance)
                        {
                            if (entry.Value.Equals(item))
                            {
                                HashTableInstance.Remove(entry.Key);
                            }
                        }
                    }
                    else
                    {
                        var e = new StructShowControllerException("找不到元素!");
                        throw e;
                    }

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (InvalidOperationException)
            {
            }
        }
        private Tuple<List, TokenParser> CreateList(Web web, ListInstance list, TokenParser parser, PnPMonitoredScope scope)
        {
            var listCreate = new ListCreationInformation();
            listCreate.Description = list.Description;
            listCreate.TemplateType = list.TemplateType;
            listCreate.Title = parser.ParseString(list.Title);

            // the line of code below doesn't add the list to QuickLaunch
            // the OnQuickLaunch property is re-set on the Created List object
            listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off;

            listCreate.Url = parser.ParseString(list.Url);
            listCreate.TemplateFeatureId = list.TemplateFeatureID;

            var createdList = web.Lists.Add(listCreate);
            createdList.Update();
            web.Context.Load(createdList, l => l.BaseTemplate);
            web.Context.ExecuteQueryRetry();

            if (!String.IsNullOrEmpty(list.DocumentTemplate))
            {
                createdList.DocumentTemplateUrl = parser.ParseString(list.DocumentTemplate);
            }

            // EnableAttachments are not supported for DocumentLibraries and Surveys
            // TODO: the user should be warned
            if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableAttachments = list.EnableAttachments;
            }

            createdList.EnableModeration = list.EnableModeration;

            // Done for all other lists than for Survey - With Surveys versioning configuration will cause an exception
            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableVersioning = list.EnableVersioning;
                if (list.EnableVersioning)
                {
            #if !CLIENTSDKV15
                    createdList.MajorVersionLimit = list.MaxVersionLimit;
            #endif

                    if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        createdList.EnableMinorVersions = list.EnableMinorVersions;
                        createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;

                        if (list.EnableMinorVersions)
                        {
                            createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero.

                            // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true
                            if (DraftVisibilityType.Approver ==
                                (DraftVisibilityType)list.DraftVersionVisibility)
                            {
                                if (list.EnableModeration)
                                {
                                    createdList.DraftVersionVisibility =
                                        (DraftVisibilityType)list.DraftVersionVisibility;
                                }
                                else
                                {
                                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true);
                                    WriteWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true, ProvisioningMessageType.Warning);
                                }
                            }
                            else
                            {
                                createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;
                            }
                        }
                    }
                }
            }

            createdList.OnQuickLaunch = list.OnQuickLaunch;
            if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
            {
                createdList.EnableFolderCreation = list.EnableFolderCreation;
            }
            createdList.Hidden = list.Hidden;
            createdList.ContentTypesEnabled = list.ContentTypesEnabled;

            createdList.Update();

            web.Context.Load(createdList.Views);
            web.Context.Load(createdList, l => l.Id);
            web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl);
            web.Context.Load(createdList.ContentTypes);
            web.Context.ExecuteQueryRetry();

            // Remove existing content types only if there are custom content type bindings
            var contentTypesToRemove = new List<ContentType>();
            if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0)
            {
                contentTypesToRemove.AddRange(createdList.ContentTypes);
            }

            ContentTypeBinding defaultCtBinding = null;
            foreach (var ctBinding in list.ContentTypeBindings)
            {
                var tempCT = web.GetContentTypeById(ctBinding.ContentTypeId, searchInSiteHierarchy: true);
                if (tempCT != null)
                {
                    // Check if CT is already available
                    var name = tempCT.EnsureProperty(ct => ct.Name);
                    if (!createdList.ContentTypeExistsByName(name))
                    {
                        createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                    }
                    if (ctBinding.Default)
                    {
                        defaultCtBinding = ctBinding;
                    }
                }
            }

            // default ContentTypeBinding should be set last because
            // list extension .SetDefaultContentTypeToList() re-sets
            // the list.RootFolder UniqueContentTypeOrder property
            // which may cause missing CTs from the "New Button"
            if (defaultCtBinding != null)
            {
                createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
            }

            // Effectively remove existing content types, if any
            foreach (var ct in contentTypesToRemove)
            {
                ct.DeleteObject();
                web.Context.ExecuteQueryRetry();
            }

            if (list.Security != null)
            {
                createdList.SetSecurity(parser, list.Security);
            }
            return Tuple.Create(createdList, parser);
        }
예제 #31
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            if (!web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                web.Context.ExecuteQuery();
            }

            var serverRelativeUrl = web.ServerRelativeUrl;

            // For each list in the site
            ListCollection lists = web.Lists;
            web.Context.Load(lists, lc => lc.IncludeWithDefaultProperties(l => l.ContentTypes, l => l.Views, l => l.RootFolder.ServerRelativeUrl, l => l.Fields));
            web.Context.ExecuteQuery();
            foreach (var item in lists)
            {
                // Do not export system lists
                if (!item.Hidden)
                {

                    int index = -1;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves perf
                        index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length)) &&
                                                                  f.TemplateType.Equals(item.BaseTemplate));
                    }

                    if (index == -1)
                    {
                        var contentTypeFields = new List<FieldRef>();
                        ListInstance list = new ListInstance();
                        list.Description = item.Description;
                        list.EnableVersioning = item.EnableVersioning;
                        list.TemplateType = item.BaseTemplate;
                        list.Title = item.Title;
                        list.Hidden = item.Hidden;
                        list.DocumentTemplate = Tokenize(item.DocumentTemplateUrl, web.Url);
                        list.ContentTypesEnabled = item.ContentTypesEnabled;
                        list.Url = item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/');

                        int count = 0;

                        foreach (var ct in item.ContentTypes)
                        {
                            web.Context.Load(ct, c => c.Parent);
                            web.Context.ExecuteQuery();
                            if (ct.Parent != null)
                            {
                                // Add the parent to the list of content types
                                if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                                {
                                    list.ContentTypeBindings.Add(new ContentTypeBinding() {ContentTypeID = ct.Parent.StringId, Default = count == 0 ? true : false});
                                }
                            }
                            else
                            {
                                list.ContentTypeBindings.Add(new ContentTypeBinding() {ContentTypeID = ct.StringId, Default = count == 0});
                            }

                            web.Context.Load(ct.FieldLinks);
                            web.Context.ExecuteQuery();
                            foreach (var fieldLink in ct.FieldLinks)
                            {
                                if (!fieldLink.Hidden)
                                {
                                    contentTypeFields.Add(new FieldRef() { ID = fieldLink.Id });
                                }
                            }
                            count++;
                        }

                        foreach (var view in item.Views)
                        {
                            if (!view.Hidden)
                            {
                                list.Views.Add(new View() { SchemaXml = view.ListViewXml });
                            }
                        }

                        var siteColumns = web.Fields;
                        web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
                        web.Context.ExecuteQuery();

                        foreach (var field in item.Fields)
                        {
                            if (!field.Hidden)
                            {
                                if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                                {
                                    if (contentTypeFields.FirstOrDefault(c => c.ID == field.Id) == null)
                                    {
                                        list.FieldRefs.Add(new FieldRef() { ID = field.Id });
                                    }
                                }
                                else
                                {
                                    list.Fields.Add((new Model.Field() { SchemaXml = field.SchemaXml }));
                                }
                            }
                        }
                        template.Lists.Add(list);
                    }
                }
            }

            return template;
        }
예제 #32
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            if (!web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                web.Context.Load(web, w => w.ServerRelativeUrl);
                web.Context.ExecuteQueryRetry();
            }

            var serverRelativeUrl = web.ServerRelativeUrl;

            // For each list in the site
            ListCollection lists = web.Lists;

            web.Context.Load(lists, lc => lc.IncludeWithDefaultProperties(l => l.ContentTypes, l => l.Views, l => l.RootFolder.ServerRelativeUrl, l => l.Fields));
            web.Context.ExecuteQuery();
            foreach (var item in lists)
            {
                // Do not export system lists
                if (!item.Hidden)
                {
                    int index = -1;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves perf
                        index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length)) &&
                                                                          f.TemplateType.Equals(item.BaseTemplate));
                    }

                    if (index == -1)
                    {
                        var          contentTypeFields = new List <FieldRef>();
                        ListInstance list = new ListInstance();
                        list.Description         = item.Description;
                        list.EnableVersioning    = item.EnableVersioning;
                        list.TemplateType        = item.BaseTemplate;
                        list.Title               = item.Title;
                        list.Hidden              = item.Hidden;
                        list.DocumentTemplate    = Tokenize(item.DocumentTemplateUrl, web.Url);
                        list.ContentTypesEnabled = item.ContentTypesEnabled;
                        list.Url = item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/');

                        int count = 0;

                        foreach (var ct in item.ContentTypes)
                        {
                            web.Context.Load(ct, c => c.Parent);
                            web.Context.ExecuteQuery();
                            if (ct.Parent != null)
                            {
                                // Add the parent to the list of content types
                                if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                                {
                                    list.ContentTypeBindings.Add(new ContentTypeBinding()
                                    {
                                        ContentTypeID = ct.Parent.StringId, Default = count == 0 ? true : false
                                    });
                                }
                            }
                            else
                            {
                                list.ContentTypeBindings.Add(new ContentTypeBinding()
                                {
                                    ContentTypeID = ct.StringId, Default = count == 0
                                });
                            }

                            web.Context.Load(ct.FieldLinks);
                            web.Context.ExecuteQueryRetry();
                            foreach (var fieldLink in ct.FieldLinks)
                            {
                                if (!fieldLink.Hidden)
                                {
                                    contentTypeFields.Add(new FieldRef()
                                    {
                                        ID = fieldLink.Id
                                    });
                                }
                            }
                            count++;
                        }

                        foreach (var view in item.Views)
                        {
                            if (!view.Hidden)
                            {
                                list.Views.Add(new View()
                                {
                                    SchemaXml = view.ListViewXml
                                });
                            }
                        }

                        var siteColumns = web.Fields;
                        web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
                        web.Context.ExecuteQueryRetry();

                        foreach (var field in item.Fields)
                        {
                            if (!field.Hidden)
                            {
                                if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                                {
                                    if (contentTypeFields.FirstOrDefault(c => c.ID == field.Id) == null)
                                    {
                                        list.FieldRefs.Add(new FieldRef()
                                        {
                                            ID = field.Id
                                        });
                                    }
                                }
                                else
                                {
                                    list.Fields.Add((new Model.Field()
                                    {
                                        SchemaXml = field.SchemaXml
                                    }));
                                }
                            }
                        }
                        template.Lists.Add(list);
                    }
                }
            }

            return(template);
        }
예제 #33
0
        private Tuple<List, TokenParser> UpdateList(Web web, List existingList, ListInstance templateList, TokenParser parser, PnPMonitoredScope scope)
        {
            try
            {
                web.Context.Load(existingList, l => l.Forms);
                web.Context.ExecuteQueryRetry();
            }
            catch (Exception ex)
            {
                scope.LogDebug("Loading forms on list {0} failed. {1}. {2}", existingList.Title, ex.Message, ex.StackTrace);
            }

            if (existingList.BaseTemplate == templateList.TemplateType)
            {
                var isDirty = false;
                if (parser.ParseString(templateList.Title) != existingList.Title)
                {
                    var oldTitle = existingList.Title;
                    existingList.Title = parser.ParseString(templateList.Title);
                    if (!oldTitle.Equals(existingList.Title, StringComparison.OrdinalIgnoreCase))
                    {
                        parser.AddToken(new ListIdToken(web, existingList.Title, existingList.Id));
                        parser.AddToken(new ListUrlToken(web, existingList.Title, existingList.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + (web.ServerRelativeUrl == "/" ? 0 : 1))));
                    }
                    isDirty = true;
                }
                if (!string.IsNullOrEmpty(templateList.DocumentTemplate))
                {
                    if (existingList.DocumentTemplateUrl != parser.ParseString(templateList.DocumentTemplate))
                    {
                        var documentTemplateUrl = parser.ParseString(templateList.DocumentTemplate);

                        var templateFolderUrl = documentTemplateUrl.Substring(0, documentTemplateUrl.LastIndexOf('/'));
                        var templateForder = web.GetFolderByServerRelativeUrl(templateFolderUrl);
                        var templateName = documentTemplateUrl.Substring(documentTemplateUrl.LastIndexOf('/') + 1);
                        var templateStream = new MemoryStream(Encoding.UTF8.GetBytes(templateList.DocumentTemplateContent));
                        templateForder.UploadFile(templateName, templateStream, true);

                        existingList.DocumentTemplateUrl = documentTemplateUrl;
                        isDirty = true;
                    }
                }
                if (!string.IsNullOrEmpty(templateList.Description) && templateList.Description != existingList.Description)
                {
                    existingList.Description = templateList.Description;
                    isDirty = true;
                }
                if (templateList.Hidden != existingList.Hidden)
                {
                    existingList.Hidden = templateList.Hidden;
                    isDirty = true;
                }
                if (templateList.OnQuickLaunch != existingList.OnQuickLaunch)
                {
                    existingList.OnQuickLaunch = templateList.OnQuickLaunch;
                    isDirty = true;
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.Survey &&
                    templateList.ContentTypesEnabled != existingList.ContentTypesEnabled)
                {
                    existingList.ContentTypesEnabled = templateList.ContentTypesEnabled;
                    isDirty = true;
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.Survey && existingList.BaseTemplate != (int)ListTemplateType.DocumentLibrary)
                {
                    // https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.splist.enableattachments.aspx
                    // The EnableAttachments property does not apply to any list that has a base type of Survey or DocumentLibrary.
                    // If you set this property to true for either type of list, it throws an SPException.
                    if (templateList.EnableAttachments != existingList.EnableAttachments)
                    {
                        existingList.EnableAttachments = templateList.EnableAttachments;
                        isDirty = true;
                    }
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
                {
                    if (templateList.EnableFolderCreation != existingList.EnableFolderCreation)
                    {
                        existingList.EnableFolderCreation = templateList.EnableFolderCreation;
                        isDirty = true;
                    }
                }
            #if !CLIENTSDKV15
                if(templateList.Title.ContainsResourceToken())
                {
                    if(existingList.TitleResource.SetUserResourceValue(templateList.Title, parser))
                    {
                        isDirty = true;
                    }
                }
            #endif
                if (templateList.EnableVersioning)
                {
                    if (existingList.EnableVersioning != templateList.EnableVersioning)
                    {
                        existingList.EnableVersioning = templateList.EnableVersioning;
                        isDirty = true;
                    }
            #if !CLIENTSDKV15
                    if (existingList.IsObjectPropertyInstantiated("MajorVersionLimit") && existingList.MajorVersionLimit != templateList.MaxVersionLimit)
                    {
                        existingList.MajorVersionLimit = templateList.MaxVersionLimit;
                        isDirty = true;
                    }
            #endif
                    if (existingList.BaseType == BaseType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        if (templateList.EnableMinorVersions != existingList.EnableMinorVersions)
                        {
                            existingList.EnableMinorVersions = templateList.EnableMinorVersions;
                            isDirty = true;
                        }
                        if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                        {
                            existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                            isDirty = true;
                        }

                        if (templateList.EnableMinorVersions)
                        {
                            if (templateList.MinorVersionLimit != existingList.MajorWithMinorVersionsLimit)
                            {
                                existingList.MajorWithMinorVersionsLimit = templateList.MinorVersionLimit;
                            }

                            if (DraftVisibilityType.Approver ==
                                (DraftVisibilityType)templateList.DraftVersionVisibility)
                            {
                                if (templateList.EnableModeration)
                                {
                                    if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                    {
                                        existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                        isDirty = true;
                                    }
                                }
                            }
                            else
                            {
                                if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                {
                                    existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                    isDirty = true;
                                }
                            }
                        }
                    }
                }
                if (isDirty)
                {
                    existingList.Update();
                    web.Context.ExecuteQueryRetry();
                }

                if (existingList.ContentTypesEnabled)
                {
                    // Check if we need to add a content type

                    var existingContentTypes = existingList.ContentTypes;

                    var bindingsToAdd = templateList.ContentTypeBindings.Where(ctb => existingContentTypes.All(ct => !ctb.ContentTypeId.Equals(ct.StringId, StringComparison.InvariantCultureIgnoreCase))).ToList();
                    var defaultCtBinding = templateList.ContentTypeBindings.FirstOrDefault(ctb => ctb.Default == true);

                    var bindingAddedToList = false;
                    foreach (var ctb in bindingsToAdd)
                    {
                        // Added a check so that if no bindings were actually added then the SetDefaultContentTypeToList method will not be executed
                        // This is to address a specific scenario when OOTB PWA lists can not be updated as they are centrally managed
                        var contentType = web.AvailableContentTypes.AsEnumerable().FirstOrDefault(item => item.Id.StringValue.Equals(ctb.ContentTypeId, StringComparison.OrdinalIgnoreCase));
                        if (contentType != null)
                        {
                            // Check if CT is already available
                            var name = contentType.EnsureProperty(ct => ct.Name);
                            if (!existingList.ContentTypes.AsEnumerable().Any(item => item.Name == name))
                            {
                                if (existingList.ContentTypesEnabled == false)
                                {
                                    existingList.ContentTypesEnabled = true;
                                    existingList.Update();
                                    existingList.Context.ExecuteQueryRetry();
                                }

                                existingList.ContentTypes.AddExistingContentType(contentType);
                            bindingAddedToList = true;
                        }
                    }
                    }

                    if (bindingAddedToList)
                    {
                        web.Context.ExecuteQueryRetry();
                    }

                    // default ContentTypeBinding should be set last because
                    // list extension .SetDefaultContentTypeToList() re-sets
                    // the list.RootFolder UniqueContentTypeOrder property
                    // which may cause missing CTs from the "New Button"
                    if (defaultCtBinding != null && bindingAddedToList)
                    {
                        existingList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                    }
                }
                if (templateList.Security != null)
                {
                    try
                    {
                        existingList.SetSecurity(parser, templateList.Security);
                    }
                    catch (Exception ex)
                    {
                        scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Updating_list__0__failed___1_____2_, templateList.Title, ex.Message, ex.StackTrace);
                    }
                }
                return Tuple.Create(existingList, parser);
            }
            else
            {
                scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_List__0____1____2___exists_but_is_of_a_different_type__Skipping_list_, templateList.Title, templateList.Url, existingList.Id);
                WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_List__0____1____2___exists_but_is_of_a_different_type__Skipping_list_, templateList.Title, templateList.Url, existingList.Id), ProvisioningMessageType.Warning);
                return null;
            }
        }
예제 #34
0
        private ListInstance ExtractFields(Web web, List siteList, List<FieldRef> contentTypeFields, ListInstance list, List<List> lists, ProvisioningTemplateCreationInformation creationInfo, ProvisioningTemplate template)
        {
            Microsoft.SharePoint.Client.FieldCollection siteColumns = null;
            if (web.IsSubSite())
            {
                var siteContext = web.Context.GetSiteCollectionContext();
                var rootWeb = siteContext.Site.RootWeb;
                siteColumns = rootWeb.Fields;
                siteContext.Load(siteColumns, scs => scs.Include(sc => sc.Id, sc => sc.DefaultValue));
                siteContext.ExecuteQueryRetry();
            }
            else
            {
                siteColumns = web.Fields;
                web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id, sc => sc.DefaultValue));
                web.Context.ExecuteQueryRetry();
            }

            foreach (var field in siteList.Fields.AsEnumerable().Where(field => !field.Hidden || SpecialFields.Contains(field.InternalName)))
            {
                var siteColumn = siteColumns.FirstOrDefault(sc => sc.Id == field.Id);
                if (siteColumn != null)
                {
                    var addField = true;
                    if (siteList.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                    {
                        if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                        {
                            addField = false;
                        }
                    }

                    if(siteColumn.DefaultValue != field.DefaultValue)
                    {
                        list.FieldDefaults.Add(field.InternalName, field.DefaultValue);
                    }

                    var fieldElement = XElement.Parse(field.SchemaXml);
                    var sourceId = fieldElement.Attribute("SourceID") != null ? fieldElement.Attribute("SourceID").Value : null;

                    if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3")
                    {
                        if (field.InternalName == "Editor" ||
                            field.InternalName == "Author" ||
                            field.InternalName == "Title" ||
                            field.InternalName == "ID" ||
                            field.InternalName == "Created" ||
                            field.InternalName == "Modified" ||
                            field.InternalName == "Attachments" ||
                            field.InternalName == "_UIVersionString" ||
                            field.InternalName == "DocIcon" ||
                            field.InternalName == "LinkTitleNoMenu" ||
                            field.InternalName == "LinkTitle" ||
                            field.InternalName == "Edit" ||
                            field.InternalName == "AppAuthor" ||
                            field.InternalName == "AppEditor" ||
                            field.InternalName == "ContentType" ||
                            field.InternalName == "ItemChildCount" ||
                            field.InternalName == "FolderChildCount" ||
                            field.InternalName == "LinkFilenameNoMenu" ||
                            field.InternalName == "LinkFilename" ||
                            field.InternalName == "_CopySource" ||
                            field.InternalName == "ParentVersionString" ||
                            field.InternalName == "ParentLeafName" ||
                            field.InternalName == "_CheckinComment" ||
                            field.InternalName == "FileLeafRef" ||
                            field.InternalName == "FileSizeDisplay" ||
                            field.InternalName == "Preview" ||
                            field.InternalName == "ThumbnailOnForm")
                        {
                            addField = false;
                        }
                    }
                    if (addField)
                    {

                        list.FieldRefs.Add(new FieldRef(field.InternalName)
                        {
                            Id = field.Id,
                            DisplayName = field.Title,
                            Required = field.Required,
                            Hidden = field.Hidden,
                        });
                        if (field.TypeAsString.StartsWith("TaxonomyField"))
                        {
                            // find the corresponding taxonomy field and include it anyway
                            var taxField = (TaxonomyField)field;
                            taxField.EnsureProperties(f => f.TextField, f => f.Id);

                            var noteField = siteList.Fields.GetById(taxField.TextField);
                            web.Context.Load(noteField, nf => nf.Id, nf => nf.Title, nf => nf.Required, nf => nf.Hidden, nf => nf.InternalName);
                            web.Context.ExecuteQueryRetry();

                            list.FieldRefs.Insert(0, new FieldRef(noteField.InternalName)
                            {
                                Id = noteField.Id,
                                DisplayName = noteField.Title,
                                Required = noteField.Required,
                                Hidden = noteField.Hidden
                            });
                        }
                    }
                }
                else
                {
                    var schemaXml = ParseFieldSchema(field.SchemaXml, lists);
                    var fieldElement = XElement.Parse(field.SchemaXml);
                    var listId = fieldElement.Attribute("List") != null ? fieldElement.Attribute("List").Value : null;

                    if (fieldElement.Attribute("Type").Value == "Calculated")
                    {
                        schemaXml = TokenizeFieldFormula(schemaXml);
                    }

                    if (creationInfo.PersistMultiLanguageResources)
                    {
            #if !SP2013
                        if (UserResourceExtensions.PersistResourceValue(field.TitleResource, string.Format("Field_{0}_DisplayName", field.Title.Replace(" ", "_")), template, creationInfo))
                        {
                            var fieldTitle = string.Format("{{res:Field_{0}_DisplayName}}", field.Title.Replace(" ", "_"));
                            fieldElement.SetAttributeValue("DisplayName", fieldTitle);

                        }
                        if (UserResourceExtensions.PersistResourceValue(field.DescriptionResource, string.Format("Field_{0}_Description", field.Title.Replace(" ", "_")), template, creationInfo))
                        {
                            var fieldDescription = string.Format("{{res:Field_{0}_Description}}", field.Title.Replace(" ", "_"));
                            fieldElement.SetAttributeValue("Description", fieldDescription);
                        }

                        schemaXml = fieldElement.ToString();
            #endif
                    }

                    if (listId == null)
                    {
                        list.Fields.Add((new Model.Field { SchemaXml = schemaXml }));
                    }
                    else
                    {
                        var listIdValue = Guid.Empty;
                        if (Guid.TryParse(listId, out listIdValue))
                        {
                            var sourceList = lists.AsEnumerable().Where(l => l.Id == listIdValue).FirstOrDefault();
                            if (sourceList != null)
                                fieldElement.Attribute("List").SetValue(String.Format("{{listid:{0}}}", sourceList.Title));
                        }

                        list.Fields.Add(new Model.Field { SchemaXml = fieldElement.ToString() });
                    }

                    if (field.TypeAsString.StartsWith("TaxonomyField"))
                    {
                        schemaXml = TokenizeTaxonomyField(web, fieldElement);

                        // find the corresponding taxonomy container text field and include it too
                        var taxField = (TaxonomyField)field;
                        taxField.EnsureProperties(f => f.TextField, f => f.Id);

                        var noteField = siteList.Fields.GetById(taxField.TextField);
                        web.Context.Load(noteField, nf => nf.SchemaXml);
                        web.Context.ExecuteQueryRetry();
                        var noteSchemaXml = XElement.Parse(noteField.SchemaXml);
                        noteSchemaXml.Attribute("SourceID").Remove();
                        list.Fields.Insert(0, new Model.Field { SchemaXml = ParseFieldSchema(noteSchemaXml.ToString(), lists) });
                    }

                }
            }
            return list;
        }
예제 #35
0
        private static ListInstance ExtractForms(Web web, List siteList, ListInstance list)
        {
            web.Context.Load(siteList, l => l.Forms);
            web.Context.ExecuteQueryRetry();

            var defaultForms = new[] { siteList.DefaultDisplayFormUrl, siteList.DefaultEditFormUrl, siteList.DefaultNewFormUrl };

            foreach (var form in siteList.Forms)
            {
                var model = new Form
                {
                    FormType = form.FormType,
                    ServerRelativeUrl = form.ServerRelativeUrl,
                    IsDefault = defaultForms.Contains(form.ServerRelativeUrl)
                };
                list.Forms.Add(model);
            }
            return list;
        }
        public void CanProvisionCalculatedFieldInListInstance()
        {
            var template = new ProvisioningTemplate();
            var listInstance = new ListInstance();
            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema });

            listInstance.Url = string.Format("lists/{0}", listName);
            listInstance.Title = listName;
            listInstance.TemplateType = (int)ListTemplateType.GenericList;

            var referencedField = new FieldRef();
            referencedField.Id = fieldId;
            listInstance.FieldRefs.Add(referencedField);

            var calculatedField = new Core.Framework.Provisioning.Model.Field();
            calculatedField.SchemaXml = TokenizedCalculatedFieldElementSchema;
            listInstance.Fields.Add(calculatedField);

            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                var parser = new TokenParser(ctx.Web, template);
                new ObjectField().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());
                new ObjectListInstance().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);

                var rf = list.GetFieldById<FieldText>(fieldId);
                var f = list.GetFieldById<FieldCalculated>(calculatedFieldId);

                Assert.IsNotNull(rf, "Referenced field not added");
                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldCalculated));
                Assert.IsFalse(f.Formula.Contains('#') || f.Formula.Contains('?'), "Calculated field was not provisioned properly");
            }
        }
        private Tuple<List, TokenParser> UpdateList(Web web, List existingList, ListInstance templateList, TokenParser parser, PnPMonitoredScope scope)
        {
            web.Context.Load(existingList,
                l => l.Title,
                l => l.Description,
                l => l.OnQuickLaunch,
                l => l.Hidden,
                l => l.ContentTypesEnabled,
                l => l.EnableAttachments,
                l => l.EnableFolderCreation,
                l => l.EnableMinorVersions,
                l => l.DraftVersionVisibility,
                l => l.Views
            #if !CLIENTSDKV15
            , l => l.MajorWithMinorVersionsLimit
            #endif
            );
            web.Context.ExecuteQueryRetry();

            if (existingList.BaseTemplate == templateList.TemplateType)
            {
                var isDirty = false;
                if (parser.ParseString(templateList.Title) != existingList.Title)
                {
                    existingList.Title = parser.ParseString(templateList.Title);
                    isDirty = true;
                }
                if (!string.IsNullOrEmpty(templateList.DocumentTemplate))
                {
                    if (existingList.DocumentTemplateUrl != parser.ParseString(templateList.DocumentTemplate))
                    {
                        existingList.DocumentTemplateUrl = parser.ParseString(templateList.DocumentTemplate);
                        isDirty = true;
                    }
                }
                if (!string.IsNullOrEmpty(templateList.Description) && templateList.Description != existingList.Description)
                {
                    existingList.Description = templateList.Description;
                    isDirty = true;
                }
                if (templateList.Hidden != existingList.Hidden)
                {
                    existingList.Hidden = templateList.Hidden;
                    isDirty = true;
                }
                if (templateList.OnQuickLaunch != existingList.OnQuickLaunch)
                {
                    existingList.OnQuickLaunch = templateList.OnQuickLaunch;
                    isDirty = true;
                }
                if (templateList.ContentTypesEnabled != existingList.ContentTypesEnabled)
                {
                    existingList.ContentTypesEnabled = templateList.ContentTypesEnabled;
                    isDirty = true;
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.Survey && existingList.BaseTemplate != (int)ListTemplateType.DocumentLibrary)
                {
                    // https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.splist.enableattachments.aspx
                    // The EnableAttachments property does not apply to any list that has a base type of Survey or DocumentLibrary.
                    // If you set this property to true for either type of list, it throws an SPException.
                    if (templateList.EnableAttachments != existingList.EnableAttachments)
                    {
                        existingList.EnableAttachments = templateList.EnableAttachments;
                        isDirty = true;
                    }
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
                {
                    if (templateList.EnableFolderCreation != existingList.EnableFolderCreation)
                    {
                        existingList.EnableFolderCreation = templateList.EnableFolderCreation;
                        isDirty = true;
                    }
                }
                if (templateList.EnableVersioning)
                {
                    if (existingList.EnableVersioning != templateList.EnableVersioning)
                    {
                        existingList.EnableVersioning = templateList.EnableVersioning;
                        isDirty = true;
                    }
            #if !CLIENTSDKV15
                    if (existingList.IsObjectPropertyInstantiated("MajorVersionLimit") && existingList.MajorVersionLimit != templateList.MaxVersionLimit)
                    {
                        existingList.MajorVersionLimit = templateList.MaxVersionLimit;
                        isDirty = true;
                    }
            #endif
                    if (existingList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        if (templateList.EnableMinorVersions != existingList.EnableMinorVersions)
                        {
                            existingList.EnableMinorVersions = templateList.EnableMinorVersions;
                            isDirty = true;
                        }
                        if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                        {
                            existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                            isDirty = true;
                        }

                        if (templateList.EnableMinorVersions)
                        {
                            if (templateList.MinorVersionLimit != existingList.MajorWithMinorVersionsLimit)
                            {
                                existingList.MajorWithMinorVersionsLimit = templateList.MinorVersionLimit;
                            }

                            if (DraftVisibilityType.Approver ==
                                (DraftVisibilityType)templateList.DraftVersionVisibility)
                            {
                                if (templateList.EnableModeration)
                                {
                                    if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                    {
                                        existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                        isDirty = true;
                                    }
                                }
                            }
                            else
                            {
                                if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                {
                                    existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                    isDirty = true;
                                }
                            }
                        }
                    }
                }
                if (isDirty)
                {
                    existingList.Update();
                    web.Context.ExecuteQueryRetry();
                }

                if (existingList.ContentTypesEnabled)
                {
                    // Check if we need to add a content type

                    var existingContentTypes = existingList.ContentTypes;
                    web.Context.Load(existingContentTypes, cts => cts.Include(ct => ct.StringId));
                    web.Context.ExecuteQueryRetry();

                    var bindingsToAdd = templateList.ContentTypeBindings.Where(ctb => existingContentTypes.All(ct => !ctb.ContentTypeId.Equals(ct.StringId, StringComparison.InvariantCultureIgnoreCase))).ToList();
                    var defaultCtBinding = templateList.ContentTypeBindings.FirstOrDefault(ctb => ctb.Default == true);
                    foreach (var ctb in bindingsToAdd)
                    {
                        existingList.AddContentTypeToListById(ctb.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                    }

                    // default ContentTypeBinding should be set last because
                    // list extension .SetDefaultContentTypeToList() re-sets
                    // the list.RootFolder UniqueContentTypeOrder property
                    // which may cause missing CTs from the "New Button"
                    if (defaultCtBinding != null)
                    {
                        existingList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                    }
                }
                if (templateList.Security != null)
                {
                    existingList.SetSecurity(parser, templateList.Security);
                }
                return Tuple.Create(existingList, parser);
            }
            else
            {
                scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_List__0____1____2___exists_but_is_of_a_different_type__Skipping_list_, templateList.Title, templateList.Url, existingList.Id);
                WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_List__0____1____2___exists_but_is_of_a_different_type__Skipping_list_, templateList.Title, templateList.Url, existingList.Id), ProvisioningMessageType.Warning);
                return null;
            }
        }
예제 #38
0
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                var serverRelativeUrl = web.ServerRelativeUrl;

                // For each list in the site
                var lists = web.Lists;

                web.Context.Load(lists,
                    lc => lc.IncludeWithDefaultProperties(
                        l => l.ContentTypes,
                        l => l.Views,
                        l => l.EnableModeration,
                        l => l.ForceCheckout,
                        l => l.BaseTemplate,
                        l => l.OnQuickLaunch,
                        l => l.RootFolder.ServerRelativeUrl,
                        l => l.UserCustomActions,
                        l => l.MajorVersionLimit,
                        l => l.MajorWithMinorVersionsLimit,
                        l => l.DraftVersionVisibility,
                        l => l.DocumentTemplateUrl,
                        l => l.Fields.IncludeWithDefaultProperties(
                            f => f.Id,
                            f => f.Title,
                            f => f.Hidden,
                            f => f.InternalName,
                            f => f.DefaultValue,
                            f => f.Required)));

                web.Context.ExecuteQueryRetry();

                var allLists = new List<List>();

                if (web.IsSubSite())
                {
                    // If current web is subweb then include the lists in the rootweb for lookup column support
                    var rootWeb = (web.Context as ClientContext).Site.RootWeb;
                    rootWeb.Context.Load(rootWeb.Lists, lsts => lsts.Include(l => l.Id, l => l.Title));
                    rootWeb.Context.ExecuteQueryRetry();
                    foreach (var rootList in rootWeb.Lists)
                    {
                        allLists.Add(rootList);
                    }
                }

                foreach (var list in lists)
                {
                    allLists.Add(list);
                }
                // Let's see if there are workflow subscriptions
                Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription[] workflowSubscriptions = null;
                try
                {
                    workflowSubscriptions = web.GetWorkflowSubscriptions();
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                // Retrieve all not hidden lists and the Workflow History Lists, just in case there are active workflow subscriptions
                foreach (var siteList in lists.AsEnumerable().Where(l => (l.Hidden == false || ((workflowSubscriptions != null && workflowSubscriptions.Length > 0) && l.BaseTemplate == 140))))
                {
                    ListInstance baseTemplateList = null;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
                        var index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
                                                                                   f.TemplateType.Equals(siteList.BaseTemplate));
                        if (index != -1)
                        {
                            baseTemplateList = creationInfo.BaseTemplate.Lists[index];
                        }
                    }

                    var contentTypeFields = new List<FieldRef>();
                    var list = new ListInstance
                    {
                        Description = siteList.Description,
                        EnableVersioning = siteList.EnableVersioning,
                        TemplateType = siteList.BaseTemplate,
                        Title = siteList.Title,
                        Hidden = siteList.Hidden,
                        EnableFolderCreation = siteList.EnableFolderCreation,
                        DocumentTemplate = Tokenize(siteList.DocumentTemplateUrl, web.Url),
                        ContentTypesEnabled = siteList.ContentTypesEnabled,
                        Url = siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/'),
                        TemplateFeatureID = siteList.TemplateFeatureId,
                        EnableAttachments = siteList.EnableAttachments,
                        OnQuickLaunch = siteList.OnQuickLaunch,
                        EnableModeration = siteList.EnableModeration,
                        MaxVersionLimit =
                            siteList.IsPropertyAvailable("MajorVersionLimit") ? siteList.MajorVersionLimit : 0,
                        EnableMinorVersions = siteList.EnableMinorVersions,
                        MinorVersionLimit =
                            siteList.IsPropertyAvailable("MajorWithMinorVersionsLimit")
                                ? siteList.MajorWithMinorVersionsLimit
                                : 0,
                        ForceCheckout = siteList.IsPropertyAvailable("ForceCheckout") ?
                            siteList.ForceCheckout : false,
                        DraftVersionVisibility = siteList.IsPropertyAvailable("DraftVersionVisibility") ? (int)siteList.DraftVersionVisibility : 0,
                    };

                    if (creationInfo.PersistMultiLanguageResources)
                    {
            #if !SP2013
                        if (UserResourceExtensions.PersistResourceValue(siteList.TitleResource, string.Format("List_{0}_Title", siteList.Title.Replace(" ", "_")), template, creationInfo))
                        {
                            list.Title = string.Format("{{res:List_{0}_Title}}", siteList.Title.Replace(" ", "_"));
                        }
                        if (UserResourceExtensions.PersistResourceValue(siteList.DescriptionResource, string.Format("List_{0}_Description", siteList.Title.Replace(" ", "_")), template, creationInfo))
                        {
                            list.Description = string.Format("{{res:List_{0}_Description}}", siteList.Title.Replace(" ", "_"));
                        }
            #endif
                    }

                    list = ExtractContentTypes(web, siteList, contentTypeFields, list);

                    list = ExtractViews(siteList, list);

                    list = ExtractFields(web, siteList, contentTypeFields, list, allLists, creationInfo, template);

                    list = ExtractUserCustomActions(web, siteList, list, creationInfo, template);

                    list.Security = siteList.GetSecurity();

                    var logCTWarning = false;
                    if (baseTemplateList != null)
                    {
                        if (!baseTemplateList.Equals(list))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                            template.Lists.Add(list);
                            if (list.ContentTypesEnabled && list.ContentTypeBindings.Any() && web.IsSubSite())
                            {
                                logCTWarning = true;
                            }
                        }
                    }
                    else
                    {
                        scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                        template.Lists.Add(list);
                        if (list.ContentTypesEnabled && list.ContentTypeBindings.Any() && web.IsSubSite())
                        {
                            logCTWarning = true;
                        }

                    }
                    if (logCTWarning)
                    {
                        scope.LogWarning("You are extracting a template from a subweb. List '{0}' refers to content types. Content types are not exported when extracting a template from a subweb", siteList.Title);
                        WriteWarning(string.Format("You are extracting a template from a subweb. List '{0}' refers to content types. Content types are not exported when extracting a template from a subweb", siteList.Title), ProvisioningMessageType.Warning);
                    }
                }

            }
            return template;
        }
예제 #39
0
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(CoreResources.Provisioning_ObjectHandlers_ListInstances))
            {
                var propertyLoadRequired = false;
                if (!web.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    web.Context.Load(web, w => w.ServerRelativeUrl);
                    propertyLoadRequired = true;
                }
                if (!web.IsPropertyAvailable("Url"))
                {
                    web.Context.Load(web, w => w.Url);
                    propertyLoadRequired = true;
                }
                if (propertyLoadRequired)
                {
                    web.Context.ExecuteQueryRetry();
                }

                var serverRelativeUrl = web.ServerRelativeUrl;

                // For each list in the site
                var lists = web.Lists;

                web.Context.Load(lists,
                    lc => lc.IncludeWithDefaultProperties(
                        l => l.ContentTypes,
                        l => l.Views,
                        l => l.OnQuickLaunch,
                        l => l.RootFolder.ServerRelativeUrl,
                        l => l.Fields.IncludeWithDefaultProperties(
                            f => f.Id,
                            f => f.Title,
                            f => f.Hidden,
                            f => f.InternalName,
                            f => f.Required)));

                web.Context.ExecuteQueryRetry();
                foreach (var item in lists.AsEnumerable().Where(l => l.Hidden == false))
                {
                    ListInstance baseTemplateList = null;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
                        var index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
                                                                                   f.TemplateType.Equals(item.BaseTemplate));
                        if (index != -1)
                        {
                            baseTemplateList = creationInfo.BaseTemplate.Lists[index];
                        }
                    }

                    var contentTypeFields = new List<FieldRef>();
                    var list = new ListInstance
                    {
                        Description = item.Description,
                        EnableVersioning = item.EnableVersioning,
                        TemplateType = item.BaseTemplate,
                        Title = item.Title,
                        Hidden = item.Hidden,
                        EnableFolderCreation = item.EnableFolderCreation,
                        DocumentTemplate = Tokenize(item.DocumentTemplateUrl, web.Url),
                        ContentTypesEnabled = item.ContentTypesEnabled,
                        Url = item.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/'),
                        TemplateFeatureID = item.TemplateFeatureId,
                        EnableAttachments = item.EnableAttachments,
                        OnQuickLaunch = item.OnQuickLaunch,
                        MaxVersionLimit =
                            item.IsObjectPropertyInstantiated("MajorVersionLimit") ? item.MajorVersionLimit : 0,
                        EnableMinorVersions = item.EnableMinorVersions,
                        MinorVersionLimit =
                            item.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit")
                                ? item.MajorWithMinorVersionsLimit
                                : 0
                    };
                    var count = 0;

                    foreach (var ct in item.ContentTypes)
                    {
                        web.Context.Load(ct, c => c.Parent);
                        web.Context.ExecuteQueryRetry();
                        if (ct.Parent != null)
                        {
                            // Add the parent to the list of content types
                            if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                            {
                                list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.Parent.StringId, Default = count == 0 });
                            }
                        }
                        else
                        {
                            list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.StringId, Default = count == 0 });
                        }

                        web.Context.Load(ct.FieldLinks);
                        web.Context.ExecuteQueryRetry();
                        foreach (var fieldLink in ct.FieldLinks)
                        {
                            if (!fieldLink.Hidden)
                            {
                                contentTypeFields.Add(new FieldRef() { Id = fieldLink.Id });
                            }
                        }
                        count++;
                    }

                    foreach (var view in item.Views.AsEnumerable().Where(view => !view.Hidden))
                    {
                        var schemaElement = XElement.Parse(view.ListViewXml);

                        // Toolbar is not supported

                        var toolbarElement = schemaElement.Descendants("Toolbar").FirstOrDefault();
                        if (toolbarElement != null)
                        {
                            toolbarElement.Remove();
                        }

                        // XslLink is not supported
                        var xslLinkElement = schemaElement.Descendants("XslLink").FirstOrDefault();
                        if (xslLinkElement != null)
                        {
                            xslLinkElement.Remove();
                        }

                        list.Views.Add(new View { SchemaXml = schemaElement.ToString() });
                    }

                    var siteColumns = web.Fields;
                    web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
                    web.Context.ExecuteQueryRetry();

                    foreach (var field in item.Fields.AsEnumerable().Where(field => !field.Hidden))
                    {
                        if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                        {
                            var addField = true;
                            if (item.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                            {
                                if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                                {
                                    addField = false;
                                }
                            }

                            var fieldElement = XElement.Parse(field.SchemaXml);
                            var sourceId = fieldElement.Attribute("SourceID") != null ? fieldElement.Attribute("SourceID").Value : null;

                            if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3")
                            {
                                if (field.InternalName == "Editor" ||
                                    field.InternalName == "Author" ||
                                    field.InternalName == "Title" ||
                                    field.InternalName == "ID" ||
                                    field.InternalName == "Created" ||
                                    field.InternalName == "Modified" ||
                                    field.InternalName == "Attachments" ||
                                    field.InternalName == "_UIVersionString" ||
                                    field.InternalName == "DocIcon" ||
                                    field.InternalName == "LinkTitleNoMenu" ||
                                    field.InternalName == "LinkTitle" ||
                                    field.InternalName == "Edit" ||
                                    field.InternalName == "AppAuthor" ||
                                    field.InternalName == "AppEditor" ||
                                    field.InternalName == "ContentType" ||
                                    field.InternalName == "ItemChildCount" ||
                                    field.InternalName == "FolderChildCount" ||
                                    field.InternalName == "LinkFilenameNoMenu" ||
                                    field.InternalName == "LinkFilename" ||
                                    field.InternalName == "_CopySource" ||
                                    field.InternalName == "ParentVersionString" ||
                                    field.InternalName == "ParentLeafName" ||
                                    field.InternalName == "_CheckinComment" ||
                                    field.InternalName == "FileLeafRef" ||
                                    field.InternalName == "FileSizeDisplay" ||
                                    field.InternalName == "Preview" ||
                                    field.InternalName == "ThumbnailOnForm")
                                {
                                    addField = false;
                                }
                            }
                            if (addField)
                            {
                                list.FieldRefs.Add(new FieldRef(field.InternalName)
                                {
                                    Id = field.Id,
                                    DisplayName = field.Title,
                                    Required = field.Required,
                                    Hidden = field.Hidden,
                                });
                            }
                        }
                        else
                        {
                            list.Fields.Add((new Model.Field { SchemaXml = field.SchemaXml }));
                        }
                    }
                    if (baseTemplateList != null)
                    {
                        if (!baseTemplateList.Equals(list))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                            template.Lists.Add(list);
                        }
                    }
                    else
                    {
                        scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                        template.Lists.Add(list);
                    }
                }

            }
            return template;
        }
예제 #40
0
        private static ListInstance ExtractUserCustomActions(Web web, List siteList, ListInstance list, ProvisioningTemplateCreationInformation creationInfo, ProvisioningTemplate template)
        {
            foreach (var userCustomAction in siteList.UserCustomActions.AsEnumerable())
            {
                web.Context.Load(userCustomAction);
                web.Context.ExecuteQueryRetry();

                var customAction = new CustomAction
                {
                    Title = userCustomAction.Title,
                    Description = userCustomAction.Description,
                    Enabled = true,
                    Name = userCustomAction.Name,
                    //RegistrationType = userCustomAction.RegistrationType,
                    //RegistrationId = userCustomAction.RegistrationId,
                    Url = userCustomAction.Url,
                    ImageUrl = userCustomAction.ImageUrl,
                    Rights = userCustomAction.Rights,
                    Sequence = userCustomAction.Sequence,
                    ScriptBlock = userCustomAction.ScriptBlock,
                    ScriptSrc = userCustomAction.ScriptSrc,
                    CommandUIExtension = !System.String.IsNullOrEmpty(userCustomAction.CommandUIExtension) ?
                        XElement.Parse(userCustomAction.CommandUIExtension) : null,
                    Group = userCustomAction.Group,
                    Location = userCustomAction.Location,
                };

            #if !ONPREMISES
                if (creationInfo.PersistMultiLanguageResources)
                {
                    siteList.EnsureProperty(l => l.Title);
                    var listKey = siteList.Title.Replace(" ", "_");
                    var resourceKey = userCustomAction.Name.Replace(" ", "_");

                    if (UserResourceExtensions.PersistResourceValue(userCustomAction.TitleResource, string.Format("List_{0}_CustomAction_{1}_Title", listKey, resourceKey), template, creationInfo))
                    {
                        var customActionTitle = string.Format("{{res:List_{0}_CustomAction_{1}_Title}}", listKey, resourceKey);
                        customAction.Title = customActionTitle;

                    }
                    if (UserResourceExtensions.PersistResourceValue(userCustomAction.DescriptionResource, string.Format("List_{0}_CustomAction_{1}_Description", listKey, resourceKey), template, creationInfo))
                    {
                        var customActionDescription = string.Format("{{res:List_{0}_CustomAction_{1}_Description}}", listKey, resourceKey);
                        customAction.Description = customActionDescription;
                    }
                }
            #endif

                list.UserCustomActions.Add(customAction);
            }

            return list;
        }
예제 #41
0
        private Tuple<List, TokenParser> CreateList(Web web, ListInstance list, TokenParser parser, PnPMonitoredScope scope, bool isNoScriptSite = false)
        {
            List createdList;
            if (list.Url.Equals("SiteAssets") && list.TemplateType == (int)ListTemplateType.DocumentLibrary)
            {
                //Ensure that the Site Assets library is created using the out of the box creation mechanism
                //Site Assets that are created using the EnsureSiteAssetsLibrary method slightly differ from
                //default Document Libraries. See issue 512 (https://github.com/OfficeDev/PnP-Sites-Core/issues/512)
                //for details about the issue fixed by this approach.
                createdList = web.Lists.EnsureSiteAssetsLibrary();
                //Check that Title and Description have the correct values
                web.Context.Load(createdList, l => l.Title,
                                              l => l.Description);
                web.Context.ExecuteQueryRetry();
                var isDirty = false;
                if (!string.Equals(createdList.Description, list.Description))
                {
                    createdList.Description = list.Description;
                    isDirty = true;
                }
                if (!string.Equals(createdList.Title, list.Title))
                {
                    createdList.Title = list.Title;
                    isDirty = true;
                }
                if (isDirty)
                {
                    createdList.Update();
                    web.Context.ExecuteQueryRetry();
                }

            }
            else
            {
                var listCreate = new ListCreationInformation();
                listCreate.Description = list.Description;
                listCreate.TemplateType = list.TemplateType;
                listCreate.Title = parser.ParseString(list.Title);

                // the line of code below doesn't add the list to QuickLaunch
                // the OnQuickLaunch property is re-set on the Created List object
                listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off;

                listCreate.Url = parser.ParseString(list.Url);
                listCreate.TemplateFeatureId = list.TemplateFeatureID;

                createdList = web.Lists.Add(listCreate);
                createdList.Update();
            }
            web.Context.Load(createdList, l => l.BaseTemplate);
            web.Context.ExecuteQueryRetry();

            #if !SP2013
            if (list.Title.ContainsResourceToken())
            {
                createdList.TitleResource.SetUserResourceValue(list.Title, parser);
            }
            if (list.Description.ContainsResourceToken())
            {
                createdList.DescriptionResource.SetUserResourceValue(list.Description, parser);
            }
            #endif
            if (!String.IsNullOrEmpty(list.DocumentTemplate))
            {
                createdList.DocumentTemplateUrl = parser.ParseString(list.DocumentTemplate);
            }

            // EnableAttachments are not supported for DocumentLibraries, Survey and PictureLibraries
            // TODO: the user should be warned
            if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary &&
                createdList.BaseTemplate != (int)ListTemplateType.Survey &&
                createdList.BaseTemplate != (int)ListTemplateType.PictureLibrary)
            {
                createdList.EnableAttachments = list.EnableAttachments;
            }

            createdList.EnableModeration = list.EnableModeration;
            createdList.ForceCheckout = list.ForceCheckout;

            // Done for all other lists than for Survey - With Surveys versioning configuration will cause an exception
            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableVersioning = list.EnableVersioning;
                if (list.EnableVersioning)
                {
            #if !SP2013
                    createdList.MajorVersionLimit = list.MaxVersionLimit;
            #endif
                    // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true
                    if (DraftVisibilityType.Approver ==
                        (DraftVisibilityType)list.DraftVersionVisibility)
                    {
                        if (list.EnableModeration)
                        {
                            createdList.DraftVersionVisibility =
                                (DraftVisibilityType)list.DraftVersionVisibility;
                        }
                        else
                        {
                            scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true);
                            WriteWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true, ProvisioningMessageType.Warning);
                        }
                    }
                    else
                    {
                        createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;
                    }

                    if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        createdList.EnableMinorVersions = list.EnableMinorVersions;
                        createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;

                        if (list.EnableMinorVersions)
                        {
                            createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero.
                        }
                    }
                }
            }

            createdList.OnQuickLaunch = list.OnQuickLaunch;
            if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard &&
                createdList.BaseTemplate != (int)ListTemplateType.Events)
            {
                createdList.EnableFolderCreation = list.EnableFolderCreation;
            }
            createdList.Hidden = list.Hidden;

            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.ContentTypesEnabled = list.ContentTypesEnabled;
            }

            createdList.Update();

            web.Context.Load(createdList.Views);
            web.Context.Load(createdList, l => l.Id);
            web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl);
            web.Context.Load(createdList.ContentTypes);
            web.Context.ExecuteQueryRetry();

            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                // Remove existing content types only if there are custom content type bindings
                var contentTypesToRemove = new List<ContentType>();
                if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0)
                {
                    contentTypesToRemove.AddRange(createdList.ContentTypes);
                }

                ContentTypeBinding defaultCtBinding = null;
                foreach (var ctBinding in list.ContentTypeBindings)
                {
                    var tempCT = web.GetContentTypeById(ctBinding.ContentTypeId, searchInSiteHierarchy: true);
                    if (tempCT != null)
                    {
                        // Get the name of the existing CT
                        var name = tempCT.EnsureProperty(ct => ct.Name);

                        // If the CT does not exist in the target list, and we don't have to remove it
                        if (!createdList.ContentTypeExistsByName(name) && !ctBinding.Remove)
                        {
                            // Then add it to the target list
                            createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                        }
                        // Else if the CT exists in the target list, and we have to remove it
                        else if (createdList.ContentTypeExistsByName(name) && ctBinding.Remove)
                        {
                            // Then remove it from the target list
                            createdList.RemoveContentTypeByName(name);
                        }

                        if (ctBinding.Default)
                        {
                            defaultCtBinding = ctBinding;
                        }
                    }
                }

                // default ContentTypeBinding should be set last because
                // list extension .SetDefaultContentTypeToList() re-sets
                // the list.RootFolder UniqueContentTypeOrder property
                // which may cause missing CTs from the "New Button"
                if (defaultCtBinding != null)
                {
                    createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                }

                // Effectively remove existing content types, if any
                foreach (var ct in contentTypesToRemove)
                {
                    var shouldDelete = true;
                    shouldDelete &= (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary || !ct.StringId.StartsWith(BuiltInContentTypeId.Folder + "00"));

                    if (shouldDelete)
                    {
                        ct.DeleteObject();
                        web.Context.ExecuteQueryRetry();
                    }
                }
            }

            // Add any custom action
            if (list.UserCustomActions.Any())
            {
                if (!isNoScriptSite)
                {
                    foreach (var userCustomAction in list.UserCustomActions)
                    {
                        CreateListCustomAction(createdList, parser, userCustomAction);
                    }

                    web.Context.ExecuteQueryRetry();
                }
                else
                {
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_SkipAddingOrUpdatingCustomActions);
                }
            }

            if (list.Security != null)
            {
                createdList.SetSecurity(parser, list.Security);
            }
            return Tuple.Create(createdList, parser);
        }
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url);

                var serverRelativeUrl = web.ServerRelativeUrl;

                // For each list in the site
                var lists = web.Lists;

                web.Context.Load(lists,
                    lc => lc.IncludeWithDefaultProperties(
                        l => l.ContentTypes,
                        l => l.Views,
                        l => l.BaseTemplate,
                        l => l.OnQuickLaunch,
                        l => l.RootFolder.ServerRelativeUrl,
                        l => l.Fields.IncludeWithDefaultProperties(
                            f => f.Id,
                            f => f.Title,
                            f => f.Hidden,
                            f => f.InternalName,
                            f => f.Required)));

                web.Context.ExecuteQueryRetry();

                // Let's see if there are workflow subscriptions
                Microsoft.SharePoint.Client.WorkflowServices.WorkflowSubscription[] workflowSubscriptions = null;
                try
                {
                    workflowSubscriptions = web.GetWorkflowSubscriptions();
                }
                catch (ServerException)
                {
                    // If there is no workflow service present in the farm this method will throw an error.
                    // Swallow the exception
                }

                // Retrieve all not hidden lists and the Workflow History Lists, just in case there are active workflow subscriptions
                var includeWorkflowSubscriptions = workflowSubscriptions != null && workflowSubscriptions.Length > 0;
               // var allowedLists = lists.Where(l => !l.Hidden || includeWorkflowSubscriptions && l.BaseTemplate == 140);

                foreach (var siteList in lists)
                {
                    ListInstance baseTemplateList = null;
                    if (creationInfo.BaseTemplate != null)
                    {
                        // Check if we need to skip this list...if so let's do it before we gather all the other information for this list...improves performance
                        var index = creationInfo.BaseTemplate.Lists.FindIndex(f => f.Url.Equals(siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length + 1)) &&
                                                                                   f.TemplateType.Equals(siteList.BaseTemplate));
                        if (index != -1)
                        {
                            baseTemplateList = creationInfo.BaseTemplate.Lists[index];
                            if (siteList.Hidden && !(includeWorkflowSubscriptions && siteList.BaseTemplate == 140))
                            {
                                continue;
                            }
                        }
                    }

                    var contentTypeFields = new List<FieldRef>();
                    var list = new ListInstance
                    {
                        Description = siteList.Description,
                        EnableVersioning = siteList.EnableVersioning,
                        TemplateType = siteList.BaseTemplate,
                        Title = siteList.Title,
                        Hidden = siteList.Hidden,
                        EnableFolderCreation = siteList.EnableFolderCreation,
                        DocumentTemplate = Tokenize(siteList.DocumentTemplateUrl, web.Url),
                        ContentTypesEnabled = siteList.ContentTypesEnabled,
                        Url = siteList.RootFolder.ServerRelativeUrl.Substring(serverRelativeUrl.Length).TrimStart('/'),
                        TemplateFeatureID = siteList.TemplateFeatureId,
                        EnableAttachments = siteList.EnableAttachments,
                        OnQuickLaunch = siteList.OnQuickLaunch,
                        MaxVersionLimit =
                            siteList.IsObjectPropertyInstantiated("MajorVersionLimit") ? siteList.MajorVersionLimit : 0,
                        EnableMinorVersions = siteList.EnableMinorVersions,
                        MinorVersionLimit =
                            siteList.IsObjectPropertyInstantiated("MajorWithMinorVersionsLimit")
                                ? siteList.MajorWithMinorVersionsLimit
                                : 0
                    };

                    list = ExtractContentTypes(web, siteList, contentTypeFields, list);

                    list = ExtractViews(siteList, list);

                    list = ExtractFields(web, siteList, contentTypeFields, list, lists);

                    list.Security = siteList.GetSecurity();

                    var logCTWarning = false;
                    if (baseTemplateList != null)
                    {
                        if (!baseTemplateList.Equals(list))
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                            template.Lists.Add(list);
                            if (list.ContentTypesEnabled && list.ContentTypeBindings.Any() && web.IsSubSite())
                            {
                                logCTWarning = true;
                            }
                        }
                    }
                    else
                    {
                        scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Adding_list___0_____1_, list.Title, list.Url);
                        template.Lists.Add(list);
                        if (list.ContentTypesEnabled && list.ContentTypeBindings.Any() && web.IsSubSite())
                        {
                            logCTWarning = true;
                        }

                    }
                    if (logCTWarning)
                    {
                        scope.LogWarning("You are extracting a template from a subweb. List '{0}' refers to content types. Content types are not exported when extracting a template from a subweb", list.Title);
                        WriteWarning(string.Format("You are extracting a template from a subweb. List '{0}' refers to content types. Content types are not exported when extracting a template from a subweb", list.Title), ProvisioningMessageType.Warning);
                    }
                }

            }
            return template;
        }
예제 #43
0
        private Tuple<List, TokenParser> CreateList(Web web, ListInstance list, TokenParser parser, PnPMonitoredScope scope)
        {
            var listCreate = new ListCreationInformation();
            listCreate.Description = list.Description;
            listCreate.TemplateType = list.TemplateType;
            listCreate.Title = parser.ParseString(list.Title);

            // the line of code below doesn't add the list to QuickLaunch
            // the OnQuickLaunch property is re-set on the Created List object
            listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off;

            listCreate.Url = parser.ParseString(list.Url);
            listCreate.TemplateFeatureId = list.TemplateFeatureID;

            var createdList = web.Lists.Add(listCreate);
            createdList.Update();
            web.Context.Load(createdList,
                l => l.BaseTemplate,
                l => l.RootFolder.ServerRelativeUrl,
                l => l.Title,
                l => l.ParentWebUrl,
                l => l.Id,
                l => l.Description,
                l => l.OnQuickLaunch,
                l => l.Hidden,
                l => l.Fields.IncludeWithDefaultProperties(
                    f => f.SchemaXml
                    ),
                l => l.ContentTypesEnabled,
                l => l.ContentTypes.IncludeWithDefaultProperties(
                    ct => ct.Id,
                    ct => ct.StringId,
                    ct => ct.Name),
                l => l.EnableAttachments,
                l => l.EnableFolderCreation,
                l => l.EnableMinorVersions,
                l => l.DraftVersionVisibility,
                l => l.Views
            #if !CLIENTSDKV15
            , l => l.MajorWithMinorVersionsLimit
            #endif
                );
            web.Context.ExecuteQueryRetry();

            #if !CLIENTSDKV15
            if (list.Title.ContainsResourceToken())
            {
                createdList.TitleResource.SetUserResourceValue(list.Title, parser);
            }
            if(list.Description.ContainsResourceToken())
            {
                createdList.DescriptionResource.SetUserResourceValue(list.Description, parser);
            }
            #endif
            if (!String.IsNullOrEmpty(list.DocumentTemplate))
            {
                var documentTemplateUrl = parser.ParseString(list.DocumentTemplate);

                var templateFolderUrl = documentTemplateUrl.Substring(0, documentTemplateUrl.LastIndexOf('/'));
                var templateForder = web.GetFolderByServerRelativeUrl(templateFolderUrl);
                var templateName = documentTemplateUrl.Substring(documentTemplateUrl.LastIndexOf('/') + 1);
                var templateStream = new MemoryStream(Encoding.UTF8.GetBytes(list.DocumentTemplateContent));
                templateForder.UploadFile(templateName, templateStream, true);

                createdList.DocumentTemplateUrl = documentTemplateUrl;
            }

            // EnableAttachments are not supported for DocumentLibraries and Surveys
            // TODO: the user should be warned
            if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableAttachments = list.EnableAttachments;
            }

            createdList.EnableModeration = list.EnableModeration;

            // Done for all other lists than for Survey - With Surveys versioning configuration will cause an exception
            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableVersioning = list.EnableVersioning;
                if (list.EnableVersioning)
                {
            #if !CLIENTSDKV15
                    createdList.MajorVersionLimit = list.MaxVersionLimit;
            #endif

                    if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        createdList.EnableMinorVersions = list.EnableMinorVersions;
                        createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;

                        if (list.EnableMinorVersions)
                        {
                            createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero.

                            // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true
                            if (DraftVisibilityType.Approver ==
                                (DraftVisibilityType)list.DraftVersionVisibility)
                            {
                                if (list.EnableModeration)
                                {
                                    createdList.DraftVersionVisibility =
                                        (DraftVisibilityType)list.DraftVersionVisibility;
                                }
                                else
                                {
                                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true);
                                    WriteWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_DraftVersionVisibility_not_applied_because_EnableModeration_is_not_set_to_true, ProvisioningMessageType.Warning);
                                }
                            }
                            else
                            {
                                createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;
                            }
                        }
                    }
                }
            }

            createdList.OnQuickLaunch = list.OnQuickLaunch;
            if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard &&
                createdList.BaseTemplate != (int)ListTemplateType.Events)
            {
                createdList.EnableFolderCreation = list.EnableFolderCreation;
            }
            createdList.Hidden = list.Hidden;

            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.ContentTypesEnabled = list.ContentTypesEnabled;
            }

            createdList.Update();

            web.Context.Load(createdList.Views);
            web.Context.Load(createdList.Forms);
            web.Context.Load(createdList, l => l.Id);
            web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl);
            web.Context.Load(createdList, l => l.ContentTypesEnabled);
            web.Context.Load(createdList.ContentTypes);
            web.Context.ExecuteQueryRetry();

            parser.AddToken(new ListIdProvisionToken(web, createdList.Id, list.ID));
            parser.AddToken(new ListNameProvisionToken(web, createdList.Id, list.ID));

            if (createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                // Remove existing content types only if there are custom content type bindings
                var contentTypesToRemove = new List<ContentType>();
                if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0)
                {
                    contentTypesToRemove.AddRange(createdList.ContentTypes);
                }

                List<ContentType> listCTypes = new List<ContentType>();
                listCTypes.AddRange(createdList.ContentTypes);

                var contentTypeAdded = false;
                ContentTypeBinding defaultCtBinding = null;
                foreach (var ctBinding in list.ContentTypeBindings)
                {
                    var contentType = web.AvailableContentTypes.AsEnumerable().FirstOrDefault(item => item.Id.StringValue.Equals(ctBinding.ContentTypeId, StringComparison.OrdinalIgnoreCase));
                    if (contentType != null)
                    {
                        // Check if CT is already available
                        var name = contentType.EnsureProperty(ct => ct.Name);
                        if (!listCTypes.Any( ct=> ct.Name == name ) )
                        {
                            if (createdList.ContentTypesEnabled == false)
                        {
                                createdList.ContentTypesEnabled = true;
                                createdList.Update();
                                createdList.Context.ExecuteQueryRetry();
                            }

                            createdList.ContentTypes.AddExistingContentType(contentType);
                            listCTypes.Add(contentType);
                            contentTypeAdded = true;
                        }
                        if (ctBinding.Default)
                        {
                            defaultCtBinding = ctBinding;
                        }
                    }
                }

                if (contentTypeAdded) {
                    web.Context.ExecuteQueryRetry();
                }

                // default ContentTypeBinding should be set last because
                // list extension .SetDefaultContentTypeToList() re-sets
                // the list.RootFolder UniqueContentTypeOrder property
                // which may cause missing CTs from the "New Button"
                if (defaultCtBinding != null)
                {
                    createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                }

                var ctDeleted = false;
                // Effectively remove existing content types, if any
                foreach (var ct in contentTypesToRemove)
                {
                    var shouldDelete = true;
                    shouldDelete &= (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary || !ct.StringId.StartsWith(BuiltInContentTypeId.Folder + "00"));

                    if (shouldDelete)
                    {
                        ct.DeleteObject();
                        ctDeleted = true;
                    }
                }
                if (ctDeleted)
                {
                        web.Context.ExecuteQueryRetry();
                    }
                }

            if (list.Security != null)
            {
                try
                {
                        createdList.SetSecurity(parser, list.Security);
                    }
                catch (Exception ex)
                {
                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Updating_list__0__failed___1_____2_, list.Title, ex.Message, ex.StackTrace);
                }
            }
            return Tuple.Create(createdList, parser);
        }
        private ListInstance ExtractFields(Web web, List siteList, List<FieldRef> contentTypeFields, ListInstance list, ListCollection lists)
        {
            var siteColumns = web.Fields;
            web.Context.Load(siteColumns, scs => scs.Include(sc => sc.Id));
            web.Context.ExecuteQueryRetry();

            var allowedFields = siteList.Fields.Where(field => !(BuiltInFieldId.Contains(field.Id) && field.Hidden));
            foreach (var field in allowedFields)
            {
                if (siteColumns.FirstOrDefault(sc => sc.Id == field.Id) != null)
                {
                    var addField = true;
                    if (siteList.ContentTypesEnabled && contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                    {
                        if (contentTypeFields.FirstOrDefault(c => c.Id == field.Id) == null)
                        {
                            addField = false;
                        }
                    }

                    var fieldElement = XElement.Parse(field.SchemaXml);
                    var sourceId = fieldElement.Attribute("SourceID") != null ? fieldElement.Attribute("SourceID").Value : null;

                    if (sourceId != null && sourceId == "http://schemas.microsoft.com/sharepoint/v3")
                    {
                        if (field.InternalName == "Editor" ||
                            field.InternalName == "Author" ||
                            field.InternalName == "Title" ||
                            field.InternalName == "ID" ||
                            field.InternalName == "Created" ||
                            field.InternalName == "Modified" ||
                            field.InternalName == "Attachments" ||
                            field.InternalName == "_UIVersionString" ||
                            field.InternalName == "DocIcon" ||
                            field.InternalName == "LinkTitleNoMenu" ||
                            field.InternalName == "LinkTitle" ||
                            field.InternalName == "Edit" ||
                            field.InternalName == "AppAuthor" ||
                            field.InternalName == "AppEditor" ||
                            field.InternalName == "ContentType" ||
                            field.InternalName == "ItemChildCount" ||
                            field.InternalName == "FolderChildCount" ||
                            field.InternalName == "LinkFilenameNoMenu" ||
                            field.InternalName == "LinkFilename" ||
                            field.InternalName == "_CopySource" ||
                            field.InternalName == "ParentVersionString" ||
                            field.InternalName == "ParentLeafName" ||
                            field.InternalName == "_CheckinComment" ||
                            field.InternalName == "FileLeafRef" ||
                            field.InternalName == "FileSizeDisplay" ||
                            field.InternalName == "Preview" ||
                            field.InternalName == "ThumbnailOnForm")
                        {
                            addField = false;
                        }
                    }
                    if (addField)
                    {

                        list.FieldRefs.Add(new FieldRef(field.InternalName)
                        {
                            Id = field.Id,
                            DisplayName = field.Title,
                            Required = field.Required,
                            Hidden = field.Hidden,
                        });
                        if (field.TypeAsString.StartsWith("TaxonomyField"))
                        {
                            // find the corresponding taxonomy field and include it anyway
                            var taxField = (TaxonomyField)field;
                            taxField.EnsureProperties(f => f.TextField, f => f.Id);

                            var noteField = siteList.Fields.GetById(taxField.TextField);
                            web.Context.Load(noteField, nf => nf.Id, nf => nf.Title, nf => nf.Required, nf => nf.Hidden, nf => nf.InternalName);
                            web.Context.ExecuteQueryRetry();

                            list.FieldRefs.Insert(0, new FieldRef(noteField.InternalName)
                            {
                                Id = noteField.Id,
                                DisplayName = noteField.Title,
                                Required = noteField.Required,
                                Hidden = noteField.Hidden
                            });
                        }
                    }
                }
                else
                {
                    var schemaXml = ParseFieldSchema(field.SchemaXml, lists);
                    var fieldElement = XElement.Parse(field.SchemaXml);
                    var listId = fieldElement.Attribute("List") != null ? fieldElement.Attribute("List").Value : null;

                    if (listId == null)
                        list.Fields.Add((new Model.Field { SchemaXml = field.SchemaXml }));
                    else
                    {
                        var listIdValue = Guid.Empty;
                        if (Guid.TryParse(listId, out listIdValue))
                        {
                            var sourceList = lists.AsEnumerable().Where(l => l.Id == listIdValue).FirstOrDefault();
                            if (sourceList != null)
                                fieldElement.Attribute("List").SetValue(String.Format("{{listid:{0}}}", sourceList.Title));
                        }

                        list.Fields.Add(new Model.Field { SchemaXml = fieldElement.ToString() });
                    }

                    if (field.TypeAsString.StartsWith("TaxonomyField"))
                    {
                        // find the corresponding taxonomy field and include it anyway
                        var taxField = (TaxonomyField)field;
                        taxField.EnsureProperties(f => f.TextField, f => f.Id);

                        var noteField = siteList.Fields.GetById(taxField.TextField);
                        web.Context.Load(noteField, nf => nf.SchemaXml);
                        web.Context.ExecuteQueryRetry();
                        var noteSchemaXml = XElement.Parse(noteField.SchemaXml);
                        noteSchemaXml.Attribute("SourceID").Remove();
                        list.Fields.Insert(0, new Model.Field { SchemaXml = ParseFieldSchema(noteSchemaXml.ToString(), lists) });
                    }

                }
            }
            return list;
        }
예제 #45
0
 internal List(int intUniqueName, Microsoft.ReportingServices.ReportProcessing.List reportItemDef, ListInstance reportItemInstance, RenderingContext renderingContext)
     : base(intUniqueName, reportItemDef, reportItemInstance, renderingContext)
 {
 }
예제 #46
0
        private Tuple<List, TokenParser> UpdateList(Web web, List existingList, ListInstance templateList, TokenParser parser, PnPMonitoredScope scope, bool isNoScriptSite = false)
        {
            web.Context.Load(existingList,
                l => l.Title,
                l => l.Description,
                l => l.OnQuickLaunch,
                l => l.Hidden,
                l => l.ContentTypesEnabled,
                l => l.EnableAttachments,
                l => l.EnableVersioning,
                l => l.EnableFolderCreation,
                l => l.EnableModeration,
                l => l.EnableMinorVersions,
                l => l.ForceCheckout,
                l => l.DraftVersionVisibility,
                l => l.Views,
                l => l.DocumentTemplateUrl,
                l => l.RootFolder,
                l => l.BaseType,
                l => l.BaseTemplate
            #if !SP2013
            , l => l.MajorWithMinorVersionsLimit
            , l => l.MajorVersionLimit
            #endif
            );
            web.Context.ExecuteQueryRetry();

            if (existingList.BaseTemplate == templateList.TemplateType)
            {
                var isDirty = false;
                if (parser.ParseString(templateList.Title) != existingList.Title)
                {
                    var oldTitle = existingList.Title;
                    existingList.Title = parser.ParseString(templateList.Title);
                    if (!oldTitle.Equals(existingList.Title, StringComparison.OrdinalIgnoreCase))
                    {
                        parser.AddToken(new ListIdToken(web, existingList.Title, existingList.Id));
                        parser.AddToken(new ListUrlToken(web, existingList.Title, existingList.RootFolder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length + 1)));
                    }
                    isDirty = true;
                }
                if (!string.IsNullOrEmpty(templateList.DocumentTemplate))
                {
                    if (existingList.DocumentTemplateUrl != parser.ParseString(templateList.DocumentTemplate))
                    {
                        existingList.DocumentTemplateUrl = parser.ParseString(templateList.DocumentTemplate);
                        isDirty = true;
                    }
                }
                if (!string.IsNullOrEmpty(templateList.Description) && templateList.Description != existingList.Description)
                {
                    existingList.Description = templateList.Description;
                    isDirty = true;
                }
                if (templateList.Hidden != existingList.Hidden)
                {
                    existingList.Hidden = templateList.Hidden;
                    isDirty = true;
                }
                if (templateList.OnQuickLaunch != existingList.OnQuickLaunch)
                {
                    existingList.OnQuickLaunch = templateList.OnQuickLaunch;
                    isDirty = true;
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.Survey &&
                    templateList.ContentTypesEnabled != existingList.ContentTypesEnabled)
                {
                    existingList.ContentTypesEnabled = templateList.ContentTypesEnabled;
                    isDirty = true;
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.Survey &&
                    existingList.BaseTemplate != (int)ListTemplateType.DocumentLibrary &&
                    existingList.BaseTemplate != (int)ListTemplateType.PictureLibrary)
                {
                    // https://msdn.microsoft.com/EN-US/library/microsoft.sharepoint.splist.enableattachments.aspx
                    // The EnableAttachments property does not apply to any list that has a base type of Survey, DocumentLibrary or PictureLibrary.
                    // If you set this property to true for either type of list, it throws an SPException.
                    if (templateList.EnableAttachments != existingList.EnableAttachments)
                    {
                        existingList.EnableAttachments = templateList.EnableAttachments;
                        isDirty = true;
                    }
                }
                if (existingList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
                {
                    if (templateList.EnableFolderCreation != existingList.EnableFolderCreation)
                    {
                        existingList.EnableFolderCreation = templateList.EnableFolderCreation;
                        isDirty = true;
                    }
                }
            #if !SP2013
                if (templateList.Title.ContainsResourceToken())
                {
                    if (existingList.TitleResource.SetUserResourceValue(templateList.Title, parser))
                    {
                        isDirty = true;
                    }
                }
            #endif
                if (existingList.EnableModeration != templateList.EnableModeration)
                {
                    existingList.EnableModeration = templateList.EnableModeration;
                    isDirty = true;
                }

                if (templateList.ForceCheckout != existingList.ForceCheckout)
                {
                    existingList.ForceCheckout = templateList.ForceCheckout;
                    isDirty = true;
                }

                if (templateList.EnableVersioning)
                {
                    if (existingList.EnableVersioning != templateList.EnableVersioning)
                    {
                        existingList.EnableVersioning = templateList.EnableVersioning;
                        isDirty = true;
                    }
            #if !SP2013
                    if (existingList.MajorVersionLimit != templateList.MaxVersionLimit)
                    {
                        existingList.MajorVersionLimit = templateList.MaxVersionLimit;
                        isDirty = true;
                    }
            #endif
                    if (existingList.BaseType == BaseType.DocumentLibrary)
                    {
                        // Only supported on Document Libraries
                        if (templateList.EnableMinorVersions != existingList.EnableMinorVersions)
                        {
                            existingList.EnableMinorVersions = templateList.EnableMinorVersions;
                            isDirty = true;
                        }

                        if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                        {
                            existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                            isDirty = true;
                        }

                        if (templateList.EnableMinorVersions)
                        {
                            if (templateList.MinorVersionLimit != existingList.MajorWithMinorVersionsLimit)
                            {
                                existingList.MajorWithMinorVersionsLimit = templateList.MinorVersionLimit;
                            }

                            if (DraftVisibilityType.Approver ==
                                (DraftVisibilityType)templateList.DraftVersionVisibility)
                            {
                                if (templateList.EnableModeration)
                                {
                                    if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                    {
                                        existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                        isDirty = true;
                                    }
                                }
                            }
                            else
                            {
                                if ((DraftVisibilityType)templateList.DraftVersionVisibility != existingList.DraftVersionVisibility)
                                {
                                    existingList.DraftVersionVisibility = (DraftVisibilityType)templateList.DraftVersionVisibility;
                                    isDirty = true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (existingList.EnableVersioning != templateList.EnableVersioning)
                    {
                        existingList.EnableVersioning = templateList.EnableVersioning;
                        isDirty = true;
                    }
                }

                if (isDirty)
                {
                    existingList.Update();
                    web.Context.ExecuteQueryRetry();
                    isDirty = false;
                }

                #region UserCustomActions
                if (!isNoScriptSite)
                {
                    // Add any UserCustomActions
                    var existingUserCustomActions = existingList.UserCustomActions;
                    web.Context.Load(existingUserCustomActions);
                    web.Context.ExecuteQueryRetry();

                    foreach (CustomAction userCustomAction in templateList.UserCustomActions)
                    {
                        // Check for existing custom actions before adding (compare by custom action name)
                        if (!existingUserCustomActions.AsEnumerable().Any(uca => uca.Name == userCustomAction.Name))
                        {
                            CreateListCustomAction(existingList, parser, userCustomAction);
                            isDirty = true;
                        }
                        else
                        {
                            var existingCustomAction = existingUserCustomActions.AsEnumerable().FirstOrDefault(uca => uca.Name == userCustomAction.Name);
                            if (existingCustomAction != null)
                            {
                                isDirty = true;

                                // If the custom action already exists
                                if (userCustomAction.Remove)
                                {
                                    // And if we need to remove it, we simply delete it
                                    existingCustomAction.DeleteObject();
                                }
                                else
                                {
                                    // Otherwise we update it, and before we force the target
                                    // registration type and ID to avoid issues
                                    userCustomAction.RegistrationType = UserCustomActionRegistrationType.List;
                                    userCustomAction.RegistrationId = existingList.Id.ToString("B").ToUpper();
                                    ObjectCustomActions.UpdateCustomAction(parser, scope, userCustomAction, existingCustomAction);
                                    // Blank out these values again to avoid inconsistent domain model data
                                    userCustomAction.RegistrationType = UserCustomActionRegistrationType.None;
                                    userCustomAction.RegistrationId = null;
                                }
                            }
                        }
                    }

                    if (isDirty)
                    {
                        existingList.Update();
                        web.Context.ExecuteQueryRetry();
                        isDirty = false;
                    }
                }
                else
                {
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_SkipAddingOrUpdatingCustomActions);
                }
                #endregion

                if (existingList.ContentTypesEnabled)
                {
                    // Check if we need to add a content type

                    var existingContentTypes = existingList.ContentTypes;
                    web.Context.Load(existingContentTypes, cts => cts.Include(ct => ct.StringId));
                    web.Context.ExecuteQueryRetry();

                    var bindingsToAdd = templateList.ContentTypeBindings.Where(ctb => existingContentTypes.All(ct => !ctb.ContentTypeId.Equals(ct.StringId, StringComparison.InvariantCultureIgnoreCase))).ToList();
                    var defaultCtBinding = templateList.ContentTypeBindings.FirstOrDefault(ctb => ctb.Default == true);
                    var currentDefaultContentTypeId = existingContentTypes.First().StringId;

                    foreach (var ctb in bindingsToAdd)
                    {
                        var tempCT = web.GetContentTypeById(ctb.ContentTypeId, searchInSiteHierarchy: true);
                        if (tempCT != null)
                        {
                            // Get the name of the existing CT
                            var name = tempCT.EnsureProperty(ct => ct.Name);

                            // If the CT does not exist in the target list, and we don't have to remove it
                            if (!existingList.ContentTypeExistsByName(name) && !ctb.Remove)
                            {
                                existingList.AddContentTypeToListById(ctb.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                            }
                            // Else if the CT exists in the target list, and we have to remove it
                            else if (existingList.ContentTypeExistsByName(name) && ctb.Remove)
                            {
                                // Then remove it from the target list
                                existingList.RemoveContentTypeByName(name);
                            }
                        }
                    }

                    // default ContentTypeBinding should be set last because
                    // list extension .SetDefaultContentTypeToList() re-sets
                    // the list.RootFolder UniqueContentTypeOrder property
                    // which may cause missing CTs from the "New Button"
                    if (defaultCtBinding != null)
                    {
                        // Only update the defualt contenttype when we detect a change in default value
                        if (!currentDefaultContentTypeId.Equals(defaultCtBinding.ContentTypeId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            existingList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
                        }
                    }
                }
                if (templateList.Security != null)
                {
                    existingList.SetSecurity(parser, templateList.Security);
                }
                return Tuple.Create(existingList, parser);
            }
            else
            {
                scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_List__0____1____2___exists_but_is_of_a_different_type__Skipping_list_, templateList.Title, templateList.Url, existingList.Id);
                WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_List__0____1____2___exists_but_is_of_a_different_type__Skipping_list_, templateList.Title, templateList.Url, existingList.Id), ProvisioningMessageType.Warning);
                return null;
            }
        }
예제 #47
0
 public List(int intUniqueName, AspNetCore.ReportingServices.ReportProcessing.List reportItemDef, ListInstance reportItemInstance, RenderingContext renderingContext)
     : base(intUniqueName, reportItemDef, reportItemInstance, renderingContext)
 {
 }
예제 #48
0
        private static ListInstance ExtractContentTypes(Web web, List siteList, List<FieldRef> contentTypeFields, ListInstance list)
        {
            var count = 0;

            foreach (var ct in siteList.ContentTypes)
            {
                web.Context.Load(ct, c => c.Parent);
                web.Context.ExecuteQueryRetry();

                if (ct.Parent != null)
                {
                    // Removed this - so that we are getting full list of content types and if it's oob content type,
                    // We are taking parent - VesaJ.
                    //if (!BuiltInContentTypeId.Contains(ct.Parent.StringId))
                    //{

                    // Exclude System Content Type to prevent getting exception during import
                    if (!ct.Parent.StringId.Equals(BuiltInContentTypeId.System))
                    {
                        list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.Parent.StringId, Default = count == 0 });
                    }

                    //}
                }
                else
                {
                    list.ContentTypeBindings.Add(new ContentTypeBinding { ContentTypeId = ct.StringId, Default = count == 0 });
                }

                web.Context.Load(ct.FieldLinks);
                web.Context.ExecuteQueryRetry();
                foreach (var fieldLink in ct.FieldLinks)
                {
                    if (!fieldLink.Hidden)
                    {
                        contentTypeFields.Add(new FieldRef() { Id = fieldLink.Id });
                    }
                }
                count++;
            }

            return list;
        }
        private ListItemCollectionPosition RetrieveItems(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, List siteList, Model.Configuration.Lists.Lists.ExtractConfiguration extractionConfiguration, CamlQuery camlQuery, Model.Configuration.Lists.Lists.ExtractQueryConfiguration queryConfig, ListInstance listInstance)
        {
            var items = siteList.GetItems(camlQuery);

            siteList.Context.Load(items, i => i.IncludeWithDefaultProperties(li => li.FieldValuesAsText), i => i.ListItemCollectionPosition);
            if (queryConfig != null && queryConfig.ViewFields != null && queryConfig.ViewFields.Count > 0)
            {
                foreach (var viewField in queryConfig.ViewFields)
                {
                    siteList.Context.Load(items, i => i.Include(li => li[viewField]));
                }
            }
            siteList.Context.ExecuteQueryRetry();
            var baseUri = new Uri(web.Url);

            if (siteList.BaseType == BaseType.DocumentLibrary)
            {
                ProcessLibraryItems(web, siteList, template, listInstance, extractionConfiguration, queryConfig, creationInfo, scope, items, baseUri);
            }
            else
            {
                ProcessListItems(web, siteList, listInstance, creationInfo, extractionConfiguration, queryConfig, baseUri, items, scope);
            }
            return(items.ListItemCollectionPosition);
        }
예제 #50
0
        private static ListInstance ExtractViews(List siteList, ListInstance list)
        {
            foreach (var view in siteList.Views.AsEnumerable().Where(view => !view.Hidden))
            {
                var schemaElement = XElement.Parse(view.ListViewXml);

                // Toolbar is not supported

                var toolbarElement = schemaElement.Descendants("Toolbar").FirstOrDefault();
                if (toolbarElement != null)
                {
                    toolbarElement.Remove();
                }

                // XslLink is not supported
                var xslLinkElement = schemaElement.Descendants("XslLink").FirstOrDefault();
                if (xslLinkElement != null)
                {
                    xslLinkElement.Remove();
                }

                list.Views.Add(new View { SchemaXml = schemaElement.ToString() });
            }

            return list;
        }
        private void ProcessDocumentRow(Web web, List siteList, Uri baseUri, ListItem listItem, ListInstance listInstance, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope, int itemCount, int itemsCount)
        {
            var myFile = listItem.File;;

            web.Context.Load(myFile,
                             f => f.Name,
#if !SP2013 && !SP2016
                             f => f.ServerRelativePath,
                             f => f.UniqueId,
#else
                             f => f.ServerRelativeUrl,
#endif
                             f => f.Level);
            web.Context.ExecuteQueryRetry();

            // If we got here it's a file, let's grab the file's path and name
#if !SP2013 && !SP2016
            var fullUri = new Uri(baseUri, myFile.ServerRelativePath.DecodedUrl);
#else
            var fullUri = new Uri(baseUri, myFile.ServerRelativeUrl);
#endif
            var folderPath = System.Web.HttpUtility.UrlDecode(fullUri.Segments.Take(fullUri.Segments.Count() - 1).ToArray().Aggregate((i, x) => i + x).TrimEnd('/'));
            var fileName   = System.Web.HttpUtility.UrlDecode(fullUri.Segments[fullUri.Segments.Count() - 1]);

            var templateFolderPath = folderPath.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray());

            WriteMessage($"Library|{listInstance.Title} : {myFile.Name}|{itemCount}|{itemsCount}", ProvisioningMessageType.Progress);

            // Avoid duplicate file entries
            Model.File newFile = null;
            bool       addFile = false;

            newFile = template.Files.FirstOrDefault(f => f.Src.Equals($"{templateFolderPath}/{fileName}", StringComparison.CurrentCultureIgnoreCase));
            if (newFile == null)
            {
                newFile = new Model.File()
                {
                    Folder         = templateFolderPath,
                    Src            = $"{templateFolderPath}/{fileName}",
                    TargetFileName = myFile.Name,
                    Overwrite      = true,
                    Level          = (Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), myFile.Level.ToString())
                };
                addFile = true;
            }

#if !SP2013 && !SP2016
            ExtractFileSettings(web, siteList, myFile.UniqueId, ref newFile, scope);
#else
            ExtractFileSettings(web, siteList, myFile.ServerRelativeUrl, ref newFile, scope);
#endif

            if (addFile && creationInfo.PersistBrandingFiles)
            {
                var file = listItem.File;
                web.Context.Load(file);
                web.Context.ExecuteQueryRetry();
                var spFileStream = file.OpenBinaryStream();
                web.Context.ExecuteQueryRetry();
                using (var streamValue = spFileStream.Value)
                {
                    template.Connector.SaveFileStream(file.Name, templateFolderPath, spFileStream.Value);
                }
                template.Files.Add(newFile);
            }
        }
예제 #52
0
        protected override void ExecuteCmdlet()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }

            var template = ReadSiteTemplate
                           .LoadSiteTemplateFromFile(Path,
                                                     TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }
            //We will remove a list if it's found so we can get the list

            ListInstance listInstance = template.Lists.Find(l => l.Title == List.Title);

            if (listInstance == null)
            {
                throw new ApplicationException("List does not exist in the template file!");
            }

            List spList = List.GetList(SelectedWeb);

            ClientContext.Load(spList, l => l.RootFolder, l => l.HasUniqueRoleAssignments);
            ClientContext.ExecuteQueryRetry();

            if (TokenizeUrls.IsPresent)
            {
                ClientContext.Load(ClientContext.Web, w => w.Url, w => w.ServerRelativeUrl, w => w.Id);
                ClientContext.Load(ClientContext.Site, s => s.Url, s => s.ServerRelativeUrl, s => s.Id);
                ClientContext.Load(ClientContext.Web.Lists, lists => lists.Include(l => l.Title, l => l.RootFolder.ServerRelativeUrl));
            }

            CamlQuery query = new CamlQuery();

            var viewFieldsStringBuilder = new StringBuilder();

            if (Fields != null)
            {
                viewFieldsStringBuilder.Append("<ViewFields>");
                foreach (var field in Fields)
                {
                    viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field);
                }
                viewFieldsStringBuilder.Append("</ViewFields>");
            }

            query.ViewXml = string.Format("<View>{0}{1}</View>", Query, viewFieldsStringBuilder);
            var listItems = spList.GetItems(query);

            ClientContext.Load(listItems, lI => lI.Include(l => l.HasUniqueRoleAssignments, l => l.ContentType.StringId));
            ClientContext.ExecuteQueryRetry();

            Microsoft.SharePoint.Client.FieldCollection fieldCollection = spList.Fields;
            ClientContext.Load(fieldCollection, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.ReadOnlyField));
            ClientContext.ExecuteQueryRetry();

            var rows = new DataRowCollection(template);

            foreach (var listItem in listItems)
            {
                //Make sure we don't pull Folders.. Of course this won't work
                if (listItem.ServerObjectIsNull == false)
                {
                    ClientContext.Load(listItem);
                    ClientContext.ExecuteQueryRetry();
                    if (!(listItem.FileSystemObjectType == FileSystemObjectType.Folder))
                    {
                        DataRow row = new DataRow();
                        if (IncludeSecurity && listItem.HasUniqueRoleAssignments)
                        {
                            row.Security.ClearSubscopes      = true;
                            row.Security.CopyRoleAssignments = false;

                            var roleAssignments = listItem.RoleAssignments;
                            ClientContext.Load(roleAssignments);
                            ClientContext.ExecuteQueryRetry();

                            ClientContext.Load(roleAssignments, r => r.Include(a => a.Member.LoginName, a => a.Member, a => a.RoleDefinitionBindings));
                            ClientContext.ExecuteQueryRetry();

                            foreach (var roleAssignment in roleAssignments)
                            {
                                var principalName = roleAssignment.Member.LoginName;
                                var roleBindings  = roleAssignment.RoleDefinitionBindings;
                                foreach (var roleBinding in roleBindings)
                                {
                                    row.Security.RoleAssignments.Add(new PnP.Framework.Provisioning.Model.RoleAssignment()
                                    {
                                        Principal = principalName, RoleDefinition = roleBinding.Name
                                    });
                                }
                            }
                        }
                        if (Fields != null)
                        {
                            foreach (var fieldName in Fields)
                            {
                                Microsoft.SharePoint.Client.Field dataField = fieldCollection.FirstOrDefault(f => f.InternalName == fieldName);

                                if (dataField != null)
                                {
                                    var defaultFieldValue = GetFieldValueAsText(ClientContext.Web, listItem, dataField);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        defaultFieldValue = Tokenize(defaultFieldValue, ClientContext.Web, ClientContext.Site);
                                    }

                                    row.Values.Add(fieldName, defaultFieldValue);
                                }
                            }
                        }
                        else
                        {
                            //All fields are added except readonly fields and unsupported field type
                            var fieldsToExport = fieldCollection.AsEnumerable()
                                                 .Where(f => !f.ReadOnlyField && !_unsupportedFieldTypes.Contains(f.FieldTypeKind));
                            foreach (var field in fieldsToExport)
                            {
                                var fldKey = (from f in listItem.FieldValues.Keys where f == field.InternalName select f).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fldKey))
                                {
                                    var fieldValue = GetFieldValueAsText(ClientContext.Web, listItem, field);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        fieldValue = Tokenize(fieldValue, ClientContext.Web, ClientContext.Site);
                                    }
                                    row.Values.Add(field.InternalName, fieldValue);
                                }
                            }
                        }

                        rows.Add(row);
                    }
                }
            }
            template.Lists.Remove(listInstance);
            listInstance.DataRows.AddRange(rows);
            template.Lists.Add(listInstance);

            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(Path, fileSystemConnector));
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }
예제 #53
0
        private List CreateList(Web web, ListInstance list)
        {
            var listCreate = new ListCreationInformation();
            listCreate.Description = list.Description;
            listCreate.TemplateType = list.TemplateType;
            listCreate.Title = list.Title;

            // the line of code below doesn't add the list to QuickLaunch
            // the OnQuickLaunch property is re-set on the Created List object
            listCreate.QuickLaunchOption = list.OnQuickLaunch ? QuickLaunchOptions.On : QuickLaunchOptions.Off;

            listCreate.Url = list.Url.ToParsedString();
            listCreate.TemplateFeatureId = list.TemplateFeatureID;

            var createdList = web.Lists.Add(listCreate);
            createdList.Update();
            web.Context.Load(createdList, l => l.BaseTemplate);
            web.Context.ExecuteQueryRetry();

            if (!String.IsNullOrEmpty(list.DocumentTemplate))
            {
                createdList.DocumentTemplateUrl = list.DocumentTemplate.ToParsedString();
            }

            // EnableAttachments are not supported for DocumentLibraries and Surveys
            // TODO: the user should be warned
            if (createdList.BaseTemplate != (int)ListTemplateType.DocumentLibrary && createdList.BaseTemplate != (int)ListTemplateType.Survey)
            {
                createdList.EnableAttachments = list.EnableAttachments;
            }

            createdList.EnableModeration = list.EnableModeration;

            createdList.EnableVersioning = list.EnableVersioning;
            if (list.EnableVersioning)
            {
                createdList.MajorVersionLimit = list.MaxVersionLimit;

                if (createdList.BaseTemplate == (int)ListTemplateType.DocumentLibrary)
                {
                    // Only supported on Document Libraries
                    createdList.EnableMinorVersions = list.EnableMinorVersions;
                    createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;

                    if (list.EnableMinorVersions)
                    {
                        createdList.MajorWithMinorVersionsLimit = list.MinorVersionLimit; // Set only if enabled, otherwise you'll get exception due setting value to zero.

                        // DraftVisibilityType.Approver is available only when the EnableModeration option of the list is true
                        if (DraftVisibilityType.Approver ==
                            (DraftVisibilityType)list.DraftVersionVisibility)
                        {
                            if (list.EnableModeration)
                            {
                                createdList.DraftVersionVisibility =
                                    (DraftVisibilityType)list.DraftVersionVisibility;
                            }
                            else
                            {
                                WriteWarning("DraftVersionVisibility not applied because EnableModeration is not set to true", ProvisioningMessageType.Warning);
                            }
                        }
                        else
                        {
                            createdList.DraftVersionVisibility = (DraftVisibilityType)list.DraftVersionVisibility;
                        }
                    }
                }
            }

            createdList.OnQuickLaunch = list.OnQuickLaunch;
            if (createdList.BaseTemplate != (int)ListTemplateType.DiscussionBoard)
            {
                createdList.EnableFolderCreation = list.EnableFolderCreation;
            }
            createdList.Hidden = list.Hidden;
            createdList.ContentTypesEnabled = list.ContentTypesEnabled;

            createdList.Update();

            web.Context.Load(createdList.Views);
            web.Context.Load(createdList, l => l.Id);
            web.Context.Load(createdList, l => l.RootFolder.ServerRelativeUrl);
            web.Context.Load(createdList.ContentTypes);
            web.Context.ExecuteQueryRetry();

            // Remove existing content types only if there are custom content type bindings
            var contentTypesToRemove = new List<ContentType>();
            if (list.RemoveExistingContentTypes && list.ContentTypeBindings.Count > 0)
            {
                contentTypesToRemove.AddRange(createdList.ContentTypes);
            }

            ContentTypeBinding defaultCtBinding = null;
            foreach (var ctBinding in list.ContentTypeBindings)
            {
                createdList.AddContentTypeToListById(ctBinding.ContentTypeId, searchContentTypeInSiteHierarchy: true);
                if (ctBinding.Default)
                {
                    defaultCtBinding = ctBinding;
                }
            }

            // default ContentTypeBinding should be set last because 
            // list extension .SetDefaultContentTypeToList() re-sets 
            // the list.RootFolder UniqueContentTypeOrder property
            // which may cause missing CTs from the "New Button"
            if (defaultCtBinding != null)
            {
                createdList.SetDefaultContentTypeToList(defaultCtBinding.ContentTypeId);
            }

            // Effectively remove existing content types, if any
            foreach (var ct in contentTypesToRemove)
            {
                ct.DeleteObject();
                web.Context.ExecuteQueryRetry();
            }

            return createdList;
        }