Пример #1
0
        private IEnumerable <ContentType> GetEntities(Web web)
        {
            var cts = web.ContentTypes;

            web.Context.Load(cts, ctCollection => ctCollection.IncludeWithDefaultProperties(ct => ct.FieldLinks));
            web.Context.ExecuteQueryRetry();

            List <ContentType> ctsToReturn = new List <ContentType>();

            foreach (var ct in cts)
            {
                if (!BuiltInContentTypeId.Contains(ct.StringId))
                {
                    ctsToReturn.Add(new ContentType
                                        (ct.StringId,
                                        ct.Name,
                                        ct.Description,
                                        ct.Group,
                                        ct.Sealed,
                                        ct.Hidden,
                                        ct.ReadOnly,
                                        ct.DocumentTemplate,
                                        false,
                                        (from fieldLink in ct.FieldLinks.AsEnumerable <FieldLink>()
                                         select new FieldRef(fieldLink.Name)
                    {
                        Id = fieldLink.Id,
                        Hidden = fieldLink.Hidden,
                        Required = fieldLink.Required,
                    })
                                        ));
                }
            }
            return(ctsToReturn);
        }
Пример #2
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            // if this is a sub site then we're not creating content type entities.
            if (web.IsSubSite())
            {
                return(template);
            }

            var cts = web.ContentTypes;

            web.Context.Load(cts);
            web.Context.ExecuteQueryRetry();

            foreach (var ct in cts)
            {
                if (!BuiltInContentTypeId.Contains(ct.StringId))
                {
                    template.ContentTypes.Add(new ContentType()
                    {
                        SchemaXml = ct.SchemaXml
                    });
                }
            }

            // If a base template is specified then use that one to "cleanup" the generated template model
            if (creationInfo.BaseTemplate != null)
            {
                template = CleanupEntities(template, creationInfo.BaseTemplate);
            }

            return(template);
        }
Пример #3
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            // if this is a sub site then we're not creating content type entities.
            if (web.IsSubSite())
            {
                return(template);
            }

            var cts = web.ContentTypes;

            web.Context.Load(cts, ctCollection => ctCollection.IncludeWithDefaultProperties(ct => ct.FieldLinks));
            web.Context.ExecuteQueryRetry();

            foreach (var ct in cts)
            {
                if (!BuiltInContentTypeId.Contains(ct.StringId))
                {
                    //   template.ContentTypes.Add(new ContentType() { SchemaXml = ct.SchemaXml });
                    template.ContentTypes.Add(new ContentType
                                                  (ct.StringId,
                                                  ct.Name,
                                                  ct.Description,
                                                  ct.Group,
                                                  ct.Sealed,
                                                  ct.Hidden,
                                                  ct.ReadOnly,
                                                  ct.DocumentTemplate,
                                                  false,
                                                  (from fieldLink in ct.FieldLinks.AsEnumerable <FieldLink>()
                                                   select new FieldRef(fieldLink.Name)
                    {
                        Id = fieldLink.Id,
                        Hidden = fieldLink.Hidden,
                        Required = fieldLink.Required,
                    })
                                                  ));
                }
            }

            // If a base template is specified then use that one to "cleanup" the generated template model
            if (creationInfo.BaseTemplate != null)
            {
                template = CleanupEntities(template, creationInfo.BaseTemplate);
            }

            return(template);
        }
        private IEnumerable <ContentType> GetEntities(Web web, PnPMonitoredScope scope)
        {
            var cts = web.ContentTypes;

            web.Context.Load(cts, ctCollection => ctCollection.IncludeWithDefaultProperties(ct => ct.FieldLinks));
            web.Context.ExecuteQueryRetry();

            List <ContentType> ctsToReturn = new List <ContentType>();

            foreach (var ct in cts)
            {
                if (!BuiltInContentTypeId.Contains(ct.StringId))
                {
                    ContentType newCT = new ContentType
                                            (ct.StringId,
                                            ct.Name,
                                            ct.Description,
                                            ct.Group,
                                            ct.Sealed,
                                            ct.Hidden,
                                            ct.ReadOnly,
                                            ct.DocumentTemplate,
                                            false,
                                            (from fieldLink in ct.FieldLinks.AsEnumerable <FieldLink>()
                                             select new FieldRef(fieldLink.Name)
                    {
                        Id = fieldLink.Id,
                        Hidden = fieldLink.Hidden,
                        Required = fieldLink.Required,
                    })
                                            )
                    {
                        DisplayFormUrl = ct.DisplayFormUrl,
                        EditFormUrl    = ct.EditFormUrl,
                        NewFormUrl     = ct.NewFormUrl,
                    };

                    // If the Content Type is a DocumentSet
                    if (Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, ct).Value ||
                        ct.StringId.StartsWith(BuiltInContentTypeId.DocumentSet)) // TODO: This is kind of an hack... we should find a better solution ...
                    {
                        Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
                            Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, ct);

                        // Retrieve the Document Set
                        web.Context.Load(documentSetTemplate,
                                         t => t.AllowedContentTypes,
                                         t => t.DefaultDocuments,
                                         t => t.SharedFields,
                                         t => t.WelcomePageFields);
                        web.Context.ExecuteQueryRetry();

                        newCT.DocumentSetTemplate = new DocumentSetTemplate(
                            null, // TODO: WelcomePage not yet supported
                            (from allowedCT in documentSetTemplate.AllowedContentTypes.AsEnumerable()
                             select allowedCT.StringValue).ToArray(),
                            (from defaultDocument in documentSetTemplate.DefaultDocuments.AsEnumerable()
                             select new DefaultDocument
                        {
                            ContentTypeId = defaultDocument.ContentTypeId.StringValue,
                            Name = defaultDocument.Name,
                            FileSourcePath = String.Empty,      // TODO: How can we extract the proper file?!
                        }).ToArray(),
                            (from sharedField in documentSetTemplate.SharedFields.AsEnumerable()
                             select sharedField.Id).ToArray(),
                            (from welcomePageField in documentSetTemplate.WelcomePageFields.AsEnumerable()
                             select welcomePageField.Id).ToArray()
                            );
                    }

                    ctsToReturn.Add(newCT);
                }
            }
            return(ctsToReturn);
        }
Пример #5
0
        private IEnumerable <ContentType> GetEntities(Web web, PnPMonitoredScope scope, ProvisioningTemplateCreationInformation creationInfo, ProvisioningTemplate template)
        {
            var cts = web.ContentTypes;

            web.Context.Load(cts, ctCollection => ctCollection.IncludeWithDefaultProperties(ct => ct.FieldLinks));
            web.Context.ExecuteQueryRetry();

            if (cts.Count > 0 && web.IsSubSite())
            {
                WriteMessage("We discovered content types in this subweb. While technically possible, we recommend moving these content types to the root site collection. Consider excluding them from this template.", ProvisioningMessageType.Warning);
            }
            List <ContentType> ctsToReturn = new List <ContentType>();
            var currentCtIndex             = 0;

            foreach (var ct in cts)
            {
                currentCtIndex++;
                WriteMessage($"Content Type|{ct.Name}|{currentCtIndex}|{cts.Count()}", ProvisioningMessageType.Progress);

                if (!BuiltInContentTypeId.Contains(ct.StringId) &&
                    (creationInfo.ContentTypeGroupsToInclude.Count == 0 || creationInfo.ContentTypeGroupsToInclude.Contains(ct.Group)))
                {
                    string ctDocumentTemplate = null;
                    if (!string.IsNullOrEmpty(ct.DocumentTemplate))
                    {
                        if (!ct.DocumentTemplate.StartsWith("_cts/"))
                        {
                            ctDocumentTemplate = ct.DocumentTemplate;
                        }
                    }

                    var newCT = new ContentType(
                        ct.StringId,
                        ct.Name,
                        ct.Description,
                        ct.Group,
                        ct.Sealed,
                        ct.Hidden,
                        ct.ReadOnly,
                        ctDocumentTemplate,
                        false,
                        (from fieldLink in ct.FieldLinks.AsEnumerable <FieldLink>()
                         select new FieldRef(fieldLink.Name)
                    {
                        Id = fieldLink.Id,
                        Hidden = fieldLink.Hidden,
                        Required = fieldLink.Required,
                    })
                        )
                    {
                        DisplayFormUrl = ct.DisplayFormUrl,
                        EditFormUrl    = ct.EditFormUrl,
                        NewFormUrl     = ct.NewFormUrl,
                    };

                    if (creationInfo.PersistMultiLanguageResources)
                    {
#if !SP2013
                        // only persist language values for content types we actually will keep...no point in spending time on this is we clean the field afterwards
                        var persistLanguages = true;
                        if (creationInfo.BaseTemplate != null)
                        {
                            int index = creationInfo.BaseTemplate.ContentTypes.FindIndex(c => c.Id.Equals(ct.StringId));

                            if (index > -1)
                            {
                                persistLanguages = false;
                            }
                        }

                        if (persistLanguages)
                        {
                            var escapedCTName = ct.Name.Replace(" ", "_");
                            if (UserResourceExtensions.PersistResourceValue(ct.NameResource, $"ContentType_{escapedCTName}_Title", template, creationInfo))
                            {
                                newCT.Name = $"{{res:ContentType_{escapedCTName}_Title}}";
                            }
                            if (UserResourceExtensions.PersistResourceValue(ct.DescriptionResource, $"ContentType_{escapedCTName}_Description", template, creationInfo))
                            {
                                newCT.Description = $"{{res:ContentType_{escapedCTName}_Description}}";
                            }
                        }
#endif
                    }

                    // If the Content Type is a DocumentSet
                    if (Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, ct).Value ||
                        ct.StringId.StartsWith(BuiltInContentTypeId.DocumentSet)) // TODO: This is kind of an hack... we should find a better solution ...
                    {
                        Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
                            Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, ct);

                        // Retrieve the Document Set
                        web.Context.Load(documentSetTemplate,
                                         t => t.AllowedContentTypes,
                                         t => t.DefaultDocuments,
                                         t => t.SharedFields,
                                         t => t.WelcomePageFields);
                        web.Context.ExecuteQueryRetry();

                        newCT.DocumentSetTemplate = new DocumentSetTemplate(
                            null, // TODO: WelcomePage not yet supported
                            (from allowedCT in documentSetTemplate.AllowedContentTypes.AsEnumerable()
                             select allowedCT.StringValue).ToArray(),
                            (from defaultDocument in documentSetTemplate.DefaultDocuments.AsEnumerable()
                             select new DefaultDocument
                        {
                            ContentTypeId = defaultDocument.ContentTypeId.StringValue,
                            Name = defaultDocument.Name,
                            FileSourcePath = String.Empty,      // TODO: How can we extract the proper file?!
                        }).ToArray(),
                            (from sharedField in documentSetTemplate.SharedFields.AsEnumerable()
                             select sharedField.Id).ToArray(),
                            (from welcomePageField in documentSetTemplate.WelcomePageFields.AsEnumerable()
                             select welcomePageField.Id).ToArray()
                            );
                    }

                    ctsToReturn.Add(newCT);
                }
            }
            WriteMessage("Done processing Content Types", ProvisioningMessageType.Completed);
            return(ctsToReturn);
        }
Пример #6
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);
        }
        private IEnumerable <PnPContentType> GetEntities(Web web, ProvisioningTemplateCreationInformation creationInfo, ProvisioningTemplate template)
        {
            var cts = web.ContentTypes;

            web.Context.Load(cts, ctCollection => ctCollection.IncludeWithDefaultProperties(ct => ct.FieldLinks));
            web.Context.ExecuteQueryRetry();

            List <PnPContentType> ctsToReturn = new List <PnPContentType>();

            foreach (var ct in cts)
            {
                if (!BuiltInContentTypeId.Contains(ct.StringId))
                {
                    string ctDocumentTemplate = null;
                    if (!String.IsNullOrEmpty(ct.DocumentTemplate))
                    {
                        if (!ct.DocumentTemplate.StartsWith("_cts/"))
                        {
                            ctDocumentTemplate = ct.DocumentTemplate;
                        }
                    }

                    PnPContentType newCT = new PnPContentType
                                               (ct.StringId,
                                               ct.Name,
                                               ct.Description,
                                               ct.Group,
                                               ct.Sealed,
                                               ct.Hidden,
                                               ct.ReadOnly,
                                               ctDocumentTemplate,
                                               false,
                                               (from fieldLink in ct.FieldLinks.AsEnumerable <FieldLink>()
                                                select new FieldRef(fieldLink.Name)
                    {
                        Id = fieldLink.Id,
                        Hidden = fieldLink.Hidden,
                        Required = fieldLink.Required,
                    })
                                               )
                    {
                        DisplayFormUrl = ct.DisplayFormUrl,
                        EditFormUrl    = ct.EditFormUrl,
                        NewFormUrl     = ct.NewFormUrl,
                    };

                    if (creationInfo.PersistMultiLanguageResources)
                    {
#if !SP2013
                        // only persist language values for content types we actually will keep...no point in spending time on this is we clean the field afterwards
                        bool persistLanguages = true;
                        if (creationInfo.BaseTemplate != null)
                        {
                            int index = creationInfo.BaseTemplate.ContentTypes.FindIndex(c => c.Id.Equals(ct.StringId));

                            if (index > -1)
                            {
                                persistLanguages = false;
                            }
                        }

                        if (persistLanguages)
                        {
                            if (PersistResourceValue(ct.NameResource, string.Format("ContentType_{0}_Title", ct.Name.Replace(" ", "_")), template, creationInfo))
                            {
                                newCT.Name = string.Format("{{res:ContentType_{0}_Title}}", ct.Name.Replace(" ", "_"));
                            }
                            if (PersistResourceValue(ct.DescriptionResource, string.Format("ContentType_{0}_Description", ct.Name.Replace(" ", "_")), template, creationInfo))
                            {
                                newCT.Description = string.Format("{{res:ContentType_{0}_Description}}", ct.Name.Replace(" ", "_"));
                            }
                        }
#endif
                    }

                    // If the Content Type is a DocumentSet
                    if (Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.IsChildOfDocumentSetContentType(web.Context, ct).Value ||
                        ct.StringId.StartsWith(BuiltInContentTypeId.DocumentSet)) // TODO: This is kind of an hack... we should find a better solution ...
                    {
                        Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
                            Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, ct);

                        // Retrieve the Document Set
                        web.Context.Load(documentSetTemplate,
                                         t => t.AllowedContentTypes,
                                         t => t.DefaultDocuments,
                                         t => t.SharedFields,
                                         t => t.WelcomePageFields);
                        web.Context.ExecuteQueryRetry();

                        newCT.DocumentSetTemplate = new DocumentSetTemplate(
                            null, // TODO: WelcomePage not yet supported
                            (from allowedCT in documentSetTemplate.AllowedContentTypes.AsEnumerable()
                             select allowedCT.StringValue).ToArray(),
                            (from defaultDocument in documentSetTemplate.DefaultDocuments.AsEnumerable()
                             select new DefaultDocument
                        {
                            ContentTypeId = defaultDocument.ContentTypeId.StringValue,
                            Name = defaultDocument.Name,
                            FileSourcePath = String.Empty,      // TODO: How can we extract the proper file?!
                        }).ToArray(),
                            (from sharedField in documentSetTemplate.SharedFields.AsEnumerable()
                             select sharedField.Id).ToArray(),
                            (from welcomePageField in documentSetTemplate.WelcomePageFields.AsEnumerable()
                             select welcomePageField.Id).ToArray()
                            );
                    }

                    ctsToReturn.Add(newCT);
                }
            }
            return(ctsToReturn);
        }
Пример #8
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);
        }