public System.IO.Stream ToFormattedTemplate(Model.ProvisioningTemplate template)
        {
            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            formatter.Initialize(this._provider);
            return(formatter.ToFormattedTemplate(template));
        }
        public Model.ProvisioningTemplate ToProvisioningTemplate(System.IO.Stream template, string identifier)
        {
            StreamReader sr         = new StreamReader(template, Encoding.Unicode);
            String       jsonString = sr.ReadToEnd();

            Model.ProvisioningTemplate result = JsonConvert.DeserializeObject <Model.ProvisioningTemplate>(jsonString);
            return(result);
        }
Esempio n. 3
0
 public override bool WillProvision(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
 {
     if (!_willProvision.HasValue)
     {
         _willProvision = template.TermGroups.Any();
     }
     return(_willProvision.Value);
 }
Esempio n. 4
0
 public override bool WillExtract(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
 {
     if (!_willExtract.HasValue)
     {
         _willExtract = creationInfo.IncludeSiteCollectionTermGroup || creationInfo.IncludeAllTermGroups;
     }
     return(_willExtract.Value);
 }
 public Model.ProvisioningTemplate ToProvisioningTemplate(System.IO.Stream template, string identifier)
 {
     using (var sr = new StreamReader(template, Encoding.Unicode))
     {
         var jsonString = sr.ReadToEnd();
         Model.ProvisioningTemplate result = JsonConvert.DeserializeObject <Model.ProvisioningTemplate>(jsonString, new BasePermissionsConverter());
         return(result);
     }
 }
        public System.IO.Stream ToFormattedTemplate(Model.ProvisioningTemplate template)
        {
            String jsonString = JsonConvert.SerializeObject(template);

            Byte[]       jsonBytes  = System.Text.Encoding.Unicode.GetBytes(jsonString);
            MemoryStream jsonStream = new MemoryStream(jsonBytes);

            jsonStream.Position = 0;

            return(jsonStream);
        }
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser,
                                                     ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                this.reusedTerms = new List <TermGroupHelper.ReusedTerm>();

                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);
                TermStore       termStore  = null;
                TermGroup       siteCollectionTermGroup = null;

                try
                {
                    termStore = taxSession.GetDefaultKeywordsTermStore();
                    web.Context.Load(termStore,
                                     ts => ts.Languages,
                                     ts => ts.DefaultLanguage,
                                     ts => ts.Groups.Include(
                                         tg => tg.Name,
                                         tg => tg.Id,
                                         tg => tg.TermSets.Include(
                                             tset => tset.Name,
                                             tset => tset.Id)));
                    siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false);
                    web.Context.Load(siteCollectionTermGroup);
                    web.Context.ExecuteQueryRetry();
                }
                catch (ServerException)
                {
                    // If the GetDefaultSiteCollectionTermStore method call fails ... raise a specific Warning
                    WriteMessage(CoreResources.Provisioning_ObjectHandlers_TermGroups_Wrong_Configuration, ProvisioningMessageType.Warning);

                    // and exit skipping the current handler
                    return(parser);
                }

                SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken =
                    new SiteCollectionTermGroupNameToken(web);

                foreach (var modelTermGroup in template.TermGroups)
                {
                    this.reusedTerms.AddRange(TermGroupHelper.ProcessGroup(web.Context as ClientContext, taxSession, termStore, modelTermGroup, siteCollectionTermGroup, parser, scope));
                }

                foreach (var reusedTerm in this.reusedTerms)
                {
                    TermGroupHelper.TryReuseTerm(web.Context as ClientContext, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope);
                }
            }
            return(parser);
        }
        /// <summary>
        /// This method allows to check if a template can be provisioned in the currently selected target
        /// </summary>
        /// <param name="web">The target Web</param>
        /// <param name="template">The Template to provision</param>
        /// <param name="applyingInformation">Any custom provisioning settings</param>
        /// <returns>A boolean stating whether the current object handler can be run during provisioning or if there are any missing requirements</returns>
        public static CanProvisionResult CanProvision(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            CanProvisionResult result = new CanProvisionResult();

            List <ICanProvisionRuleSite> rules = GetCanProvisionRules <ICanProvisionRuleSite>();

            foreach (var rule in rules)
            {
                var ruleResult = rule.CanProvision(web, template, applyingInformation);
                result.CanProvision &= ruleResult.CanProvision;
                result.Issues.AddRange(ruleResult.Issues);
            }

            return(result);
        }
        public System.IO.Stream ToFormattedTemplate(Model.ProvisioningTemplate template)
        {
            TextWriter writer = new StringWriter();
            // Get all ProvisioningTemplate-level serializers to run in automated mode, ordered by DeserializationSequence
            var serializers = GetWritersForCurrentContext(WriterScope.ProvisioningTemplate, a => a?.WriterSequence);

            // Invoke all the ProvisioningTemplate-level serializers
            InvokeWriters(template, writer, serializers);


            Byte[]       markdownBytes  = System.Text.Encoding.Unicode.GetBytes(writer.ToString());
            MemoryStream markdownStream = new MemoryStream(markdownBytes)
            {
                Position = 0
            };

            return(markdownStream);
        }
        public Model.ProvisioningTemplate ToProvisioningTemplate(Stream template, String identifier)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            // Crate a copy of the source stream
            MemoryStream sourceStream = new MemoryStream();
            template.CopyTo(sourceStream);
            sourceStream.Position = 0;

            // Check the provided template against the XML schema
            if (!this.IsValid(sourceStream))
            {
                // TODO: Use resource file
                throw new ApplicationException("The provided template is not valid!");
            }

            sourceStream.Position = 0;
            XDocument xml = XDocument.Load(sourceStream);
            XNamespace pnp = XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_05;

            // Prepare a variable to hold the single source formatted template
            V201505.ProvisioningTemplate source = null;

            // Prepare a variable to hold the resulting ProvisioningTemplate instance
            Model.ProvisioningTemplate result = new Model.ProvisioningTemplate();

            // Determine if we're working on a wrapped SharePointProvisioningTemplate or not
            if (xml.Root.Name == pnp + "Provisioning")
            {
                // Deserialize the whole wrapper
                V201505.Provisioning wrappedResult = XMLSerializer.Deserialize<V201505.Provisioning>(xml);

                // Handle the wrapper schema parameters
                if (wrappedResult.Preferences != null &&
                    wrappedResult.Preferences.Parameters != null &&
                    wrappedResult.Preferences.Parameters.Length > 0)
                {
                    foreach (var parameter in wrappedResult.Preferences.Parameters)
                    {
                        result.Parameters.Add(parameter.Key, parameter.Text != null ? parameter.Text.Aggregate(String.Empty, (acc, i) => acc + i) : null);
                    }
                }

                foreach (var templates in wrappedResult.Templates)
                {
                    // Let's see if we have an in-place template with the provided ID or if we don't have a provided ID at all
                    source = templates.ProvisioningTemplate.FirstOrDefault(spt => spt.ID == identifier || String.IsNullOrEmpty(identifier));

                    // If we don't have a template, but there are external file references
                    if (source == null && templates.ProvisioningTemplateFile.Length > 0)
                    {
                        // Otherwise let's see if we have an external file for the template
                        var externalSource = templates.ProvisioningTemplateFile.FirstOrDefault(sptf => sptf.ID == identifier);

                        Stream externalFileStream = this._provider.Connector.GetFileStream(externalSource.File);
                        xml = XDocument.Load(externalFileStream);

                        if (xml.Root.Name != pnp + "ProvisioningTemplate")
                        {
                            throw new ApplicationException("Invalid external file format. Expected a ProvisioningTemplate file!");
                        }
                        else
                        {
                            source = XMLSerializer.Deserialize<V201505.ProvisioningTemplate>(xml);
                        }
                    }

                    if (source != null)
                    {
                        break;
                    }
                }
            }
            else if (xml.Root.Name == pnp + "ProvisioningTemplate")
            {
                var IdAttribute = xml.Root.Attribute("ID");

                // If there is a provided ID, and if it doesn't equal the current ID
                if (!String.IsNullOrEmpty(identifier) &&
                    IdAttribute != null &&
                    IdAttribute.Value != identifier)
                {
                    // TODO: Use resource file
                    throw new ApplicationException("The provided template identifier is not available!");
                }
                else
                {
                    source = XMLSerializer.Deserialize<V201505.ProvisioningTemplate>(xml);
                }
            }

            #region Basic Properties
            // Translate basic properties
            result.Id = source.ID;
            result.Version = (Double)source.Version;
            result.SitePolicy = source.SitePolicy;
            #endregion

            #region Property Bag
            // Translate PropertyBagEntries, if any
            if (source.PropertyBagEntries != null)
            {
                result.PropertyBagEntries.AddRange(
                    from bag in source.PropertyBagEntries
                    select new Model.PropertyBagEntry
                    {
                        Key = bag.Key,
                        Value = bag.Value,
                        Indexed = bag.Indexed
                    });
            }
            #endregion

            #region Security
            // Translate Security configuration, if any
            if (source.Security != null)
            {
                if (source.Security.AdditionalAdministrators != null)
                {
                    result.Security.AdditionalAdministrators.AddRange(
                    from user in source.Security.AdditionalAdministrators
                    select new Model.User
                    {
                        Name = user.Name,
                    });
                }
                if (source.Security.AdditionalOwners != null)
                {
                    result.Security.AdditionalOwners.AddRange(
                    from user in source.Security.AdditionalOwners
                    select new Model.User
                    {
                        Name = user.Name,
                    });
                }
                if (source.Security.AdditionalMembers != null)
                {
                    result.Security.AdditionalMembers.AddRange(
                    from user in source.Security.AdditionalMembers
                    select new Model.User
                    {
                        Name = user.Name,
                    });
                }
                if (source.Security.AdditionalVisitors != null)
                {
                    result.Security.AdditionalVisitors.AddRange(
                    from user in source.Security.AdditionalVisitors
                    select new Model.User
                    {
                        Name = user.Name,
                    });
                }
            }
            #endregion

            #region Site Columns
            // Translate Site Columns (Fields), if any
            if ((source.SiteFields != null) && (source.SiteFields.Any != null))
            {
                result.SiteFields.AddRange(
                    from field in source.SiteFields.Any
                    select new Field
                    {
                        SchemaXml = field.OuterXml,
                    });
            }
            #endregion

            #region Content Types
            // Translate ContentTypes, if any
            if ((source.ContentTypes != null) && (source.ContentTypes != null))
            {
                result.ContentTypes.AddRange(
                    from contentType in source.ContentTypes
                    select new ContentType(
                        contentType.ID,
                        contentType.Name,
                        contentType.Description,
                        contentType.Group,
                        contentType.Sealed,
                        contentType.Hidden,
                        contentType.ReadOnly,
                        (contentType.DocumentTemplate != null ?
                            contentType.DocumentTemplate.TargetName : null),
                        contentType.Overwrite,
                        (contentType.FieldRefs != null ?
                            (from fieldRef in contentType.FieldRefs
                             select new Model.FieldRef(fieldRef.Name)
                             {
                                 Id = Guid.Parse(fieldRef.ID),
                                 Hidden = fieldRef.Hidden,
                                 Required = fieldRef.Required
                             }) : null)
                        )
                    );
            }
            #endregion

            #region List Instances
            // Translate Lists Instances, if any
            if (source.Lists != null)
            {
                result.Lists.AddRange(
                    from list in source.Lists
                    select new Model.ListInstance(
                        (list.ContentTypeBindings != null ?
                                (from contentTypeBinding in list.ContentTypeBindings
                                 select new Model.ContentTypeBinding
                                 {
                                     ContentTypeId = contentTypeBinding.ContentTypeID,
                                     Default = contentTypeBinding.Default,
                                 }) : null),
                        (list.Views != null ?
                                (from view in list.Views.Any
                                 select new View
                                 {
                                     SchemaXml = view.OuterXml,
                                 }) : null),
                        (list.Fields != null ?
                                (from field in list.Fields.Any
                                 select new Field
                                 {
                                     SchemaXml = field.OuterXml,
                                 }) : null),
                        (list.FieldRefs != null ?
                                 (from fieldRef in list.FieldRefs
                                  select new Model.FieldRef(fieldRef.Name)
                                  {
                                      DisplayName = fieldRef.DisplayName,
                                      Hidden = fieldRef.Hidden,
                                      Required = fieldRef.Required,
                                      Id = Guid.Parse(fieldRef.ID)
                                  }) : null),
                        (list.DataRows != null ?
                                 (from dataRow in list.DataRows
                                  select new Model.DataRow(
                                     (from dataValue in dataRow
                                      select dataValue).ToDictionary(k => k.FieldName, v => v.Value)
                                  )).ToList() : null)
                        )
                    {
                        ContentTypesEnabled = list.ContentTypesEnabled,
                        Description = list.Description,
                        DocumentTemplate = list.DocumentTemplate,
                        EnableVersioning = list.EnableVersioning,
                        EnableMinorVersions = list.EnableMinorVersions,
                        DraftVersionVisibility = list.DraftVersionVisibility,
                        EnableModeration = list.EnableModeration,
                        Hidden = list.Hidden,
                        MinorVersionLimit = list.MinorVersionLimitSpecified ? list.MinorVersionLimit : 0,
                        MaxVersionLimit = list.MaxVersionLimitSpecified ? list.MaxVersionLimit : 0,
                        OnQuickLaunch = list.OnQuickLaunch,
                        EnableAttachments = list.EnableAttachments,
                        EnableFolderCreation = list.EnableFolderCreation,
                        RemoveExistingContentTypes = list.RemoveExistingContentTypes,
                        TemplateFeatureID = !String.IsNullOrEmpty(list.TemplateFeatureID) ? Guid.Parse(list.TemplateFeatureID) : Guid.Empty,
                        RemoveExistingViews = list.Views != null ? list.Views.RemoveExistingViews : false,
                        TemplateType = list.TemplateType,
                        Title = list.Title,
                        Url = list.Url,
                    });
            }
            #endregion

            #region Features
            // Translate Features, if any
            if (source.Features != null)
            {
                if (result.Features.SiteFeatures != null && source.Features.SiteFeatures != null)
                {
                    result.Features.SiteFeatures.AddRange(
                        from feature in source.Features.SiteFeatures
                        select new Model.Feature
                        {
                            Id = new Guid(feature.ID),
                            Deactivate = feature.Deactivate,
                        });
                }
                if (result.Features.WebFeatures != null && source.Features.WebFeatures != null)
                {
                    result.Features.WebFeatures.AddRange(
                        from feature in source.Features.WebFeatures
                        select new Model.Feature
                        {
                            Id = new Guid(feature.ID),
                            Deactivate = feature.Deactivate,
                        });
                }
            }
            #endregion

            #region Custom Actions
            // Translate CustomActions, if any
            if (source.CustomActions != null)
            {
                if (result.CustomActions.SiteCustomActions != null && source.CustomActions.SiteCustomActions != null)
                {
                    result.CustomActions.SiteCustomActions.AddRange(
                        from customAction in source.CustomActions.SiteCustomActions
                        select new Model.CustomAction
                        {
                            CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
                                (new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
                            Description = customAction.Description,
                            Enabled = customAction.Enabled,
                            Group = customAction.Group,
                            ImageUrl = customAction.ImageUrl,
                            Location = customAction.Location,
                            Name = customAction.Name,
                            RightsValue = customAction.RightsSpecified ? customAction.Rights : 0,
                            ScriptBlock = customAction.ScriptBlock,
                            ScriptSrc = customAction.ScriptSrc,
                            Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
                            Title = customAction.Title,
                            Url = customAction.Url,
                        });
                }
                if (result.CustomActions.WebCustomActions != null && source.CustomActions.WebCustomActions != null)
                {
                    result.CustomActions.WebCustomActions.AddRange(
                        from customAction in source.CustomActions.WebCustomActions
                        select new Model.CustomAction
                        {
                            CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
                                (new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
                            Description = customAction.Description,
                            Enabled = customAction.Enabled,
                            Group = customAction.Group,
                            ImageUrl = customAction.ImageUrl,
                            Location = customAction.Location,
                            Name = customAction.Name,
                            RightsValue = customAction.RightsSpecified ? customAction.Rights : 0,
                            ScriptBlock = customAction.ScriptBlock,
                            ScriptSrc = customAction.ScriptSrc,
                            Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
                            Title = customAction.Title,
                            Url = customAction.Url,
                        });
                }
            }
            #endregion

            #region Files
            // Translate Files, if any
            if (source.Files != null)
            {
                result.Files.AddRange(
                    from file in source.Files
                    select new Model.File(file.Src,
                        file.Folder,
                        file.Overwrite,
                        file.WebParts != null ?
                            (from wp in file.WebParts
                             select new Model.WebPart
                             {
                                 Order = (uint)wp.Order,
                                 Zone = wp.Zone,
                                 Title = wp.Title,
                                 Contents = wp.Contents
                             }) : null,
                        file.Properties != null ? file.Properties.ToDictionary(k => k.Key, v => v.Value) : null
                        )
                    );
            }
            #endregion

            #region Pages
            // Translate Pages, if any
            if (source.Pages != null)
            {
                foreach (var page in source.Pages)
                {

                    var pageLayout = WikiPageLayout.OneColumn;
                    switch (page.Layout)
                    {
                        case V201505.WikiPageLayout.OneColumn:
                            pageLayout = WikiPageLayout.OneColumn;
                            break;
                        case V201505.WikiPageLayout.OneColumnSidebar:
                            pageLayout = WikiPageLayout.OneColumnSideBar;
                            break;
                        case V201505.WikiPageLayout.TwoColumns:
                            pageLayout = WikiPageLayout.TwoColumns;
                            break;
                        case V201505.WikiPageLayout.TwoColumnsHeader:
                            pageLayout = WikiPageLayout.TwoColumnsHeader;
                            break;
                        case V201505.WikiPageLayout.TwoColumnsHeaderFooter:
                            pageLayout = WikiPageLayout.TwoColumnsHeaderFooter;
                            break;
                        case V201505.WikiPageLayout.ThreeColumns:
                            pageLayout = WikiPageLayout.ThreeColumns;
                            break;
                        case V201505.WikiPageLayout.ThreeColumnsHeader:
                            pageLayout = WikiPageLayout.ThreeColumnsHeader;
                            break;
                        case V201505.WikiPageLayout.ThreeColumnsHeaderFooter:
                            pageLayout = WikiPageLayout.ThreeColumnsHeaderFooter;
                            break;
                    }

                    result.Pages.Add(new Model.Page(page.Url, page.Overwrite, pageLayout,
                        (page.WebParts != null ?
                            (from wp in page.WebParts
                             select new Model.WebPart
                             {
                                 Title = wp.Title,
                                 Column = (uint)wp.Column,
                                 Row = (uint)wp.Row,
                                 Contents = wp.Contents

                             }).ToList() : null), page.WelcomePage, null));

                }
            }
            #endregion

            #region Taxonomy
            // Translate Termgroups, if any
            if (source.TermGroups != null)
            {
                result.TermGroups.AddRange(
                    from termGroup in source.TermGroups
                    select new Model.TermGroup(
                        !string.IsNullOrEmpty(termGroup.ID) ? Guid.Parse(termGroup.ID) : Guid.Empty,
                        termGroup.Name,
                        new List<Model.TermSet>(
                            from termSet in termGroup.TermSets
                            select new Model.TermSet(
                                !string.IsNullOrEmpty(termSet.ID) ? Guid.Parse(termSet.ID) : Guid.Empty,
                                termSet.Name,
                                termSet.LanguageSpecified ? (int?)termSet.Language : null,
                                termSet.IsAvailableForTagging,
                                termSet.IsOpenForTermCreation,
                                termSet.Terms != null ? termSet.Terms.FromSchemaTermsToModelTermsV201505() : null,
                                termSet.CustomProperties != null ? termSet.CustomProperties.ToDictionary(k => k.Key, v => v.Value) : null)
                            {
                                Description = termSet.Description,
                            })
                        )
                    {
                        Description = termGroup.Description,
                    });
            }
            #endregion

            #region Composed Looks
            // Translate ComposedLook, if any
            if (source.ComposedLook != null)
            {
                result.ComposedLook.AlternateCSS = source.ComposedLook.AlternateCSS;
                result.ComposedLook.BackgroundFile = source.ComposedLook.BackgroundFile;
                result.ComposedLook.ColorFile = source.ComposedLook.ColorFile;
                result.ComposedLook.FontFile = source.ComposedLook.FontFile;
                result.ComposedLook.MasterPage = source.ComposedLook.MasterPage;
                result.ComposedLook.Name = source.ComposedLook.Name;
                result.ComposedLook.SiteLogo = source.ComposedLook.SiteLogo;
                result.ComposedLook.Version = source.ComposedLook.Version;
            }
            #endregion

            #region Providers
            // Translate Providers, if any
            if (source.Providers != null)
            {
                foreach (var provider in source.Providers)
                {
                    if (!String.IsNullOrEmpty(provider.HandlerType))
                    {
                        var handlerType = Type.GetType(provider.HandlerType, false);
                        if (handlerType != null)
                        {
                            result.Providers.Add(
                                new Model.Provider
                                {
                                    Assembly = handlerType.Assembly.FullName,
                                    Type = handlerType.FullName,
                                    Configuration = provider.Configuration != null ? provider.Configuration.ToProviderConfiguration() : null,
                                    Enabled = provider.Enabled,
                                });
                        }
                    }
                }
            }
            #endregion

            return (result);
        }
Esempio n. 11
0
        public override Model.ProvisioningTemplate ExtractObjects(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (creationInfo.IncludeSiteCollectionTermGroup || creationInfo.IncludeAllTermGroups)
                {
                    // Find the site collection termgroup, if any
                    TaxonomySession session   = TaxonomySession.GetTaxonomySession(web.Context);
                    TermStore       termStore = null;

                    try
                    {
                        termStore = session.GetDefaultSiteCollectionTermStore();
                        web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage, t => t.OrphanedTermsTermSet);
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (ServerException)
                    {
                        // Skip the exception and go to the next check
                    }

                    if (null == termStore || termStore.ServerObjectIsNull())
                    {
                        // If the GetDefaultSiteCollectionTermStore method call fails ... raise a specific Warning
                        WriteMessage(CoreResources.Provisioning_ObjectHandlers_TermGroups_Wrong_Configuration, ProvisioningMessageType.Warning);

                        // and exit skipping the current handler
                        return(template);
                    }

                    var orphanedTermsTermSetId = default(Guid);
                    if (!termStore.OrphanedTermsTermSet.ServerObjectIsNull())
                    {
                        termStore.OrphanedTermsTermSet.EnsureProperty(ts => ts.Id);
                        orphanedTermsTermSetId = termStore.OrphanedTermsTermSet.Id;
                        if (termStore.ServerObjectIsNull.Value)
                        {
                            termStore = session.GetDefaultKeywordsTermStore();
                            web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage);
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                    var propertyBagKey = $"SiteCollectionGroupId{termStore.Id}";

                    // Ensure to grab the property from the rootweb
                    var site = (web.Context as ClientContext).Site;
                    web.Context.Load(site, s => s.RootWeb);
                    web.Context.ExecuteQueryRetry();

                    var siteCollectionTermGroupId = site.RootWeb.GetPropertyBagValueString(propertyBagKey, "");

                    Guid termGroupGuid;
                    Guid.TryParse(siteCollectionTermGroupId, out termGroupGuid);

                    List <TermGroup> termGroups = new List <TermGroup>();
                    if (creationInfo.IncludeAllTermGroups)
                    {
                        web.Context.Load(termStore.Groups, groups => groups.Include(tg => tg.Name,
                                                                                    tg => tg.Id,
                                                                                    tg => tg.Description,
                                                                                    tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.CustomSortOrder)));
                        web.Context.ExecuteQueryRetry();
                        termGroups = termStore.Groups.ToList();
                    }
                    else
                    {
                        if (termGroupGuid != Guid.Empty)
                        {
                            var termGroup = termStore.GetGroup(termGroupGuid);
                            web.Context.Load(termGroup,
                                             tg => tg.Name,
                                             tg => tg.Id,
                                             tg => tg.Description,
                                             tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.Description, ts => ts.CustomSortOrder));

                            web.Context.ExecuteQueryRetry();

                            termGroups = new List <TermGroup>()
                            {
                                termGroup
                            };
                        }
                    }

                    foreach (var termGroup in termGroups)
                    {
                        Boolean isSiteCollectionTermGroup = termGroupGuid != Guid.Empty && termGroup.Id == termGroupGuid;

                        var modelTermGroup = new Model.TermGroup
                        {
                            Name                    = isSiteCollectionTermGroup ? "{sitecollectiontermgroupname}" : termGroup.Name,
                            Id                      = isSiteCollectionTermGroup ? Guid.Empty : termGroup.Id,
                            Description             = termGroup.Description,
                            SiteCollectionTermGroup = isSiteCollectionTermGroup
                        };

#if !ONPREMISES
                        // If we need to include TermGroups security
                        if (creationInfo.IncludeTermGroupsSecurity)
                        {
                            termGroup.EnsureProperties(tg => tg.ContributorPrincipalNames, tg => tg.GroupManagerPrincipalNames);

                            // Extract the TermGroup contributors
                            modelTermGroup.Contributors.AddRange(
                                from c in termGroup.ContributorPrincipalNames
                                select new Model.User {
                                Name = c
                            });

                            // Extract the TermGroup managers
                            modelTermGroup.Managers.AddRange(
                                from m in termGroup.GroupManagerPrincipalNames
                                select new Model.User {
                                Name = m
                            });
                        }
#endif

                        web.EnsureProperty(w => w.Url);

                        foreach (var termSet in termGroup.TermSets)
                        {
                            // Do not include the orphan term set
                            if (termSet.Id == orphanedTermsTermSetId)
                            {
                                continue;
                            }

                            // Extract all other term sets
                            var modelTermSet = new Model.TermSet();
                            modelTermSet.Name = termSet.Name;
                            if (!isSiteCollectionTermGroup)
                            {
                                modelTermSet.Id = termSet.Id;
                            }
                            modelTermSet.IsAvailableForTagging = termSet.IsAvailableForTagging;
                            modelTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                            modelTermSet.Description           = termSet.Description;
                            modelTermSet.Terms.AddRange(GetTerms <TermSet>(web.Context, termSet, termStore.DefaultLanguage, isSiteCollectionTermGroup));
                            foreach (var property in termSet.CustomProperties)
                            {
                                if (property.Key.Equals("_Sys_Nav_AttachedWeb_SiteId", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    modelTermSet.Properties.Add(property.Key, "{sitecollectionid}");
                                }
                                else if (property.Key.Equals("_Sys_Nav_AttachedWeb_WebId", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    modelTermSet.Properties.Add(property.Key, "{siteid}");
                                }
                                else
                                {
                                    modelTermSet.Properties.Add(property.Key, Tokenize(property.Value, web.Url, web));
                                }
                            }
                            modelTermGroup.TermSets.Add(modelTermSet);
                        }

                        template.TermGroups.Add(modelTermGroup);
                    }
                }
            }
            return(template);
        }
Esempio n. 12
0
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser,
                                                     ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                this.reusedTerms = new List <ReusedTerm>();

                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);
                TermStore       termStore  = null;
                TermGroup       siteCollectionTermGroup = null;

                try
                {
                    termStore = taxSession.GetDefaultKeywordsTermStore();
                    web.Context.Load(termStore,
                                     ts => ts.Languages,
                                     ts => ts.DefaultLanguage,
                                     ts => ts.Groups.Include(
                                         tg => tg.Name,
                                         tg => tg.Id,
                                         tg => tg.TermSets.Include(
                                             tset => tset.Name,
                                             tset => tset.Id)));
                    siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false);
                    web.Context.Load(siteCollectionTermGroup);
                    web.Context.ExecuteQueryRetry();
                }
                catch (ServerException)
                {
                    // If the GetDefaultSiteCollectionTermStore method call fails ... raise a specific Warning
                    WriteMessage(CoreResources.Provisioning_ObjectHandlers_TermGroups_Wrong_Configuration, ProvisioningMessageType.Warning);

                    // and exit skipping the current handler
                    return(parser);
                }

                SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken =
                    new SiteCollectionTermGroupNameToken(web);

                foreach (var modelTermGroup in template.TermGroups)
                {
                    #region Group

                    var newGroup            = false;
                    var normalizedGroupName = TaxonomyItem.NormalizeName(web.Context, modelTermGroup.Name);
                    web.Context.ExecuteQueryRetry();

                    TermGroup group = termStore.Groups.FirstOrDefault(
                        g => g.Id == modelTermGroup.Id || g.Name == normalizedGroupName.Value);
                    if (group == null)
                    {
                        var parsedGroupName   = parser.ParseString(modelTermGroup.Name);
                        var parsedDescription = parser.ParseString(modelTermGroup.Description);

                        if (modelTermGroup.Name == "Site Collection" ||
                            parsedGroupName == siteCollectionTermGroupNameToken.GetReplaceValue() ||
                            modelTermGroup.SiteCollectionTermGroup)
                        {
                            var site = (web.Context as ClientContext).Site;
                            group = termStore.GetSiteCollectionGroup(site, true);
                            web.Context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include(
                                                 tset => tset.Name,
                                                 tset => tset.Id));
                            web.Context.ExecuteQueryRetry();
                        }
                        else
                        {
                            var parsedNormalizedGroupName = TaxonomyItem.NormalizeName(web.Context, parsedGroupName);
                            web.Context.ExecuteQueryRetry();

                            group = termStore.Groups.FirstOrDefault(g => g.Name == parsedNormalizedGroupName.Value);

                            if (group == null)
                            {
                                if (modelTermGroup.Id == Guid.Empty)
                                {
                                    modelTermGroup.Id = Guid.NewGuid();
                                }
                                group = termStore.CreateGroup(parsedGroupName, modelTermGroup.Id);

                                group.Description = parsedDescription;

#if !ONPREMISES
                                // Handle TermGroup Contributors, if any
                                if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0)
                                {
                                    foreach (var c in modelTermGroup.Contributors)
                                    {
                                        group.AddContributor(c.Name);
                                    }
                                }

                                // Handle TermGroup Managers, if any
                                if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0)
                                {
                                    foreach (var m in modelTermGroup.Managers)
                                    {
                                        group.AddGroupManager(m.Name);
                                    }
                                }
#endif

                                termStore.CommitAll();
                                web.Context.Load(group);
                                web.Context.ExecuteQueryRetry();

                                newGroup = true;
                            }
                        }
                    }

                    #endregion

                    #region TermSets

                    foreach (var modelTermSet in modelTermGroup.TermSets)
                    {
                        TermSet set        = null;
                        var     newTermSet = false;

                        var normalizedTermSetName = TaxonomyItem.NormalizeName(web.Context, modelTermSet.Name);
                        web.Context.ExecuteQueryRetry();

                        if (!newGroup)
                        {
                            set =
                                group.TermSets.FirstOrDefault(
                                    ts => ts.Id == modelTermSet.Id || ts.Name == normalizedTermSetName.Value);
                        }
                        if (set == null)
                        {
                            if (modelTermSet.Id == Guid.Empty)
                            {
                                modelTermSet.Id = Guid.NewGuid();
                            }
                            set = group.CreateTermSet(parser.ParseString(modelTermSet.Name), modelTermSet.Id,
                                                      modelTermSet.Language ?? termStore.DefaultLanguage);
                            parser.AddToken(new TermSetIdToken(web, group.Name, modelTermSet.Name, modelTermSet.Id));
                            if (!siteCollectionTermGroup.ServerObjectIsNull.Value)
                            {
                                if (group.Name == siteCollectionTermGroup.Name)
                                {
                                    parser.AddToken((new SiteCollectionTermSetIdToken(web, modelTermSet.Name, modelTermSet.Id)));
                                }
                            }
                            newTermSet                = true;
                            set.Description           = parser.ParseString(modelTermSet.Description);
                            set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation;
                            set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging;
                            foreach (var property in modelTermSet.Properties)
                            {
                                set.SetCustomProperty(property.Key, parser.ParseString(property.Value));
                            }
                            if (modelTermSet.Owner != null)
                            {
                                set.Owner = modelTermSet.Owner;
                            }
                            termStore.CommitAll();
                            web.Context.Load(set);
                            web.Context.ExecuteQueryRetry();
                        }

                        web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                        web.Context.ExecuteQueryRetry();
                        var terms = set.Terms;

                        foreach (var modelTerm in modelTermSet.Terms)
                        {
                            if (!newTermSet)
                            {
                                if (terms.Any())
                                {
                                    var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id);
                                    if (term == null)
                                    {
                                        var normalizedTermName = TaxonomyItem.NormalizeName(web.Context, modelTerm.Name);
                                        web.Context.ExecuteQueryRetry();

                                        term = terms.FirstOrDefault(t => t.Name == normalizedTermName.Value);
                                        if (term == null)
                                        {
                                            var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                            if (returnTuple != null)
                                            {
                                                modelTerm.Id = returnTuple.Item1;
                                                parser       = returnTuple.Item2;
                                            }
                                        }
                                        else
                                        {
                                            modelTerm.Id = term.Id;
                                        }
                                    }
                                    else
                                    {
                                        modelTerm.Id = term.Id;
                                    }

                                    if (term != null)
                                    {
                                        CheckChildTerms(web, modelTerm, term, termStore, parser, scope);
                                    }
                                }
                                else
                                {
                                    var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                    if (returnTuple != null)
                                    {
                                        modelTerm.Id = returnTuple.Item1;
                                        parser       = returnTuple.Item2;
                                    }
                                }
                            }
                            else
                            {
                                var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                if (returnTuple != null)
                                {
                                    modelTerm.Id = returnTuple.Item1;
                                    parser       = returnTuple.Item2;
                                }
                            }
                        }

                        // do we need custom sorting?
                        if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1))
                        {
                            var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder);

                            var customSortString = sortedTerms.Aggregate(string.Empty,
                                                                         (a, i) => a + i.Id.ToString() + ":");
                            customSortString = customSortString.TrimEnd(new[] { ':' });

                            set.CustomSortOrder = customSortString;
                            termStore.CommitAll();
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                    #endregion
                }

                foreach (var reusedTerm in this.reusedTerms)
                {
                    TryReuseTerm(web, reusedTerm.ModelTerm, reusedTerm.Parent, reusedTerm.TermStore, parser, scope);
                }
            }
            return(parser);
        }
        public override CanProvisionResult CanProvision(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            // Prepare the default output
            var result = new CanProvisionResult();

#if !ONPREMISES
            Model.ProvisioningTemplate targetTemplate = null;

            if (template.ParentHierarchy != null)
            {
                // If we have a hierarchy, search for a template with ALM settings, if any
                targetTemplate = template.ParentHierarchy.Templates.FirstOrDefault(t => t.ApplicationLifecycleManagement.Apps.Count > 0 ||
                                                                                   (t.ApplicationLifecycleManagement.AppCatalog != null && t.ApplicationLifecycleManagement.AppCatalog.Packages.Count > 0));

                if (targetTemplate == null)
                {
                    // or use the first in the hierarchy
                    targetTemplate = template.ParentHierarchy.Templates[0];
                }
            }
            else
            {
                // Otherwise, use the provided template
                targetTemplate = template;
            }

            // Verify if we need the App Catalog (i.e. the template contains apps or packages)
            if ((targetTemplate.ApplicationLifecycleManagement?.Apps != null && targetTemplate.ApplicationLifecycleManagement?.Apps?.Count > 0) ||
                (targetTemplate.ApplicationLifecycleManagement?.AppCatalog != null &&
                 targetTemplate.ApplicationLifecycleManagement?.AppCatalog?.Packages != null && targetTemplate.ApplicationLifecycleManagement?.AppCatalog?.Packages.Count > 0) ||
                (targetTemplate.ParentHierarchy != null && targetTemplate.ParentHierarchy?.Tenant?.AppCatalog != null &&
                 targetTemplate.ParentHierarchy?.Tenant?.AppCatalog?.Packages != null && targetTemplate.ParentHierarchy?.Tenant?.AppCatalog?.Packages.Count > 0))
            {
                // First of all check if the currently connected user is a Tenant Admin
                if (!TenantExtensions.IsCurrentUserTenantAdmin(web.Context as ClientContext))
                {
                    result.CanProvision = false;
                    result.Issues.Add(new CanProvisionIssue()
                    {
                        Source              = this.Name,
                        Tag                 = CanProvisionIssueTags.USER_IS_NOT_TENANT_ADMIN,
                        Message             = CanProvisionIssuesMessages.User_Is_Not_Tenant_Admin,
                        ExceptionMessage    = null, // Here we don't have any specific exception
                        ExceptionStackTrace = null, // Here we don't have any specific exception
                    });
                }

                using (var scope = new PnPMonitoredScope(this.Name))
                {
                    // Try to access the AppCatalog
                    var appCatalogUri = web.GetAppCatalog();
                    if (appCatalogUri == null)
                    {
                        // And if we fail, raise a CanProvisionIssue
                        result.CanProvision = false;
                        result.Issues.Add(new CanProvisionIssue()
                        {
                            Source              = this.Name,
                            Tag                 = CanProvisionIssueTags.MISSING_APP_CATALOG,
                            Message             = CanProvisionIssuesMessages.Missing_App_Catalog,
                            ExceptionMessage    = null, // Here we don't have any specific exception
                            ExceptionStackTrace = null, // Here we don't have any specific exception
                        });
                    }
                    else
                    {
                        // Try to access the AppCatalog with the current user

                        try
                        {
                            using (var appCatalogContext = web.Context.Clone(appCatalogUri))
                            {
                                // Get a reference to the "Apps for SharePoint" library
                                var appCatalogLibrary = appCatalogContext.Web.GetListByUrl("AppCatalog");

                                // Check its permissions
                                appCatalogContext.Web.CurrentUser.EnsureProperty(u => u.LoginName);
                                var userEffectivePermissions = appCatalogLibrary.GetUserEffectivePermissions(
                                    appCatalogContext.Web.CurrentUser.LoginName);
                                appCatalogContext.ExecuteQueryRetry();

                                if (!userEffectivePermissions.Value.Has(PermissionKind.EditListItems))
                                {
                                    throw new SecurityException("Invalid user's permissions for the AppCatalog");
                                }

                                // we seem to have access, but is it done fully provisioning?

                                var rootFolder  = appCatalogContext.Web.EnsureProperty(w => w.RootFolder);
                                var timeCreated = rootFolder.TimeCreated;

                                if (DateTime.UtcNow.Subtract(timeCreated).Hours < 2)
                                {
                                    result.CanProvision = false;
                                    result.Issues.Add(new CanProvisionIssue()
                                    {
                                        Source              = this.Name,
                                        Tag                 = CanProvisionIssueTags.APP_CATALOG_NOT_YEY_FULLY_PROVISIONED,
                                        Message             = CanProvisionIssuesMessages.App_Catalog_Not_Yet_Fully_Provisioned,
                                        ExceptionMessage    = null, // Here we don't have any specific exception
                                        ExceptionStackTrace = null, // Here we don't have any specific exception
                                    });
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            // And if we fail, raise a CanProvisionIssue
                            result.CanProvision = false;
                            result.Issues.Add(new CanProvisionIssue()
                            {
                                Source              = this.Name,
                                Tag                 = CanProvisionIssueTags.MISSING_APP_CATALOG_PERMISSIONS,
                                Message             = CanProvisionIssuesMessages.Missing_Permissions_for_App_Catalog,
                                ExceptionMessage    = ex.Message,
                                ExceptionStackTrace = ex.StackTrace,
                            });
                        }
                    }
                }
            }
#else
            result.CanProvision = false;
#endif
            return(result);
        }
Esempio n. 14
0
        public override void ProvisionObjects(Microsoft.SharePoint.Client.Web web, Model.ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_TermGroups);

            TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);

            var termStore = taxSession.GetDefaultKeywordsTermStore();

            web.Context.Load(termStore,
                             ts => ts.DefaultLanguage,
                             ts => ts.Groups.Include(
                                 tg => tg.Name,
                                 tg => tg.Id,
                                 tg => tg.TermSets.Include(
                                     tset => tset.Name,
                                     tset => tset.Id)));
            web.Context.ExecuteQueryRetry();

            foreach (var modelTermGroup in template.TermGroups)
            {
                #region Group

                var newGroup = false;

                TermGroup group = termStore.Groups.FirstOrDefault(g => g.Id == modelTermGroup.Id);
                if (group == null)
                {
                    group = termStore.Groups.FirstOrDefault(g => g.Name == modelTermGroup.Name);

                    if (group == null)
                    {
                        if (modelTermGroup.Id == Guid.Empty)
                        {
                            modelTermGroup.Id = Guid.NewGuid();
                        }
                        group = termStore.CreateGroup(modelTermGroup.Name.ToParsedString(), modelTermGroup.Id);

                        group.Description = modelTermGroup.Description;

                        termStore.CommitAll();
                        web.Context.Load(group);
                        web.Context.ExecuteQueryRetry();

                        newGroup = true;
                    }
                }

                #endregion

                #region TermSets

                foreach (var modelTermSet in modelTermGroup.TermSets)
                {
                    TermSet set        = null;
                    var     newTermSet = false;
                    if (!newGroup)
                    {
                        set = group.TermSets.FirstOrDefault(ts => ts.Id == modelTermSet.Id);
                        if (set == null)
                        {
                            set = group.TermSets.FirstOrDefault(ts => ts.Name == modelTermSet.Name);
                        }
                    }
                    if (set == null)
                    {
                        if (modelTermSet.Id == Guid.Empty)
                        {
                            modelTermSet.Id = Guid.NewGuid();
                        }
                        set = group.CreateTermSet(modelTermSet.Name.ToParsedString(), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage);
                        TokenParser.AddToken(new TermSetIdToken(web, modelTermGroup.Name, modelTermSet.Name, modelTermSet.Id));
                        newTermSet = true;
                        set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation;
                        set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging;
                        foreach (var property in modelTermSet.Properties)
                        {
                            set.SetCustomProperty(property.Key, property.Value);
                        }
                        if (modelTermSet.Owner != null)
                        {
                            set.Owner = modelTermSet.Owner;
                        }
                        termStore.CommitAll();
                        web.Context.Load(set);
                        web.Context.ExecuteQueryRetry();
                    }

                    web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                    web.Context.ExecuteQueryRetry();
                    var terms = set.Terms;

                    foreach (var modelTerm in modelTermSet.Terms)
                    {
                        if (!newTermSet)
                        {
                            if (terms.Any())
                            {
                                var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id);
                                if (term == null)
                                {
                                    term = terms.FirstOrDefault(t => t.Name == modelTerm.Name);
                                    if (term == null)
                                    {
                                        modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore);
                                    }
                                    else
                                    {
                                        modelTerm.Id = term.Id;
                                    }
                                }
                                else
                                {
                                    modelTerm.Id = term.Id;
                                }
                            }
                            else
                            {
                                modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore);
                            }
                        }
                        else
                        {
                            modelTerm.Id = CreateTerm <TermSet>(web, modelTerm, set, termStore);
                        }
                    }

                    // do we need custom sorting?
                    if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1))
                    {
                        var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder);

                        var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":");
                        customSortString = customSortString.TrimEnd(new[] { ':' });

                        set.CustomSortOrder = customSortString;
                        termStore.CommitAll();
                        web.Context.ExecuteQueryRetry();
                    }
                }

                #endregion
            }
        }
 protected override void SerializeTemplate(Model.ProvisioningTemplate template, object persistenceTemplate)
 {
     base.SerializeTemplate(template, persistenceTemplate);
 }
Esempio n. 16
0
        public override Model.ProvisioningTemplate ExtractObjects(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            if (creationInfo.IncludeSiteCollectionTermGroup || creationInfo.IncludeAllTermGroups)
            {
                // Find the site collection termgroup, if any
                TaxonomySession session   = TaxonomySession.GetTaxonomySession(web.Context);
                var             termStore = session.GetDefaultSiteCollectionTermStore();
                web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage);
                web.Context.ExecuteQueryRetry();

                List <TermGroup> termGroups = new List <TermGroup>();
                if (creationInfo.IncludeAllTermGroups)
                {
                    web.Context.Load(termStore.Groups, groups => groups.Include(tg => tg.Name,
                                                                                tg => tg.Id,
                                                                                tg => tg.Description,
                                                                                tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.CustomSortOrder)));
                    web.Context.ExecuteQueryRetry();
                    termGroups = termStore.Groups.ToList();
                }
                else
                {
                    var propertyBagKey = string.Format("SiteCollectionGroupId{0}", termStore.Id);

                    var siteCollectionTermGroupId = web.GetPropertyBagValueString(propertyBagKey, "");

                    Guid termGroupGuid = Guid.Empty;
                    if (Guid.TryParse(siteCollectionTermGroupId, out termGroupGuid))
                    {
                        var termGroup = termStore.GetGroup(termGroupGuid);
                        web.Context.Load(termGroup,
                                         tg => tg.Name,
                                         tg => tg.Id,
                                         tg => tg.Description,
                                         tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.CustomSortOrder));

                        web.Context.ExecuteQueryRetry();

                        termGroups = new List <TermGroup>()
                        {
                            termGroup
                        };
                    }
                }

                foreach (var termGroup in termGroups)
                {
                    var modelTermGroup = new Model.TermGroup
                    {
                        Name        = termGroup.Name,
                        Id          = termGroup.Id,
                        Description = termGroup.Description
                    };

                    foreach (var termSet in termGroup.TermSets)
                    {
                        var modelTermSet = new Model.TermSet();
                        modelTermSet.Name = termSet.Name;
                        modelTermSet.Id   = termSet.Id;
                        modelTermSet.IsAvailableForTagging = termSet.IsAvailableForTagging;
                        modelTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                        modelTermSet.Description           = termSet.Description;
                        modelTermSet.Terms.AddRange(GetTerms <TermSet>(web.Context, termSet, termStore.DefaultLanguage));
                        foreach (var property in termSet.CustomProperties)
                        {
                            modelTermSet.Properties.Add(property.Key, property.Value);
                        }
                        modelTermGroup.TermSets.Add(modelTermSet);
                    }

                    template.TermGroups.Add(modelTermGroup);
                }
            }
            return(template);
        }
Esempio n. 17
0
        public override TokenParser ProvisionObjects(Web web, Model.ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);

                var termStore = taxSession.GetDefaultKeywordsTermStore();

                web.Context.Load(termStore,
                                 ts => ts.DefaultLanguage,
                                 ts => ts.Groups.Include(
                                     tg => tg.Name,
                                     tg => tg.Id,
                                     tg => tg.TermSets.Include(
                                         tset => tset.Name,
                                         tset => tset.Id)));
                web.Context.ExecuteQueryRetry();

                SiteCollectionTermGroupNameToken siteCollectionTermGroupNameToken = new SiteCollectionTermGroupNameToken(web);
                foreach (var modelTermGroup in template.TermGroups)
                {
                    #region Group

                    var newGroup = false;

                    TermGroup group = termStore.Groups.FirstOrDefault(
                        g => g.Id == modelTermGroup.Id || g.Name == modelTermGroup.Name);
                    if (group == null)
                    {
                        if (modelTermGroup.Name == "Site Collection" ||
                            parser.ParseString(modelTermGroup.Name) == siteCollectionTermGroupNameToken.GetReplaceValue() ||
                            modelTermGroup.SiteCollectionTermGroup)
                        {
                            var site = (web.Context as ClientContext).Site;
                            group = termStore.GetSiteCollectionGroup(site, true);
                            web.Context.Load(group, g => g.Name, g => g.Id, g => g.TermSets.Include(
                                                 tset => tset.Name,
                                                 tset => tset.Id));
                            web.Context.ExecuteQueryRetry();
                        }
                        else
                        {
                            var parsedGroupName = parser.ParseString(modelTermGroup.Name);
                            group = termStore.Groups.FirstOrDefault(g => g.Name == parsedGroupName);

                            if (group == null)
                            {
                                if (modelTermGroup.Id == Guid.Empty)
                                {
                                    modelTermGroup.Id = Guid.NewGuid();
                                }
                                group = termStore.CreateGroup(parsedGroupName, modelTermGroup.Id);

                                group.Description = modelTermGroup.Description;

                                #if !ONPREMISES
                                // Handle TermGroup Contributors, if any
                                if (modelTermGroup.Contributors != null && modelTermGroup.Contributors.Count > 0)
                                {
                                    foreach (var c in modelTermGroup.Contributors)
                                    {
                                        group.AddContributor(c.Name);
                                    }
                                }

                                // Handle TermGroup Managers, if any
                                if (modelTermGroup.Managers != null && modelTermGroup.Managers.Count > 0)
                                {
                                    foreach (var m in modelTermGroup.Managers)
                                    {
                                        group.AddGroupManager(m.Name);
                                    }
                                }
                                #endif

                                termStore.CommitAll();
                                web.Context.Load(group);
                                web.Context.ExecuteQueryRetry();

                                newGroup = true;
                            }
                        }
                    }

                    #endregion

                    #region TermSets

                    foreach (var modelTermSet in modelTermGroup.TermSets)
                    {
                        TermSet set        = null;
                        var     newTermSet = false;
                        if (!newGroup)
                        {
                            set = group.TermSets.FirstOrDefault(ts => ts.Id == modelTermSet.Id || ts.Name == modelTermSet.Name);
                        }
                        if (set == null)
                        {
                            if (modelTermSet.Id == Guid.Empty)
                            {
                                modelTermSet.Id = Guid.NewGuid();
                            }
                            set = group.CreateTermSet(parser.ParseString(modelTermSet.Name), modelTermSet.Id, modelTermSet.Language ?? termStore.DefaultLanguage);
                            parser.AddToken(new TermSetIdToken(web, group.Name, modelTermSet.Name, modelTermSet.Id));
                            newTermSet                = true;
                            set.Description           = modelTermSet.Description;
                            set.IsOpenForTermCreation = modelTermSet.IsOpenForTermCreation;
                            set.IsAvailableForTagging = modelTermSet.IsAvailableForTagging;
                            foreach (var property in modelTermSet.Properties)
                            {
                                set.SetCustomProperty(property.Key, parser.ParseString(property.Value));
                            }
                            if (modelTermSet.Owner != null)
                            {
                                set.Owner = modelTermSet.Owner;
                            }
                            termStore.CommitAll();
                            web.Context.Load(set);
                            web.Context.ExecuteQueryRetry();
                        }

                        web.Context.Load(set, s => s.Terms.Include(t => t.Id, t => t.Name));
                        web.Context.ExecuteQueryRetry();
                        var terms = set.Terms;

                        foreach (var modelTerm in modelTermSet.Terms)
                        {
                            if (!newTermSet)
                            {
                                if (terms.Any())
                                {
                                    var term = terms.FirstOrDefault(t => t.Id == modelTerm.Id);
                                    if (term == null)
                                    {
                                        term = terms.FirstOrDefault(t => t.Name == modelTerm.Name);
                                        if (term == null)
                                        {
                                            var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                            modelTerm.Id = returnTuple.Item1;
                                            parser       = returnTuple.Item2;
                                        }
                                        else
                                        {
                                            modelTerm.Id = term.Id;
                                        }
                                    }
                                    else
                                    {
                                        modelTerm.Id = term.Id;
                                    }
                                }
                                else
                                {
                                    var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                    modelTerm.Id = returnTuple.Item1;
                                    parser       = returnTuple.Item2;
                                }
                            }
                            else
                            {
                                var returnTuple = CreateTerm <TermSet>(web, modelTerm, set, termStore, parser, scope);
                                modelTerm.Id = returnTuple.Item1;
                                parser       = returnTuple.Item2;
                            }
                        }

                        // do we need custom sorting?
                        if (modelTermSet.Terms.Any(t => t.CustomSortOrder > -1))
                        {
                            var sortedTerms = modelTermSet.Terms.OrderBy(t => t.CustomSortOrder);

                            var customSortString = sortedTerms.Aggregate(string.Empty, (a, i) => a + i.Id.ToString() + ":");
                            customSortString = customSortString.TrimEnd(new[] { ':' });

                            set.CustomSortOrder = customSortString;
                            termStore.CommitAll();
                            web.Context.ExecuteQueryRetry();
                        }
                    }

                    #endregion
                }
            }
            return(parser);
        }
Esempio n. 18
0
 public override Model.ProvisioningTemplate CreateEntities(Microsoft.SharePoint.Client.Web web, Model.ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
 {
     return(template);
 }
Esempio n. 19
0
 public override void ProvisionObjects(Microsoft.SharePoint.Client.Web web, Model.ProvisioningTemplate template)
 {
     ProcessLookupFields(web, template);
 }
 protected override void DeserializeTemplate(object persistenceTemplate, Model.ProvisioningTemplate template)
 {
     base.DeserializeTemplate(persistenceTemplate, template);
 }
        public override CanProvisionResult CanProvision(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            // Prepare the default output
            var result = new CanProvisionResult();

#if !ONPREMISES
            Model.ProvisioningTemplate targetTemplate = null;

            if (template.ParentHierarchy != null)
            {
                // If we have a hierarchy, search for a template with Taxonomy settings, if any
                targetTemplate = template.ParentHierarchy.Templates.FirstOrDefault(t => t.TermGroups.Count > 0);

                if (targetTemplate == null)
                {
                    // or use the first in the hierarchy
                    targetTemplate = template.ParentHierarchy.Templates[0];
                }
            }
            else
            {
                // Otherwise, use the provided template
                targetTemplate = template;
            }


            // Verify if we need the Term Store permissions (i.e. the template contains term groups to provision, or sequences with TermStore settings)
            if ((targetTemplate.TermGroups != null && targetTemplate.TermGroups?.Count > 0) ||
                targetTemplate.ParentHierarchy.Sequences.Any(
                    s => s.TermStore?.TermGroups != null && s.TermStore?.TermGroups?.Count > 0))
            {
                using (var scope = new PnPMonitoredScope(this.Name))
                {
                    try
                    {
                        // Try to access the Term Store
                        TaxonomySession taxSession = TaxonomySession.GetTaxonomySession(web.Context);
                        TermStore       termStore  = taxSession.GetDefaultKeywordsTermStore();
                        web.Context.Load(termStore,
                                         ts => ts.Languages,
                                         ts => ts.DefaultLanguage,
                                         ts => ts.Groups.Include(
                                             tg => tg.Name,
                                             tg => tg.Id,
                                             tg => tg.TermSets.Include(
                                                 tset => tset.Name,
                                                 tset => tset.Id)));
                        var siteCollectionTermGroup = termStore.GetSiteCollectionGroup((web.Context as ClientContext).Site, false);
                        web.Context.Load(siteCollectionTermGroup);
                        web.Context.ExecuteQueryRetry();

                        var termGroupId = Guid.NewGuid();
                        var group       = termStore.CreateGroup($"Temp-{termGroupId.ToString()}", termGroupId);
                        termStore.CommitAll();
                        web.Context.Load(group);
                        web.Context.ExecuteQueryRetry();

                        // Now delete the just created termGroup, to cleanup the Term Store
                        group.DeleteObject();
                        web.Context.ExecuteQueryRetry();
                    }
                    catch (Exception ex)
                    {
                        // And if we fail, raise a CanProvisionIssue
                        result.CanProvision = false;
                        result.Issues.Add(new CanProvisionIssue()
                        {
                            Source              = this.Name,
                            Tag                 = CanProvisionIssueTags.MISSING_TERMSTORE_PERMISSIONS,
                            Message             = CanProvisionIssuesMessages.Term_Store_Not_Admin,
                            ExceptionMessage    = ex.Message,    // Here we have a specific exception
                            ExceptionStackTrace = ex.StackTrace, // Here we have a specific exception
                        });
                    }
                }
            }
#else
            result.CanProvision = false;
#endif
            return(result);
        }
        public Model.ProvisioningTemplate ToProvisioningTemplate(Stream template, String identifier)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            // Crate a copy of the source stream
            MemoryStream sourceStream = new MemoryStream();
            template.CopyTo(sourceStream);
            sourceStream.Position = 0;

            // Check the provided template against the XML schema
            if (!this.IsValid(sourceStream))
            {
                // TODO: Use resource file
                throw new ApplicationException("The provided template is not valid!");
            }

            sourceStream.Position = 0;
            XDocument xml = XDocument.Load(sourceStream);
            XNamespace pnp = XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2016_12;

            // Prepare a variable to hold the single source formatted template
            V201612.ProvisioningTemplate source = null;

            // Prepare a variable to hold the resulting ProvisioningTemplate instance
            Model.ProvisioningTemplate result = new Model.ProvisioningTemplate();

            // Determine if we're working on a wrapped SharePointProvisioningTemplate or not
            if (xml.Root.Name == pnp + "Provisioning")
            {
                // Deserialize the whole wrapper
                V201612.Provisioning wrappedResult = XMLSerializer.Deserialize<V201612.Provisioning>(xml);

                // Handle the wrapper schema parameters
                if (wrappedResult.Preferences != null &&
                    wrappedResult.Preferences.Parameters != null &&
                    wrappedResult.Preferences.Parameters.Length > 0)
                {
                    foreach (var parameter in wrappedResult.Preferences.Parameters)
                    {
                        result.Parameters.Add(parameter.Key, parameter.Text != null ? parameter.Text.Aggregate(String.Empty, (acc, i) => acc + i) : null);
                    }
                }

                // Handle Localizations
                if (wrappedResult.Localizations != null)
                {
                    result.Localizations.AddRange(
                        from l in wrappedResult.Localizations
                        select new Localization
                        {
                            LCID = l.LCID,
                            Name = l.Name,
                            ResourceFile = l.ResourceFile,
                        });
                }

                foreach (var templates in wrappedResult.Templates)
                {
                    // Let's see if we have an in-place template with the provided ID or if we don't have a provided ID at all
                    source = templates.ProvisioningTemplate.FirstOrDefault(spt => spt.ID == identifier || String.IsNullOrEmpty(identifier));

                    // If we don't have a template, but there are external file references
                    if (source == null && templates.ProvisioningTemplateFile.Length > 0)
                    {
                        // Otherwise let's see if we have an external file for the template
                        var externalSource = templates.ProvisioningTemplateFile.FirstOrDefault(sptf => sptf.ID == identifier);

                        Stream externalFileStream = this._provider.Connector.GetFileStream(externalSource.File);
                        xml = XDocument.Load(externalFileStream);

                        if (xml.Root.Name != pnp + "ProvisioningTemplate")
                        {
                            throw new ApplicationException("Invalid external file format. Expected a ProvisioningTemplate file!");
                        }
                        else
                        {
                            source = XMLSerializer.Deserialize<V201612.ProvisioningTemplate>(xml);
                        }
                    }

                    if (source != null)
                    {
                        break;
                    }
                }
            }
            else if (xml.Root.Name == pnp + "ProvisioningTemplate")
            {
                var IdAttribute = xml.Root.Attribute("ID");

                // If there is a provided ID, and if it doesn't equal the current ID
                if (!String.IsNullOrEmpty(identifier) &&
                    IdAttribute != null &&
                    IdAttribute.Value != identifier)
                {
                    // TODO: Use resource file
                    throw new ApplicationException("The provided template identifier is not available!");
                }
                else
                {
                    source = XMLSerializer.Deserialize<V201612.ProvisioningTemplate>(xml);
                }
            }

            #region Basic Properties

            // Translate basic properties
            result.Id = source.ID;
            result.Version = (Double)source.Version;
            result.SitePolicy = source.SitePolicy;
            result.ImagePreviewUrl = source.ImagePreviewUrl;
            result.DisplayName = source.DisplayName;
            result.Description = source.Description;
            result.BaseSiteTemplate = source.BaseSiteTemplate;

            if (source.Properties != null && source.Properties.Length > 0)
            {
                result.Properties.AddRange(
                    (from p in source.Properties
                     select p).ToDictionary(i => i.Key, i => i.Value));
            }

            #endregion

            #region Property Bag

            // Translate PropertyBagEntries, if any
            if (source.PropertyBagEntries != null)
            {
                result.PropertyBagEntries.AddRange(
                    from bag in source.PropertyBagEntries
                    select new Model.PropertyBagEntry
                    {
                        Key = bag.Key,
                        Value = bag.Value,
                        Indexed = bag.Indexed,
                        Overwrite = bag.OverwriteSpecified ? bag.Overwrite : false,
                    });
            }

            #endregion

            #region Web Settings

            if (source.WebSettings != null)
            {
                result.WebSettings = new Model.WebSettings
                {
                    NoCrawl = source.WebSettings.NoCrawlSpecified ? source.WebSettings.NoCrawl : false,
                    RequestAccessEmail = source.WebSettings.RequestAccessEmail,
                    WelcomePage = source.WebSettings.WelcomePage,
                    Title = source.WebSettings.Title,
                    Description = source.WebSettings.Description,
                    SiteLogo = source.WebSettings.SiteLogo,
                    AlternateCSS = source.WebSettings.AlternateCSS,
                    MasterPageUrl = source.WebSettings.MasterPageUrl,
                    CustomMasterPageUrl = source.WebSettings.CustomMasterPageUrl,
                };
            }

            #endregion

            #region Regional Settings

            if (source.RegionalSettings != null)
            {
                result.RegionalSettings = new Model.RegionalSettings()
                {
                    AdjustHijriDays = source.RegionalSettings.AdjustHijriDaysSpecified ? source.RegionalSettings.AdjustHijriDays : 0,
                    AlternateCalendarType = source.RegionalSettings.AlternateCalendarTypeSpecified ? source.RegionalSettings.AlternateCalendarType.FromSchemaToTemplateCalendarTypeV201612() : Microsoft.SharePoint.Client.CalendarType.None,
                    CalendarType = source.RegionalSettings.CalendarTypeSpecified ? source.RegionalSettings.CalendarType.FromSchemaToTemplateCalendarTypeV201612() : Microsoft.SharePoint.Client.CalendarType.None,
                    Collation = source.RegionalSettings.CollationSpecified ? source.RegionalSettings.Collation : 0,
                    FirstDayOfWeek = source.RegionalSettings.FirstDayOfWeekSpecified ?
                        (System.DayOfWeek)Enum.Parse(typeof(System.DayOfWeek), source.RegionalSettings.FirstDayOfWeek.ToString()) : System.DayOfWeek.Sunday,
                    FirstWeekOfYear = source.RegionalSettings.FirstWeekOfYearSpecified ? source.RegionalSettings.FirstWeekOfYear : 0,
                    LocaleId = source.RegionalSettings.LocaleIdSpecified ? source.RegionalSettings.LocaleId : 1033,
                    ShowWeeks = source.RegionalSettings.ShowWeeksSpecified ? source.RegionalSettings.ShowWeeks : false,
                    Time24 = source.RegionalSettings.Time24Specified ? source.RegionalSettings.Time24 : false,
                    TimeZone = !String.IsNullOrEmpty(source.RegionalSettings.TimeZone) ? Int32.Parse(source.RegionalSettings.TimeZone) : 0,
                    WorkDayEndHour = source.RegionalSettings.WorkDayEndHourSpecified ? source.RegionalSettings.WorkDayEndHour.FromSchemaToTemplateWorkHourV201612() : Model.WorkHour.PM0600,
                    WorkDays = source.RegionalSettings.WorkDaysSpecified ? source.RegionalSettings.WorkDays : 5,
                    WorkDayStartHour = source.RegionalSettings.WorkDayStartHourSpecified ? source.RegionalSettings.WorkDayStartHour.FromSchemaToTemplateWorkHourV201612() : Model.WorkHour.AM0900,
                };
            }
            else
            {
                result.RegionalSettings = null;
            }

            #endregion

            #region Supported UI Languages

            if (source.SupportedUILanguages != null && source.SupportedUILanguages.Length > 0)
            {
                result.SupportedUILanguages.AddRange(
                    from l in source.SupportedUILanguages
                    select new SupportedUILanguage
                    {
                        LCID = l.LCID,
                    });
            }

            #endregion

            #region Audit Settings

            if (source.AuditSettings != null)
            {
                result.AuditSettings = new Model.AuditSettings
                {
                    AuditLogTrimmingRetention = source.AuditSettings.AuditLogTrimmingRetentionSpecified ? source.AuditSettings.AuditLogTrimmingRetention : 0,
                    TrimAuditLog = source.AuditSettings.TrimAuditLogSpecified ? source.AuditSettings.TrimAuditLog : false,
                    AuditFlags = source.AuditSettings.Audit.Aggregate(Microsoft.SharePoint.Client.AuditMaskType.None, (acc, next) => acc |= (Microsoft.SharePoint.Client.AuditMaskType)Enum.Parse(typeof(Microsoft.SharePoint.Client.AuditMaskType), next.AuditFlag.ToString())),
                };
            }

            #endregion

            #region Security

            // Translate Security configuration, if any
            if (source.Security != null)
            {
                result.Security.BreakRoleInheritance = source.Security.BreakRoleInheritance;
                result.Security.CopyRoleAssignments = source.Security.CopyRoleAssignments;
                result.Security.ClearSubscopes = source.Security.ClearSubscopes;

                if (source.Security.AdditionalAdministrators != null)
                {
                    result.Security.AdditionalAdministrators.AddRange(
                        from user in source.Security.AdditionalAdministrators
                        select new Model.User
                        {
                            Name = user.Name,
                        });
                }
                if (source.Security.AdditionalOwners != null)
                {
                    result.Security.AdditionalOwners.AddRange(
                        from user in source.Security.AdditionalOwners
                        select new Model.User
                        {
                            Name = user.Name,
                        });
                }
                if (source.Security.AdditionalMembers != null)
                {
                    result.Security.AdditionalMembers.AddRange(
                        from user in source.Security.AdditionalMembers
                        select new Model.User
                        {
                            Name = user.Name,
                        });
                }
                if (source.Security.AdditionalVisitors != null)
                {
                    result.Security.AdditionalVisitors.AddRange(
                        from user in source.Security.AdditionalVisitors
                        select new Model.User
                        {
                            Name = user.Name,
                        });
                }
                if (source.Security.SiteGroups != null)
                {
                    result.Security.SiteGroups.AddRange(
                        from g in source.Security.SiteGroups
                        select new Model.SiteGroup(g.Members != null ? from m in g.Members select new Model.User { Name = m.Name } : null)
                        {
                            AllowMembersEditMembership = g.AllowMembersEditMembershipSpecified ? g.AllowMembersEditMembership : false,
                            AllowRequestToJoinLeave = g.AllowRequestToJoinLeaveSpecified ? g.AllowRequestToJoinLeave : false,
                            AutoAcceptRequestToJoinLeave = g.AutoAcceptRequestToJoinLeaveSpecified ? g.AutoAcceptRequestToJoinLeave : false,
                            Description = g.Description,
                            OnlyAllowMembersViewMembership = g.OnlyAllowMembersViewMembershipSpecified ? g.OnlyAllowMembersViewMembership : false,
                            Owner = g.Owner,
                            RequestToJoinLeaveEmailSetting = g.RequestToJoinLeaveEmailSetting,
                            Title = g.Title,
                        });
                }
                if (source.Security.Permissions != null)
                {
                    if (source.Security.Permissions.RoleAssignments != null && source.Security.Permissions.RoleAssignments.Length > 0)
                    {
                        result.Security.SiteSecurityPermissions.RoleAssignments.AddRange
                            (from ra in source.Security.Permissions.RoleAssignments
                             select new Model.RoleAssignment
                             {
                                 Principal = ra.Principal,
                                 RoleDefinition = ra.RoleDefinition,
                             });
                    }
                    if (source.Security.Permissions.RoleDefinitions != null && source.Security.Permissions.RoleDefinitions.Length > 0)
                    {
                        result.Security.SiteSecurityPermissions.RoleDefinitions.AddRange
                            (from rd in source.Security.Permissions.RoleDefinitions
                             select new Model.RoleDefinition(
                                 from p in rd.Permissions
                                 select (Microsoft.SharePoint.Client.PermissionKind)Enum.Parse(typeof(Microsoft.SharePoint.Client.PermissionKind), p.ToString()))
                             {
                                 Description = rd.Description,
                                 Name = rd.Name,
                             });
                    }
                }
            }

            #endregion

            #region Navigation

            if (source.Navigation != null)
            {
                result.Navigation = new Model.Navigation(
                    source.Navigation.GlobalNavigation != null ?
                        new GlobalNavigation(
                            (GlobalNavigationType)Enum.Parse(typeof(GlobalNavigationType), source.Navigation.GlobalNavigation.NavigationType.ToString()),
                            source.Navigation.GlobalNavigation.StructuralNavigation != null ?
                                new Model.StructuralNavigation
                                {
                                    RemoveExistingNodes = source.Navigation.GlobalNavigation.StructuralNavigation.RemoveExistingNodes,
                                } : null,
                            source.Navigation.GlobalNavigation.ManagedNavigation != null ?
                                new Model.ManagedNavigation
                                {
                                    TermSetId = source.Navigation.GlobalNavigation.ManagedNavigation.TermSetId,
                                    TermStoreId = source.Navigation.GlobalNavigation.ManagedNavigation.TermStoreId,
                                } : null
                        )
                        : null,
                    source.Navigation.CurrentNavigation != null ?
                        new CurrentNavigation(
                            (CurrentNavigationType)Enum.Parse(typeof(CurrentNavigationType), source.Navigation.CurrentNavigation.NavigationType.ToString()),
                            source.Navigation.CurrentNavigation.StructuralNavigation != null ?
                                new Model.StructuralNavigation
                                {
                                    RemoveExistingNodes = source.Navigation.CurrentNavigation.StructuralNavigation.RemoveExistingNodes,
                                } : null,
                            source.Navigation.CurrentNavigation.ManagedNavigation != null ?
                                new Model.ManagedNavigation
                                {
                                    TermSetId = source.Navigation.CurrentNavigation.ManagedNavigation.TermSetId,
                                    TermStoreId = source.Navigation.CurrentNavigation.ManagedNavigation.TermStoreId,
                                } : null
                        )
                        : null
                    );

                // If I need to update the Global Structural Navigation nodes
                if (result.Navigation.GlobalNavigation != null &&
                    result.Navigation.GlobalNavigation.StructuralNavigation != null &&
                    source.Navigation.GlobalNavigation != null &&
                    source.Navigation.GlobalNavigation.StructuralNavigation != null)
                {
                    result.Navigation.GlobalNavigation.StructuralNavigation.NavigationNodes.AddRange(
                        from n in source.Navigation.GlobalNavigation.StructuralNavigation.NavigationNode
                        select n.FromSchemaNavigationNodeToModelNavigationNodeV201612()
                        );
                }

                // If I need to update the Current Structural Navigation nodes
                if (result.Navigation.CurrentNavigation != null &&
                    result.Navigation.CurrentNavigation.StructuralNavigation != null &&
                    source.Navigation.CurrentNavigation != null &&
                    source.Navigation.CurrentNavigation.StructuralNavigation != null)
                {
                    result.Navigation.CurrentNavigation.StructuralNavigation.NavigationNodes.AddRange(
                        from n in source.Navigation.CurrentNavigation.StructuralNavigation.NavigationNode
                        select n.FromSchemaNavigationNodeToModelNavigationNodeV201612()
                        );
                }
            }

            #endregion

            #region Site Columns

            // Translate Site Columns (Fields), if any
            if ((source.SiteFields != null) && (source.SiteFields.Any != null))
            {
                result.SiteFields.AddRange(
                    from field in source.SiteFields.Any
                    select new Model.Field
                    {
                        SchemaXml = field.OuterXml,
                    });
            }

            #endregion

            #region Content Types

            // Translate ContentTypes, if any
            if ((source.ContentTypes != null) && (source.ContentTypes != null))
            {
                result.ContentTypes.AddRange(
                    from contentType in source.ContentTypes
                    select new ContentType(
                        contentType.ID,
                        contentType.Name,
                        contentType.Description,
                        contentType.Group,
                        contentType.Sealed,
                        contentType.Hidden,
                        contentType.ReadOnly,
                        (contentType.DocumentTemplate != null ?
                            contentType.DocumentTemplate.TargetName : null),
                        contentType.Overwrite,
                        (contentType.FieldRefs != null ?
                            (from fieldRef in contentType.FieldRefs
                             select new Model.FieldRef(fieldRef.Name)
                             {
                                 Id = Guid.Parse(fieldRef.ID),
                                 Hidden = fieldRef.Hidden,
                                 Required = fieldRef.Required
                             }) : null)
                        )
                    {
                        DocumentSetTemplate = contentType.DocumentSetTemplate != null ?
                            new Model.DocumentSetTemplate(
                                contentType.DocumentSetTemplate.WelcomePage,
                                contentType.DocumentSetTemplate.AllowedContentTypes != null ?
                                    (from act in contentType.DocumentSetTemplate.AllowedContentTypes
                                     select act.ContentTypeID) : null,
                                contentType.DocumentSetTemplate.DefaultDocuments != null ?
                                    (from dd in contentType.DocumentSetTemplate.DefaultDocuments
                                     select new Model.DefaultDocument
                                     {
                                         ContentTypeId = dd.ContentTypeID,
                                         FileSourcePath = dd.FileSourcePath,
                                         Name = dd.Name,
                                     }) : null,
                                contentType.DocumentSetTemplate.SharedFields != null ?
                                    (from sf in contentType.DocumentSetTemplate.SharedFields
                                     select Guid.Parse(sf.ID)) : null,
                                contentType.DocumentSetTemplate.WelcomePageFields != null ?
                                    (from wpf in contentType.DocumentSetTemplate.WelcomePageFields
                                     select Guid.Parse(wpf.ID)) : null
                                ) : null,
                        DisplayFormUrl = contentType.DisplayFormUrl,
                        EditFormUrl = contentType.EditFormUrl,
                        NewFormUrl = contentType.NewFormUrl,
                    }
                );
            }

            #endregion

            #region List Instances

            // Translate Lists Instances, if any
            if (source.Lists != null)
            {
                result.Lists.AddRange(
                    from list in source.Lists
                    select new Model.ListInstance(
                        (list.ContentTypeBindings != null ?
                                (from contentTypeBinding in list.ContentTypeBindings
                                 select new Model.ContentTypeBinding
                                 {
                                     ContentTypeId = contentTypeBinding.ContentTypeID,
                                     Default = contentTypeBinding.Default,
                                     Remove = contentTypeBinding.Remove,
                                 }) : null),
                        (list.Views != null ?
                                (from view in list.Views.Any
                                 select new Model.View
                                 {
                                     SchemaXml = view.OuterXml,
                                 }) : null),
                        (list.Fields != null ?
                                (from field in list.Fields.Any
                                 select new Model.Field
                                 {
                                     SchemaXml = field.OuterXml,
                                 }) : null),
                        (list.FieldRefs != null ?
                                    (from fieldRef in list.FieldRefs
                                     select new Model.FieldRef(fieldRef.Name)
                                     {
                                         DisplayName = fieldRef.DisplayName,
                                         Hidden = fieldRef.Hidden,
                                         Required = fieldRef.Required,
                                         Id = Guid.Parse(fieldRef.ID)
                                     }) : null),
                        (list.DataRows != null ?
                                    (from dataRow in list.DataRows
                                     select new Model.DataRow(
                                 (from dataValue in dataRow.DataValue
                                  select dataValue).ToDictionary(k => k.FieldName, v => v.Value),
                                 dataRow.Security.FromSchemaToTemplateObjectSecurityV201612()
                             )).ToList() : null),
                        (list.FieldDefaults != null ?
                            (from fd in list.FieldDefaults
                             select fd).ToDictionary(k => k.FieldName, v => v.Value) : null),
                        list.Security.FromSchemaToTemplateObjectSecurityV201612(),
                        (list.Folders != null ?
                            (new List<Model.Folder>(from folder in list.Folders
                                                    select folder.FromSchemaToTemplateFolderV201612())) : null),
                        (list.UserCustomActions != null ?
                            (new List<Model.CustomAction>(
                                from customAction in list.UserCustomActions
                                select new Model.CustomAction
                                {
                                    CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
                                        (new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
                                    Description = customAction.Description,
                                    Enabled = customAction.Enabled,
                                    Group = customAction.Group,
                                    ImageUrl = customAction.ImageUrl,
                                    Location = customAction.Location,
                                    Name = customAction.Name,
                                    Rights = customAction.Rights.ToBasePermissionsV201612(),
                                    ScriptBlock = customAction.ScriptBlock,
                                    ScriptSrc = customAction.ScriptSrc,
                                    RegistrationId = customAction.RegistrationId,
                                    RegistrationType = (UserCustomActionRegistrationType)Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType.ToString(), true),
                                    Remove = customAction.Remove,
                                    Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
                                    Title = customAction.Title,
                                    Url = customAction.Url,
                                })) : null)
                        )
                    {
                        ContentTypesEnabled = list.ContentTypesEnabled,
                        Description = list.Description,
                        DocumentTemplate = list.DocumentTemplate,
                        EnableVersioning = list.EnableVersioning,
                        EnableMinorVersions = list.EnableMinorVersions,
                        DraftVersionVisibility = list.DraftVersionVisibility,
                        EnableModeration = list.EnableModeration,
                        Hidden = list.Hidden,
                        MinorVersionLimit = list.MinorVersionLimitSpecified ? list.MinorVersionLimit : 0,
                        MaxVersionLimit = list.MaxVersionLimitSpecified ? list.MaxVersionLimit : 0,
                        OnQuickLaunch = list.OnQuickLaunch,
                        EnableAttachments = list.EnableAttachments,
                        EnableFolderCreation = list.EnableFolderCreation,
                        ForceCheckout = list.ForceCheckout,
                        RemoveExistingContentTypes = list.RemoveExistingContentTypes,
                        TemplateFeatureID = !String.IsNullOrEmpty(list.TemplateFeatureID) ? Guid.Parse(list.TemplateFeatureID) : Guid.Empty,
                        RemoveExistingViews = list.Views != null ? list.Views.RemoveExistingViews : false,
                        TemplateType = list.TemplateType,
                        Title = list.Title,
                        Url = list.Url,
                    });
            }

            #endregion

            #region Features

            // Translate Features, if any
            if (source.Features != null)
            {
                if (result.Features.SiteFeatures != null && source.Features.SiteFeatures != null)
                {
                    result.Features.SiteFeatures.AddRange(
                        from feature in source.Features.SiteFeatures
                        select new Model.Feature
                        {
                            Id = new Guid(feature.ID),
                            Deactivate = feature.Deactivate,
                        });
                }
                if (result.Features.WebFeatures != null && source.Features.WebFeatures != null)
                {
                    result.Features.WebFeatures.AddRange(
                        from feature in source.Features.WebFeatures
                        select new Model.Feature
                        {
                            Id = new Guid(feature.ID),
                            Deactivate = feature.Deactivate,
                        });
                }
            }

            #endregion

            #region Custom Actions

            // Translate CustomActions, if any
            if (source.CustomActions != null)
            {
                if (result.CustomActions.SiteCustomActions != null && source.CustomActions.SiteCustomActions != null)
                {
                    result.CustomActions.SiteCustomActions.AddRange(
                        from customAction in source.CustomActions.SiteCustomActions
                        select new Model.CustomAction
                        {
                            CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
                                (new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
                            Description = customAction.Description,
                            Enabled = customAction.Enabled,
                            Group = customAction.Group,
                            ImageUrl = customAction.ImageUrl,
                            Location = customAction.Location,
                            Name = customAction.Name,
                            Rights = customAction.Rights.ToBasePermissionsV201612(),
                            ScriptBlock = customAction.ScriptBlock,
                            ScriptSrc = customAction.ScriptSrc,
                            RegistrationId = customAction.RegistrationId,
                            RegistrationType = (UserCustomActionRegistrationType)Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType.ToString(), true),
                            Remove = customAction.Remove,
                            Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
                            Title = customAction.Title,
                            Url = customAction.Url,
                        });
                }
                if (result.CustomActions.WebCustomActions != null && source.CustomActions.WebCustomActions != null)
                {
                    result.CustomActions.WebCustomActions.AddRange(
                        from customAction in source.CustomActions.WebCustomActions
                        select new Model.CustomAction
                        {
                            CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
                                (new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
                            Description = customAction.Description,
                            Enabled = customAction.Enabled,
                            Group = customAction.Group,
                            ImageUrl = customAction.ImageUrl,
                            Location = customAction.Location,
                            Name = customAction.Name,
                            Rights = customAction.Rights.ToBasePermissionsV201612(),
                            ScriptBlock = customAction.ScriptBlock,
                            ScriptSrc = customAction.ScriptSrc,
                            RegistrationId = customAction.RegistrationId,
                            RegistrationType = (UserCustomActionRegistrationType)Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType.ToString(), true),
                            Remove = customAction.Remove,
                            Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
                            Title = customAction.Title,
                            Url = customAction.Url,
                        });
                }
            }

            #endregion

            #region Files

            // Translate Files and Directories, if any
            if (source.Files != null)
            {
                if (source.Files.File != null && source.Files.File.Length > 0)
                {
                    // Handle Files
                    result.Files.AddRange(
                        from file in source.Files.File
                        select new Model.File(file.Src,
                            file.Folder,
                            file.Overwrite,
                            file.WebParts != null ?
                                (from wp in file.WebParts
                                 select new Model.WebPart
                                 {
                                     Order = (uint)wp.Order,
                                     Zone = wp.Zone,
                                     Title = wp.Title,
                                     Contents = wp.Contents.InnerXml
                                 }) : null,
                            file.Properties != null ? file.Properties.ToDictionary(k => k.Key, v => v.Value) : null,
                            file.Security.FromSchemaToTemplateObjectSecurityV201612(),
                            file.LevelSpecified ?
                                (Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), file.Level.ToString()) :
                                Model.FileLevel.Draft
                            )
                        );
                }

                if (source.Files.Directory != null && source.Files.Directory.Length > 0)
                {
                    // Handle Directories of files
                    result.Directories.AddRange(
                        from dir in source.Files.Directory
                        select new Model.Directory(dir.Src,
                            dir.Folder,
                            dir.Overwrite,
                            dir.LevelSpecified ?
                                (Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), dir.Level.ToString()) :
                                Model.FileLevel.Draft,
                            dir.Recursive,
                            dir.IncludedExtensions,
                            dir.ExcludedExtensions,
                            dir.MetadataMappingFile,
                            dir.Security.FromSchemaToTemplateObjectSecurityV201612()
                            )
                        );
                }
            }

            #endregion

            #region Pages

            // Translate Pages, if any
            if (source.Pages != null)
            {
                foreach (var page in source.Pages)
                {

                    var pageLayout = WikiPageLayout.OneColumn;
                    switch (page.Layout)
                    {
                        case V201612.WikiPageLayout.OneColumn:
                            pageLayout = WikiPageLayout.OneColumn;
                            break;
                        case V201612.WikiPageLayout.OneColumnSidebar:
                            pageLayout = WikiPageLayout.OneColumnSideBar;
                            break;
                        case V201612.WikiPageLayout.TwoColumns:
                            pageLayout = WikiPageLayout.TwoColumns;
                            break;
                        case V201612.WikiPageLayout.TwoColumnsHeader:
                            pageLayout = WikiPageLayout.TwoColumnsHeader;
                            break;
                        case V201612.WikiPageLayout.TwoColumnsHeaderFooter:
                            pageLayout = WikiPageLayout.TwoColumnsHeaderFooter;
                            break;
                        case V201612.WikiPageLayout.ThreeColumns:
                            pageLayout = WikiPageLayout.ThreeColumns;
                            break;
                        case V201612.WikiPageLayout.ThreeColumnsHeader:
                            pageLayout = WikiPageLayout.ThreeColumnsHeader;
                            break;
                        case V201612.WikiPageLayout.ThreeColumnsHeaderFooter:
                            pageLayout = WikiPageLayout.ThreeColumnsHeaderFooter;
                            break;
                        case V201612.WikiPageLayout.Custom:
                            pageLayout = WikiPageLayout.Custom;
                            break;
                    }

                    result.Pages.Add(new Model.Page(page.Url, page.Overwrite, pageLayout,
                        (page.WebParts != null ?
                            (from wp in page.WebParts
                             select new Model.WebPart
                             {
                                 Title = wp.Title,
                                 Column = (uint)wp.Column,
                                 Row = (uint)wp.Row,
                                 Contents = wp.Contents.InnerXml
                             }).ToList() : null),
                        page.Security.FromSchemaToTemplateObjectSecurityV201612(),
                        (page.Fields != null && page.Fields.Length > 0) ?
                             (from f in page.Fields
                              select f).ToDictionary(i => i.FieldName, i => i.Value) : null
                        ));
                }
            }

            #endregion

            #region Taxonomy

            // Translate Termgroups, if any
            if (source.TermGroups != null)
            {
                result.TermGroups.AddRange(
                    from termGroup in source.TermGroups
                    select new Model.TermGroup(
                        !string.IsNullOrEmpty(termGroup.ID) ? Guid.Parse(termGroup.ID) : Guid.Empty,
                        termGroup.Name,
                        new List<Model.TermSet>(
                            from termSet in termGroup.TermSets
                            select new Model.TermSet(
                                !string.IsNullOrEmpty(termSet.ID) ? Guid.Parse(termSet.ID) : Guid.Empty,
                                termSet.Name,
                                termSet.LanguageSpecified ? (int?)termSet.Language : null,
                                termSet.IsAvailableForTagging,
                                termSet.IsOpenForTermCreation,
                                termSet.Terms != null ? termSet.Terms.FromSchemaTermsToModelTermsV201612() : null,
                                termSet.CustomProperties != null ? termSet.CustomProperties.ToDictionary(k => k.Key, v => v.Value) : null)
                            {
                                Description = termSet.Description,
                            }),
                        termGroup.SiteCollectionTermGroup,
                        termGroup.Contributors != null ? (from c in termGroup.Contributors
                                                          select new Model.User { Name = c.Name }).ToArray() : null,
                        termGroup.Managers != null ? (from m in termGroup.Managers
                                                      select new Model.User { Name = m.Name }).ToArray() : null
                        )
                    {
                        Description = termGroup.Description,
                    });
            }

            #endregion

            #region Composed Looks

            // Translate ComposedLook, if any
            if (source.ComposedLook != null)
            {
                result.ComposedLook.BackgroundFile = source.ComposedLook.BackgroundFile;
                result.ComposedLook.ColorFile = source.ComposedLook.ColorFile;
                result.ComposedLook.FontFile = source.ComposedLook.FontFile;
                result.ComposedLook.Name = source.ComposedLook.Name;
                result.ComposedLook.Version = source.ComposedLook.Version;
            }

            #endregion

            #region Workflows

            if (source.Workflows != null)
            {
                result.Workflows = new Model.Workflows(
                    (source.Workflows.WorkflowDefinitions != null &&
                    source.Workflows.WorkflowDefinitions.Length > 0) ?
                        (from wd in source.Workflows.WorkflowDefinitions
                         select new Model.WorkflowDefinition(
                             (wd.Properties != null && wd.Properties.Length > 0) ?
                             (from p in wd.Properties
                              select p).ToDictionary(i => i.Key, i => i.Value) : null)
                         {
                             AssociationUrl = wd.AssociationUrl,
                             Description = wd.Description,
                             DisplayName = wd.DisplayName,
                             DraftVersion = wd.DraftVersion,
                             FormField = wd.FormField != null ? wd.FormField.OuterXml : null,
                             Id = Guid.Parse(wd.Id),
                             InitiationUrl = wd.InitiationUrl,
                             Published = wd.PublishedSpecified ? wd.Published : false,
                             RequiresAssociationForm = wd.RequiresAssociationFormSpecified ? wd.RequiresAssociationForm : false,
                             RequiresInitiationForm = wd.RequiresInitiationFormSpecified ? wd.RequiresInitiationForm : false,
                             RestrictToScope = wd.RestrictToScope,
                             RestrictToType = wd.RestrictToType.ToString(),
                             XamlPath = wd.XamlPath,
                         }) : null,
                    (source.Workflows.WorkflowSubscriptions != null &&
                    source.Workflows.WorkflowSubscriptions.Length > 0) ?
                        (from ws in source.Workflows.WorkflowSubscriptions
                         select new Model.WorkflowSubscription(
                             (ws.PropertyDefinitions != null && ws.PropertyDefinitions.Length > 0) ?
                             (from pd in ws.PropertyDefinitions
                              select pd).ToDictionary(i => i.Key, i => i.Value) : null)
                         {
                             DefinitionId = Guid.Parse(ws.DefinitionId),
                             Enabled = ws.Enabled,
                             EventSourceId = ws.EventSourceId,
                             EventTypes = (new String[] {
                                ws.ItemAddedEvent? "ItemAdded" : null,
                                ws.ItemUpdatedEvent? "ItemUpdated" : null,
                                ws.WorkflowStartEvent? "WorkflowStart" : null }).Where(e => e != null).ToList(),
                             ListId = ws.ListId,
                             ManualStartBypassesActivationLimit = ws.ManualStartBypassesActivationLimitSpecified ? ws.ManualStartBypassesActivationLimit : false,
                             Name = ws.Name,
                             ParentContentTypeId = ws.ParentContentTypeId,
                             StatusFieldName = ws.StatusFieldName,
                         }) : null
                    );
            }

            #endregion

            #region Search Settings

            if (source.SearchSettings != null && source.SearchSettings.SiteSearchSettings != null)
            {
                result.SiteSearchSettings = source.SearchSettings.SiteSearchSettings.OuterXml;
            }

            if (source.SearchSettings != null && source.SearchSettings.WebSearchSettings != null)
            {
                result.WebSearchSettings = source.SearchSettings.WebSearchSettings.OuterXml;
            }

            #endregion

            #region Publishing

            if (source.Publishing != null)
            {
                result.Publishing = new Model.Publishing(
                    (Model.AutoCheckRequirementsOptions)Enum.Parse(typeof(Model.AutoCheckRequirementsOptions), source.Publishing.AutoCheckRequirements.ToString()),
                    source.Publishing.DesignPackage != null ?
                    new Model.DesignPackage
                    {
                        DesignPackagePath = source.Publishing.DesignPackage.DesignPackagePath,
                        MajorVersion = source.Publishing.DesignPackage.MajorVersionSpecified ? source.Publishing.DesignPackage.MajorVersion : 0,
                        MinorVersion = source.Publishing.DesignPackage.MinorVersionSpecified ? source.Publishing.DesignPackage.MinorVersion : 0,
                        PackageGuid = Guid.Parse(source.Publishing.DesignPackage.PackageGuid),
                        PackageName = source.Publishing.DesignPackage.PackageName,
                    } : null,
                    source.Publishing.AvailableWebTemplates != null && source.Publishing.AvailableWebTemplates.Length > 0 ?
                         (from awt in source.Publishing.AvailableWebTemplates
                          select new Model.AvailableWebTemplate
                          {
                              LanguageCode = awt.LanguageCodeSpecified ? awt.LanguageCode : 1033,
                              TemplateName = awt.TemplateName,
                          }) : null,
                    source.Publishing.PageLayouts != null && source.Publishing.PageLayouts.PageLayout != null && source.Publishing.PageLayouts.PageLayout.Length > 0 ?
                        (from pl in source.Publishing.PageLayouts.PageLayout
                         select new Model.PageLayout
                         {
                             IsDefault = pl.Path == source.Publishing.PageLayouts.Default,
                             Path = pl.Path,
                         }) : null,
                    source.Publishing.PublishingPages != null && source.Publishing.PublishingPages.Length > 0 ?
                        (from pp in source.Publishing.PublishingPages
                         select new Model.PublishingPage
                         {
                             FileName = pp.FileName,
                             Layout = pp.Layout,
                             Overwrite = pp.Overwrite,
                             Publish = pp.Publish,
                             Title = pp.Title,
                             WelcomePage = pp.WelcomePage,
                             Properties = pp.Properties != null ? pp.Properties.ToDictionary(k => k.Key, v => v.Value) : null,
                             WebParts =  pp.WebParts != null ?
                                (from wp in pp.WebParts
                                 select new Model.PublishingPageWebPart
                                 {
                                     DefaultViewDisplayName = wp.DefaultViewDisplayName,
                                     Order = (uint)wp.Order,
                                     Title = wp.Title,
                                     Contents = wp.Contents.OuterXml,
                                     Zone = wp.Zone,
                                 }).ToList() : null
                         }) : null
                    );
            }

            #endregion

            #region AddIns

            if (source.AddIns != null && source.AddIns.Length > 0)
            {
                result.AddIns.AddRange(
                     from addin in source.AddIns
                     select new Model.AddIn
                     {
                         PackagePath = addin.PackagePath,
                         Source = addin.Source.ToString(),
                     });
            }

            #endregion

            #region Providers

            // Translate Providers, if any
            if (source.Providers != null)
            {
                foreach (var provider in source.Providers)
                {
                    if (!String.IsNullOrEmpty(provider.HandlerType))
                    {
                        var handlerType = Type.GetType(provider.HandlerType, false);
                        if (handlerType != null)
                        {
                            result.ExtensibilityHandlers.Add(
                                new Model.ExtensibilityHandler
                                {
                                    Assembly = handlerType.Assembly.FullName,
                                    Type = handlerType.FullName,
                                    Configuration = provider.Configuration != null ? provider.Configuration.ToProviderConfiguration() : null,
                                    Enabled = provider.Enabled,
                                });
                        }
                    }
                }
            }

            #endregion

            return (result);
        }
Esempio n. 23
0
        public override Model.ProvisioningTemplate ExtractObjects(Web web, Model.ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (creationInfo.IncludeSiteCollectionTermGroup || creationInfo.IncludeAllTermGroups)
                {
                    // Find the site collection termgroup, if any
                    TaxonomySession session   = TaxonomySession.GetTaxonomySession(web.Context);
                    var             termStore = session.GetDefaultSiteCollectionTermStore();
                    web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage, t => t.OrphanedTermsTermSet);
                    web.Context.ExecuteQueryRetry();

                    var orphanedTermsTermSetId = termStore.OrphanedTermsTermSet.Id;
                    if (termStore.ServerObjectIsNull.Value)
                    {
                        termStore = session.GetDefaultKeywordsTermStore();
                        web.Context.Load(termStore, t => t.Id, t => t.DefaultLanguage);
                        web.Context.ExecuteQueryRetry();
                    }

                    var propertyBagKey = string.Format("SiteCollectionGroupId{0}", termStore.Id);

                    var siteCollectionTermGroupId = web.GetPropertyBagValueString(propertyBagKey, "");

                    Guid termGroupGuid = Guid.Empty;
                    Guid.TryParse(siteCollectionTermGroupId, out termGroupGuid);

                    List <TermGroup> termGroups = new List <TermGroup>();
                    if (creationInfo.IncludeAllTermGroups)
                    {
                        web.Context.Load(termStore.Groups, groups => groups.Include(tg => tg.Name,
                                                                                    tg => tg.Id,
                                                                                    tg => tg.Description,
                                                                                    tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.CustomSortOrder)));
                        web.Context.ExecuteQueryRetry();
                        termGroups = termStore.Groups.ToList();
                    }
                    else
                    {
                        if (termGroupGuid != Guid.Empty)
                        {
                            var termGroup = termStore.GetGroup(termGroupGuid);
                            web.Context.Load(termGroup,
                                             tg => tg.Name,
                                             tg => tg.Id,
                                             tg => tg.Description,
                                             tg => tg.TermSets.IncludeWithDefaultProperties(ts => ts.CustomSortOrder));

                            web.Context.ExecuteQueryRetry();

                            termGroups = new List <TermGroup>()
                            {
                                termGroup
                            };
                        }
                    }

                    foreach (var termGroup in termGroups)
                    {
                        Boolean isSiteCollectionTermGroup = termGroupGuid != Guid.Empty && termGroup.Id == termGroupGuid;

                        var modelTermGroup = new Model.TermGroup
                        {
                            Name        = isSiteCollectionTermGroup ? "{sitecollectiontermgroupname}" : termGroup.Name,
                            Id          = isSiteCollectionTermGroup ? Guid.Empty : termGroup.Id,
                            Description = termGroup.Description
                        };

                        foreach (var termSet in termGroup.TermSets)
                        {
                            // Do not include the orphan term set
                            if (termSet.Id == orphanedTermsTermSetId)
                            {
                                continue;
                            }

                            // Extract all other term sets
                            var modelTermSet = new Model.TermSet();
                            modelTermSet.Name = termSet.Name;
                            if (!isSiteCollectionTermGroup)
                            {
                                modelTermSet.Id = termSet.Id;
                            }
                            modelTermSet.IsAvailableForTagging = termSet.IsAvailableForTagging;
                            modelTermSet.IsOpenForTermCreation = termSet.IsOpenForTermCreation;
                            modelTermSet.Description           = termSet.Description;
                            modelTermSet.Terms.AddRange(GetTerms <TermSet>(web.Context, termSet, termStore.DefaultLanguage, isSiteCollectionTermGroup));
                            foreach (var property in termSet.CustomProperties)
                            {
                                modelTermSet.Properties.Add(property.Key, property.Value);
                            }
                            modelTermGroup.TermSets.Add(modelTermSet);
                        }

                        template.TermGroups.Add(modelTermGroup);
                    }
                }
            }
            return(template);
        }