Exemple #1
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            base.DeployModel(modelHost, model);

            var folderModelHost = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull());

            var folder     = folderModelHost.CurrentListFolder;
            var definition = model.WithAssertAndCast <JavaScriptDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            var file     = GetItemFile(folderModelHost.CurrentList, folder, definition.FileName);
            var spObject = file.ListItemAllFields;

            var context = spObject.Context;

            context.Load(spObject);
            context.ExecuteQueryWithTrace();

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            assert.ShouldBeEqual(m => m.Standalone, o => o.GetStandalone());
            assert.ShouldBeEqual(m => m.TargetControlType, o => o.GetTargetControlType());
            assert.ShouldBeEqual(m => m.TargetListTemplateId, o => o.GetTargetListTemplateId());
            assert.ShouldBeEqual(m => m.TargetScope, o => o.GetTargetScope());

            #region icon url

            if (!string.IsNullOrEmpty(definition.IconUrl))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.IconUrl);
                    var isValid = d.GetDisplayTemplateJSIconUrl().Url == s.IconUrl;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.IconUrl, "IconUrl is NULL. Skipping");
            }

            if (!string.IsNullOrEmpty(definition.IconDescription))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.IconDescription);
                    var isValid = d.GetDisplayTemplateJSIconUrl().Description == s.IconDescription;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.IconDescription, "IconDescription is NULL. Skipping");
            }

            #endregion
        }
Exemple #2
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var web        = ExtractWeb(modelHost);
            var definition = model.WithAssertAndCast <ContentTypeDefinition>("model", value => value.RequireNotNull());

            var site = web.Site;

            var contentTypes = web.AvailableContentTypes;
            var spObject     = contentTypes[definition.Name];

            if (spObject == null)
            {
                spObject = web.ContentTypes[definition.Name];
            }

            var assert = ServiceFactory.AssertService.NewAssert(definition, spObject);

            assert
            .ShouldNotBeNull(spObject)
            .ShouldBeEqual(m => m.Name, o => o.Name)
            .ShouldBeEqual(m => m.Group, o => o.Group)
            .ShouldBeEqual(m => m.Hidden, o => o.Hidden);
            //.ShouldBeEqual(m => m.Description, o => o.Description);


            if (definition.Sealed.HasValue)
            {
                assert.ShouldBeEqual(m => m.Sealed, o => o.Sealed);
            }
            else
            {
                assert.SkipProperty(m => m.Sealed, "Sealed is null or empty. Skipping.");
            }

            if (definition.ReadOnly.HasValue)
            {
                assert.ShouldBeEqual(m => m.ReadOnly, o => o.ReadOnly);
            }
            else
            {
                assert.SkipProperty(m => m.ReadOnly, "ReadOnly is null or empty. Skipping.");
            }


            if (!string.IsNullOrEmpty(definition.JSLink))
            {
                assert.ShouldBeEqual(m => m.JSLink, o => o.JSLink);
            }
            else
            {
                assert.SkipProperty(m => m.JSLink, "JSLink is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.Description))
            {
                assert.ShouldBeEqual(m => m.Description, o => o.Description);
            }
            else
            {
                assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping.");
            }

            if (definition.Id == default(Guid))
            {
                assert.SkipProperty(m => m.IdNumberValue, string.Format("Skipping Id as it is default(Guid)"));
            }
            else
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Id);
                    var dstProp = d.GetExpressionValue(ct => ct.GetId());

                    var srcCtId = s.GetContentTypeId();
                    var dstCtId = d.GetId();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = dstCtId.ToString().ToUpper() == dstCtId.ToString().ToUpper()
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.IdNumberValue))
            {
                assert.SkipProperty(m => m.IdNumberValue, string.Format("Skipping IdNumberValue as it is Empty"));
            }
            else
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Id);
                    var dstProp = d.GetExpressionValue(ct => ct.GetId());

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = srcProp.ToString().ToUpper() == dstProp.ToString().ToUpper()
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.DocumentTemplate))
            {
                assert.SkipProperty(m => m.DocumentTemplate, string.Format("Skipping DocumentTemplate as it is Empty"));
            }
            else
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.DocumentTemplate);
                    var dstProp = d.GetExpressionValue(ct => ct.DocumentTemplateUrl);

                    var srcUrl = srcProp.Value as string;
                    var dstUrl = dstProp.Value as string;

                    var isValid = false;

                    if (s.DocumentTemplate.Contains("~sitecollection"))
                    {
                        var siteCollectionUrl = web.Site.ServerRelativeUrl == "/" ? string.Empty : web.Site.ServerRelativeUrl;

                        isValid = srcUrl.Replace("~sitecollection", siteCollectionUrl) == dstUrl;
                    }
                    else if (s.DocumentTemplate.Contains("~site"))
                    {
                        var siteCollectionUrl = web.ServerRelativeUrl == "/" ? string.Empty : web.ServerRelativeUrl;

                        isValid = srcUrl.Replace("~site", siteCollectionUrl) == dstUrl;
                    }
                    else
                    {
                        isValid = dstUrl.EndsWith(srcUrl);
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }

            /// localization
            if (definition.NameResource.Any())
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.NameResource);
                    var isValid = true;

                    foreach (var userResource in s.NameResource)
                    {
                        var culture = LocalizationService.GetUserResourceCultureInfo(userResource);
                        var value   = d.NameResource.GetValueForUICulture(culture);

                        isValid = userResource.Value == value;

                        if (!isValid)
                        {
                            break;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.NameResource, "NameResource is NULL or empty. Skipping.");
            }

            if (definition.DescriptionResource.Any())
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.DescriptionResource);
                    var isValid = true;

                    foreach (var userResource in s.DescriptionResource)
                    {
                        var culture = LocalizationService.GetUserResourceCultureInfo(userResource);
                        var value   = d.DescriptionResource.GetValueForUICulture(culture);

                        isValid = userResource.Value == value;

                        if (!isValid)
                        {
                            break;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is NULL or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.NewFormUrl))
            {
                assert.ShouldBeEqual(m => m.NewFormUrl, o => o.NewFormUrl);
            }
            else
            {
                assert.SkipProperty(m => m.NewFormUrl, "NewFormUrl is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.NewFormTemplateName))
            {
                assert.ShouldBeEqual(m => m.NewFormTemplateName, o => o.NewFormTemplateName);
            }
            else
            {
                assert.SkipProperty(m => m.NewFormTemplateName, "NewFormTemplateName is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.EditFormUrl))
            {
                assert.ShouldBeEqual(m => m.EditFormUrl, o => o.EditFormUrl);
            }
            else
            {
                assert.SkipProperty(m => m.EditFormUrl, "EditFormUrl is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.EditFormTemplateName))
            {
                assert.ShouldBeEqual(m => m.EditFormTemplateName, o => o.EditFormTemplateName);
            }
            else
            {
                assert.SkipProperty(m => m.EditFormTemplateName, "EditFormTemplateName is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.DisplayFormUrl))
            {
                assert.ShouldBeEqual(m => m.DisplayFormUrl, o => o.DisplayFormUrl);
            }
            else
            {
                assert.SkipProperty(m => m.DisplayFormUrl, "DisplayFormUrl is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.DisplayFormTemplateName))
            {
                assert.ShouldBeEqual(m => m.DisplayFormTemplateName, o => o.DisplayFormTemplateName);
            }
            else
            {
                assert.SkipProperty(m => m.DisplayFormTemplateName, "DisplayFormTemplateName is null or empty. Skipping.");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var folderModelHost     = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull());
            var publishingPageModel = model.WithAssertAndCast <PublishingPageLayoutDefinition>("model", value => value.RequireNotNull());

            var folder = folderModelHost.CurrentListFolder;
            var list   = folderModelHost.CurrentList;

            ContentType siteContentType = null;

            if (!string.IsNullOrEmpty(publishingPageModel.AssociatedContentTypeId))
            {
                siteContentType = folderModelHost.HostSite.RootWeb.AvailableContentTypes.GetById(publishingPageModel.AssociatedContentTypeId);

                folderModelHost.HostSite.Context.Load(siteContentType);
                folderModelHost.HostSite.Context.ExecuteQueryWithTrace();
            }

            var context = folder.Context;

            var pageName        = GetSafePageFileName(publishingPageModel);
            var currentPageFile = GetCurrentPage(list, folder, pageName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentPageFile,
                ObjectType       = typeof(File),
                ObjectDefinition = publishingPageModel,
                ModelHost        = modelHost
            });

            ModuleFileModelHandler.WithSafeFileOperation(list, currentPageFile, f =>
            {
                var file = new FileCreationInformation();

                file.Url       = pageName;
                file.Content   = Encoding.UTF8.GetBytes(publishingPageModel.Content);
                file.Overwrite = publishingPageModel.NeedOverride;

                return(folder.Files.Add(file));
            },
                                                         newFile =>
            {
                var newFileItem = newFile.ListItemAllFields;
                context.Load(newFileItem);
                context.ExecuteQueryWithTrace();

                var site = folderModelHost.HostSite;
                var currentPageLayoutItem = FindPageLayoutItem(site, publishingPageModel.FileName);


                var currentPageLayoutItemContext = currentPageLayoutItem.Context;
                var publishingFile = currentPageLayoutItem.File;

                currentPageLayoutItemContext.Load(currentPageLayoutItem);
                currentPageLayoutItemContext.Load(currentPageLayoutItem, i => i.DisplayName);
                currentPageLayoutItemContext.Load(publishingFile);

                currentPageLayoutItemContext.ExecuteQueryWithTrace();

                newFileItem[BuiltInInternalFieldNames.Title]         = publishingPageModel.Title;
                newFileItem["MasterPageDescription"]                 = publishingPageModel.Description;
                newFileItem[BuiltInInternalFieldNames.ContentTypeId] = BuiltInPublishingContentTypeId.PageLayout;

                if (siteContentType != null)
                {
                    newFileItem["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", siteContentType.Name, siteContentType.Id.ToString());
                }
                newFileItem.Update();

                context.ExecuteQueryWithTrace();
            });

            currentPageFile = GetCurrentPage(folderModelHost.CurrentList, folder, pageName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentPageFile,
                ObjectType       = typeof(File),
                ObjectDefinition = publishingPageModel,
                ModelHost        = modelHost
            });

            context.ExecuteQueryWithTrace();
        }
Exemple #4
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            this.ModelHost = modelHost;

            if (!(modelHost is SiteModelHost ||
                  modelHost is WebModelHost ||
                  modelHost is ListModelHost))
            {
                throw new ArgumentException("modelHost needs to be SiteModelHost/WebModelHost/ListModelHost instance.");
            }

            CurrentHostClientContext = (modelHost as CSOMModelHostBase).HostClientContext;
            CurrentModelHost         = modelHost.WithAssertAndCast <CSOMModelHostBase>("modelHost", value => value.RequireNotNull());

            HostSite = ExtractSiteFromHost(modelHost);
            HostWeb  = ExtractWebFromHost(modelHost);

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Casting field model definition");
            var fieldModel = model.WithAssertAndCast <FieldDefinition>("model", value => value.RequireNotNull());

            Field currentField           = null;
            ClientRuntimeContext context = null;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = null,
                ObjectType       = GetTargetFieldType(fieldModel),
                ObjectDefinition = model,
                ModelHost        = modelHost
            });

            if (modelHost is ListModelHost)
            {
                var listHost = modelHost as ListModelHost;
                context = listHost.HostList.Context;

                currentField = DeployListField(modelHost as ListModelHost, fieldModel);
            }
            else if (modelHost is WebModelHost)
            {
                var webHost = modelHost as WebModelHost;
                context = webHost.HostWeb.Context;

                currentField = DeployWebField(webHost as WebModelHost, fieldModel);
            }

            else if (modelHost is SiteModelHost)
            {
                var siteHost = modelHost as SiteModelHost;
                context = siteHost.HostSite.Context;

                currentField = DeploySiteField(siteHost as SiteModelHost, fieldModel);
            }
            else
            {
                throw new ArgumentException("modelHost needs to be SiteModelHost/WebModelHost/ListModelHost instance.");
            }

            object typedField = null;

            // emulate context.CastTo<>() call for typed field type
            if (GetTargetFieldType(fieldModel) != currentField.GetType())
            {
                var targetFieldType = GetTargetFieldType(fieldModel);

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Calling context.CastTo() to field type: [{0}]", targetFieldType);

                var method  = context.GetType().GetMethod("CastTo");
                var generic = method.MakeGenericMethod(targetFieldType);

                typedField = generic.Invoke(context, new object[] { currentField });
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = typedField ?? currentField,
                ObjectType       = GetTargetFieldType(fieldModel),
                ObjectDefinition = model,
                ModelHost        = modelHost
            });

            if (fieldModel.PushChangesToLists.HasValue)
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall,
                                     string.Format("UpdateAndPushChanges({0})", fieldModel.PushChangesToLists));

                currentField.UpdateAndPushChanges(fieldModel.PushChangesToLists.Value);
            }
            else
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "UpdateAndPushChanges(true)");
                // Why does SSOM handler distinguish between list and web/site fields and csom doesn't?
                currentField.UpdateAndPushChanges(true);
            }

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "ExecuteQuery()");
            context.ExecuteQueryWithTrace();

            CurrentHostClientContext = null;
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            base.DeployModel(modelHost, model);

            var typedModelHost = modelHost.WithAssertAndCast <SSOMModelHostBase>("modelHost", value => value.RequireNotNull());
            var definition     = model.WithAssertAndCast <TaxonomyFieldDefinition>("model", value => value.RequireNotNull());

            var site     = ExtractSite(typedModelHost);
            var spObject = GetField(modelHost, definition) as TaxonomyField;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject)
                         .ShouldBeEqual(m => m.IsMulti, o => o.AllowMultipleValues);

            if (definition.CreateValuesInEditForm.HasValue)
            {
                assert.ShouldBeEqual(m => m.CreateValuesInEditForm, o => o.CreateValuesInEditForm);
            }
            else
            {
                assert.SkipProperty(m => m.CreateValuesInEditForm, "CreateValuesInEditForm is null. Skipping property.");
            }

            if (definition.Open.HasValue)
            {
                assert.ShouldBeEqual(m => m.Open, o => o.Open);
            }
            else
            {
                assert.SkipProperty(m => m.Open, "Open is null. Skipping property.");
            }

            if (definition.IsPathRendered.HasValue)
            {
                assert.ShouldBeEqual(m => m.IsPathRendered, o => o.IsPathRendered);
            }
            else
            {
                assert.SkipProperty(m => m.IsPathRendered, "IsPathRendered is null. Skipping property.");
            }

            // SSP
            if (definition.SspId.HasValue)
            {
                assert.ShouldBeEqual(m => m.SspId, o => o.SspId);
            }
            else
            {
                assert.SkipProperty(m => m.SspId, "SspId is null. Skipping property.");
            }

            if (!string.IsNullOrEmpty(definition.SspName))
            {
                // TODO
            }
            else
            {
                assert.SkipProperty(m => m.SspName, "SspName is null. Skipping property.");
            }

            if (definition.UseDefaultSiteCollectionTermStore == true)
            {
                var taxSession = new TaxonomySession(site);
                var termStore  = taxSession.DefaultSiteCollectionTermStore;

                var isValid = termStore.Id == spObject.SspId;

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.UseDefaultSiteCollectionTermStore);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.UseDefaultSiteCollectionTermStore, "UseDefaultSiteCollectionTermStore is null. Skipping property.");
            }

            // is site collectiongroup
            if (definition.IsSiteCollectionGroup.HasValue && definition.IsSiteCollectionGroup.Value)
            {
                var termStore = TaxonomyFieldModelHandler.LookupTermStore(site, definition);

                Group group = null;

                // cause binding might be only by group AND (termset || term)
                var termSet = TaxonomyFieldModelHandler.LookupTermSet(site, termStore, definition);
                var term    = TaxonomyFieldModelHandler.LookupTerm(site, termStore, definition);

                if (termSet != null)
                {
                    group = termSet.Group;
                }
                else if (term != null)
                {
                    group = term.TermSet.Group;
                }

                var isValid = group.IsSiteCollectionGroup;

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.IsSiteCollectionGroup);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.IsSiteCollectionGroup, "IsSiteCollectionGroup is null. Skipping property.");
            }

            // term group
            if (definition.TermGroupId.HasValue)
            {
                var termStore = TaxonomyFieldModelHandler.LookupTermStore(site, definition);

                Group group = null;

                // cause binding might be only by group AND (termset || term)
                var termSet = TaxonomyFieldModelHandler.LookupTermSet(site, termStore, definition);
                var term    = TaxonomyFieldModelHandler.LookupTerm(site, termStore, definition);

                if (termSet != null)
                {
                    group = termSet.Group;
                }
                else if (term != null)
                {
                    group = term.TermSet.Group;
                }

                var isValid = group.Id == definition.TermGroupId;

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.TermGroupId);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.TermGroupId, "TermGroupId is null. Skipping property.");
            }

            if (!string.IsNullOrEmpty(definition.TermGroupName))
            {
                var termStore = TaxonomyFieldModelHandler.LookupTermStore(site, definition);

                Group group = null;

                // cause binding might be only by group AND (termset || term)
                var termSet = TaxonomyFieldModelHandler.LookupTermSet(site, termStore, definition);
                var term    = TaxonomyFieldModelHandler.LookupTerm(site, termStore, definition);

                if (termSet != null)
                {
                    group = termSet.Group;
                }
                else if (term != null)
                {
                    group = term.TermSet.Group;
                }

                var isValid = group.Name == definition.TermGroupName;

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.TermGroupName);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.TermGroupName, "TermGroupName is null. Skipping property.");
            }

            // term set
            if (definition.TermSetId.HasValue)
            {
                assert.ShouldBeEqual(m => m.TermSetId, o => o.TermSetId);
            }
            else
            {
                assert.SkipProperty(m => m.TermSetId, "TermSetId is null. Skipping property.");
            }

            if (!string.IsNullOrEmpty(definition.TermSetName))
            {
                var termStore = TaxonomyFieldModelHandler.LookupTermStore(site, definition);
                var termSet   = TaxonomyFieldModelHandler.LookupTermSet(site, termStore, definition);

                var isValid = spObject.TermSetId == termSet.Id;

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.TermSetName);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.TermSetName, "TermSetName is null. Skipping property.");
            }

            /// term

            if (definition.TermId.HasValue)
            {
                assert.ShouldBeEqual(m => m.TermId, o => o.AnchorId);
            }
            else
            {
                assert.SkipProperty(m => m.TermId, "TermId is null. Skipping property.");
            }

            if (!string.IsNullOrEmpty(definition.TermName))
            {
                var termStore = TaxonomyFieldModelHandler.LookupTermStore(site, definition);
                var term      = TaxonomyFieldModelHandler.LookupTerm(site, termStore, definition);

                var isValid = spObject.AnchorId == term.Id;

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.TermName);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.TermName, "TermName is null. Skipping property.");
            }

            // etc
            assert.SkipProperty(m => m.TermLCID, "TermLCID. Skipping property.");
            assert.SkipProperty(m => m.TermSetLCID, "TermSetLCID. Skipping property.");

            if (definition.UserCreated.HasValue)
            {
                assert.ShouldBeEqual(m => m.UserCreated, o => o.UserCreated);
            }
            else
            {
                assert.SkipProperty(m => m.UserCreated, "UserCreated is null. Skipping property.");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webAppModelHost = modelHost.WithAssertAndCast <WebApplicationModelHost>("modelHost", value => value.RequireNotNull());
            var definition      = model.WithAssertAndCast <SiteDefinition>("model", value => value.RequireNotNull());

            var spObject = GetExistingSite(webAppModelHost.HostWebApplication, definition);

            //  [FALSE] - [Name]
            //[FALSE] - [Description]
            //[FALSE] - [Url]
            //[FALSE] - [PrefixName]
            //[FALSE] - [SiteTemplate]
            //[FALSE] - [LCID]
            //[FALSE] - [OwnerLogin]
            //[FALSE] - [OwnerName]
            //[FALSE] - [OwnerEmail]
            //[FALSE] - [SecondaryContactName]
            //[FALSE] - [SecondaryContactEmail]
            //[FALSE] - [DatabaseName]

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            assert
            .ShouldBeEqual(m => m.Name, o => o.GetSiteName())
            .ShouldBeEqual(m => m.Description, o => o.GetSiteDescription())
            .ShouldBeEqual(m => m.SiteTemplate, o => o.GetSiteTemplate())
            //.ShouldBeEndOf(m => m.Url, o => o.Url)
            //.ShouldBePartOf(m => m.PrefixName, o => o.Url)

            .ShouldBePartOf(m => m.OwnerLogin, o => o.GetOwnerLogin())
            .ShouldBePartOf(m => m.OwnerName, o => o.GetOwnerName())
            .SkipProperty(m => m.OwnerEmail, "Skipping OwnerEmail validation.")

            //.ShouldBePartOf(m => m.SecondaryContactLogin, o => o.GetSecondOwnerLogin())
            //.ShouldBePartOf(m => m.SecondaryContactName, o => o.GeSecondtOwnerName())
            .SkipProperty(m => m.SecondaryContactEmail, "Skipping SecondaryContactEmail validation.")

            .ShouldBeEqual(m => m.LCID, o => o.GetSiteLCID());

            if (string.IsNullOrEmpty(definition.Url) || definition.Url == "/")
            {
                // Enhance SiteDefinition provision - enable provision under the managed path  #853
                // the URL would end with the managed path
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.Url);
                    var isValid = true;

                    isValid = d.Url.EndsWith(s.PrefixName);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                // should be an end if set
                assert.ShouldBeEndOf(m => m.Url, o => o.Url);
            }

            if (!string.IsNullOrEmpty(definition.SecondaryContactLogin))
            {
                assert.ShouldBePartOf(m => m.SecondaryContactLogin, o => o.GetSecondOwnerLogin());
            }
            else
            {
                assert.SkipProperty(m => m.SecondaryContactLogin, "SecondaryContactLogin is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.SecondaryContactName))
            {
                assert.ShouldBePartOf(m => m.SecondaryContactName, o => o.GeSecondtOwnerName());
            }
            else
            {
                assert.SkipProperty(m => m.SecondaryContactName, "SecondaryContactName is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.PrefixName))
            {
                assert.ShouldBePartOf(m => m.PrefixName, o => o.Url);
            }
            else
            {
                assert.SkipProperty(m => m.PrefixName, "PrefixName is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.DatabaseName))
            {
                assert.ShouldBeEqual(m => m.DatabaseName, o => o.GetContentDbName());
            }
            else
            {
                assert.SkipProperty(m => m.DatabaseName, "DatabaseName is null or empty. Skipping.");
            }
        }
Exemple #7
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var folderModelHost = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull());
            var definition      = model.WithAssertAndCast <MasterPageDefinitionBase>("model", value => value.RequireNotNull());

            var folder = folderModelHost.CurrentListFolder;
            var list   = folderModelHost.CurrentList;

            var context = folder.Context;

            var pageName        = GetSafePageFileName(definition);
            var currentPageFile = GetCurrentPage(list, folder, pageName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentPageFile,
                ObjectType       = typeof(File),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            ModuleFileModelHandler.WithSafeFileOperation(list, currentPageFile, f =>
            {
                var file = new FileCreationInformation();

                file.Url       = pageName;
                file.Content   = definition.Content;
                file.Overwrite = definition.NeedOverride;

                return(folder.Files.Add(file));
            },
                                                         newFile =>
            {
                var newFileItem = newFile.ListItemAllFields;
                context.Load(newFileItem);
                context.ExecuteQueryWithTrace();

                //var site = folderModelHost.HostSite;
                //var currentPageLayoutItem = FindPageLayoutItem(site, definition.FileName);

                //var currentPageLayoutItemContext = currentPageLayoutItem.Context;
                //var publishingFile = currentPageLayoutItem.File;

                //currentPageLayoutItemContext.Load(currentPageLayoutItem);
                //currentPageLayoutItemContext.Load(currentPageLayoutItem, i => i.DisplayName);
                //currentPageLayoutItemContext.Load(publishingFile);

                //currentPageLayoutItemContext.ExecuteQueryWithTrace();

                // ** SIC.. found with Problem with url in MasterPageSettings #936
                // https://github.com/SubPointSolutions/spmeta2/issues/936

                // * /_catalogs/masterpage - would have 'Title' field (and correct content types)
                // * /my-sub-web/_catalogs/masterpage - would NOT have 'Title' fiels so that provision fails

                // so performing Title update only for the root web
                if (folderModelHost.HostSite.ServerRelativeUrl == folderModelHost.HostWeb.ServerRelativeUrl)
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Updating master page 'Title' on the root web.", null);
                    newFileItem[BuiltInInternalFieldNames.Title] = definition.Title;
                }
                else
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Skipping master page 'Title' update. Subweb is detcted.", null);
                }

                newFileItem["MasterPageDescription"] = definition.Description;
                newFileItem[BuiltInInternalFieldNames.ContentTypeId] = PageContentTypeId;

                if (definition.UIVersion.Count > 0)
                {
                    newFileItem["UIVersion"] = string.Join(";#", definition.UIVersion.ToArray());
                }

                newFileItem["DefaultCssFile"] = definition.DefaultCSSFile;

                newFileItem.Update();

                context.ExecuteQueryWithTrace();
            });

            currentPageFile = GetCurrentPage(folderModelHost.CurrentList, folder, pageName);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentPageFile,
                ObjectType       = typeof(File),
                ObjectDefinition = definition,
                ModelHost        = modelHost
            });

            context.ExecuteQueryWithTrace();
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var securableObject        = ExtractSecurableObject(modelHost);
            var securityGroupLinkModel = model.WithAssertAndCast <SecurityGroupLinkDefinition>("model", value => value.RequireNotNull());

            var web     = GetWebFromSPSecurableObject(securableObject);
            var context = web.Context;

            context.Load(web, w => w.SiteGroups);
            context.Load(web, w => w.RoleDefinitions);

            context.Load(securableObject, s => s.HasUniqueRoleAssignments);
            context.Load(securableObject, s => s.RoleAssignments.Include(r => r.Member));

            context.ExecuteQueryWithTrace();

            Group securityGroup = ResolveSecurityGroup(securityGroupLinkModel, web, context);

            if (!securableObject.HasUniqueRoleAssignments)
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "securableObject.HasUniqueRoleAssignments = false. Breaking with false-false options.");
                securableObject.BreakRoleInheritance(false, false);
            }

            var roleAssignment = FindRoleRoleAssignment(securableObject.RoleAssignments, securityGroup);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = roleAssignment,
                ObjectType       = typeof(RoleAssignment),
                ObjectDefinition = securityGroupLinkModel,
                ModelHost        = modelHost
            });

            if (roleAssignment == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security group link");

                // add default guest role as hidden one
                // we need to at least one role in order to create assignment
                // further provision will chech of there is only one role - Reader, and will remove it
                var bindings = new RoleDefinitionBindingCollection(context);
                bindings.Add(web.RoleDefinitions.GetByType(RoleType.Reader));

                var assegnment = securableObject.RoleAssignments.Add(securityGroup, bindings);

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioned,
                    Object           = assegnment,
                    ObjectType       = typeof(RoleAssignment),
                    ObjectDefinition = securityGroupLinkModel,
                    ModelHost        = modelHost
                });

                context.ExecuteQuery();
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security group link");

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioned,
                    Object           = roleAssignment,
                    ObjectType       = typeof(RoleAssignment),
                    ObjectDefinition = securityGroupLinkModel,
                    ModelHost        = modelHost
                });
            }
        }
Exemple #9
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webHost    = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());
            var definition = model.WithAssertAndCast <SharePointDesignerSettingsDefinition>("model", value => value.RequireNotNull());

            var spObject = webHost.HostSite.RootWeb;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            if (definition.EnableCustomizingMasterPagesAndPageLayouts.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.EnableCustomizingMasterPagesAndPageLayouts);
                    var isValid = true;

                    var dstValue = ConvertUtils.ToBool(spObject.AllProperties[BuiltInWebPropertyId.AllowMasterpageEditing]);

                    isValid = s.EnableCustomizingMasterPagesAndPageLayouts.Value == dstValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid,
                        Message = string.Format("{0} - {1}", BuiltInWebPropertyId.AllowMasterpageEditing, dstValue)
                    });
                });
            }
            else
            {
                assert.SkipProperty(o => o.EnableCustomizingMasterPagesAndPageLayouts, "EnableCustomizingMasterPagesAndPageLayouts is NULL. Skipping");
            }

            if (definition.EnableDetachingPages.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.EnableDetachingPages);
                    var isValid = true;

                    var dstValue = ConvertUtils.ToBool(spObject.AllProperties[BuiltInWebPropertyId.AllowRevertFromTemplate]);

                    isValid = s.EnableDetachingPages.Value == dstValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid,
                        Message = string.Format("{0} - {1}", BuiltInWebPropertyId.AllowMasterpageEditing, dstValue)
                    });
                });
            }
            else
            {
                assert.SkipProperty(o => o.EnableDetachingPages, "EnableDetachingPages is NULL. Skipping");
            }

            if (definition.EnableManagingWebSiteUrlStructure.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.EnableManagingWebSiteUrlStructure);
                    var isValid = true;

                    var dstValue = ConvertUtils.ToBool(spObject.AllProperties[BuiltInWebPropertyId.ShowUrlStructure]);

                    isValid = s.EnableManagingWebSiteUrlStructure.Value == dstValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid,
                        Message = string.Format("{0} - {1}", BuiltInWebPropertyId.AllowMasterpageEditing, dstValue)
                    });
                });
            }
            else
            {
                assert.SkipProperty(o => o.EnableManagingWebSiteUrlStructure, "EnableManagingWebSiteUrlStructure is NULL. Skipping");
            }

            if (definition.EnableSharePointDesigner.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.EnableSharePointDesigner);
                    var isValid = true;

                    var dstValue = ConvertUtils.ToBool(spObject.AllProperties[BuiltInWebPropertyId.AllowDesigner]);

                    isValid = s.EnableSharePointDesigner.Value == dstValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid,
                        Message = string.Format("{0} - {1}", BuiltInWebPropertyId.AllowMasterpageEditing, dstValue)
                    });
                });
            }
            else
            {
                assert.SkipProperty(o => o.EnableSharePointDesigner, "EnableSharePointDesigner is NULL. Skipping");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <DesignPackageDefinition>("model", value => value.RequireNotNull());

            var spObject = this.FindExistingSolutionById(siteModelHost, definition.SolutionId);
            var context  = spObject.Context;

            var site    = siteModelHost.HostSite;
            var rootWeb = site.RootWeb;

            var fileItem = spObject.ListItemAllFields;

            context.Load(fileItem);
            context.Load(rootWeb, w => w.AllProperties);

            context.ExecuteQueryWithTrace();

            var assert = ServiceFactory.AssertService.NewAssert(definition, fileItem);

            assert
            .ShouldNotBeNull(fileItem)

            //.ShouldBeEqual(d => d, o => o.GetSolutionActivationStatus())
            .ShouldBeEqual(d => d.SolutionId, o => o.GetSolutionId())

            .SkipProperty(d => d.Content, "Content is fine.")
            .SkipProperty(d => d.FileName, "Randomly generated by CSOM activation.");

            if (definition.Apply)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    // once applied, design package sets AppliedDesignGuid property in the root web
                    // checking is all good
                    var installedPackageId = ConvertUtils.ToGuid(rootWeb.AllProperties["AppliedDesignGuid"]);

                    var srcProp = s.GetExpressionValue(m => m.Apply);
                    var isValid = spObject != null &&
                                  installedPackageId == definition.SolutionId;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Apply, "Apply is false");
            }

            if (definition.Install)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.Install);
                    var isValid = spObject != null;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.Install, "Install is false");
            }

            assert.SkipProperty(m => m.MajorVersion, string.Empty);
            assert.SkipProperty(m => m.MinorVersion, string.Empty);
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var definition = model.WithAssertAndCast <UserCustomActionDefinition>("model", value => value.RequireNotNull());
            var spObject   = GetCurrentCustomUserAction(modelHost, definition);

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, definition, spObject)
                         .ShouldNotBeNull(spObject)
                         .ShouldBeEqual(m => m.Name, o => o.Name)
                         .ShouldBeEqual(m => m.Title, o => o.Title)
                         .ShouldBeEqual(m => m.Description, o => o.Description)
                         .ShouldBeEqual(m => m.Group, o => o.Group)
                         .ShouldBeEqual(m => m.Location, o => o.Location)

                         .ShouldBeEqual(m => m.Sequence, o => o.Sequence)
                         .ShouldBeEqual(m => m.Url, o => o.Url)
                         //.ShouldBeEqual(m => m.RegistrationId, o => o.RegistrationId)
                         .ShouldBeEqual(m => m.RegistrationType, o => o.GetRegistrationType());

            assert
            .ShouldBeEqual(m => m.ScriptSrc, o => o.ScriptSrc)
            .ShouldBeEqual(m => m.ScriptBlock, o => o.ScriptBlock);

            var registrationIdIsGuid = ConvertUtils.ToGuid(spObject.RegistrationId);

            if (registrationIdIsGuid.HasValue)
            {
                // this is list scoped user custom action reg
                // skipping validation
                assert.SkipProperty(m => m.RegistrationId, "RegistrationId is GUID. List scope user custom action. Skipping validation.");
            }
            else
            {
                assert.ShouldBeEqual(m => m.RegistrationId, o => o.RegistrationId);
            }

            assert
            .ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(def => def.Rights);
                var dstProp = d.GetExpressionValue(ct => ct.Rights);

                var hasCorrectRights = true;

                foreach (var srcRight in s.Rights)
                {
                    var srcPermission = (SPBasePermissions)Enum.Parse(typeof(SPBasePermissions), srcRight);

                    var tmpRight = d.Rights.HasFlag(srcPermission);

                    if (tmpRight == false)
                    {
                        hasCorrectRights = false;
                    }
                }

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = hasCorrectRights
                });
            });
        }
Exemple #12
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            base.DeployModel(modelHost, model);

            var folderModelHost = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull());

            var folder     = folderModelHost.CurrentListFolder;
            var definition = model.WithAssertAndCast <FilterDisplayTemplateDefinition>("model", value => value.RequireNotNull());

            var file     = GetItemFile(folderModelHost.CurrentList, folder, definition.FileName);
            var spObject = file.ListItemAllFields;

            var context = spObject.Context;

            context.Load(spObject);
            context.ExecuteQueryWithTrace();

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);



            if (!string.IsNullOrEmpty(definition.CompatibleManagedProperties))
            {
                assert.ShouldBeEqual(m => m.CompatibleManagedProperties, o => o.GetCompatibleManagedProperties());
            }
            else
            {
                assert.SkipProperty(m => m.CompatibleManagedProperties);
            }

            #region crawler xslt file

            if (!string.IsNullOrEmpty(definition.CrawlerXSLFileURL))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var isValid = false;

                    var srcProp        = s.GetExpressionValue(m => m.CrawlerXSLFileURL);
                    var crawlerXSLFile = d.GetCrawlerXSLFile();

                    if (crawlerXSLFile != null)
                    {
                        isValid = d.GetCrawlerXSLFile().Url == s.CrawlerXSLFileURL;
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.CrawlerXSLFileURL, "PreviewURL is NULL. Skipping");
            }

            if (!string.IsNullOrEmpty(definition.CrawlerXSLFileDescription))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var isValid = false;
                    var srcProp = s.GetExpressionValue(m => m.CrawlerXSLFileDescription);

                    var crawlerXSLFile = d.GetCrawlerXSLFile();

                    if (crawlerXSLFile != null)
                    {
                        isValid = d.GetCrawlerXSLFile().Description == s.CrawlerXSLFileDescription;
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.CrawlerXSLFileDescription, "PreviewDescription is NULL. Skipping");
            }

            #endregion


            if (definition.CompatibleSearchDataTypes.Count > 0)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CompatibleSearchDataTypes);
                    var isValid = true;

                    var targetValues = (d["CompatibleSearchDataTypes"] as string[])
                                       .Select(v => v.ToUpper()).ToList();

                    foreach (var v in s.CompatibleSearchDataTypes)
                    {
                        if (!targetValues.Contains(v.ToUpper()))
                        {
                            isValid = false;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.CompatibleSearchDataTypes, "CompatibleSearchDataTypes count is 0. Skipping");
            }
        }
Exemple #13
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var definition = model.WithAssertAndCast <FieldDefinition>("model", value => value.RequireNotNull());
            var spObject   = GetField(modelHost, definition);

            var assert = ServiceFactory.AssertService.NewAssert(model, definition, spObject);

            ValidateField(assert, spObject, definition);

            var textField      = spObject as SPFieldMultiChoice;
            var textDefinition = model.WithAssertAndCast <MultiChoiceFieldDefinition>("model", value => value.RequireNotNull());

            var textFieldAssert = ServiceFactory.AssertService.NewAssert(model, textDefinition, textField);

            textFieldAssert.ShouldBeEqual(m => m.FillInChoice, o => o.FillInChoice);

            // choices
            if (textDefinition.Choices.Count > 0)
            {
                var hasChoices = true;

                foreach (var dstChoice in textField.Choices)
                {
                    if (textDefinition.Choices.FirstOrDefault(c => c.ToUpper() == dstChoice.ToUpper()) == null)
                    {
                        hasChoices = false;
                    }
                }

                textFieldAssert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.Choices);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = hasChoices == true
                    });
                });
            }
            else
            {
                textFieldAssert.SkipProperty(m => m.Choices, "Choices.Count == 0. Skipping.");
            }

            // mappings
            if (textDefinition.Mappings.Count > 0)
            {
                var hasMapping = true;

                var mappings = XDocument.Parse(textField.Mappings)
                               .Descendants("MAPPING")
                               .Select(v => v.Value);

                foreach (var dstMapping in mappings)
                {
                    if (textDefinition.Mappings.FirstOrDefault(c => c.ToUpper() == dstMapping.ToUpper()) == null)
                    {
                        hasMapping = false;
                    }
                }

                textFieldAssert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.Mappings);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = hasMapping == true
                    });
                });
            }
            else
            {
                textFieldAssert.SkipProperty(m => m.Mappings, "Mappings.Count == 0. Skipping.");
            }
        }
Exemple #14
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            base.DeployModel(modelHost, model);

            var listModelHost = modelHost.WithAssertAndCast <FolderModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <ControlDisplayTemplateDefinition>("model", value => value.RequireNotNull());
            var folder        = listModelHost.CurrentLibraryFolder;

            var spObject = GetCurrentObject(folder, definition);
            var file     = spObject.File;

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject);

            #region crawler xslt file

            if (!string.IsNullOrEmpty(definition.CrawlerXSLFileURL))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CrawlerXSLFileURL);
                    var isValid = d.GetCrawlerXSLFile().Url == s.CrawlerXSLFileURL;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.CrawlerXSLFileURL, "PreviewURL is NULL. Skipping");
            }

            if (!string.IsNullOrEmpty(definition.CrawlerXSLFileDescription))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CrawlerXSLFileDescription);
                    var isValid = d.GetCrawlerXSLFile().Description == s.CrawlerXSLFileDescription;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.CrawlerXSLFileDescription, "PreviewDescription is NULL. Skipping");
            }

            #endregion

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(m => m.Content);
                //var dstProp = d.GetExpressionValue(ct => ct.GetId());

                var isContentValid = false;

                var srcStringContent = Encoding.UTF8.GetString(s.Content);
                var dstStringContent = Encoding.UTF8.GetString(file.GetContent());

                isContentValid = dstStringContent.Contains(srcStringContent);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    // Dst = dstProp,
                    IsValid = isContentValid
                });
            });
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            if (modelHost is SiteModelHost)
            {
                var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());
                var site          = siteModelHost.HostSite;

                var definition = model.WithAssertAndCast <SecurityGroupDefinition>("model", value => value.RequireNotNull());

                var web = site.RootWeb;

                var securityGroups = web.SiteGroups;
                var spObject       = securityGroups[definition.Name];

                var assert = ServiceFactory.AssertService
                             .NewAssert(definition, spObject)
                             .ShouldBeEqual(m => m.Name, o => o.Name)
                             .ShouldBeEqual(m => m.OnlyAllowMembersViewMembership, o => o.OnlyAllowMembersViewMembership);
                //ShouldBeEqual(m => m.Description, o => o.Description);

                if (!string.IsNullOrEmpty(definition.Description))
                {
                    assert.ShouldBeEqual(m => m.Description, o => o.Description);
                }
                else
                {
                    assert.SkipProperty(m => m.Description, "Description is NULL. Skipping.");
                }

                if (definition.AllowMembersEditMembership.HasValue)
                {
                    assert.ShouldBeEqual(m => m.AllowMembersEditMembership, o => o.AllowMembersEditMembership);
                }
                else
                {
                    assert.SkipProperty(m => m.AllowMembersEditMembership, "AllowMembersEditMembership is NULL. Skipping.");
                }

                if (definition.AllowRequestToJoinLeave.HasValue)
                {
                    assert.ShouldBeEqual(m => m.AllowRequestToJoinLeave, o => o.AllowRequestToJoinLeave);
                }
                else
                {
                    assert.SkipProperty(m => m.AllowRequestToJoinLeave, "AllowRequestToJoinLeave is NULL. Skipping.");
                }

                if (definition.AutoAcceptRequestToJoinLeave.HasValue)
                {
                    assert.ShouldBeEqual(m => m.AutoAcceptRequestToJoinLeave, o => o.AutoAcceptRequestToJoinLeave);
                }
                else
                {
                    assert.SkipProperty(m => m.AutoAcceptRequestToJoinLeave, "AutoAcceptRequestToJoinLeave is NULL. Skipping.");
                }


                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Owner);
                    var dstProp = d.GetExpressionValue(ct => ct.GetOwnerLogin());

                    var isValid = srcProp.Value.ToString().ToUpper().Replace("\\", "/") ==
                                  dstProp.Value.ToString().ToUpper().Replace("\\", "/");


                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.DefaultUser);
                    var dstProp = d.GetExpressionValue(ct => ct.GetDefaultUserLoginName());

                    var isValid = srcProp.Value.ToString().ToUpper().Replace("\\", "/") ==
                                  dstProp.Value.ToString().ToUpper().Replace("\\", "/");

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else if (modelHost is SecurityGroupModelHost)
            {
                // skip everything, just check if the group is therw

                var securityGroupModelHost = modelHost.WithAssertAndCast <SecurityGroupModelHost>("modelHost", value => value.RequireNotNull());
                var definition             = model.WithAssertAndCast <SecurityGroupDefinition>("model", value => value.RequireNotNull());

                var webMember = securityGroupModelHost.SecurityGroup.ParentWeb.EnsureUser(definition.Name);
                var spObject  = securityGroupModelHost.SecurityGroup.Users.OfType <SPPrincipal>()
                                .FirstOrDefault(u => u.ID == webMember.ID);

                var assert = ServiceFactory.AssertService
                             .NewAssert(definition, spObject)
                             .ShouldNotBeNull(spObject);

                assert.SkipProperty(m => m.Name);
                assert.SkipProperty(m => m.AllowMembersEditMembership, "");
                assert.SkipProperty(m => m.AllowRequestToJoinLeave, "");
                assert.SkipProperty(m => m.AutoAcceptRequestToJoinLeave, "");
                assert.SkipProperty(m => m.DefaultUser, "");
                assert.SkipProperty(m => m.Description, "");
                assert.SkipProperty(m => m.IsAssociatedMemberGroup, "");
                assert.SkipProperty(m => m.IsAssociatedVisitorsGroup, "");
                assert.SkipProperty(m => m.IsAssociatedOwnerGroup, "");

                assert.SkipProperty(m => m.OnlyAllowMembersViewMembership, "");
                assert.SkipProperty(m => m.Owner, "");
            }
            else
            {
                throw new SPMeta2UnsupportedModelHostException("modelHost");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var securableObject = ExtractSecurableObject(modelHost);
            var definition      = model.WithAssertAndCast <SecurityGroupLinkDefinition>("model", value => value.RequireNotNull());

            var web      = GetWebFromSPSecurableObject(securableObject);
            var spObject = ResolveSecurityGroup(web, definition);

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);


            if (!string.IsNullOrEmpty(definition.SecurityGroupName))
            {
                assert.ShouldBeEqual(m => m.SecurityGroupName, o => o.Name);
            }
            else
            {
                assert.SkipProperty(m => m.SecurityGroupName, "SecurityGroupName is null or empty. Skipping.");
            }

            if (definition.IsAssociatedMemberGroup)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.IsAssociatedMemberGroup);
                    var dstProp = d.GetExpressionValue(o => o.GetAssociatedMemberGroup());

                    var isValid = spObject.ID == web.AssociatedMemberGroup.ID;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.IsAssociatedMemberGroup, "IsAssociatedMemberGroup is false. Skipping.");
            }

            if (definition.IsAssociatedOwnerGroup)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.IsAssociatedOwnerGroup);
                    var dstProp = d.GetExpressionValue(o => o.GetAssociatedOwnerGroup());

                    var isValid = spObject.ID == web.AssociatedOwnerGroup.ID;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.IsAssociatedOwnerGroup, "IsAssociatedOwnerGroup is false. Skipping.");
            }

            if (definition.IsAssociatedVisitorGroup)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.IsAssociatedVisitorGroup);
                    var dstProp = d.GetExpressionValue(o => o.GetAssociatedVisitorGroup());

                    var isValid = spObject.ID == web.AssociatedVisitorGroup.ID;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.IsAssociatedVisitorGroup, "IsAssociatedVisitorsGroup is false. Skipping.");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <ListFieldLinkDefinition>("model", value => value.RequireNotNull());

            var list     = listModelHost.HostList;
            var spObject = FindExistingListField(list, definition);

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            if (!string.IsNullOrEmpty(definition.FieldInternalName))
            {
                assert.ShouldBeEqual(m => m.FieldInternalName, o => o.InternalName);
            }
            else
            {
                assert.SkipProperty(m => m.FieldInternalName, "FieldInternalName is null or empty. Skipping");
            }

            if (definition.FieldId.HasGuidValue())
            {
                assert.ShouldBeEqual(m => m.FieldId, o => o.Id);
            }
            else
            {
                assert.SkipProperty(m => m.FieldId, "FieldId is null or empty. Skipping");
            }

            if (!string.IsNullOrEmpty(definition.DisplayName))
            {
                assert.ShouldBeEqual(m => m.DisplayName, o => o.Title);
            }
            else
            {
                assert.SkipProperty(m => m.DisplayName, "DisplayName is null or empty. Skipping");
            }

            if (definition.Required.HasValue)
            {
                assert.ShouldBeEqual(m => m.Required, o => o.Required);
            }
            else
            {
                assert.SkipProperty(m => m.Required, "Required is null or empty. Skipping");
            }

            if (definition.Hidden.HasValue)
            {
                assert.ShouldBeEqual(m => m.Hidden, o => o.Hidden);
            }
            else
            {
                assert.SkipProperty(m => m.Hidden, "Hidden is null or empty. Skipping");
            }

            if (definition.AddFieldOptions.HasFlag(BuiltInAddFieldOptions.DefaultValue))
            {
                assert.SkipProperty(m => m.AddFieldOptions, "BuiltInAddFieldOptions.DefaultValue. Skipping.");
            }

            if (definition.AddFieldOptions.HasFlag(BuiltInAddFieldOptions.AddToAllContentTypes))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.AddFieldOptions);
                    var isValid = true;

                    var listContentTypes = list.ContentTypes;

                    foreach (SPContentType ct in listContentTypes)
                    {
                        // TODO!
                        if (ct.Name == "Folder")
                        {
                            // skip folder content type
                            continue;
                        }

                        isValid = ct.FieldLinks.OfType <SPFieldLink>().Count(l => l.Name == spObject.InternalName) > 0;

                        if (!isValid)
                        {
                            break;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }

            if (definition.AddFieldOptions.HasFlag(BuiltInAddFieldOptions.AddFieldToDefaultView))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.AddFieldOptions);
                    var isValid = false;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }

            if (definition.AddToDefaultView)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.AddToDefaultView);
                    var field   = FindExistingListField(list, definition);

                    var isValid = list.DefaultView
                                  .ViewFields
                                  .ToStringCollection()
                                  .Contains(field.InternalName);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.AddToDefaultView, "AddToDefaultView is false. Skipping.");
            }
        }
Exemple #18
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            base.DeployModel(modelHost, model);

            var listItemModelHost = modelHost.WithAssertAndCast <ListItemModelHost>("modelHost", value => value.RequireNotNull());
            var definition        = model.WithAssertAndCast <ContentBySearchWebPartDefinition>("model", value => value.RequireNotNull());

            var pageItem = listItemModelHost.HostListItem;

            WithWithExistingWebPart(pageItem, definition, spObject =>
            {
                var assert = ServiceFactory.AssertService
                             .NewAssert(model, definition, spObject)
                             .ShouldNotBeNull(spObject);

                if (!string.IsNullOrEmpty(definition.GroupTemplateId))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.GroupTemplateId, "GroupTemplateId is null or empty, skipping.");
                }

                if (!string.IsNullOrEmpty(definition.ItemTemplateId))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.ItemTemplateId, "ItemTemplateId is null or empty, skipping.");
                }

                if (!string.IsNullOrEmpty(definition.RenderTemplateId))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.RenderTemplateId, "RenderTemplateId is null or empty, skipping.");
                }

                if (!string.IsNullOrEmpty(definition.DataProviderJSON))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.DataProviderJSON, "DataProviderJSON is null or empty, skipping.");
                }

                if (definition.NumberOfItems.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.NumberOfItems, "NumberOfItems is null or empty, skipping.");
                }

                if (definition.ResultsPerPage.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.ResultsPerPage, "ResultsPerPage is null or empty, skipping.");
                }

                //
                if (!string.IsNullOrEmpty(definition.PropertyMappings))
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.PropertyMappings, "PropertyMappings is null or empty, skipping.");
                }

                if (definition.OverwriteResultPath.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.OverwriteResultPath, "OverwriteResultPath is null or empty, skipping.");
                }

                if (definition.ShouldHideControlWhenEmpty.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.ShouldHideControlWhenEmpty, "ShouldHideControlWhenEmpty is null or empty, skipping.");
                }

                if (definition.LogAnalyticsViewEvent.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.LogAnalyticsViewEvent, "LogAnalyticsViewEvent is null or empty, skipping.");
                }

                if (definition.AddSEOPropertiesFromSearch.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.AddSEOPropertiesFromSearch, "AddSEOPropertiesFromSearch is null or empty, skipping.");
                }

                if (definition.StartingItemIndex.HasValue)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    assert.SkipProperty(m => m.StartingItemIndex, "StartingItemIndex is null or empty, skipping.");
                }
            });
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());
            var definition   = model.WithAssertAndCast <WebNavigationSettingsDefinition>("model",
                                                                                         value => value.RequireNotNull());

            var spObject = GetWebNavigationSettings(webModelHost, definition);
            var web      = webModelHost.HostWeb;

            var context = web.Context;

            context.Load(spObject);
            context.Load(spObject.GlobalNavigation);
            context.Load(spObject.CurrentNavigation);

            context.Load(web, w => w.AllProperties);

            context.ExecuteQueryWithTrace();

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            //  web??/_layouts/15/AreaNavigationSettings.aspx
            // extra protection, downbloading HTML page and making sure checkboxes are there :)

            //<input name="ctl00$PlaceHolderMain$globalNavSection$ctl02$globalIncludeSubSites" type="checkbox" id="ctl00_PlaceHolderMain_globalNavSection_ctl02_globalIncludeSubSites" checked="checked">
            //<input name="ctl00$PlaceHolderMain$globalNavSection$ctl02$globalIncludePages" type="checkbox" id="ctl00_PlaceHolderMain_globalNavSection_ctl02_globalIncludePages" disabled="disabled">


            //<input name="ctl00$PlaceHolderMain$currentNavSection$ctl02$currentIncludeSubSites" type="checkbox" id="ctl00_PlaceHolderMain_currentNavSection_ctl02_currentIncludeSubSites">
            //<input name="ctl00$PlaceHolderMain$currentNavSection$ctl02$currentIncludePages" type="checkbox" id="ctl00_PlaceHolderMain_currentNavSection_ctl02_currentIncludePages" disabled="disabled">
            var pageUrl = UrlUtility.CombineUrl(web.Url, "/_layouts/15/AreaNavigationSettings.aspx");

            var client = new WebClient();

            if (context.Credentials != null)
            {
                client.Credentials = context.Credentials;
                client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            }
            else
            {
                client.UseDefaultCredentials = true;
            }

            var pageContent = client.DownloadString(new Uri(pageUrl));
            CQ  j           = pageContent;

            // so not only API, but also real checkboxed on browser page check
            var globalSubSites      = j.Select("input[id$='globalIncludeSubSites']").First();
            var globalSubSitesValue = globalSubSites.Attr("checked") == "checked";

            var globalIncludePages      = j.Select("input[id$='globalIncludePages']").First();
            var globalIncludePagesValue = globalIncludePages.Attr("checked") == "checked";

            var currentIncludeSubSites      = j.Select("input[id$='currentIncludeSubSites']").First();
            var currentIncludeSubSitesValue = currentIncludeSubSites.Attr("checked") == "checked";

            var currentIncludePages      = j.Select("input[id$='currentIncludePages']").First();
            var currentIncludePagesValue = currentIncludePages.Attr("checked") == "checked";

            // global types
            if (definition.GlobalNavigationShowSubsites.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var navIncludeTypesValueString = web.AllProperties.FieldValues.ContainsKey(BuiltInWebPropertyId.GlobalNavigationIncludeTypes)
                   ? web.AllProperties[BuiltInWebPropertyId.GlobalNavigationIncludeTypes]
                   : string.Empty;

                    var globalNavIncludeTypesValue = ConvertUtils.ToInt(navIncludeTypesValueString);

                    var isGlobalNavIncludeTypesValid = false;

                    if (definition.GlobalNavigationShowSubsites.Value)
                    {
                        isGlobalNavIncludeTypesValid =
                            ((globalNavIncludeTypesValue & 1) == 1) && (globalSubSitesValue);
                    }
                    else
                    {
                        isGlobalNavIncludeTypesValid =
                            ((globalNavIncludeTypesValue & 1) != 1) && (!globalSubSitesValue);
                    }


                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationShowSubsites);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isGlobalNavIncludeTypesValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.GlobalNavigationShowSubsites,
                                    "GlobalNavigationShowSubsites is null or empty");
            }

            if (definition.GlobalNavigationShowPages.HasValue)
            {
                var currentNavIncludeTypesValueString = web.AllProperties.FieldValues.ContainsKey(BuiltInWebPropertyId.GlobalNavigationIncludeTypes)
                    ? web.AllProperties[BuiltInWebPropertyId.GlobalNavigationIncludeTypes]
                    : string.Empty;

                var globalNavIncludeTypesValue =
                    ConvertUtils.ToInt(currentNavIncludeTypesValueString);

                var isGlobalNavIncludeTypesValid = false;

                if (definition.GlobalNavigationShowPages.Value)
                {
                    isGlobalNavIncludeTypesValid =
                        ((globalNavIncludeTypesValue & 2) == 2) && (globalIncludePagesValue);
                }
                else
                {
                    isGlobalNavIncludeTypesValid =
                        ((globalNavIncludeTypesValue & 2) != 2 && (!globalIncludePagesValue));
                }

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationShowPages);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isGlobalNavIncludeTypesValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.GlobalNavigationShowPages,
                                    "GlobalNavigationShowPages is null or empty");
            }


            if (definition.CurrentNavigationShowSubsites.HasValue)
            {
                var currentNavIncludeTypesValueString = web.AllProperties.FieldValues.ContainsKey(BuiltInWebPropertyId.CurrentNavigationIncludeTypes)
                    ? web.AllProperties[BuiltInWebPropertyId.CurrentNavigationIncludeTypes]
                    : string.Empty;

                var currentNavIncludeTypesValue = ConvertUtils.ToInt(currentNavIncludeTypesValueString);

                var isGlobalNavIncludeTypesValid = false;

                if (definition.CurrentNavigationShowSubsites.Value)
                {
                    isGlobalNavIncludeTypesValid =
                        ((currentNavIncludeTypesValue & 1) == 1) && (currentIncludeSubSitesValue);
                }
                else
                {
                    isGlobalNavIncludeTypesValid =
                        ((currentNavIncludeTypesValue & 1) != 1) && (!currentIncludeSubSitesValue);
                }


                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationShowSubsites);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isGlobalNavIncludeTypesValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.CurrentNavigationShowSubsites,
                                    "CurrentNavigationShowSubsites is null or empty");
            }

            if (definition.CurrentNavigationShowPages.HasValue)
            {
                var currentNavIncludeTypesValueString = web.AllProperties.FieldValues.ContainsKey(BuiltInWebPropertyId.CurrentNavigationIncludeTypes)
                    ? web.AllProperties[BuiltInWebPropertyId.CurrentNavigationIncludeTypes]
                    : string.Empty;

                var currentNavIncludeTypesValue = ConvertUtils.ToInt(currentNavIncludeTypesValueString);

                var isGlobalNavIncludeTypesValid = false;

                if (definition.CurrentNavigationShowPages.Value)
                {
                    isGlobalNavIncludeTypesValid =
                        ((currentNavIncludeTypesValue & 2) == 2) && (currentIncludeSubSitesValue);
                }
                else
                {
                    isGlobalNavIncludeTypesValid =
                        ((currentNavIncludeTypesValue & 2) != 2) && (!currentIncludeSubSitesValue);
                }

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationShowPages);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isGlobalNavIncludeTypesValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.CurrentNavigationShowPages,
                                    "CurrentNavigationShowPages is null or empty");
            }

            // items count
            if (definition.GlobalNavigationMaximumNumberOfDynamicItems.HasValue)
            {
                var globalDynamicChildLimitValue =
                    ConvertUtils.ToInt(web.AllProperties[BuiltInWebPropertyId.GlobalDynamicChildLimit]);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationMaximumNumberOfDynamicItems);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.GlobalNavigationMaximumNumberOfDynamicItems == globalDynamicChildLimitValue
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.GlobalNavigationMaximumNumberOfDynamicItems,
                                    "GlobalNavigationMaximumNumberOfDynamicItems is null or empty");
            }

            if (definition.CurrentNavigationMaximumNumberOfDynamicItems.HasValue)
            {
                var currentDynamicChildLimitValue =
                    ConvertUtils.ToInt(web.AllProperties[BuiltInWebPropertyId.CurrentDynamicChildLimit]);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationMaximumNumberOfDynamicItems);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.CurrentNavigationMaximumNumberOfDynamicItems == currentDynamicChildLimitValue
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.CurrentNavigationMaximumNumberOfDynamicItems,
                                    "CurrentNavigationMaximumNumberOfDynamicItems is null or empty");
            }

            if (definition.DisplayShowHideRibbonAction.HasValue)
            {
                var displayShowHideRibbonActionValue =
                    ConvertUtils.ToBool(web.AllProperties[BuiltInWebPropertyId.DisplayShowHideRibbonActionId]);

                // If displayShowHideRibbonActionValue has no value, property should be skipped, but I don't know how to get ShouldBeEqualIfHasValue to work

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.DisplayShowHideRibbonAction);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.DisplayShowHideRibbonAction.Value == displayShowHideRibbonActionValue.Value
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.DisplayShowHideRibbonAction,
                                    "DisplayShowHideRibbonAction is null or empty");
            }

            // nav sources
            if (!string.IsNullOrEmpty(definition.GlobalNavigationSource))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.GlobalNavigationSource);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.GlobalNavigationSource == spObject.GlobalNavigation.Source.ToString()
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.GlobalNavigationSource,
                                    "GlobalNavigationSource is null or empty");
            }

            if (!string.IsNullOrEmpty(definition.CurrentNavigationSource))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.CurrentNavigationSource);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = s.CurrentNavigationSource == spObject.CurrentNavigation.Source.ToString()
                    });
                });
            }
            else
            {
                assert.SkipProperty(d => d.CurrentNavigationSource,
                                    "CurrentNavigationSource is null or empty");
            }

            if (definition.AddNewPagesToNavigation.HasValue)
            {
                if (!string.IsNullOrEmpty(definition.GlobalNavigationSource) || !string.IsNullOrEmpty(definition.CurrentNavigationSource))
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(m => m.AddNewPagesToNavigation);

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = s.AddNewPagesToNavigation.Value == spObject.AddNewPagesToNavigation
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(d => d.AddNewPagesToNavigation,
                                        "AddNewPagesToNavigation requires GlobalNavigationSource or CurrentNavigationSource to be not null");
                }
            }
            else
            {
                assert.SkipProperty(d => d.AddNewPagesToNavigation,
                                    "AddNewPagesToNavigation is null");
            }

            if (definition.CreateFriendlyUrlsForNewPages.HasValue)
            {
                if (!string.IsNullOrEmpty(definition.GlobalNavigationSource) || !string.IsNullOrEmpty(definition.CurrentNavigationSource))
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(m => m.CreateFriendlyUrlsForNewPages);

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = s.CreateFriendlyUrlsForNewPages.Value == spObject.CreateFriendlyUrlsForNewPages
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(d => d.CreateFriendlyUrlsForNewPages,
                                        "CreateFriendlyUrlsForNewPages requires GlobalNavigationSource or CurrentNavigationSource to be not null");
                }
            }
            else
            {
                assert.SkipProperty(d => d.CreateFriendlyUrlsForNewPages,
                                    "CreateFriendlyUrlsForNewPages is null");
            }
        }
Exemple #20
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());

            var web       = webModelHost.HostWeb;
            var listModel = model.WithAssertAndCast <ListDefinition>("model", value => value.RequireNotNull());

            var context = web.Context;

            context.Load(web, w => w.ServerRelativeUrl);
            context.ExecuteQueryWithTrace();

            List currentList = null;

            var loadedList = LoadCurrentList(web, listModel);

            if (loadedList != null)
            {
                currentList = loadedList;
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = null,
                ObjectType       = typeof(List),
                ObjectDefinition = model,
                ModelHost        = modelHost
            });

            // gosh!
            //currentList = FindListByUrl(lists, listModel.GetListUrl());

            if (currentList == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list");

                // no support for the TemplateName yet
                var listInfo = new ListCreationInformation
                {
                    Title       = listModel.Title,
                    Description = listModel.Description ?? string.Empty,
#pragma warning disable 618
                    Url = listModel.GetListUrl()
#pragma warning restore 618
                };

                if (listModel.TemplateType > 0)
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateType: [{0}]", listModel.TemplateType);

                    listInfo.TemplateType = listModel.TemplateType;
                }
                else if (!string.IsNullOrEmpty(listModel.TemplateName))
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Creating list by TemplateName: [{0}]", listModel.TemplateName);


                    var listTemplate = ResolveListTemplate(webModelHost, listModel);

                    listInfo.TemplateFeatureId = listTemplate.FeatureId;
                    listInfo.TemplateType      = listTemplate.ListTemplateTypeKind;
                }
                else
                {
                    TraceService.Error((int)LogEventId.ModelProvisionCoreCall, "Either TemplateType or TemplateName has to be specified. Throwing SPMeta2Exception");

                    throw new SPMeta2Exception("Either TemplateType or TemplateName has to be specified.");
                }

                var newList = web.Lists.Add(listInfo);
                currentList = newList;

                currentList.Update();
                context.ExecuteQueryWithTrace();

                currentList = LoadCurrentList(web, listModel);
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list");
            }

            MapListProperties(currentList, listModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentList,
                ObjectType       = typeof(List),
                ObjectDefinition = model,
                ModelHost        = modelHost
            });

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentList.Update()");

            currentList.Update();
            context.ExecuteQueryWithTrace();
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            Folder targetFolder = null;
            Web    web          = null;

            if (modelHost is ListModelHost)
            {
                targetFolder = (modelHost as ListModelHost).HostList.RootFolder;
                web          = (modelHost as ListModelHost).HostWeb;
            }
            if (modelHost is FolderModelHost)
            {
                targetFolder = (modelHost as FolderModelHost).CurrentListFolder;
                web          = (modelHost as FolderModelHost).HostWeb;
            }

            var definition = model.WithAssertAndCast <WebpartPresenceOnPageDefinition>("model", value => value.RequireNotNull());

            var folder  = targetFolder;
            var allItem = folder.ListItemAllFields;

            var context = folder.Context;

            context.Load(folder, f => f.ServerRelativeUrl);
            context.Load(allItem);

            context.ExecuteQuery();

            var pageName = GetSafeWikiPageFileName(definition.PageFileName);
            var file     = web.GetFileByServerRelativeUrl(UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName));

            context.Load(file);
            context.ExecuteQueryWithTrace();

            var serverUrl = web.Url;

            if (web.ServerRelativeUrl != "/")
            {
                serverUrl = serverUrl.Replace(web.ServerRelativeUrl, string.Empty);
            }

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, file)
                         // dont' need to check that, not the pupose of the test
                         //.ShouldBeEqual(m => m.PageFileName, o => o.GetName())
                         .ShouldNotBeNull(file);

            var pageUrl = UrlUtility.CombineUrl(new[] {
                serverUrl,
                folder.ServerRelativeUrl,
                pageName
            });

            if (definition.WebPartDefinitions.Any())
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var client = new WebClient();
                    client.UseDefaultCredentials = true;

                    if (context.Credentials != null)
                    {
                        client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                        client.Credentials = context.Credentials;
                    }

                    var pageContent = client.DownloadString(new Uri(pageUrl));
                    var srcProp     = s.GetExpressionValue(m => m.WebPartDefinitions);

                    var isValid = true;

                    TraceUtils.WithScope(trace =>
                    {
                        trace.WriteLine(string.Format("Checking web part presence on the page:[{0}]", pageUrl));

                        // so, essentially there should be a span with web part title
                        foreach (var webpart in definition.WebPartDefinitions)
                        {
                            var targetSpan = string.Format("<span>{0}</span>", webpart.Title);
                            var hasWebPart = pageContent.Contains(targetSpan);

                            if (!hasWebPart)
                            {
                                trace.WriteLine(
                                    string.Format("[ERR] Page [{0}] misses web part with title:[{1}] and def:[{2}]",
                                                  new object[]
                                {
                                    pageUrl,
                                    webpart.Title,
                                    webpart
                                }));

                                isValid = false;
                            }
                            else
                            {
                                trace.WriteLine(string.Format("[True] Page [{0}] has web part with title:[{1}] and def:[{2}]",
                                                              new object[]
                                {
                                    pageUrl,
                                    webpart.Title,
                                    webpart
                                }));
                            }
                        }
                    });

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        //Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.WebPartDefinitions, "WebPartDefinitions.Count = 0. Skipping");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var host       = modelHost.WithAssertAndCast <WebpartPageModelHost>("modelHost", value => value.RequireNotNull());
            var definition = model.WithAssertAndCast <WebPartDefinition>("model", value => value.RequireNotNull());

            var item = host.PageListItem;

            WebPartExtensions.WithExistingWebPart(item, definition, (spWebPartManager, spObject) =>
            {
                //[FALSE] - [Title]
                //                        [FALSE] - [Id]
                //                        [FALSE] - [ZoneId]
                //                        [FALSE] - [ZoneIndex]
                //                        [FALSE] - [WebpartFileName]
                //                        [FALSE] - [WebpartType]
                //                        [FALSE] - [WebpartXmlTemplate]

                var assert = ServiceFactory.AssertService
                             .NewAssert(definition, spObject)
                             .ShouldNotBeNull(spObject);

                if (!string.IsNullOrEmpty(definition.Id))
                {
                    assert.ShouldBeEqual(m => m.Id, o => o.ID);
                }
                else
                {
                    assert.SkipProperty(m => m.Id, "Id is null or empty. Skipping.");
                }

                if (!string.IsNullOrEmpty(definition.Title))
                {
                    assert.ShouldBeEqual(m => m.Title, o => o.Title);
                }
                else
                {
                    assert.SkipProperty(m => m.Title, "Title is null or empty. Skipping.");
                }

                if (!string.IsNullOrEmpty(definition.ZoneId))
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(m => m.ZoneId);
                        //var dstProp = d.GetExpressionValue(ct => ct.GetId());

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = object.Equals(s.ZoneId, spWebPartManager.GetZoneID(d))
                        });
                    });
                }

                else
                {
                    assert.SkipProperty(m => m.ZoneId, "ZoneId is null or empty. Skipping.");
                }

                //if (definition.ZoneIndex > 0)
                //    assert.ShouldBeEqual(m => m.ZoneIndex, o => o.ZoneIndex);
                //else
                //    assert.SkipProperty(m => m.ZoneIndex, "ZoneIndex == 0. Skipping.");

                assert.SkipProperty(m => m.ZoneIndex, "Skipping.");

                if (!string.IsNullOrEmpty(definition.WebpartFileName))
                {
                    var site = host.PageListItem.Web.Site;

                    var webPartManager = host.SPLimitedWebPartManager;

                    var webpartFileName = definition.WebpartFileName;
                    var rootWeb         = site.RootWeb;

                    // load definition from WP catalog
                    var webpartCatalog = rootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                    var webpartItem    = webpartCatalog.Items.OfType <SPListItem>().FirstOrDefault(
                        i => string.Compare(i.Name, webpartFileName, true) == 0);

                    if (webpartItem == null)
                    {
                        throw new ArgumentException(string.Format("webpartItem. Can't find web part file with name: {0}", webpartFileName));
                    }

                    using (var streamReader = new MemoryStream(webpartItem.File.OpenBinary()))
                    {
                        using (var xmlReader = XmlReader.Create(streamReader))
                        {
                            var errMessage          = string.Empty;
                            var webpartInstance     = webPartManager.ImportWebPart(xmlReader, out errMessage);
                            var webPartInstanceType = webpartInstance.GetType();

                            assert.ShouldBeEqual((p, s, d) =>
                            {
                                var srcProp = s.GetExpressionValue(m => m.WebpartFileName);
                                //var dstProp = d.GetExpressionValue(ct => ct.GetId());

                                return(new PropertyValidationResult
                                {
                                    Tag = p.Tag,
                                    Src = srcProp,
                                    Dst = null,
                                    IsValid = webPartInstanceType == d.GetType()
                                });
                            });
                        }
                    }
                }
                else
                {
                    assert.SkipProperty(m => m.WebpartFileName, "ZoneIndex == 0. Skipping.");
                }

                if (!string.IsNullOrEmpty(definition.WebpartType))
                {
                    var webPartInstance     = WebPartExtensions.ResolveWebPartInstance(host.PageListItem.Web.Site, host.SPLimitedWebPartManager, definition);
                    var webPartInstanceType = webPartInstance.GetType();

                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(m => m.WebpartType);
                        //var dstProp = d.GetExpressionValue(ct => ct.GetId());

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = webPartInstanceType == d.GetType()
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.WebpartType, "WebpartType is empty. Skipping.");
                }

                if (!string.IsNullOrEmpty(definition.WebpartXmlTemplate))
                {
                    throw new SPMeta2NotImplementedException("WebpartXmlTemplate validation is not supported yet.");
                }
                else
                {
                    assert.SkipProperty(m => m.WebpartXmlTemplate, "WebpartXmlTemplate is empty. Skipping.");
                }
            });
        }
Exemple #23
0
 public override void DeployModel(object modelHost, DefinitionBase model)
 {
     var web      = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());
     var webModel = model.WithAssertAndCast <WebDefinition>("model", value => value.RequireNotNull());
 }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());
            var web          = webModelHost.HostWeb;

            var definition = model.WithAssertAndCast <ListDefinition>("model", value => value.RequireNotNull());

#pragma warning disable 618
            var spObject = web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, definition.GetListUrl()));
#pragma warning restore 618

            var assert = ServiceFactory.AssertService.NewAssert(model, definition, spObject);

            assert
            .ShouldBeEqual(m => m.Title, o => o.Title)
            //.ShouldBeEqual(m => m.Hidden, o => o.Hidden)
            //.ShouldBeEqual(m => m.Description, o => o.Description)
            //.ShouldBeEqual(m => m.IrmEnabled, o => o.IrmEnabled)
            //.ShouldBeEqual(m => m.IrmExpire, o => o.IrmExpire)
            //.ShouldBeEqual(m => m.IrmReject, o => o.IrmReject)
            //.ShouldBeEndOf(m => m.GetListUrl(), m => m.Url, o => o.GetServerRelativeUrl(), o => o.GetServerRelativeUrl())
            .ShouldBeEqual(m => m.ContentTypesEnabled, o => o.ContentTypesEnabled);

            if (!string.IsNullOrEmpty(definition.Description))
            {
                assert.ShouldBeEqual(m => m.Description, o => o.Description);
            }
            else
            {
                assert.SkipProperty(m => m.Description);
            }


            if (!string.IsNullOrEmpty(definition.DraftVersionVisibility))
            {
                var draftOption = (DraftVisibilityType)Enum.Parse(typeof(DraftVisibilityType), definition.DraftVersionVisibility);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.DraftVersionVisibility);
                    var dstProp = d.GetExpressionValue(m => m.DraftVersionVisibility);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = draftOption == (DraftVisibilityType)dstProp.Value
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.DraftVersionVisibility, "Skipping from validation. DraftVersionVisibility IS NULL");
            }

#pragma warning disable 618
            if (!string.IsNullOrEmpty(definition.Url))
            {
                assert.ShouldBeEndOf(m => m.GetListUrl(), m => m.Url, o => o.GetServerRelativeUrl(), o => o.GetServerRelativeUrl());
            }
            else
            {
                assert.SkipProperty(m => m.Url, "Skipping from validation. Url IS NULL");
            }
#pragma warning restore 618

            if (!string.IsNullOrEmpty(definition.CustomUrl))
            {
                assert.ShouldBeEndOf(m => m.CustomUrl, o => o.GetServerRelativeUrl());
            }
            else
            {
                assert.SkipProperty(m => m.CustomUrl, "Skipping from validation. CustomUrl IS NULL");
            }

            // common
            if (definition.EnableAttachments.HasValue)
            {
                assert.ShouldBeEqual(m => m.EnableAttachments, o => o.EnableAttachments);
            }
            else
            {
                assert.SkipProperty(m => m.EnableAttachments, "Skipping from validation. EnableAttachments IS NULL");
            }

            if (definition.EnableFolderCreation.HasValue)
            {
                assert.ShouldBeEqual(m => m.EnableFolderCreation, o => o.EnableFolderCreation);
            }
            else
            {
                assert.SkipProperty(m => m.EnableFolderCreation, "Skipping from validation. EnableFolderCreation IS NULL");
            }

            if (definition.EnableMinorVersions.HasValue)
            {
                assert.ShouldBeEqual(m => m.EnableMinorVersions, o => o.EnableMinorVersions);
            }
            else
            {
                assert.SkipProperty(m => m.EnableMinorVersions, "Skipping from validation. EnableMinorVersions IS NULL");
            }

            if (definition.EnableModeration.HasValue)
            {
                assert.ShouldBeEqual(m => m.EnableModeration, o => o.EnableModeration);
            }
            else
            {
                assert.SkipProperty(m => m.EnableModeration, "Skipping from validation. EnableModeration IS NULL");
            }

            if (definition.EnableVersioning.HasValue)
            {
                assert.ShouldBeEqual(m => m.EnableVersioning, o => o.EnableVersioning);
            }
            else
            {
                assert.SkipProperty(m => m.EnableVersioning, "Skipping from validation. EnableVersioning IS NULL");
            }

            if (definition.ForceCheckout.HasValue)
            {
                assert.ShouldBeEqual(m => m.ForceCheckout, o => o.ForceCheckout);
            }
            else
            {
                assert.SkipProperty(m => m.ForceCheckout, "Skipping from validation. ForceCheckout IS NULL");
            }

            if (definition.Hidden.HasValue)
            {
                assert.ShouldBeEqual(m => m.Hidden, o => o.Hidden);
            }
            else
            {
                assert.SkipProperty(m => m.Hidden, "Skipping from validation. Hidden IS NULL");
            }

            if (definition.NoCrawl.HasValue)
            {
                assert.ShouldBeEqual(m => m.NoCrawl, o => o.NoCrawl);
            }
            else
            {
                assert.SkipProperty(m => m.NoCrawl, "Skipping from validation. NoCrawl IS NULL");
            }


            if (definition.OnQuickLaunch.HasValue)
            {
                assert.ShouldBeEqual(m => m.OnQuickLaunch, o => o.OnQuickLaunch);
            }
            else
            {
                assert.SkipProperty(m => m.OnQuickLaunch, "Skipping from validation. OnQuickLaunch IS NULL");
            }

            // IRM
            if (definition.IrmEnabled.HasValue)
            {
                assert.ShouldBeEqual(m => m.IrmEnabled, o => o.IrmEnabled);
            }
            else
            {
                assert.SkipProperty(m => m.IrmEnabled, "Skipping from validation. IrmEnabled IS NULL");
            }

            if (definition.IrmExpire.HasValue)
            {
                assert.ShouldBeEqual(m => m.IrmExpire, o => o.IrmExpire);
            }
            else
            {
                assert.SkipProperty(m => m.IrmExpire, "Skipping from validation. IrmExpire IS NULL");
            }

            if (definition.IrmReject.HasValue)
            {
                assert.ShouldBeEqual(m => m.IrmReject, o => o.IrmReject);
            }
            else
            {
                assert.SkipProperty(m => m.IrmReject, "Skipping from validation. IrmReject IS NULL");
            }

            if (definition.TemplateType > 0)
            {
                assert
                .ShouldBeEqual(m => m.TemplateType, o => (int)o.BaseTemplate)
                .SkipProperty(m => m.TemplateName, "Skipping from validation. TemplateType should be == 0");
            }
            else
            {
                assert
                .SkipProperty(m => m.TemplateType, "Skipping from validation. TemplateName should be empty");

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp      = s.GetExpressionValue(m => m.TemplateName);
                    var listTemplate = ResolveListTemplate(web, definition);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid =
                            (spObject.TemplateFeatureId == listTemplate.FeatureId) &&
                            ((int)spObject.BaseTemplate == (int)listTemplate.Type)
                    });
                });
            }

            if (definition.MajorVersionLimit.HasValue)
            {
                assert.ShouldBeEqual(m => m.MajorVersionLimit, o => o.MajorVersionLimit);
            }
            else
            {
                assert.SkipProperty(m => m.MajorVersionLimit, "Skipping from validation. MajorVersionLimit IS NULL");
            }

            if (definition.MajorWithMinorVersionsLimit.HasValue)
            {
                assert.ShouldBeEqual(m => m.MajorWithMinorVersionsLimit, o => o.MajorWithMinorVersionsLimit);
            }
            else
            {
                assert.SkipProperty(m => m.MajorWithMinorVersionsLimit, "Skipping from validation. MajorWithMinorVersionsLimit IS NULL");
            }


            // template url
            if (string.IsNullOrEmpty(definition.DocumentTemplateUrl) || !(spObject is SPDocumentLibrary))
            {
                assert.SkipProperty(m => m.DocumentTemplateUrl, string.Format("Skipping DocumentTemplateUrl or list is not a document library. Skipping."));
            }
            else
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.DocumentTemplateUrl);
                    var dstProp = (spObject as SPDocumentLibrary).DocumentTemplateUrl;

                    var srcUrl = srcProp.Value as string;
                    var dstUrl = dstProp;

                    if (!dstUrl.StartsWith("/"))
                    {
                        dstUrl = "/" + dstUrl;
                    }

                    if (!srcUrl.StartsWith("/"))
                    {
                        srcUrl = "/" + srcUrl;
                    }

                    srcUrl = srcUrl.ToLower();
                    dstUrl = dstUrl.ToLower();

                    var isValid = false;

                    if (s.DocumentTemplateUrl.Contains("~sitecollection"))
                    {
                        var siteCollectionUrl = web.Site.ServerRelativeUrl == "/" ? string.Empty : web.Site.ServerRelativeUrl;

                        isValid = srcUrl
                                  .Replace("~sitecollection", siteCollectionUrl)
                                  .Replace("//", "/") == dstUrl;
                    }
                    else if (s.DocumentTemplateUrl.Contains("~site"))
                    {
                        var siteCollectionUrl = web.ServerRelativeUrl == "/" ? string.Empty : web.ServerRelativeUrl;

                        isValid = srcUrl
                                  .Replace("~site", siteCollectionUrl)
                                  .Replace("//", "/") == dstUrl;
                    }
                    else
                    {
                        isValid = dstUrl.EndsWith(srcUrl);
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }


            /// localization
            if (definition.TitleResource.Any())
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.TitleResource);
                    var isValid = true;

                    foreach (var userResource in s.TitleResource)
                    {
                        var culture = LocalizationService.GetUserResourceCultureInfo(userResource);
                        var value   = d.TitleResource.GetValueForUICulture(culture);

                        isValid = userResource.Value == value;

                        if (!isValid)
                        {
                            break;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping.");
            }

            if (definition.DescriptionResource.Any())
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.DescriptionResource);
                    var isValid = true;

                    foreach (var userResource in s.DescriptionResource)
                    {
                        var culture = LocalizationService.GetUserResourceCultureInfo(userResource);
                        var value   = d.DescriptionResource.GetValueForUICulture(culture);

                        isValid = userResource.Value == value;

                        if (!isValid)
                        {
                            break;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.DescriptionResource, "DescriptionResource is NULL or empty. Skipping.");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());
            var site          = siteModelHost.HostSite;

            var securityGroupModel = model.WithAssertAndCast <SecurityGroupDefinition>("model", value => value.RequireNotNull());

            var web = site.RootWeb;

            //var site = web.Site;
            var currentGroup    = (SPGroup)null;
            var hasInitialGroup = false;

            try
            {
                currentGroup    = site.RootWeb.SiteGroups[securityGroupModel.Name];
                hasInitialGroup = true;

                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing security group");
            }
            catch (SPException)
            {
                var ownerUser   = EnsureOwnerUser(web, securityGroupModel);
                var defaultUser = EnsureDefaultUser(web, securityGroupModel);

                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new security group");

                web.SiteGroups.Add(securityGroupModel.Name, ownerUser, defaultUser, securityGroupModel.Description);
                currentGroup = web.SiteGroups[securityGroupModel.Name];
            }

            if (hasInitialGroup)
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = currentGroup,
                    ObjectType       = typeof(SPGroup),
                    ObjectDefinition = securityGroupModel,
                    ModelHost        = modelHost
                });
            }
            else
            {
                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model            = null,
                    EventType        = ModelEventType.OnProvisioning,
                    Object           = null,
                    ObjectType       = typeof(SPGroup),
                    ObjectDefinition = securityGroupModel,
                    ModelHost        = modelHost
                });
            }

            currentGroup.OnlyAllowMembersViewMembership = securityGroupModel.OnlyAllowMembersViewMembership;
            currentGroup.Owner       = EnsureOwnerUser(web, securityGroupModel);
            currentGroup.Description = securityGroupModel.Description;

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentGroup,
                ObjectType       = typeof(SPGroup),
                ObjectDefinition = securityGroupModel,
                ModelHost        = modelHost
            });

            currentGroup.Update();
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var listMOdelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull());
            var listViewModel = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull());

            var list = listMOdelHost.HostList;

            var currentView = FindView(list, listViewModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioning,
                Object           = currentView,
                ObjectType       = typeof(View),
                ObjectDefinition = listViewModel,
                ModelHost        = modelHost
            });

            if (currentView == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new list view");

                var newView = new ViewCreationInformation
                {
                    Title            = string.IsNullOrEmpty(listViewModel.Url) ? listViewModel.Title : GetSafeViewUrl(listViewModel.Url),
                    RowLimit         = (uint)listViewModel.RowLimit,
                    SetAsDefaultView = listViewModel.IsDefault,
                    Paged            = listViewModel.IsPaged
                };

                if (!string.IsNullOrEmpty(listViewModel.Query))
                {
                    newView.Query = listViewModel.Query;
                }

                if (listViewModel.Fields != null && listViewModel.Fields.Any())
                {
                    newView.ViewFields = listViewModel.Fields.ToArray();
                }

                if (!string.IsNullOrEmpty(listViewModel.Type))
                {
                    newView.ViewTypeKind = (ViewType)Enum.Parse(typeof(ViewType),
                                                                string.IsNullOrEmpty(listViewModel.Type) ? BuiltInViewType.Html : listViewModel.Type);
                }

                currentView = list.Views.Add(newView);

                MapListViewProperties(list, currentView, listViewModel);

                currentView.Update();

                list.Context.ExecuteQueryWithTrace();
                currentView = FindView(list, listViewModel);

                list.Context.Load(currentView);
                list.Context.ExecuteQueryWithTrace();
            }
            else
            {
                list.Context.Load(currentView);
                list.Context.ExecuteQueryWithTrace();

                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing list view");
                MapListViewProperties(list, currentView, listViewModel);
            }

            ProcessLocalization(currentView, listViewModel);

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model            = null,
                EventType        = ModelEventType.OnProvisioned,
                Object           = currentView,
                ObjectType       = typeof(View),
                ObjectDefinition = listViewModel,
                ModelHost        = modelHost
            });

            TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Calling currentView.Update()");
            currentView.Update();

            list.Context.ExecuteQueryWithTrace();
        }
Exemple #27
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var webAppModelHost = modelHost.WithAssertAndCast <WebApplicationModelHost>("modelHost", value => value.RequireNotNull());
            var definition      = model.WithAssertAndCast <PeoplePickerSettingsDefinition>("model", value => value.RequireNotNull());

            var spObject = GetCurrentPeoplePickerSettings(webAppModelHost.HostWebApplication);

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldNotBeNull(spObject);

            if (!string.IsNullOrEmpty(definition.ActiveDirectoryCustomFilter))
            {
                assert.ShouldBeEqual(m => m.ActiveDirectoryCustomFilter, o => o.ActiveDirectoryCustomFilter);
            }
            else
            {
                assert.SkipProperty(m => m.ActiveDirectoryCustomFilter, "ActiveDirectoryCustomFilter is NULL or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.ActiveDirectoryCustomQuery))
            {
                assert.ShouldBeEqual(m => m.ActiveDirectoryCustomQuery, o => o.ActiveDirectoryCustomQuery);
            }
            else
            {
                assert.SkipProperty(m => m.ActiveDirectoryCustomQuery, "ActiveDirectoryCustomQuery is NULL or empty. Skipping.");
            }

            if (definition.ActiveDirectoryRestrictIsolatedNameLevel.HasValue)
            {
                assert.ShouldBeEqual(m => m.ActiveDirectoryRestrictIsolatedNameLevel, o => o.ActiveDirectoryRestrictIsolatedNameLevel);
            }
            else
            {
                assert.SkipProperty(m => m.ActiveDirectoryRestrictIsolatedNameLevel, "ActiveDirectoryRestrictIsolatedNameLevel is not set. Skipping.");
            }

            if (definition.AllowLocalAccount.HasValue)
            {
                assert.ShouldBeEqual(m => m.AllowLocalAccount, o => o.AllowLocalAccount);
            }
            else
            {
                assert.SkipProperty(m => m.AllowLocalAccount, "AllowLocalAccount is not set. Skipping.");
            }

            if (definition.NoWindowsAccountsForNonWindowsAuthenticationMode.HasValue)
            {
                assert.ShouldBeEqual(m => m.NoWindowsAccountsForNonWindowsAuthenticationMode, o => o.NoWindowsAccountsForNonWindowsAuthenticationMode);
            }
            else
            {
                assert.SkipProperty(m => m.NoWindowsAccountsForNonWindowsAuthenticationMode, "NoWindowsAccountsForNonWindowsAuthenticationMode is not set. Skipping.");
            }

            if (definition.OnlySearchWithinSiteCollection.HasValue)
            {
                assert.ShouldBeEqual(m => m.OnlySearchWithinSiteCollection, o => o.OnlySearchWithinSiteCollection);
            }
            else
            {
                assert.SkipProperty(m => m.OnlySearchWithinSiteCollection, "OnlySearchWithinSiteCollection is not set. Skipping.");
            }

            if (definition.PeopleEditorOnlyResolveWithinSiteCollection.HasValue)
            {
                assert.ShouldBeEqual(m => m.PeopleEditorOnlyResolveWithinSiteCollection, o => o.PeopleEditorOnlyResolveWithinSiteCollection);
            }
            else
            {
                assert.SkipProperty(m => m.PeopleEditorOnlyResolveWithinSiteCollection, "PeopleEditorOnlyResolveWithinSiteCollection is not set. Skipping.");
            }

            if (definition.ActiveDirectorySearchTimeout.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.ActiveDirectorySearchTimeout);
                    var dsrProp = d.GetExpressionValue(m => m.ActiveDirectorySearchTimeout);

                    var isValid = s.ActiveDirectorySearchTimeout.Value.TotalSeconds ==
                                  d.ActiveDirectorySearchTimeout.TotalSeconds;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.ActiveDirectorySearchTimeout, "ActiveDirectorySearchTimeout is not set. Skipping.");
            }
        }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull());

            var list = listModelHost.HostList;

            var context = list.Context;

            context.Load(list, l => l.Fields);
            context.Load(list, l => l.Views.Include(
                             v => v.ViewFields,
                             v => v.Title,
                             v => v.DefaultView,
                             v => v.ViewQuery,
                             v => v.RowLimit,
                             v => v.Paged,
                             v => v.Scope,
                             v => v.Hidden,
                             v => v.JSLink,
                             v => v.ServerRelativeUrl,
                             v => v.DefaultViewForContentType,
                             v => v.ContentTypeId,
                             v => v.AggregationsStatus,
                             v => v.Aggregations,
                             v => v.ViewType,
                             v => v.IncludeRootFolder,
                             v => v.HtmlSchemaXml,
                             v => v.ViewData));

            context.ExecuteQueryWithTrace();

            var spObject = FindViewByTitle(list.Views, definition.Title);
            var assert   = ServiceFactory.AssertService
                           .NewAssert(definition, spObject);

            assert
            .ShouldNotBeNull(spObject)
            .ShouldBeEqual(m => m.Title, o => o.Title)
            .ShouldBeEqual(m => m.IsDefault, o => o.DefaultView)
            .ShouldBeEqual(m => m.Hidden, o => o.Hidden)
            .ShouldBeEqual(m => m.RowLimit, o => (int)o.RowLimit)
            .ShouldBeEqual(m => m.IsPaged, o => o.Paged);

            if (!string.IsNullOrEmpty(definition.Scope))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Scope);
                    var dstProp = d.GetExpressionValue(o => o.Scope);

                    var scopeValue = ListViewScopeTypesConvertService.NormilizeValueToCSOMType(definition.Scope);

                    var isValid = scopeValue == d.Scope.ToString();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Scope);
            }

            if (!string.IsNullOrEmpty(definition.ViewData))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ViewData);
                    var dstProp = d.GetExpressionValue(o => o.ViewData);

                    var srcViewDate = assert.Src.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");
                    var dstViewDate = assert.Dst.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");

                    // replacing all new lines
                    srcViewDate = Regex.Replace(srcViewDate, @"\r\n?|\n", string.Empty);
                    dstViewDate = Regex.Replace(dstViewDate, @"\r\n?|\n", string.Empty);

                    var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.ViewData);
            }

            if (definition.Types.Count() == 0)
            {
                assert.SkipProperty(m => m.Types, "Types.Count == 0");

                if (!string.IsNullOrEmpty(definition.Type))
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.Type);
                        var dstProp = d.GetExpressionValue(o => o.ViewType);

                        var isValid = srcProp.Value.ToString().ToUpper() ==
                                      dstProp.Value.ToString().ToUpper();

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = dstProp,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.Type);
                }
            }
            else
            {
                assert.SkipProperty(m => m.Type, "Types.Count != 0");

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Types);
                    //var dstProp = d.GetExpressionValue(o => o.Type);

                    var isValid = false;

                    ViewType?srcType = null;

                    foreach (var type in s.Types)
                    {
                        var tmpViewType = (ViewType)Enum.Parse(typeof(ViewType), type);

                        if (srcType == null)
                        {
                            srcType = tmpViewType;
                        }
                        else
                        {
                            srcType = srcType | tmpViewType;
                        }
                    }

                    var srcTypeValue = (int)srcType;
                    var dstTypeValue = (int)0;

                    // checking if only reccurence set
                    // test designed that way only
                    if (((int)srcTypeValue & (int)(ViewType.Recurrence)) ==
                        (int)ViewType.Recurrence)
                    {
                        // nah, whatever, it works and does the job
                        isValid = d.HtmlSchemaXml.Contains("RecurrenceRowset=\"TRUE\"");
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }

            assert.SkipProperty(m => m.ViewStyleId, "ViewStyleId unsupported by SP CSOM API yet. Skipping.");
            assert.SkipProperty(m => m.TabularView, "TabularView unsupported by SP CSOM API yet. Skipping.");
            assert.SkipProperty(m => m.InlineEdit, "InlineEdit unsupported by SP CSOM API yet. Skipping.");

            assert.ShouldBeEqualIfNotNullOrEmpty(m => m.JSLink, o => o.JSLink);

            if (definition.IncludeRootFolder.HasValue)
            {
                assert.ShouldBeEqual(m => m.IncludeRootFolder, o => o.IncludeRootFolder);
            }
            else
            {
                assert.SkipProperty(m => m.IncludeRootFolder, "IncludeRootFolder is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.Query))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Query);
                    var dstProp = d.GetExpressionValue(o => o.ViewQuery);

                    var srcViewDate = assert.Src.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");
                    var dstViewDate = assert.Dst.ViewQuery.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");

                    // replacing all new lines
                    srcViewDate = Regex.Replace(srcViewDate, @"\r\n?|\n", string.Empty);
                    dstViewDate = Regex.Replace(dstViewDate, @"\r\n?|\n", string.Empty);

                    var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Query, "Query is null or empty. Skipping.");
            }

            assert.ShouldBeEqualIfHasValue(m => m.DefaultViewForContentType, o => o.DefaultViewForContentType);

            if (string.IsNullOrEmpty(definition.ContentTypeName))
            {
                assert.SkipProperty(m => m.ContentTypeName, "ContentTypeName is null or empty. Skipping.");
            }
            else
            {
                var contentTypeId = LookupListContentTypeByName(list, definition.ContentTypeName);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ContentTypeName);
                    var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId);

                    var isValis = contentTypeId.StringValue == d.ContentTypeId.StringValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValis
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.ContentTypeId))
            {
                assert.SkipProperty(m => m.ContentTypeId, "ContentTypeId is null or empty. Skipping.");
            }
            else
            {
                var contentTypeId = LookupListContentTypeById(list, definition.ContentTypeId);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ContentTypeId);
                    var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId);

                    var isValis = contentTypeId.StringValue == d.ContentTypeId.StringValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValis
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.AggregationsStatus))
            {
                assert.SkipProperty(m => m.AggregationsStatus, "Aggregationsstatus is null or empty. Skipping.");
            }
            else
            {
                assert.ShouldBeEqual(m => m.AggregationsStatus, o => o.AggregationsStatus);
            }

            if (string.IsNullOrEmpty(definition.Aggregations))
            {
                assert.SkipProperty(m => m.Aggregations, "Aggregations is null or empty. Skipping.");
            }
            else
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Aggregations);
                    var dstProp = d.GetExpressionValue(ct => ct.Aggregations);

                    var isValid = s.Aggregations
                                  .Replace("'", string.Empty)
                                  .Replace(" ", string.Empty)
                                  .Replace("\"", string.Empty) ==
                                  d.Aggregations
                                  .Replace("'", string.Empty)
                                  .Replace(" ", string.Empty)
                                  .Replace("\"", string.Empty);

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }

            assert.ShouldBePartOfIfNotNullOrEmpty(m => m.Url, o => o.ServerRelativeUrl);

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(def => def.Fields);
                var dstProp = d.GetExpressionValue(ct => ct.ViewFields);

                var hasAllFields = true;

                foreach (var srcField in s.Fields)
                {
                    var listField = list.Fields.ToList().FirstOrDefault(f => f.StaticName == srcField);

                    // if list-scoped field we need to check by internal name
                    // internal name is changed for list scoped-fields
                    // that's why to check by BOTH, definition AND real internal name

                    if (!d.ViewFields.ToList().Contains(srcField) &&
                        !d.ViewFields.ToList().Contains(listField.InternalName))
                    {
                        hasAllFields = false;
                    }
                }

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = hasAllFields
                });
            });

            var supportsLocalization = ReflectionUtils.HasProperties(spObject, new[]
            {
                "TitleResource"
            });

            if (supportsLocalization)
            {
                if (definition.TitleResource.Any())
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.TitleResource);
                        var isValid = true;

                        foreach (var userResource in s.TitleResource)
                        {
                            var culture        = LocalizationService.GetUserResourceCultureInfo(userResource);
                            var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "TitleResource");

                            var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture")
                                        .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>;

                            context.ExecuteQuery();

                            isValid = userResource.Value == value.Value;

                            if (!isValid)
                            {
                                break;
                            }
                        }

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping.");
                }
            }
            else
            {
                TraceService.Critical((int)LogEventId.ModelProvisionCoreCall,
                                      "CSOM runtime doesn't have Web.TitleResource and Web.DescriptionResource() methods support. Skipping validation.");

                assert.SkipProperty(m => m.TitleResource, "TitleResource is null or empty. Skipping.");
            }
        }
Exemple #29
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var hostClientContext = ExtractHostClientContext(modelHost);

            var parentWeb  = ExtractWeb(modelHost);
            var definition = model.WithAssertAndCast <WebDefinition>("model", value => value.RequireNotNull());

            var currentWebUrl = GetCurrentWebUrl(parentWeb.Context, parentWeb, definition);
            var spObject      = GetExistingWeb(hostClientContext.Site, parentWeb, currentWebUrl);
            var context       = spObject.Context;

            context.Load(spObject,
                         w => w.HasUniqueRoleAssignments,
                         w => w.Description,
                         w => w.Url,
                         w => w.Language,
                         w => w.WebTemplate,
                         w => w.Configuration,
                         w => w.Title,
                         w => w.Id,
                         w => w.Url
                         );

            context.ExecuteQueryWithTrace();

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldBeEqual(m => m.Title, o => o.Title)
                         .ShouldBeEqual(m => m.LCID, o => o.GetLCID())
                         .ShouldBeEqual(m => m.WebTemplate, o => o.GetWebTemplate())
                         .ShouldBeEqual(m => m.UseUniquePermission, o => o.HasUniqueRoleAssignments);

            //.ShouldBeEqual(m => m.Description, o => o.Description);


            if (!string.IsNullOrEmpty(definition.Description))
            {
                assert.ShouldBeEqual(m => m.Description, o => o.Description);
            }
            else
            {
                assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping.");
            }


            assert.ShouldBeEqual((p, s, d) =>
            {
                if (!parentWeb.IsObjectPropertyInstantiated("Url"))
                {
                    parentWeb.Context.Load(parentWeb, o => o.Url);
                    parentWeb.Context.ExecuteQueryWithTrace();
                }

                var srcProp = s.GetExpressionValue(def => def.Url);
                var dstProp = d.GetExpressionValue(ct => ct.Url);

                var srcUrl = s.Url;
                var dstUrl = d.Url;

                var dstSubUrl = dstUrl.Replace(parentWeb.Url + "/", string.Empty);

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = srcUrl == dstSubUrl
                });
            });
        }
Exemple #30
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull());

            var list     = listModelHost.HostList;
            var spObject = list.Views.FindByName(definition.Title);

            var assert = ServiceFactory.AssertService
                         .NewAssert(definition, spObject)
                         .ShouldBeEqual(m => m.Title, o => o.Title)
                         .ShouldBeEqual(m => m.IsDefault, o => o.IsDefaul())
                         .ShouldBeEqual(m => m.Hidden, o => o.Hidden)
                         .ShouldBeEqual(m => m.RowLimit, o => (int)o.RowLimit)
                         .ShouldBeEqual(m => m.IsPaged, o => o.Paged);


            if (definition.InlineEdit.HasValue)
            {
                assert.ShouldBeEqual(m => m.InlineEdit.ToString().ToLower(), o => o.InlineEdit.ToLower());
            }
            else
            {
                assert.SkipProperty(m => m.InlineEdit);
            }


            if (!string.IsNullOrEmpty(definition.Scope))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Scope);
                    var dstProp = d.GetExpressionValue(o => o.Scope);

                    var scopeValue = ListViewScopeTypesConvertService.NormilizeValueToSSOMType(definition.Scope);

                    var isValid = scopeValue == d.Scope.ToString();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Scope);
            }

            if (!string.IsNullOrEmpty(definition.Query))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Query);
                    var dstProp = d.GetExpressionValue(o => o.Query);

                    var srcViewDate = assert.Src.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");
                    var dstViewDate = assert.Dst.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");

                    var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Query);
            }


            if (!string.IsNullOrEmpty(definition.ViewData))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ViewData);
                    var dstProp = d.GetExpressionValue(o => o.ViewData);

                    var srcViewDate = assert.Src.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");
                    var dstViewDate = assert.Dst.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");

                    var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.ViewData);
            }

            if (!string.IsNullOrEmpty(definition.Type))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Type);
                    var dstProp = d.GetExpressionValue(o => o.Type);

                    var isValid = srcProp.Value.ToString().ToUpper() ==
                                  dstProp.Value.ToString().ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Type);
            }

            if (definition.ViewStyleId.HasValue)
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ViewStyleId);

                    var isValid = false;

                    var srcViewId  = s.ViewStyleId;
                    var destViewId = 0;

                    var doc    = XDocument.Parse(d.SchemaXml);
                    destViewId = ConvertUtils.ToInt(doc.Descendants("ViewStyle")
                                                    .First()
                                                    .GetAttributeValue("ID")
                                                    ).Value;

                    isValid = srcViewId == destViewId;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.ViewStyleId, "ViewStyleId is null");
            }

            if (!string.IsNullOrEmpty(definition.JSLink))
            {
                assert.ShouldBeEqual(m => m.JSLink, o => o.JSLink);
            }
            else
            {
                assert.SkipProperty(m => m.JSLink);
            }

            if (definition.DefaultViewForContentType.HasValue)
            {
                assert.ShouldBeEqual(m => m.DefaultViewForContentType, o => o.DefaultViewForContentType);
            }
            else
            {
                assert.SkipProperty(m => m.DefaultViewForContentType, "DefaultViewForContentType is null or empty. Skipping.");
            }

            if (definition.TabularView.HasValue)
            {
                assert.ShouldBeEqual(m => m.TabularView, o => o.TabularView);
            }
            else
            {
                assert.SkipProperty(m => m.TabularView, "TabularView is null or empty. Skipping.");
            }

            if (string.IsNullOrEmpty(definition.ContentTypeName))
            {
                assert.SkipProperty(m => m.ContentTypeName, "ContentTypeName is null or empty. Skipping.");
            }
            else
            {
                var contentTypeId = LookupListContentTypeByName(list, definition.ContentTypeName);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ContentTypeName);
                    var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId);

                    var isValis = contentTypeId == d.ContentTypeId;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValis
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.ContentTypeId))
            {
                assert.SkipProperty(m => m.ContentTypeId, "ContentTypeId is null or empty. Skipping.");
            }
            else
            {
                var contentTypeId = LookupListContentTypeById(list, definition.ContentTypeId);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ContentTypeId);
                    var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId);

                    var isValis = contentTypeId == d.ContentTypeId;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValis
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.AggregationsStatus))
            {
                assert.SkipProperty(m => m.AggregationsStatus, "Aggregationsstatus is null or empty. Skipping.");
            }
            else
            {
                assert.ShouldBeEqual(m => m.AggregationsStatus, o => o.AggregationsStatus);
            }

            if (string.IsNullOrEmpty(definition.Aggregations))
            {
                assert.SkipProperty(m => m.Aggregations, "Aggregations is null or empty. Skipping.");
            }
            else
            {
                assert.ShouldBeEqual(m => m.Aggregations, o => o.Aggregations);
            }

            if (string.IsNullOrEmpty(definition.Url))
            {
                assert.SkipProperty(m => m.Url, "Url is null or empty. Skipping.");
            }
            else
            {
                assert.ShouldBePartOf(m => m.Url, o => o.ServerRelativeUrl);
            }

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(def => def.Fields);
                var dstProp = d.GetExpressionValue(ct => ct.ViewFields);

                var hasAllFields = true;

                foreach (var srcField in s.Fields)
                {
                    var listField = d.ParentList.Fields.OfType <SPField>().FirstOrDefault(f => f.StaticName == srcField);

                    // if list-scoped field we need to check by internal name
                    // internal name is changed for list scoped-fields
                    // that's why to check by BOTH, definition AND real internal name

                    if (!d.ViewFields.ToStringCollection().Contains(srcField) &&
                        !d.ViewFields.ToStringCollection().Contains(listField.InternalName))
                    {
                        hasAllFields = false;
                    }
                }

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = hasAllFields
                });
            });

            /// localization
            if (definition.TitleResource.Any())
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.TitleResource);
                    var isValid = true;

                    foreach (var userResource in s.TitleResource)
                    {
                        var culture = LocalizationService.GetUserResourceCultureInfo(userResource);
                        var value   = d.TitleResource.GetValueForUICulture(culture);

                        isValid = userResource.Value == value;

                        if (!isValid)
                        {
                            break;
                        }
                    }

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = null,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping.");
            }
        }