public void CanDeploy_ContentType_WithDocTemplate_In_SubWeb_DocumentLibrary() { var siteContentType = ModelGeneratorService.GetRandomDefinition <ContentTypeDefinition>(); var documentTemplate = ModelGeneratorService.GetRandomDefinition <ModuleFileDefinition>(def => { def.Content = DocumentTemplates.SPMeta2_MSWord_Template; def.FileName = Rnd.String() + ".dotx"; }); var documentTemplateLibrary = ModelGeneratorService.GetRandomDefinition <ListDefinition>(def => { def.TemplateType = BuiltInListTemplateTypeId.DocumentLibrary; }); var subWebDef = ModelGeneratorService.GetRandomDefinition <WebDefinition>(); siteContentType.DocumentTemplate = UrlUtility.CombineUrl(new[] { "~sitecollection", subWebDef.Url, #pragma warning disable 618 documentTemplateLibrary.Url, #pragma warning restore 618 documentTemplate.FileName }); var siteModel = SPMeta2Model.NewSiteModel(site => { site.AddContentType(siteContentType); }); var webModel = SPMeta2Model.NewWebModel(web => { web.AddWeb(subWebDef, subWeb => { subWeb.AddList(documentTemplateLibrary, list => { list.AddModuleFile(documentTemplate); }); }); }); var contentModel = SPMeta2Model.NewWebModel(web => { web.AddRandomDocumentLibrary(list => { list.AddContentTypeLink(siteContentType); }); }); TestModels(new ModelNode[] { webModel, siteModel, contentModel }); }
private string GetSafeFileUrl(SPFolder folder, ModuleFileDefinition moduleFile) { var result = moduleFile.FileName; if (folder.ServerRelativeUrl != "/") { result = UrlUtility.CombineUrl(folder.ServerRelativeUrl, moduleFile.FileName); } result = result.Replace("//", "/"); return(result); }
public static QuickLaunchNavigationNodeDefinition QuickLaunch() { return(new QuickLaunchNavigationNodeDefinition { Title = List().Title, Url = UrlUtility.CombineUrl(new string[] { "~site", List().CustomUrl, AllItems().Url }) }); }
private List <string> GetFoldersForPath(string path) { InitShadowFileSystem(); return(GetShadowFoldersForPath(path)); var result = new List <string>(); WithSPContext(context => { var isRootFolder = string.IsNullOrEmpty(path); var nuGetFolderUrl = UrlUtility.CombineUrl(Root, LibraryUrl); if (!isRootFolder) { nuGetFolderUrl = UrlUtility.CombineUrl(nuGetFolderUrl, path); } var web = context.Web; var exists = false; var folder = web.GetFolderByServerRelativeUrl(nuGetFolderUrl); try { context.ExecuteQuery(); exists = true; } catch (Exception ex) { } if (exists) { var folderCollection = folder.Folders; context.Load(folderCollection); context.ExecuteQuery(); foreach (var f in folderCollection) { result.Add(f.Name); } if (result.Count == 0 && isRootFolder) { result.Add("/"); } } }); return(result); }
private Folder LookupFolderByPath(string path, bool create = false) { NuGetLogUtils.Verbose("Fetching folders for path: " + path); Folder result = null; WithSPContext(context => { var web = context.Web; var nuGetFolderUrl = UrlUtility.CombineUrl(Root, LibraryUrl); var targetFolderUrl = UrlUtility.CombineUrl(nuGetFolderUrl, path); try { result = web.GetFolderByServerRelativeUrl(targetFolderUrl); context.Load(result); context.ExecuteQuery(); if (result.ServerObjectIsNull.HasValue && result.ServerObjectIsNull.Value) { throw new Exception("ServerObjectIsNull is null. Folrder does not exist."); } } catch (Exception ex) { if (create) { var rootFolder = web.GetFolderByServerRelativeUrl(nuGetFolderUrl); rootFolder.Folders.Add(path); context.ExecuteQuery(); result = web.GetFolderByServerRelativeUrl(targetFolderUrl); context.ExecuteQuery(); } else { result = null; } } }); NuGetLogUtils.Verbose("Fetched folders for path: " + path); return(result); }
public void UrlConcatenation() { // fast on two params var smQueryUrl = UrlUtility.CombineUrl("http://goole.com", "?q=spmeta2"); // a bigger one var bgQueryUrl = UrlUtility.CombineUrl(new string[] { "http://goole.com", "?", "q=1", "&p1=3", "&p2=tmp" }); }
public void Can_Replace_Site_Token_On_SubSubWeb() { // Incorrect ~site token resolution for CSOM for the subwebs #863 // https://github.com/SubPointSolutions/spmeta2/issues/863 var subWeb1Url = string.Format("web1-{0}", Rnd.String()); var subWeb2Url = string.Format("web2-{0}", Rnd.String()); var linkUrl = UrlUtility.CombineUrl(new[] { "lib-" + Rnd.String(), "content.html" }); // target URL with token and expected URL with the sub site var tokenUrl = UrlUtility.CombineUrl(new[] { "~site", linkUrl }); var expectedUrl = UrlUtility.CombineUrl(new[] { "/", subWeb2Url, linkUrl }); var web1Definition = ModelGeneratorService.GetRandomDefinition <WebDefinition>(def => { def.Url = subWeb1Url; }); var web2Definition = ModelGeneratorService.GetRandomDefinition <WebDefinition>(def => { def.Url = subWeb2Url; }); var cewpDef = ModelGeneratorService.GetRandomDefinition <ContentEditorWebPartDefinition>(def => { def.Content = string.Empty; def.ContentLink = tokenUrl; }); var model = SPMeta2Model.NewWebModel(web => { web.AddWeb(web1Definition, sub1Web => { web.AddWeb(web2Definition, sub2Web => { sub2Web.AddRandomDocumentLibrary(list => { list.AddRandomWebPartPage(page => { page.AddContentEditorWebPart(cewpDef); }); }); }); }); }); TestModelAndUrl(model, expectedUrl); }
//[SampleMetadataTag(Name = BuiltInTagNames.SampleHidden)] public void CanDeploContentEditorWebpartWithUrlLink() { var htmlContent = new ModuleFileDefinition { FileName = "m2-cewp-content.html", Content = Encoding.UTF8.GetBytes("M2 is everything you need to deploy stuff to Sharepoint"), Overwrite = true, }; var cewp = new ContentEditorWebPartDefinition { Title = "Content Editor Webpart with URL link", Id = "m2ContentLinkCEWP", ZoneIndex = 20, ZoneId = "Main", ContentLink = UrlUtility.CombineUrl(new string[] { "~sitecollection", BuiltInListDefinitions.StyleLibrary.GetListUrl(), htmlContent.FileName }) }; var webPartPage = new WebPartPageDefinition { Title = "M2 CEWP provision", FileName = "cewp-provision.aspx", PageLayoutTemplate = BuiltInWebPartPageTemplates.spstd1 }; var model = SPMeta2Model.NewWebModel(web => { web .AddHostList(BuiltInListDefinitions.StyleLibrary, list => { list.AddModuleFile(htmlContent); }) .AddHostList(BuiltInListDefinitions.SitePages, list => { list.AddWebPartPage(webPartPage, page => { page.AddContentEditorWebPart(cewp); }); }); }); DeployModel(model); }
private static List LoadCurrentList(Web web, ListDefinition listModel) { var context = web.Context; List currentList = null; var listUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, listModel.GetListUrl()); Folder folder = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { folder = web.GetFolderByServerRelativeUrl(listUrl); context.Load(folder); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); if (!scope.HasException && folder != null && folder.ServerObjectIsNull != true) { folder = web.GetFolderByServerRelativeUrl(listUrl); context.Load(folder.Properties); context.ExecuteQueryWithTrace(); var listId = new Guid(folder.Properties["vti_listname"].ToString()); var list = web.Lists.GetById(listId); context.Load(list); context.ExecuteQueryWithTrace(); currentList = list; } return(currentList); }
public void CanDeploy_LookupField_AsSingleSelectAndBindToListUrl_OnSubWeb() { var subWeb = ModelGeneratorService.GetRandomDefinition <WebDefinition>(def => { }); var lookupEnvironment = GetLookupFieldEnvironment(env => { env.LookupField.LookupListUrl = env.ChildList.GetListUrl(); env.LookupField.LookupWebUrl = UrlUtility.CombineUrl("~sitecollection", subWeb.Url); }, subWeb); TestModels(new ModelNode[] { lookupEnvironment.ChildListModel, lookupEnvironment.SiteModel, lookupEnvironment.MasterListModel }); }
public void CanDeploy_LookupField_AsSingleSelectAndBindToListByTitle_OnSubWeb() { WithDisabledPropertyUpdateValidation(() => { var subWeb = ModelGeneratorService.GetRandomDefinition <WebDefinition>(def => { }); var lookupEnvironment = GetLookupFieldEnvironment(env => { env.LookupField.LookupListTitle = env.ChildList.Title; env.LookupField.LookupWebUrl = UrlUtility.CombineUrl("~sitecollection", subWeb.Url); }, subWeb); TestModels(new ModelNode[] { lookupEnvironment.ChildListModel, lookupEnvironment.SiteModel, lookupEnvironment.MasterListModel }); }); }
public void CanDeploy_LookupField_AsSingleSelectAndBindToListById_OnSubWeb() { var subWeb = ModelGeneratorService.GetRandomDefinition <WebDefinition>(def => { }); var lookupEnvironment = GetLookupFieldEnvironment(env => { env.ChildListNode.OnProvisioned <object>(context => { env.LookupField.LookupList = ExtractListId(context).ToString(); env.LookupField.LookupWebUrl = UrlUtility.CombineUrl("~sitecollection", subWeb.Url); }); }, subWeb); TestModels(new ModelNode[] { lookupEnvironment.ChildListModel, lookupEnvironment.SiteModel, lookupEnvironment.MasterListModel }); }
protected virtual string GetServerRelativeUrlFromFullUrl(string siteServerRelativeUrl, string fullUrl) { // TMP fix // Improve ComposedLookItemLinkDefinition provision, upper/lower case in the URLs #652 // https://github.com/SubPointSolutions/spmeta2/issues/652 // upper/lower cases should will be included into the regression tests siteServerRelativeUrl = siteServerRelativeUrl.ToLower(); fullUrl = fullUrl.ToLower(); if (!fullUrl.Contains("://")) { return(fullUrl); } var safeFullUrlParts = fullUrl.Split(new string[] { "://" }, StringSplitOptions.None); var safeFullUrl = safeFullUrlParts.Count() > 1 ? safeFullUrlParts[1] : safeFullUrlParts[0]; safeFullUrl = safeFullUrl.Replace("//", "/"); var fullBits = safeFullUrl.Split(new[] { siteServerRelativeUrl }, StringSplitOptions.None).ToList(); if (fullBits.Any()) { fullBits.RemoveAt(0); } var resultArray = new List <string>(); resultArray.Add(siteServerRelativeUrl); resultArray.AddRange(fullBits); var result = UrlUtility.CombineUrl(resultArray); return(result); }
public override void WithResolvingModelHost(object modelHost, DefinitionBase model, Type childModelType, Action <object> action) { var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull()); var site = siteModelHost.HostSite; var contentTypeModel = model as ContentTypeDefinition; if (site != null && contentTypeModel != null) { var rootWeb = site.RootWeb; var context = rootWeb.Context; var id = contentTypeModel.GetContentTypeId(); var currentContentType = rootWeb.ContentTypes.GetById(id); context.ExecuteQueryWithTrace(); if (childModelType == typeof(ModuleFileDefinition)) { TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Resolving content type resource folder for ModuleFileDefinition"); if (!currentContentType.IsPropertyAvailable("SchemaXml")) { context.Load(rootWeb, w => w.ServerRelativeUrl); currentContentType.Context.Load(currentContentType, c => c.SchemaXml); currentContentType.Context.ExecuteQuery(); } var ctDocument = XDocument.Parse(currentContentType.SchemaXml); var folderUrlNode = ctDocument.Descendants().FirstOrDefault(d => d.Name == "Folder"); var webRelativeFolderUrl = folderUrlNode.Attribute("TargetName").Value; var serverRelativeFolderUrl = UrlUtility.CombineUrl(rootWeb.ServerRelativeUrl, webRelativeFolderUrl); TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "webRelativeFolderUrl is: [{0}]", webRelativeFolderUrl); var ctFolder = rootWeb.GetFolderByServerRelativeUrl(serverRelativeFolderUrl); context.ExecuteQueryWithTrace(); var folderModelHost = ModelHostBase.Inherit <FolderModelHost>(siteModelHost, host => { host.CurrentContentType = currentContentType; host.CurrentContentTypeFolder = ctFolder; }); action(folderModelHost); } else { // ModelHostContext is a cheat for client OM // the issue is that having ContenType instance to work with FieldLinks is not enought - you need RootWeb // and RootWeb could be accessed only via Site // so, somehow we need to pass this info to the model handler action(new ModelHostContext { Site = site, ContentType = currentContentType }); } TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Calling currentContentType.Update(true)"); currentContentType.Update(true); context.ExecuteQueryWithTrace(); } else { action(modelHost); } }
public static string GetServerRelativeUrl(this ListDefinition listDef, Web web) { return(UrlUtility.CombineUrl(web.ServerRelativeUrl, listDef.GetListUrl())); }
public override void DeployModel(object modelHost, DefinitionBase model) { var definition = model.WithAssertAndCast <FieldDefinition>("model", value => value.RequireNotNull()); var spObject = GetField(modelHost, definition); HostList = ExtractListFromHost(modelHost); HostSite = ExtractSiteFromHost(modelHost); CurrentModelHost = modelHost.WithAssertAndCast <CSOMModelHostBase>("CurrentModelHost", value => value.RequireNotNull()); var assert = ServiceFactory.AssertService.NewAssert(model, definition, spObject); ValidateField(assert, spObject, definition); var typedField = spObject.Context.CastTo <FieldLookup>(spObject); var typedDefinition = model.WithAssertAndCast <LookupFieldDefinition>("model", value => value.RequireNotNull()); var typedFieldAssert = ServiceFactory.AssertService.NewAssert(model, typedDefinition, typedField); if (SkipAllowMultipleValuesValidation) { // CSOM provision for DependentLookupFieldDefinition does not update AllowMultipleValues // seems to be a by design SharePoint issue // https://github.com/SubPointSolutions/spmeta2/issues/753 typedFieldAssert.SkipProperty(m => m.AllowMultipleValues, "Skipping. SkipAllowMultipleValuesValidation = true"); } else { typedFieldAssert.ShouldBeEqual(m => m.AllowMultipleValues, o => o.AllowMultipleValues); } if (typedDefinition.LookupWebId.HasValue) { typedFieldAssert.ShouldBeEqual(m => m.LookupWebId, o => o.LookupWebId); } else { typedFieldAssert.SkipProperty(m => m.LookupWebId, "LookupWebId is NULL. Skipping."); } if (!string.IsNullOrEmpty(typedDefinition.LookupWebUrl)) { } else { typedFieldAssert.SkipProperty(m => m.LookupWebUrl, "LookupWebUrl is NULL. Skipping."); } if (!string.IsNullOrEmpty(typedDefinition.RelationshipDeleteBehavior)) { typedFieldAssert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.RelationshipDeleteBehavior); var isValid = s.RelationshipDeleteBehavior == d.RelationshipDeleteBehavior.ToString(); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { typedFieldAssert.SkipProperty(m => m.RelationshipDeleteBehavior, "RelationshipDeleteBehavior is NULL. Skipping."); } // web url if (!string.IsNullOrEmpty(typedDefinition.LookupWebUrl)) { var lookupFieldModelHandler = new LookupFieldModelHandler(); ReflectionUtils.SetNonPublicPropertyValue(lookupFieldModelHandler, "CurrentModelHost", CurrentModelHost); ReflectionUtils.SetNonPublicPropertyValue(lookupFieldModelHandler, "ModelHost", CurrentModelHost); var targetWeb = lookupFieldModelHandler.GetTargetWeb(HostSite, typedDefinition); typedFieldAssert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.LookupWebUrl); var isValid = d.LookupWebId == targetWeb.Id; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { typedFieldAssert.SkipProperty(m => m.LookupWebUrl, "LookupWebUrl is NULL. Skipping."); } if (!string.IsNullOrEmpty(typedDefinition.LookupListTitle)) { var site = HostSite; var context = site.Context; var lookupFieldModelHandler = new LookupFieldModelHandler(); ReflectionUtils.SetNonPublicPropertyValue(lookupFieldModelHandler, "CurrentModelHost", CurrentModelHost); ReflectionUtils.SetNonPublicPropertyValue(lookupFieldModelHandler, "ModelHost", CurrentModelHost); var web = lookupFieldModelHandler.GetTargetWeb(site, typedDefinition); context.Load(web); context.ExecuteQueryWithTrace(); var list = web.Lists.GetByTitle(typedDefinition.LookupListTitle); context.Load(list); context.ExecuteQueryWithTrace(); typedFieldAssert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.LookupListTitle); var isValid = list.Id == new Guid(typedField.LookupList); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { typedFieldAssert.SkipProperty(m => m.LookupListTitle, "LookupListTitle is NULL. Skipping."); } if (!string.IsNullOrEmpty(typedDefinition.LookupListUrl)) { var site = HostSite; var context = site.Context; var lookupFieldModelHandler = new LookupFieldModelHandler(); ReflectionUtils.SetNonPublicPropertyValue(lookupFieldModelHandler, "CurrentModelHost", CurrentModelHost); ReflectionUtils.SetNonPublicPropertyValue(lookupFieldModelHandler, "ModelHost", CurrentModelHost); var web = lookupFieldModelHandler.GetTargetWeb(site, typedDefinition); context.Load(web); context.ExecuteQueryWithTrace(); var list = web.QueryAndGetListByUrl(UrlUtility.CombineUrl(web.ServerRelativeUrl, typedDefinition.LookupListUrl)); context.Load(list); context.ExecuteQueryWithTrace(); typedFieldAssert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.LookupListUrl); var isValid = list.Id == new Guid(typedField.LookupList); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { typedFieldAssert.SkipProperty(m => m.LookupListUrl, "LookupListUrl is NULL. Skipping."); } if (!string.IsNullOrEmpty(typedDefinition.LookupList)) { if (typedDefinition.LookupList.ToUpper() == "USERINFO") { typedFieldAssert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.LookupList); var site = HostSite; var context = site.Context; var userInfoList = site.RootWeb.SiteUserInfoList; context.Load(userInfoList); context.ExecuteQueryWithTrace(); var isValid = userInfoList.Id == new Guid(typedField.LookupList); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { typedFieldAssert.ShouldBeEqual(m => m.LookupList, o => o.LookupList); } } else { typedFieldAssert.SkipProperty(m => m.LookupList, "LookupList is NULL. Skipping."); } if (SkipLookupFieldValidation) { // CSOM provision for DependentLookupFieldDefinition does not update LookupField // seems to be a by design SharePoint issue // https://github.com/SubPointSolutions/spmeta2/issues/753 typedFieldAssert.SkipProperty(m => m.LookupField, "Skipping. SkipLookupFieldValidation = true"); } else { if (!string.IsNullOrEmpty(typedDefinition.LookupField)) { typedFieldAssert.ShouldBeEqual(m => m.LookupField, o => o.LookupField); } else { typedFieldAssert.SkipProperty(m => m.LookupField, "LookupField is NULL. Skipping."); } } if (typedDefinition.CountRelated.HasValue) { typedFieldAssert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.CountRelated); var dstXmlNode = XDocument.Parse(d.SchemaXml).Root; var isValid = bool.Parse(dstXmlNode.Attribute("CountRelated").Value) == typedDefinition.CountRelated.Value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); //typedFieldAssert.ShouldBeEqual(m => m.CountRelated, o => o.cou); } else { typedFieldAssert.SkipProperty(m => m.CountRelated, "CountRelated is NULL. Skipping."); } }
protected override void ProcessFieldProperties(Field field, FieldDefinition fieldModel) { var site = HostSite; var context = site.Context; // let base setting be setup base.ProcessFieldProperties(field, fieldModel); var typedField = field.Context.CastTo <FieldLookup>(field); var typedFieldModel = fieldModel.WithAssertAndCast <LookupFieldDefinition>("model", value => value.RequireNotNull()); if (!typedField.IsPropertyAvailable("LookupList")) { if (field.Context.HasPendingRequest) { field.Update(); field.Context.ExecuteQueryWithTrace(); } typedField.Context.Load(typedField); typedField.Context.ExecuteQueryWithTrace(); } typedField.AllowMultipleValues = typedFieldModel.AllowMultipleValues; if (typedFieldModel.AllowMultipleValues) { typedField.TypeAsString = "LookupMulti"; } else { typedField.TypeAsString = "Lookup"; } if (typedFieldModel.LookupWebId.HasGuidValue()) { typedField.LookupWebId = typedFieldModel.LookupWebId.Value; } else if (!string.IsNullOrEmpty(typedFieldModel.LookupWebUrl)) { var targetWeb = GetTargetWeb(site, typedFieldModel); typedField.LookupWebId = targetWeb.Id; } if (!string.IsNullOrEmpty(typedFieldModel.RelationshipDeleteBehavior)) { var value = (RelationshipDeleteBehaviorType)Enum.Parse(typeof(RelationshipDeleteBehaviorType), typedFieldModel.RelationshipDeleteBehavior); typedField.RelationshipDeleteBehavior = value; } if (string.IsNullOrEmpty(typedField.LookupList)) { if (!string.IsNullOrEmpty(typedFieldModel.LookupList)) { typedField.LookupList = typedFieldModel.LookupList; } else if (!string.IsNullOrEmpty(typedFieldModel.LookupListUrl)) { var targetWeb = GetTargetWeb(site, typedFieldModel); if (!targetWeb.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(targetWeb, w => w.ServerRelativeUrl); context.ExecuteQueryWithTrace(); } var list = targetWeb.QueryAndGetListByUrl(UrlUtility.CombineUrl(targetWeb.ServerRelativeUrl, typedFieldModel.LookupListUrl)); typedField.LookupList = list.Id.ToString(); } else if (!string.IsNullOrEmpty(typedFieldModel.LookupListTitle)) { var targetWeb = GetTargetWeb(site, typedFieldModel); var list = targetWeb.Lists.GetByTitle(typedFieldModel.LookupListTitle); context.Load(list); context.ExecuteQueryWithTrace(); typedField.LookupList = list.Id.ToString(); } } if (!string.IsNullOrEmpty(typedFieldModel.LookupField)) { typedField.LookupField = typedFieldModel.LookupField; } }
public override void DeployModel(object modelHost, DefinitionBase model) { var listItemModelHost = modelHost.WithAssertAndCast <ListItemModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast <WebPartDefinition>("model", value => value.RequireNotNull()); var pageFile = listItemModelHost.HostFile; var context = pageFile.Context; context.Load(pageFile); context.ExecuteQueryWithTrace(); var siteServerUrl = listItemModelHost.HostSite.ServerRelativeUrl; var webUrl = listItemModelHost.HostWeb.Url; var serverUrl = context.Url; if (siteServerUrl != "/") { serverUrl = context.Url.Split(new string[] { siteServerUrl }, StringSplitOptions.RemoveEmptyEntries)[0]; } var absItemUrl = UrlUtility.CombineUrl(serverUrl, pageFile.ServerRelativeUrl); WithExistingWebPart(pageFile, definition, (spObject, spObjectDefintion) => { var webpartExportUrl = UrlUtility.CombineUrl(new[] { webUrl, "_vti_bin/exportwp.aspx?pageurl=" + absItemUrl + "&" + "guidstring=" + spObjectDefintion.Id.ToString() }); var assert = ServiceFactory.AssertService .NewAssert(model, definition, spObject) .ShouldNotBeNull(spObject); var webClient = new WebClient(); if (context.Credentials != null) { webClient.Credentials = context.Credentials; webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); } else { webClient.UseDefaultCredentials = true; } var webPartXmlString = webClient.DownloadString(webpartExportUrl); CurrentWebPartXml = WebpartXmlExtensions.LoadWebpartXmlDocument(webPartXmlString); assert.ShouldBeEqual(m => m.Title, o => o.Title); // checking the web part type, shoul be as expected // Add regression on 'expected' web part type #690 var currentType = CurrentWebPartXml.GetWebPartAssemblyQualifiedName(); var currentClassName = currentType.Split(',').First().Trim(); var expectedTypeAttr = (definition.GetType().GetCustomAttributes(typeof(ExpectWebpartType)) .FirstOrDefault() as ExpectWebpartType); // NULL can be on generic web part // test should not care about that case, there other tests to enfore that attr usage if (expectedTypeAttr != null) { var expectedType = expectedTypeAttr.WebPartType; var expectedClassName = expectedType.Split(',').First().Trim(); assert.ShouldBeEqual((p, s, d) => { var isValid = true; isValid = currentClassName.ToUpper() == expectedClassName.ToUpper(); return(new PropertyValidationResult { Tag = p.Tag, Src = null, Dst = null, IsValid = isValid }); }); } // props if (definition.Properties.Count > 0) { assert.ShouldBeEqual((p, s, d) => { var isValid = true; foreach (var prop in definition.Properties) { // returns correct one depending on the V2/V3 var value = CurrentWebPartXml.GetProperty(prop.Name); // that True / true issue give a pain // toLower for the time being isValid = value.ToLower() == prop.Value.ToLower(); if (!isValid) { break; } } var srcProp = s.GetExpressionValue(m => m.Properties); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Properties, "Properties are empty. Skipping."); } if (!string.IsNullOrEmpty(definition.ExportMode)) { var value = CurrentWebPartXml.GetExportMode(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ExportMode); var isValid = definition.ExportMode == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ExportMode, "ExportMode is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.ChromeState)) { var value = CurrentWebPartXml.GetChromeState(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ChromeState); var isValid = definition.ChromeState == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ChromeState, "ChromeState is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.ChromeType)) { // returns correct one depending on the V2/V3 var value = CurrentWebPartXml.GetChromeType(); var chromeType = string.Empty; if (CurrentWebPartXml.IsV3version()) { chromeType = WebPartChromeTypesConvertService.NormilizeValueToPartChromeTypes(definition.ChromeType); } else if (CurrentWebPartXml.IsV2version()) { chromeType = WebPartChromeTypesConvertService.NormilizeValueToFrameTypes(definition.ChromeType); } assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ChromeType); var isValid = chromeType == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ChromeType, "ChromeType is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.Description)) { var value = CurrentWebPartXml.GetProperty("Description"); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.Description); var isValid = (srcProp.Value as string) == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping."); } if (definition.Height.HasValue) { var value = ConvertUtils.ToInt(CurrentWebPartXml.GetProperty("Height").Replace("px", string.Empty)); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.Height); var isValid = definition.Height == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Height, "Height is null or empty. Skipping."); } if (definition.Width.HasValue) { var value = ConvertUtils.ToInt(CurrentWebPartXml.GetProperty("Width").Replace("px", string.Empty)); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.Width); var isValid = definition.Width == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Width, "Width is NULL, skipping"); } if (!string.IsNullOrEmpty(definition.ImportErrorMessage)) { var value = CurrentWebPartXml.GetImportErrorMessage(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ImportErrorMessage); var isValid = definition.ImportErrorMessage == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ImportErrorMessage, "ImportErrorMessage is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.TitleIconImageUrl)) { var value = CurrentWebPartXml.GetTitleIconImageUrl(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.TitleIconImageUrl); var isValid = definition.TitleIconImageUrl == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleIconImageUrl, "TitleIconImageUrl is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.TitleUrl)) { var value = CurrentWebPartXml.GetTitleUrl(); var defValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext { Context = listItemModelHost.HostClientContext, Value = value }).Value; var isValid = defValue.ToUpper() == value.ToUpper(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.TitleUrl); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleUrl, "TitleUrl is null or empty. Skipping."); } assert.SkipProperty(m => m.WebpartFileName, "WebpartFileName is null or empty. Skipping."); assert.SkipProperty(m => m.WebpartType, "WebpartType is null or empty. Skipping."); assert.SkipProperty(m => m.WebpartXmlTemplate, "WebpartXmlTemplate is null or empty. Skipping."); assert.SkipProperty(m => m.ZoneId, "ZoneId is null or empty. Skipping."); assert.SkipProperty(m => m.ZoneIndex, "ZoneIndex is null or empty. Skipping."); assert.SkipProperty(m => m.Id, "Id is null or empty. Skipping."); if (definition.ParameterBindings.Count == 0) { assert.SkipProperty(m => m.ParameterBindings, "ParameterBindings is null or empty. Skipping."); } else { // TODO } }); }
public Stream OpenFile(string path) { NuGetLogUtils.Verbose("Opening file for path: " + path); Stream result = null; WithSPContext(context => { var web = context.Web; if (!web.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQuery(); } var rootFolderUrl = UrlUtility.CombineUrl(web.ServerRelativeUrl, LibraryUrl).ToLower(); // /sites/ci-121/metapack-gallery/metapack.sharepointpnp.ci.1.2017.0414.0657/metapack.sharepointpnp.ci.1.2017.0414.0657.nupkg var folderRelatedFileUrl = path; if (folderRelatedFileUrl.Contains(rootFolderUrl)) { folderRelatedFileUrl = folderRelatedFileUrl.Split(new string[] { rootFolderUrl }, StringSplitOptions.None)[1]; } var fileUrl = UrlUtility.CombineUrl(rootFolderUrl, folderRelatedFileUrl); // try file item first, shadow this for optimization NuGetLogUtils.Verbose("Opening file for path: " + fileUrl); var file = web.GetFileByServerRelativeUrl(fileUrl); var item = file.ListItemAllFields; context.Load(item); context.ExecuteQuery(); if (item == null || (item.ServerObjectIsNull.HasValue && item.ServerObjectIsNull.Value)) { throw new MetaPackException(string.Format( "Cannot find file by server relative path:[{0}]", fileUrl)); } var nuspecXml = (string)item["PackageNuspecXml"]; var useNuspecXml = true; // faking nuget package here to improve performance // PackageNuspecXml stores nuget package manifest // in that case, NuGet does not download the whole package from SharePoint! if (!string.IsNullOrEmpty(nuspecXml) && useNuspecXml) { NuGetLogUtils.Verbose("Using PackageNuspecXml..."); var nuspecXmlDoc = XDocument.Parse(nuspecXml); var packagingService = new FakeNuGetSolutionPackageService(); using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream)) { var fakeSolutionPackageBase = (new Core.Packaging.SolutionPackageBase { Authors = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Authors"), Company = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Company"), Copyright = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Copyright"), Description = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Description"), IconUrl = GetNuGetPackageMetadataValue(nuspecXmlDoc, "IconUrl"), Id = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Id"), LicenseUrl = GetNuGetPackageMetadataValue(nuspecXmlDoc, "LicenseUrl"), Name = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Name"), Owners = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Owners"), ProjectUrl = GetNuGetPackageMetadataValue(nuspecXmlDoc, "ProjectUrl"), ReleaseNotes = GetNuGetPackageMetadataValue(nuspecXmlDoc, "ReleaseNotes"), Summary = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Summary"), Tags = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Tags"), Title = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Title"), Version = GetNuGetPackageMetadataValue(nuspecXmlDoc, "Version") }); // TODO, dependencies result = packagingService.Pack(fakeSolutionPackageBase, null); } } return; } NuGetLogUtils.Verbose("Using raw file content..."); // fallback on the actual file // that's slow, NuGet download the whole package to get the metadata var q = file.OpenBinaryStream(); context.Load(file); context.ExecuteQuery(); result = q.Value; var memoryStream = new MemoryStream(); CopyStream(q.Value, memoryStream); memoryStream.Position = 0; result = memoryStream; }); NuGetLogUtils.Verbose("Opened file for path: " + path); return(result); }
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 pageUrl = UrlUtility.CombineUrl(new[] { serverUrl, folder.ServerRelativeUrl, pageName }); 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 userAgentString = "User-Agent"; var userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"; client.Headers.Add(userAgentString, userAgent); var pageContent = client.DownloadString(new Uri(pageUrl)); ValidateHtmlPage( file, pageUrl, pageContent, definition); }
private string GetSafeFileUrl(Folder folder, ModuleFileDefinition moduleFile) { return(UrlUtility.CombineUrl(folder.ServerRelativeUrl, moduleFile.FileName)); }
protected File SearchFileByName(List list, Folder folder, string pageName) { var context = list.Context; if (folder != null) { if (!folder.IsPropertyAvailable("ServerRelativeUrl") // || !folder.IsPropertyAvailable("Properties")) ) { folder.Context.Load(folder, f => f.ServerRelativeUrl); //folder.Context.Load(folder, f => f.Properties); folder.Context.ExecuteQueryWithTrace(); } } // one more time.. var dQuery = new CamlQuery(); string QueryString = "<View><Query><Where>" + "<Eq>" + "<FieldRef Name=\"FileLeafRef\"/>" + "<Value Type=\"Text\">" + pageName + "</Value>" + "</Eq>" + "</Where></Query></View>"; dQuery.ViewXml = QueryString; if (folder != null) { dQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl; } var collListItems = list.GetItems(dQuery); context.Load(collListItems); context.ExecuteQueryWithTrace(); var item = collListItems.FirstOrDefault(); if (item != null) { return(item.File); } //one more time // by full path var fileServerRelativePath = UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName); File file = null; var scope = new ExceptionHandlingScope(context); using (scope.StartScope()) { using (scope.StartTry()) { file = list.ParentWeb.GetFileByServerRelativeUrl(fileServerRelativePath); context.Load(file); } using (scope.StartCatch()) { } } context.ExecuteQueryWithTrace(); // Forms folder im the libraries // otherwise pure list items search if (!scope.HasException && file != null && file.ServerObjectIsNull != null) { context.Load(file); context.Load(file, f => f.Exists); context.ExecuteQueryWithTrace(); if (file.Exists) { return(file); } } return(null); }
public override void DeployModel(object modelHost, DefinitionBase model) { var listItemModelHost = modelHost.WithAssertAndCast <ListItemModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast <WebPartDefinition>("model", value => value.RequireNotNull()); var pageItem = listItemModelHost.HostListItem; var context = pageItem.Context; var siteServerUrl = listItemModelHost.HostSite.ServerRelativeUrl; var webUrl = listItemModelHost.HostWeb.Url; var serverUrl = context.Url; if (siteServerUrl != "/") { serverUrl = context.Url.Split(new string[] { siteServerUrl }, StringSplitOptions.RemoveEmptyEntries)[0]; } var absItemUrl = UrlUtility.CombineUrl(serverUrl, pageItem["FileRef"].ToString()); WithWithExistingWebPart(pageItem, definition, (spObject, spObjectDefintion) => { var webpartExportUrl = UrlUtility.CombineUrl(new[] { webUrl, "_vti_bin/exportwp.aspx?pageurl=" + absItemUrl + "&" + "guidstring=" + spObjectDefintion.Id.ToString() }); var assert = ServiceFactory.AssertService .NewAssert(model, definition, spObject) .ShouldNotBeNull(spObject); var webClient = new WebClient(); if (context.Credentials != null) { webClient.Credentials = context.Credentials; } else { webClient.UseDefaultCredentials = true; } var webPartXmlString = webClient.DownloadString(webpartExportUrl); CurrentWebPartXml = WebpartXmlExtensions.LoadWebpartXmlDocument(webPartXmlString); assert.ShouldBeEqual(m => m.Title, o => o.Title); if (!string.IsNullOrEmpty(definition.ExportMode)) { var value = CurrentWebPartXml.GetExportMode(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ExportMode); var isValid = definition.ExportMode == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ExportMode, "ExportMode is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.ChromeState)) { var value = CurrentWebPartXml.GetChromeState(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ChromeState); var isValid = definition.ChromeState == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ChromeState, "ChromeState is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.ChromeType)) { // returns correct one depending on the V2/V3 var value = CurrentWebPartXml.GetChromeType(); var chromeType = string.Empty; if (CurrentWebPartXml.IsV3version()) { chromeType = WebPartChromeTypesConvertService.NormilizeValueToPartChromeTypes(definition.ChromeType); } else if (CurrentWebPartXml.IsV2version()) { chromeType = WebPartChromeTypesConvertService.NormilizeValueToFrameTypes(definition.ChromeType); } assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ChromeType); var isValid = chromeType == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ChromeType, "ChromeType is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.Description)) { } else { assert.SkipProperty(m => m.Description, "Description is null or empty. Skipping."); } if (definition.Height.HasValue) { var value = ConvertUtils.ToInt(CurrentWebPartXml.GetProperty("Height").Replace("px", string.Empty)); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.Height); var isValid = definition.Height == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Height, "Height is null or empty. Skipping."); } if (definition.Width.HasValue) { var value = ConvertUtils.ToInt(CurrentWebPartXml.GetProperty("Width").Replace("px", string.Empty)); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.Width); var isValid = definition.Width == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.Width, "Width is NULL, skipping"); } if (!string.IsNullOrEmpty(definition.ImportErrorMessage)) { var value = CurrentWebPartXml.GetImportErrorMessage(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.ImportErrorMessage); var isValid = definition.ImportErrorMessage == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.ImportErrorMessage, "ImportErrorMessage is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.TitleIconImageUrl)) { var value = CurrentWebPartXml.GetTitleIconImageUrl(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.TitleIconImageUrl); var isValid = definition.TitleIconImageUrl == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleIconImageUrl, "TitleIconImageUrl is null or empty. Skipping."); } if (!string.IsNullOrEmpty(definition.TitleUrl)) { var value = CurrentWebPartXml.GetTitleUrl(); assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.TitleIconImageUrl); var isValid = definition.TitleIconImageUrl == value; return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.TitleUrl, "TitleUrl is null or empty. Skipping."); } assert.SkipProperty(m => m.WebpartFileName, "WebpartFileName is null or empty. Skipping."); assert.SkipProperty(m => m.WebpartType, "WebpartType is null or empty. Skipping."); assert.SkipProperty(m => m.WebpartXmlTemplate, "WebpartXmlTemplate is null or empty. Skipping."); assert.SkipProperty(m => m.ZoneId, "ZoneId is null or empty. Skipping."); assert.SkipProperty(m => m.ZoneIndex, "ZoneIndex is null or empty. Skipping."); assert.SkipProperty(m => m.Id, "Id is null or empty. Skipping."); if (definition.ParameterBindings.Count == 0) { assert.SkipProperty(m => m.ParameterBindings, "ParameterBindings is null or empty. Skipping."); } else { // TODO } }); }
protected string GetCurrentWebUrl(ClientRuntimeContext context, Web parentWeb, WebDefinition webModel) { var result = UrlUtility.CombineUrl(parentWeb.ServerRelativeUrl, webModel.Url); return(result.ToLower()); }
public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext) { var modelHost = modelHostContext.ModelHost; var model = modelHostContext.Model; var childModelType = modelHostContext.ChildModelType; var action = modelHostContext.Action; var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var web = listModelHost.HostWeb; var list = listModelHost.HostList; var listViewDefinition = model as ListViewDefinition; var context = web.Context; if (typeof(WebPartDefinitionBase).IsAssignableFrom(childModelType) || childModelType == typeof(DeleteWebPartsDefinition)) { var targetView = FindView(list, listViewDefinition); var serverRelativeFileUrl = string.Empty; Folder targetFolder = null; if (list.BaseType == BaseType.DocumentLibrary) { targetFolder = FolderModelHandler.GetLibraryFolder(list.RootFolder, "Forms"); } if (targetView != null) { serverRelativeFileUrl = targetView.ServerRelativeUrl; } else { context.Load(list.RootFolder); context.ExecuteQueryWithTrace(); // maybe forms files? // they aren't views, but files if (list.BaseType == BaseType.DocumentLibrary) { serverRelativeFileUrl = UrlUtility.CombineUrl(new[] { list.RootFolder.ServerRelativeUrl, "Forms", listViewDefinition.Url }); } else { serverRelativeFileUrl = UrlUtility.CombineUrl(new[] { list.RootFolder.ServerRelativeUrl, listViewDefinition.Url }); } } var file = web.GetFileByServerRelativeUrl(serverRelativeFileUrl); context.Load(file); context.ExecuteQueryWithTrace(); var listItemHost = ModelHostBase.Inherit <ListItemModelHost>(listModelHost, itemHost => { itemHost.HostFolder = targetFolder; //itemHost.HostListItem = folderModelHost.CurrentListItem; itemHost.HostFile = file; itemHost.HostList = list; }); action(listItemHost); } else { action(listModelHost); } }
public override void DeployModel(object modelHost, DefinitionBase model) { SPFolder targetFolder = null; SPWeb web = null; if (modelHost is ListModelHost) { targetFolder = (modelHost as ListModelHost).HostList.RootFolder; web = (modelHost as ListModelHost).HostList.ParentWeb; } if (modelHost is FolderModelHost) { targetFolder = (modelHost as FolderModelHost).CurrentLibraryFolder; web = (modelHost as FolderModelHost).CurrentWeb; } var definition = model.WithAssertAndCast <WebpartPresenceOnPageDefinition>("model", value => value.RequireNotNull()); var folder = targetFolder; var pageName = GetSafeWikiPageFileName(definition.PageFileName); var file = web.GetFile(UrlUtility.CombineUrl(folder.ServerRelativeUrl, pageName)); 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; 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 WithResolvingModelHost(ModelHostResolveContext modelHostContext) { var modelHost = modelHostContext.ModelHost; var model = modelHostContext.Model; var childModelType = modelHostContext.ChildModelType; var action = modelHostContext.Action; var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull()); var list = listModelHost.HostList; var web = list.ParentWeb; if (typeof(WebPartDefinitionBase).IsAssignableFrom(childModelType)) { var listViewDefinition = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull()); var currentView = FindView(list, listViewDefinition); var serverRelativeFileUrl = string.Empty; if (currentView != null) { serverRelativeFileUrl = currentView.ServerRelativeUrl; } else { // maybe forms files? // they aren't views, but files if (list.BaseType == SPBaseType.DocumentLibrary) { serverRelativeFileUrl = UrlUtility.CombineUrl(new[] { list.RootFolder.ServerRelativeUrl, "Forms", listViewDefinition.Url }); } else { serverRelativeFileUrl = UrlUtility.CombineUrl(new[] { list.RootFolder.ServerRelativeUrl, listViewDefinition.Url }); } } var targetFile = web.GetFile(serverRelativeFileUrl); using (var webPartManager = targetFile.GetLimitedWebPartManager(PersonalizationScope.Shared)) { var webpartPageHost = new WebpartPageModelHost { HostFile = targetFile, PageListItem = targetFile.Item, SPLimitedWebPartManager = webPartManager }; action(webpartPageHost); } } else { action(modelHost); } }
public IEnumerable <string> GetFiles(string path, string filter, bool recursive) { return(GetShadowFiles(path, filter, recursive)); var hasFolderMatch = Regex.IsMatch(path.ToLower(), WildCardToRegular(filter.ToLower().Replace(".nupkg", string.Empty)).ToLower()); if (!hasFolderMatch) { return(Enumerable.Empty <string>()); } NuGetLogUtils.Verbose(string.Format("Fetching files. Path:[{0}] Filter:[{1}] Recursive:[{2}]", path, filter, recursive)); if (recursive) { throw new NotSupportedException("recursive = true"); } var isRootFolder = string.IsNullOrEmpty(path); path = path.ToLower(); var files = new List <VirtualFile>(); WithSPContext(context => { var nuGetFolderUrl = UrlUtility.CombineUrl(Root, LibraryUrl); if (!isRootFolder) { nuGetFolderUrl = UrlUtility.CombineUrl(nuGetFolderUrl, path); } var web = context.Web; var exists = false; var folder = web.GetFolderByServerRelativeUrl(nuGetFolderUrl); try { context.ExecuteQuery(); exists = true; } catch (Exception ex) { } if (exists) { files = new List <VirtualFile>(); if (!_cachedPathToFiles.ContainsKey(path)) { _cachedPathToFiles.Add(path, files); } else { files = _cachedPathToFiles[path]; } var items = folder.Files; context.Load(items); context.ExecuteQuery(); foreach (var f in items) { files.Add(new VirtualFile { Path = f.Name, LastModified = f.TimeLastModified, RelativePath = Path.Combine(path, f.Name) }); } } else { } }); var result = new List <string>(); foreach (var file in files) { if (string.IsNullOrEmpty(filter)) { result.Add(file.Path); } else { var fileName = file.Path; var fileMatch = Regex.IsMatch(fileName.ToLower(), WildCardToRegular(filter).ToLower()); if (fileMatch) { result.Add(fileName); } } } // make relative path if (result.Any()) { result = result.Select(p => Path.Combine(path, p)).ToList(); } NuGetLogUtils.Verbose("Fetched files for path with filter: " + filter + " : " + path); return(result); }
public override void DeployModel(object modelHost, DefinitionBase model) { var web = ExtractWeb(modelHost); var contentTypeModel = model.WithAssertAndCast <ContentTypeDefinition>("model", value => value.RequireNotNull()); var site = web.Site; var targetWeb = web; // SPBug, it has to be new SPWen for every content type operation inside feature event handler using (var tmpWeb = site.OpenWeb(targetWeb.ID)) { var contentTypeId = new SPContentTypeId(contentTypeModel.GetContentTypeId()); // by ID, by Name var targetContentType = tmpWeb.ContentTypes[contentTypeId]; if (targetContentType == null) { targetContentType = tmpWeb.ContentTypes .OfType <SPContentType>() .FirstOrDefault(f => f.Name.ToUpper() == contentTypeModel.Name.ToUpper()); } InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = targetContentType, ObjectType = typeof(SPContentType), ObjectDefinition = contentTypeModel, ModelHost = modelHost }); if (targetContentType == null) { TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new content type"); targetContentType = tmpWeb .ContentTypes .Add(new SPContentType(contentTypeId, tmpWeb.ContentTypes, contentTypeModel.Name)); } else { TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing content type"); } targetContentType.Hidden = contentTypeModel.Hidden; targetContentType.Name = contentTypeModel.Name; targetContentType.Group = contentTypeModel.Group; // SPBug, description cannot be null targetContentType.Description = contentTypeModel.Description ?? string.Empty; if (!string.IsNullOrEmpty(contentTypeModel.DocumentTemplate)) { var processedDocumentTemplateUrl = TokenReplacementService.ReplaceTokens(new TokenReplacementContext { Value = contentTypeModel.DocumentTemplate, Context = tmpWeb }).Value; // resource related path if (!processedDocumentTemplateUrl.Contains('/') && !processedDocumentTemplateUrl.Contains('\\')) { processedDocumentTemplateUrl = UrlUtility.CombineUrl(new string[] { targetContentType.ResourceFolder.ServerRelativeUrl, processedDocumentTemplateUrl }); } targetContentType.DocumentTemplate = processedDocumentTemplateUrl; } ProcessLocalization(targetContentType, contentTypeModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = targetContentType, ObjectType = typeof(SPContentType), ObjectDefinition = contentTypeModel, ModelHost = modelHost }); TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Calling currentContentType.Update(true)"); targetContentType.UpdateIncludingSealedAndReadOnly(true); tmpWeb.Update(); } }
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"); } }