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

            var cts = web.ContentTypes;
            web.Context.Load(cts);
            web.Context.ExecuteQueryRetry();

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

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

            return template;
        }
 public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
 {
     using (var scope = new PnPMonitoredScope(this.Name))
     {
         var context = web.Context as ClientContext;
         foreach (var handler in template.ExtensibilityHandlers
             .Union(template.Providers)
             .Union(applyingInformation.ExtensibilityHandlers))
         {
             if (handler.Enabled)
             {
                 try
                 {
                     if (!string.IsNullOrEmpty(handler.Configuration))
                     {
                         //replace tokens in configuration data
                         handler.Configuration = parser.ParseString(handler.Configuration);
                     }
                     scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_Calling_extensibility_callout__0_, handler.Assembly);
                     _extManager.ExecuteExtensibilityProvisionCallOut(context, handler, template, applyingInformation, parser, scope);
                 }
                 catch (Exception ex)
                 {
                     scope.LogError(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_callout_failed___0_____1_, ex.Message, ex.StackTrace);
                     throw;
                 }
             }
         }
     }
     return parser;
 }
        public override void AddPage(ListItem item, ProvisioningTemplate template)
        {
            string url = GetUrl(item, true);
            if (null == template.Pages.Find((p) => string.Equals(p.Url, url, System.StringComparison.OrdinalIgnoreCase)))
            {
                var fieldValues = item.FieldValues;

                var pageLayoutUrl = string.Empty;
                if (fieldValues.ContainsKey("PublishingPageLayout"))
                {
                    pageLayoutUrl = fieldValues["PublishingPageLayout"] == null ? "" : (fieldValues["PublishingPageLayout"] as FieldUrlValue).Url;
                }
                pageLayoutUrl = this.TokenParser.TokenizeUrl(pageLayoutUrl);

                string html = "";
                if (fieldValues.ContainsKey("PublishingPageContent"))
                {
                    html = fieldValues["PublishingPageContent"] == null ? " " : fieldValues["PublishingPageContent"].ToString();
                }

                var title = fieldValues["Title"] == null ? "" : fieldValues["Title"].ToString();

                bool needToOverwrite = NeedOverride(item);
                var webParts = GetWebParts(item);
                bool isHomePage = IsWelcomePage(item);
                PublishingPage page = new PublishingPage(url, title, html, pageLayoutUrl, needToOverwrite, webParts, isHomePage);
                template.Pages.Add(page);
            }
        }
        public void CanProvisionAuditSettings()
        {
            using (var scope = new Core.Diagnostics.PnPMonitoredScope("CanProvisionAuditSettings"))
            {
                using (var ctx = TestCommon.CreateClientContext())
                {
                    // Load the base template which will be used for the comparison work
                    var template = new ProvisioningTemplate();

                    template.AuditSettings = new AuditSettings();
                    template.AuditSettings.AuditFlags = AuditMaskType.CheckIn;
                    template.AuditSettings.AuditLogTrimmingRetention = 5;
                    template.AuditSettings.TrimAuditLog = true;

                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectAuditSettings().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                    var site = ctx.Site;

                    var auditSettings = site.Audit;
                    ctx.Load(auditSettings, af => af.AuditFlags);
                    ctx.Load(site, s => s.AuditLogTrimmingRetention, s => s.TrimAuditLog);
                    ctx.ExecuteQueryRetry();

                    Assert.IsTrue(auditSettings.AuditFlags == AuditMaskType.CheckIn);
                    Assert.IsTrue(site.AuditLogTrimmingRetention == 5);
                    Assert.IsTrue(site.TrimAuditLog = true);
                }
            }
        }
        public void CanProvisionRegionalSettings()
        {
            using (var scope = new Core.Diagnostics.PnPMonitoredScope("CanProvisionRegionalSettings"))
            {
                using (var ctx = TestCommon.CreateClientContext())
                {
                    // Load the base template which will be used for the comparison work
                    var template = new ProvisioningTemplate();

                    template.RegionalSettings = new Core.Framework.Provisioning.Model.RegionalSettings();
                    template.RegionalSettings.FirstDayOfWeek = System.DayOfWeek.Monday;
                    template.RegionalSettings.WorkDayEndHour = WorkHour.PM0700;
                    template.RegionalSettings.TimeZone = 5;
                    template.RegionalSettings.Time24 = true;

                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectRegionalSettings().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                    ctx.Load(ctx.Web.RegionalSettings);
                    ctx.Load(ctx.Web.RegionalSettings.TimeZone, tz => tz.Id);
                    ctx.ExecuteQueryRetry();

                    Assert.IsTrue(ctx.Web.RegionalSettings.Time24);
                    Assert.IsTrue(ctx.Web.RegionalSettings.WorkDayEndHour == (short)WorkHour.PM0700);
                    Assert.IsTrue(ctx.Web.RegionalSettings.FirstDayOfWeek == (uint)System.DayOfWeek.Monday);
                    Assert.IsTrue(ctx.Web.RegionalSettings.TimeZone.Id == 5);
                }
            }
        }
예제 #6
0
 private void HandleSitePolicy(ProvisioningTemplate provisioningTemplate, SiteRequestInformation siteRequest)
 {
     if(!string.IsNullOrWhiteSpace(siteRequest.SitePolicy))
     {
         provisioningTemplate.SitePolicy = siteRequest.SitePolicy;
     }
 }
예제 #7
0
 /// <summary>
 /// Member to handle the Url of custom actions
 /// </summary>
 /// <param name="provisioningTemplate"></param>
 /// <param name="siteRequest"></param>
 private void HandleCustomActions(ProvisioningTemplate provisioningTemplate, SiteRequestInformation siteRequest)
 {
     if (provisioningTemplate.CustomActions != null)
     {
         //handle site custom actions
         foreach (var _siteCustomActions in provisioningTemplate.CustomActions.SiteCustomActions)
         {
             //IF ITS A SCRIPT SRC WE DO NOT WANT TO MODIFY
             if (!string.IsNullOrEmpty(_siteCustomActions.Url))
             {
                 var _escapedURI = Uri.EscapeUriString(siteRequest.Url);
                 _siteCustomActions.Url = string.Format(_siteCustomActions.Url, _escapedURI);
             }
         }
         //handle web custom actions
         foreach( var _webActions in provisioningTemplate.CustomActions.WebCustomActions)
         {
             //IF ITS A SCRIPT SRC WE DO NOT WANT TO MODIFY
             if (!string.IsNullOrEmpty(_webActions.Url))
             {
                  var _escapedURI = Uri.EscapeUriString(siteRequest.Url);
                 _webActions.Url = string.Format(_webActions.Url, _escapedURI);
             }
         }
     }
 }
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();


            var contentType = new ContentType()
            {
                Id = "0x010100503B9E20E5455344BFAC2292DC6FE805",
                Name = "Test Content Type",
                Group = "PnP",
                Description = "Test Description",
                Overwrite = true,
                Hidden = false
            };

            contentType.FieldRefs.Add(new FieldRef()
            {
                Id = BuiltInFieldId.Category,
                DisplayName = "Test Category",
            });
            template.ContentTypes.Add(contentType);

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

                var ct = ctx.Web.GetContentTypeByName("Test Content Type");

                Assert.IsNotNull(ct);

            }
        }
예제 #9
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();

            FileSystemConnector connector = new FileSystemConnector(resourceFolder,"");

            template.Connector = connector;

            template.Files.Add(new Core.Framework.Provisioning.Model.File() { Overwrite = true, Src = fileName, Folder = folder });

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

                if (!ctx.Web.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    ctx.Load(ctx.Web, w => w.ServerRelativeUrl);
                    ctx.ExecuteQueryRetry();
                }

                var file = ctx.Web.GetFileByServerRelativeUrl(
                    UrlUtility.Combine(ctx.Web.ServerRelativeUrl,
                        UrlUtility.Combine(folder, fileName)));
                ctx.Load(file, f => f.Exists);
                ctx.ExecuteQueryRetry();
                Assert.IsTrue(file.Exists);
            }
        }
예제 #10
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            var context = web.Context as ClientContext;
            bool isSubSite = web.IsSubSite();
            var webCustomActions = web.GetCustomActions();
            var siteCustomActions = context.Site.GetCustomActions();

            var customActions = new CustomActions();
            foreach (var customAction in webCustomActions)
            {
                customActions.WebCustomActions.Add(CopyUserCustomAction(customAction));
            }
            
            // if this is a sub site then we're not creating entities for site collection scoped custom actions
            if (!isSubSite)
            {
                foreach (var customAction in siteCustomActions)
                {
                    customActions.SiteCustomActions.Add(CopyUserCustomAction(customAction));
                }
            }

            template.CustomActions = customActions;

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

            return template;
        }
예제 #11
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();
            var listInstance = new Core.Framework.Provisioning.Model.ListInstance();

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

            Dictionary<string, string> dataValues = new Dictionary<string, string>();
            dataValues.Add("Title","Test");
            DataRow dataRow = new DataRow(dataValues);

            listInstance.DataRows.Add(dataRow);

            template.Lists.Add(listInstance);

            using (var ctx = TestCommon.CreateClientContext())
            {
                TokenParser.Initialize(ctx.Web, template);

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

                var list = ctx.Web.GetListByUrl(listInstance.Url);
                Assert.IsNotNull(list);
                
                var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
                ctx.Load(items, itms => itms.Include(item => item["Title"]));
                ctx.ExecuteQueryRetry();

                Assert.IsTrue(items.Count == 1);
                Assert.IsTrue(items[0]["Title"].ToString() == "Test");
            }
        }
 public TokenParser AddExtendedTokens(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
 {
     using (var scope = new PnPMonitoredScope(this.Name))
     {
         var context = web.Context as ClientContext;
         foreach (var provider in template.Providers)
         {
             if (provider.Enabled)
             {
                 try
                 {
                     if (!string.IsNullOrEmpty(provider.Configuration))
                     {
                         provider.Configuration = parser.ParseString(provider.Configuration);
                     }
                     scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_Calling_tokenprovider_extensibility_callout__0_, provider.Assembly);
                     var _providedTokens = _extManager.ExecuteTokenProviderCallOut(context, provider, template);
                     if (_providedTokens != null)
                     {
                         foreach (var token in _providedTokens)
                         {
                             parser.AddToken(token);
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     scope.LogError(CoreResources.Provisioning_ObjectHandlers_ExtensibilityProviders_tokenprovider_callout_failed___0_____1_, ex.Message, ex.StackTrace);
                     throw;
                 }
             }
         }
         return parser;
     }
 }
예제 #13
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();

            template.Files.Add(new Core.Framework.Provisioning.Model.File() { Src = fileResource, Folder = folder });

            using (var ctx = TestCommon.CreateClientContext())
            {
                new ObjectFiles().ProvisionObjects(ctx.Web, template);


                if (!ctx.Web.IsPropertyAvailable("ServerRelativeUrl"))
                {
                    ctx.Load(ctx.Web, w => w.ServerRelativeUrl);
                    ctx.ExecuteQueryRetry();
                }

                var file = ctx.Web.GetFileByServerRelativeUrl(
                    UrlUtility.Combine(ctx.Web.ServerRelativeUrl,
                        UrlUtility.Combine(folder, fileName)));
                ctx.Load(file, f => f.Exists);
                ctx.ExecuteQueryRetry();
                Assert.IsTrue(file.Exists);
            }
        }
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {

                web.Context.Load(web.RegionalSettings);
                web.Context.Load(web.RegionalSettings.TimeZone, tz => tz.Id);
                web.Context.ExecuteQueryRetry();

                Model.RegionalSettings settings = new Model.RegionalSettings();

                settings.AdjustHijriDays = web.RegionalSettings.AdjustHijriDays;
                settings.AlternateCalendarType = (CalendarType)web.RegionalSettings.AlternateCalendarType;
                settings.CalendarType = (CalendarType)web.RegionalSettings.CalendarType;
                settings.Collation = web.RegionalSettings.Collation;
                settings.FirstDayOfWeek = (DayOfWeek)web.RegionalSettings.FirstDayOfWeek;
                settings.FirstWeekOfYear = web.RegionalSettings.FirstWeekOfYear;
                settings.LocaleId = (int)web.RegionalSettings.LocaleId;
                settings.ShowWeeks = web.RegionalSettings.ShowWeeks;
                settings.Time24 = web.RegionalSettings.Time24;
                settings.TimeZone = web.RegionalSettings.TimeZone.Id;
                settings.WorkDayEndHour = (WorkHour)web.RegionalSettings.WorkDayEndHour;
                settings.WorkDays = web.RegionalSettings.WorkDays;
                settings.WorkDayStartHour = (WorkHour)web.RegionalSettings.WorkDayStartHour;

                template.RegionalSettings = settings;

                // We're not comparing regional settings with the value stored in the base template as base templates are always for the US locale (1033)
            }
            return template;
        }
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();
            template.SiteFields.Add(new Core.Framework.Provisioning.Model.Field() { SchemaXml = ElementSchema });

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

                var f = ctx.Web.GetFieldById<FieldLookup>(fieldId);

                Assert.IsNotNull(f);
                Assert.IsInstanceOfType(f, typeof(FieldLookup));

                var schemaXml = f.SchemaXml;
                // so listId MUST have braces
                Assert.IsTrue(schemaXml.Contains("List=\""+_listIdWithBraces+"\""));
                // web id should NOT have braces
                Assert.IsTrue(schemaXml.Contains("WebId=\"" + ctx.Web.Id.ToString()+ "\""));
                // Source ID MUST have braces
                Assert.IsTrue(schemaXml.Contains("SourceID=\"" + ctx.Web.Id.ToString("B") + "\""));
            }

        }
예제 #16
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            // if this is a sub site then we're not provisioning security as by default security is inherited from the root site
            if (web.IsSubSite())
            {
                return;
            }

            var siteSecurity = template.Security;

            var ownerGroup = web.AssociatedOwnerGroup;
            var memberGroup = web.AssociatedMemberGroup;
            var visitorGroup = web.AssociatedVisitorGroup;

            web.Context.Load(ownerGroup, o => o.Users);
            web.Context.Load(memberGroup, o => o.Users);
            web.Context.Load(visitorGroup, o => o.Users);

            web.Context.ExecuteQueryRetry();

            AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners);
            AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers);
            AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors);

            foreach (var admin in siteSecurity.AdditionalAdministrators)
            {
                var user = web.EnsureUser(admin.Name);
                user.IsSiteAdmin = true;
                user.Update();
                web.Context.ExecuteQueryRetry();
            }

        }
예제 #17
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var context = web.Context as ClientContext;
                var site = context.Site;

                // Check if this is not a noscript site as we're not allowed to update some properties
                bool isNoScriptSite = web.IsNoScriptSite();

                // if this is a sub site then we're not enabling the site collection scoped custom actions
                if (!web.IsSubSite())
                {
                    var siteCustomActions = template.CustomActions.SiteCustomActions;
                    ProvisionCustomActionImplementation(site, siteCustomActions, parser, scope, isNoScriptSite);
                }

                var webCustomActions = template.CustomActions.WebCustomActions;
                ProvisionCustomActionImplementation(web, webCustomActions, parser, scope, isNoScriptSite);

                // Switch parser context back to it's original context
                parser.Rebase(web);
            }
            return parser;
        }
        public bool Validate(ContentTypeCollection sourceCollection, ContentTypeCollection targetCollection, TokenParser tokenParser)
        {
            // Convert object collections to XML 
            List<SerializedContentType> sourceContentTypes = new List<SerializedContentType>();
            List<SerializedContentType> targetContentTypes = new List<SerializedContentType>();

            foreach (ContentType ct in sourceCollection)
            {
                ProvisioningTemplate pt = new ProvisioningTemplate();
                pt.ContentTypes.Add(ct);

                sourceContentTypes.Add(new SerializedContentType() { SchemaXml = ExtractElementXml(pt) });                
            }

            foreach (ContentType ct in targetCollection)
            {
                ProvisioningTemplate pt = new ProvisioningTemplate();
                pt.ContentTypes.Add(ct);

                targetContentTypes.Add(new SerializedContentType() { SchemaXml = ExtractElementXml(pt) });
            }

            // Use XML validation logic to compare source and target
            Dictionary<string, string[]> parserSettings = new Dictionary<string, string[]>();
            parserSettings.Add("SchemaXml", null);
            bool isContentTypeMatch = ValidateObjectsXML(sourceContentTypes, targetContentTypes, "SchemaXml", new List<string> { "ID" }, tokenParser, parserSettings);
            Console.WriteLine("-- Content type validation " + isContentTypeMatch);
            return isContentTypeMatch;
        }
        public bool Validate(ProvisioningTemplate ptSource, ProvisioningTemplate ptTarget, TokenParser sParser, TokenParser tParser)
        {
            bool isValid = false;

            #region SiteFields
            if (ptTarget.SiteFields.Count > 0)
            {
                isValid = ValidateSiteFields(ptSource.SiteFields, ptTarget.SiteFields, sParser, tParser);
                if (!isValid) { return false; }
            }
            #endregion

            #region ContentTypes
            if (ptTarget.ContentTypes.Count > 0)
            {
                isValid = ValidateContentTypes(ptSource.ContentTypes, ptTarget.ContentTypes, sParser, tParser);
                if (!isValid) { return false; }
            }
            #endregion

            #region ListInstances
            isValid = ValidateListInstances(ptSource.Lists, ptTarget.Lists, sParser, tParser);
            if (!isValid) { return false; }
            #endregion

#if !ONPREMISES
            #region Custom Action
            isValid = ValidateCustomActions(ptSource.CustomActions, ptTarget.CustomActions, sParser, tParser, ptTarget.SiteFields.Count > 0);
            if (!isValid) { return false; }
            #endregion
#endif
            return isValid;
        }
예제 #20
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            TokenParser parser = new TokenParser(web);
            var context = web.Context as ClientContext;

            if (!web.IsPropertyAvailable("ServerRelativeUrl"))
            {
                context.Load(web, w => w.ServerRelativeUrl);
                context.ExecuteQueryRetry();
            }

            foreach (var file in template.Files)
            {

                var folderName = parser.Parse(file.Folder);

                if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower())))
                {
                    folderName = folderName.Substring(web.ServerRelativeUrl.Length);
                }
                

                var folder = web.EnsureFolderPath(folderName);

                using (var stream = template.Connector.GetFileStream(file.Src))
                {
                    folder.UploadFile(file.Src, stream, true);
                }

            }

        }
예제 #21
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {
            // if this is a sub site then we're not provisioning content types. Technically this can be done but it's not a recommended practice
            if (web.IsSubSite())
            {
                return;
            }

            var existingCts = web.AvailableContentTypes;
            web.Context.Load(existingCts, cts => cts.Include(ct => ct.StringId));
            web.Context.ExecuteQueryRetry();

            var existingCtsIds = existingCts.Select(cts => cts.StringId.ToLower()).ToList();

            foreach (var ct in template.ContentTypes)
            {
                // find the id of the content type
                XDocument document = XDocument.Parse(ct.SchemaXml);
                var contentTypeId = document.Root.Attribute("ID").Value;
                if (!existingCtsIds.Contains(contentTypeId.ToLower()))
                {
                    web.CreateContentTypeFromXMLString(ct.SchemaXml);
                    existingCtsIds.Add(contentTypeId);
                }
            }
        }
예제 #22
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {

            // if this is a sub site then we're not creating security entities as by default security is inherited from the root site
            if (web.IsSubSite())
            {
                return template;
            }

            var ownerGroup = web.AssociatedOwnerGroup;
            var memberGroup = web.AssociatedMemberGroup;
            var visitorGroup = web.AssociatedVisitorGroup;

            web.Context.Load(ownerGroup, o => o.Users);
            web.Context.Load(memberGroup, o => o.Users);
            web.Context.Load(visitorGroup, o => o.Users);

            web.Context.ExecuteQueryRetry();

            var owners = ownerGroup.IsObjectPropertyInstantiated("Users") ? 
                ownerGroup.Users.AsEnumerable().Select(u => new User(){ Name = u.LoginName}).ToList() : 
                new List<User>();

            var members = memberGroup.IsObjectPropertyInstantiated("Users") ?
                memberGroup.Users.AsEnumerable().Select(u => new User() { Name = u.LoginName }).ToList() : 
                new List<User>();

            var visitors = visitorGroup.IsObjectPropertyInstantiated("Users") ?
                visitorGroup.Users.AsEnumerable().Select(u => new User() { Name = u.LoginName }).ToList() : 
                new List<User>();

            var siteSecurity = new SiteSecurity();
            siteSecurity.AdditionalOwners.AddRange(owners);
            siteSecurity.AdditionalMembers.AddRange(members);
            siteSecurity.AdditionalVisitors.AddRange(visitors);

            var allUsers = web.SiteUsers;
            web.Context.Load(allUsers, users => users.Include(u => u.LoginName, u => u.IsSiteAdmin));
            web.Context.ExecuteQueryRetry();

            var admins = new List<User>();
            foreach (var member in allUsers)
            {
                if (member.IsSiteAdmin)
                {
                    admins.Add(new User() {Name = member.LoginName});
                }
            }
            siteSecurity.AdditionalAdministrators.AddRange(admins);

            template.Security = siteSecurity;

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

            return template;
        }
예제 #23
0
파일: ObjectField.cs 프로젝트: nats31/PnP
        public override void ProvisionObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Fields);

            // if this is a sub site then we're not provisioning fields. Technically this can be done but it's not a recommended practice
            if (web.IsSubSite())
            {
                return;
            }


            var existingFields = web.Fields;

            web.Context.Load(existingFields, fs => fs.Include(f => f.Id));
            web.Context.ExecuteQueryRetry();
            var existingFieldIds = existingFields.AsEnumerable<SPField>().Select(l => l.Id).ToList();
            var fields = template.SiteFields;

            foreach (var field in fields)
            {
                XElement templateFieldElement = XElement.Parse(field.SchemaXml.ToParsedString("~sitecollection", "~site"));
                var fieldId = templateFieldElement.Attribute("ID").Value;

                if (!existingFieldIds.Contains(Guid.Parse(fieldId)))
                {
                    CreateField(web, templateFieldElement);
                }
                else
                {
                    UpdateField(web, fieldId, templateFieldElement);
                }
            }
        }
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                // Check if this is not a noscript site as we're not allowed to write to the web property bag is that one
                bool isNoScriptSite = web.IsNoScriptSite();
                if (isNoScriptSite)
                {

                    return parser;
                }

                web.SetPropertyBagValue("_PnP_ProvisioningTemplateId", template.Id != null ? template.Id : "");
                web.AddIndexedPropertyBagKey("_PnP_ProvisioningTemplateId");

                ProvisioningTemplateInfo info = new ProvisioningTemplateInfo();
                info.TemplateId = template.Id != null ? template.Id : "";
                info.TemplateVersion = template.Version;
                info.TemplateSitePolicy = template.SitePolicy;
                info.Result = true;
                info.ProvisioningTime = DateTime.Now;

                string jsonInfo = JsonConvert.SerializeObject(info);

                web.SetPropertyBagValue("_PnP_ProvisioningTemplateInfo", jsonInfo);
            }
            return parser;
        }
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {

                web.Context.Load(web.RegionalSettings);
                web.Context.Load(web.RegionalSettings.TimeZone, tz => tz.Id);
                web.Context.ExecuteQueryRetry();

                Model.RegionalSettings settings = new Model.RegionalSettings();

                settings.AdjustHijriDays = web.RegionalSettings.AdjustHijriDays;
                settings.AlternateCalendarType = (CalendarType)web.RegionalSettings.AlternateCalendarType;
                settings.Collation = web.RegionalSettings.Collation;
                settings.FirstDayOfWeek = (DayOfWeek)web.RegionalSettings.FirstDayOfWeek;
                settings.FirstWeekOfYear = web.RegionalSettings.FirstWeekOfYear;
                settings.LocaleId = (int)web.RegionalSettings.LocaleId;
                settings.ShowWeeks = web.RegionalSettings.ShowWeeks;
                settings.Time24 = web.RegionalSettings.Time24;
                settings.TimeZone = web.RegionalSettings.TimeZone.Id;
                settings.WorkDayEndHour = (WorkHour)web.RegionalSettings.WorkDayEndHour;
                settings.WorkDays = web.RegionalSettings.WorkDays;
                settings.WorkDayStartHour = (WorkHour)web.RegionalSettings.WorkDayStartHour;

                template.RegionalSettings = settings;

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

                }
            }
            return template;
        }
        public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                var site = (web.Context as ClientContext).Site;
                try
                {
                    var siteSearchSettings = site.GetSearchConfiguration();

                    if (!String.IsNullOrEmpty(siteSearchSettings))
                    {
                        template.SiteSearchSettings = siteSearchSettings;
                    }

                    var webSearchSettings = web.GetSearchConfiguration();

                    if (!String.IsNullOrEmpty(webSearchSettings))
                    {
                        template.WebSearchSettings = webSearchSettings;
                    }
                }
                catch (ServerException)
                {
                    // The search service is not necessarily configured
                    // Swallow the exception
                }
            }
            return template;
        }
예제 #27
0
        public override void ProvisionObjects(Web web, ProvisioningTemplate template)
        {

            // if this is a sub site then we're not provisioning fields. Technically this can be done but it's not a recommended practice
            if (web.IsSubSite())
            {
                return;
            }

            var parser = new TokenParser(web);
            var existingFields = web.Fields;

            web.Context.Load(existingFields, fs => fs.Include(f => f.Id));
            web.Context.ExecuteQueryRetry();
            var existingFieldIds = existingFields.Select(l => l.Id).ToList();

            var fields = template.SiteFields;

            foreach (var field in fields)
            {
                XDocument document = XDocument.Parse(field.SchemaXml);
                var fieldId = document.Root.Attribute("ID").Value;


                if (!existingFieldIds.Contains(Guid.Parse(fieldId)))
                {
                    var fieldXml = parser.Parse(field.SchemaXml);
                    web.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue);
                    web.Context.ExecuteQueryRetry();
                }
            }
        }
예제 #28
0
        public override ProvisioningTemplate CreateEntities(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo)
        {
            // if this is a sub site then we're not creating field entities.
            if (web.IsSubSite())
            {
                return template;
            }

            var existingFields = web.Fields;
            web.Context.Load(existingFields, fs => fs.Include(f => f.Id, f => f.SchemaXml));
            web.Context.ExecuteQueryRetry();


            foreach (var field in existingFields)
            {
                if (!BuiltInFieldId.Contains(field.Id))
                {
                    template.SiteFields.Add(new Field() { SchemaXml = field.SchemaXml });
                }
            }
            // If a base template is specified then use that one to "cleanup" the generated template model
            if (creationInfo.BaseTemplate != null)
            {
                template = CleanupEntities(template, creationInfo.BaseTemplate);
            }

            return template;
        }
        public void CanProvisionSupportedUILanguages()
        {
            using (var scope = new Core.Diagnostics.PnPMonitoredScope("CanProvisionSupportedUILanguages"))
            {
                using (var ctx = TestCommon.CreateClientContext())
                {
                    // Load the base template which will be used for the comparison work
                    var template = new ProvisioningTemplate();

                    template.SupportedUILanguages.Add(new SupportedUILanguage() { LCID = 1033 }); // English
                    template.SupportedUILanguages.Add(new SupportedUILanguage() { LCID = 1032 }); // Greek

                    var parser = new TokenParser(ctx.Web, template);
                    new ObjectSupportedUILanguages().ProvisionObjects(ctx.Web, template, parser, new ProvisioningTemplateApplyingInformation());

                    ctx.Load(ctx.Web, w => w.SupportedUILanguageIds);

                    ctx.ExecuteQueryRetry();

                    Assert.IsTrue(ctx.Web.SupportedUILanguageIds.Count() == 2);
                    Assert.IsTrue(ctx.Web.SupportedUILanguageIds.Any(i => i == 1033));
                    Assert.IsTrue(ctx.Web.SupportedUILanguageIds.Any(i => i == 1032));
                }
            }
        }
예제 #30
0
        public void CanProvisionObjects()
        {
            var template = new ProvisioningTemplate();


            foreach (var user in admins)
            {
                template.Security.AdditionalMembers.Add(new User() { Name = user.LoginName});
            }



            using (var ctx = TestCommon.CreateClientContext())
            {
                TokenParser.Initialize(ctx.Web, template);
                new ObjectSiteSecurity().ProvisionObjects(ctx.Web, template);

                var memberGroup = ctx.Web.AssociatedMemberGroup;
                ctx.Load(memberGroup, g => g.Users);
                ctx.ExecuteQueryRetry();
                foreach (var user in admins)
                {
                    var existingUser = memberGroup.Users.GetByLoginName(user.LoginName);
                    ctx.Load(existingUser);
                    ctx.ExecuteQueryRetry();
                    Assert.IsNotNull(existingUser);
                }
            }
        }
예제 #31
0
        public DeployTemplateItem GetDeployItem(Services.ILogService logService)
        {
            LoadedXMLProvisioningTemplate loadedTemplate = null;

            try
            {
                //load the template xml file
                loadedTemplate = this.TemplateInfo.LoadXmlTemplate();
            }
            catch (Exception ex)
            {
                logService.Exception("Error reading template file " + this.ItemPath, ex);
                return(null);
            }

            if (loadedTemplate.Template != null)
            {
                if (this.TemplateInfo.TemplatePath == this.ItemPath)
                {
                    //deploy complete template
                    var deployItem = new DeployTemplateItem()
                    {
                        Config             = this.ProvisioningConfig,
                        Template           = loadedTemplate.Template,
                        TemplateName       = loadedTemplate.TemplateFileName,
                        IsCompleteTemplate = true,
                    };
                    return(deployItem);
                }
                else
                {
                    //deploy specific file(s)
                    var src = Helpers.ProvisioningHelper.MakeRelativePath(this.ItemPath, this.TemplateInfo.ResourcesPath);

                    var files = loadedTemplate.Template.Files.Where(
                        f => f.Src.StartsWith(src, StringComparison.InvariantCultureIgnoreCase)
                        ).ToList();

                    if (files.Count > 0)
                    {
                        //create a new template for the specified file
                        var filesUnderFolderTemplate = new OfficeDevPnP.Core.Framework.Provisioning.Model.ProvisioningTemplate(loadedTemplate.Template.Connector);
                        filesUnderFolderTemplate.Files.AddRange(files);

                        var deployItem = new DeployTemplateItem()
                        {
                            Config             = this.ProvisioningConfig,
                            Template           = filesUnderFolderTemplate,
                            TemplateName       = loadedTemplate.TemplateFileName,
                            IsCompleteTemplate = false,
                        };
                        return(deployItem);
                    }
                }
            }

            return(null);
        }
예제 #32
0
 /// <summary>
 /// Constructor for DataRowCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public DataRowCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #33
0
 /// <summary>
 /// Constructor for SiteFooterLinkCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public SiteFooterLinkCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }
 protected override void RemoveItem(int index)
 {
     this.Items[index].ParentTemplate = null;
     base.RemoveItem(index);
 }
예제 #35
0
 /// <summary>
 /// Constructor for PackagesCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public PackageCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }
예제 #36
0
 public ContentTypeCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #37
0
 /// <summary>
 /// Constructor for WorkflowDefinitionCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public WorkflowDefinitionCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }
 public DirectoryCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
 /// <summary>
 /// Custom constructor to manage the ParentTemplate for the collection
 /// and all the children of the collection
 /// </summary>
 /// <param name="parentTemplate"></param>
 public ProvisioningTemplateCollection(ProvisioningTemplate parentTemplate)
 {
     this.ParentTemplate = parentTemplate;
 }
예제 #40
0
 /// <summary>
 /// Constructor for Folder class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public FolderCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
 /// <summary>
 /// Constructor for RoleAssignmentCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public RoleAssignmentCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
 public DefaultDocumentCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #43
0
 /// <summary>
 /// Constructor for CanvasZoneCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public CanvasZoneCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }
 public SupportedUILanguageCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #45
0
 /// <summary>
 /// Constructor for SiteDesignGrantCollection
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public SiteDesignGrantCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #46
0
 /// <summary>
 /// Constructor for CanvasControlCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public CanvasControlCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }
예제 #47
0
 /// <summary>
 /// Constructor for WebPartCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public WebPartCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #48
0
 /// <summary>
 /// Constructor for AvailableWebTemplateCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public AvailableWebTemplateCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
 /// <summary>
 /// Custom constructor to manage the ParentTemplate for the collection
 /// and all the children of the collection
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public ProvisioningTemplateDictionary(ProvisioningTemplate parentTemplate)
 {
     this.ParentTemplate = parentTemplate;
 }
예제 #50
0
 public TermGroupCollection(ProvisioningTemplate parentTemplate) : base(parentTemplate)
 {
 }
예제 #51
0
 /// <summary>
 /// Custom constructor to manage the ParentTemplate for the collection
 /// and all the children of the collection
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public BaseProvisioningTemplateObjectCollection(ProvisioningTemplate parentTemplate)
 {
     this.ParentTemplate = parentTemplate;
 }
 /// <summary>
 /// Constructor for CdnOriginCollection class
 /// </summary>
 /// <param name="parentTemplate">Parent provisioning template</param>
 public CdnOriginCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }
 public NavigationNodeCollection(ProvisioningTemplate parentTemplate) :
     base(parentTemplate)
 {
 }