public void SeattleMasterPageIsUnchangedTest() { using (var context = TestCommon.CreateClientContext()) { var web = context.Web; //need to get the server relative url context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); //Use the existing context to directly get a copy of the seattle master page string masterpageGalleryServerRelativeUrl = UrlUtility.Combine(UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl), "_catalogs/masterpage/"); var serverRelativeUrlOfSeattle = UrlUtility.Combine(masterpageGalleryServerRelativeUrl, builtInMasterSeattle); // OpenBinaryDirect fails when used with app only //FileInformation seattle = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, serverRelativeUrlOfSeattle); var seattle = context.Web.GetFileByServerRelativeUrl(serverRelativeUrlOfSeattle); web.Context.Load(seattle); web.Context.ExecuteQueryRetry(); Assert.IsNotNull(seattle); ClientResult <Stream> data = seattle.OpenBinaryStream(); context.Load(seattle); context.ExecuteQueryRetry(); //Dump seattle.master //if (data != null) //{ // int position = 1; // int bufferSize = 200000; // Byte[] readBuffer = new Byte[bufferSize]; // string localFilePath = "C:\\Temp\\seattle.master"; // using (System.IO.Stream stream = System.IO.File.Create(localFilePath)) // { // while (position > 0) // { // // data.Value holds the Stream // position = data.Value.Read(readBuffer, 0, bufferSize); // stream.Write(readBuffer, 0, position); // readBuffer = new Byte[bufferSize]; // } // stream.Flush(); // } //} MemoryStream memStream = new MemoryStream(); data.Value.CopyTo(memStream); //Compute a hash of the file var hashAlgorithm = HashAlgorithm.Create(); byte[] hash = hashAlgorithm.ComputeHash(memStream); //Convert to a hex string for human consumption string hex = BitConverter.ToString(hash); //Check against last known hash Assert.AreEqual(knownHashOfSeattle, hex); } }
public void SubSiteExistsTest() { using (var tenantContext = TestCommon.CreateTenantClientContext()) { var tenant = new Tenant(tenantContext); string devSiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"]; Console.WriteLine("SubSiteExistsTest: step 1"); string siteToCreateUrl = CreateTestSiteCollection(tenant, sitecollectionName); Console.WriteLine("SubSiteExistsTest: step 1.1"); string subSiteUrlGood = ""; string subSiteUrlWrong = ""; Site site = tenant.GetSiteByUrl(siteToCreateUrl); tenant.Context.Load(site); tenant.Context.ExecuteQueryRetry(); Web web = site.RootWeb; web.Context.Load(web); web.Context.ExecuteQueryRetry(); Console.WriteLine("SubSiteExistsTest: step 1.2"); //Create sub site SiteEntity sub = new SiteEntity() { Title = "Test Sub", Url = "sub", Description = "Test" }; web.CreateWeb(sub); siteToCreateUrl = UrlUtility.EnsureTrailingSlash(siteToCreateUrl); subSiteUrlGood = String.Format("{0}{1}", siteToCreateUrl, sub.Url); subSiteUrlWrong = String.Format("{0}{1}", siteToCreateUrl, "8988980"); // Check real sub site Console.WriteLine("SubSiteExistsTest: step 2"); bool subSiteExists = tenant.SubSiteExists(subSiteUrlGood); Console.WriteLine("SubSiteExistsTest: step 2.1"); Assert.IsTrue(subSiteExists); // check non existing sub site Console.WriteLine("SubSiteExistsTest: step 3"); bool subSiteExists2 = tenant.SubSiteExists(subSiteUrlWrong); Console.WriteLine("SubSiteExistsTest: step 3.1"); Assert.IsFalse(subSiteExists2); // check root site (= site collection). Will return true when existing Console.WriteLine("SubSiteExistsTest: step 4"); bool subSiteExists3 = tenant.SubSiteExists(siteToCreateUrl); Console.WriteLine("SubSiteExistsTest: step 4.1"); Assert.IsTrue(subSiteExists3); // check root site (= site collection) that does not exist. Will return false when non-existant Console.WriteLine("SubSiteExistsTest: step 5"); bool subSiteExists4 = tenant.SubSiteExists(siteToCreateUrl + "8808809808"); Console.WriteLine("SubSiteExistsTest: step 5.1"); Assert.IsFalse(subSiteExists4); } }
public void ProveThatWeCanAddHtmlToPageAfterChangingLayoutTest() { var web = Setup(); web.AddLayoutToWikiPage(folder, WikiPageLayout.TwoColumns, pageName); web.AddHtmlToWikiPage(folder, "<h1>I got text</h1>", pageName, 1, 1); var content = web.GetWikiPageContent(UrlUtility.Combine(UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl), folder, pageName)); Assert.IsTrue(content.Contains("<h1>I got text</h1>")); Teardown(web); }
/// <summary> /// Add web part to a wiki style page /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="folder">System name of the wiki page library - typically sitepages</param> /// <param name="webPart">Information about the web part to insert</param> /// <param name="page">Page to add the web part on</param> /// <param name="row">Row of the wiki table that should hold the inserted web part</param> /// <param name="col">Column of the wiki table that should hold the inserted web part</param> /// <param name="addSpace">Does a blank line need to be added after the web part (to space web parts)</param> public static void AddWebPartToWikiPage(this Web web, string folder, WebPartEntity webPart, string page, int row, int col, bool addSpace) { if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl")) { web.Context.Load(web, w => w.ServerRelativeUrl); web.Context.ExecuteQuery(); } var webServerRelativeUrl = UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl); var serverRelativeUrl = UrlUtility.Combine(folder, page); AddWebPartToWikiPage(web, webServerRelativeUrl + serverRelativeUrl, webPart, row, col, addSpace); }
/// <summary> /// Deletes a web part from a page /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="folder">System name of the wiki page library - typically sitepages</param> /// <param name="title">Title of the web part that needs to be deleted</param> /// <param name="page">Page to remove the web part from</param> public static void DeleteWebPart(this Web web, string folder, string title, string page) { if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl")) { web.Context.Load(web, w => w.ServerRelativeUrl); web.Context.ExecuteQuery(); } var webServerRelativeUrl = UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl); var serverRelativeUrl = UrlUtility.Combine(folder, page); DeleteWebPart(web, webServerRelativeUrl + serverRelativeUrl, title); }
/// <summary> /// Add a HTML fragment to a location on a wiki style page /// </summary> /// <param name="web">Site to be processed - can be root web or sub site</param> /// <param name="folder">System name of the wiki page library - typically sitepages</param> /// <param name="html">html to be inserted</param> /// <param name="page">Page to add the web part on</param> /// <param name="row">Row of the wiki table that should hold the inserted web part</param> /// <param name="col">Column of the wiki table that should hold the inserted web part</param> public static void AddHtmlToWikiPage(this Web web, string folder, string html, string page, int row, int col) { if (!web.IsObjectPropertyInstantiated("ServerRelativeUrl")) { web.Context.Load(web, w => w.ServerRelativeUrl); web.Context.ExecuteQuery(); } var webServerRelativeUrl = UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl); var serverRelativeUrl = UrlUtility.Combine(folder, page); AddHtmlToWikiPage(web, serverRelativeUrl, html, row, col); }
public void OOBMasterPagesHaveChangedTest() { using (var context = TestCommon.CreateClientContext()) { var web = context.Web; //need to get the server relative url context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); string masterpageGalleryServerRelativeUrl = UrlUtility.Combine(UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl), "_catalogs/masterpage/"); // Test seattle.master TestFile(context, UrlUtility.Combine(masterpageGalleryServerRelativeUrl, "seattle.master")); // Test oslo.master TestFile(context, UrlUtility.Combine(masterpageGalleryServerRelativeUrl, "oslo.master")); } }
/// <summary> /// Generic uploader for the file to context web /// </summary> /// <param name="context"></param> /// <param name="fullFilePath"></param> /// <param name="folder"></param> public void UploadFileToWeb(ClientContext context, Web web, string fullFilePath, Folder folder) { try { FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(fullFilePath); newFile.Url = UrlUtility.EnsureTrailingSlash(folder.ServerRelativeUrl) + Path.GetFileName(fullFilePath); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(newFile); context.Load(uploadFile); context.ExecuteQuery(); } catch (Exception ex) { // TODO - Proper logging on exceptions... this is not really acceptable string fuu = ex.ToString(); } }
private void SetSiteLogo(ClientContext cc, Web web, XElement templateConfig) { Web rootWeb = null; if (EnsureWeb(cc, web, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant() != EnsureSite(cc, cc.Site, "ServerRelativeUrl").ServerRelativeUrl.ToLowerInvariant()) { // get instances to root web, since we are processign currently sub site rootWeb = cc.Site.RootWeb; cc.Load(rootWeb); cc.ExecuteQuery(); } else { // Let's double check that the web is available rootWeb = EnsureWeb(cc, web, "Title"); } string fullPathToLogo = GetWebRelativeFolderPath(templateConfig.Attribute("SiteLogoUrl").Value); // Not natively supported, but we can update the themed site icon. If initial theme was just applied, image is at // _themes/themed/themeID/siteIcon-2129F729.themedpng // New model for themes //Folder rootFolder = rootWeb.RootFolder; //Folder themeFolder = ResolveSubFolder(cc, rootFolder, "_themes"); //Folder themeAssetsFolder = ResolveSubFolder(cc, themeFolder, "Themed"); //Folder themedFolder = ResolveFirstSubFolder(cc, themeAssetsFolder); // Old tenant model Folder rootFolder = web.RootFolder; Folder themeFolder = ResolveSubFolder(cc, rootFolder, "_themes"); Folder themeAssetsFolder = ResolveSubFolder(cc, themeFolder, "0"); // Use CSOM to uplaod the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(fullPathToLogo); newFile.Url = UrlUtility.EnsureTrailingSlash(themeAssetsFolder.ServerRelativeUrl) + "siteIcon-2129F729.themedpng"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = themeAssetsFolder.Files.Add(newFile); cc.Load(uploadFile); cc.ExecuteQuery(); }
private void UploadJSToRootSiteCollection(ClientContext ctx, string siteUrl, string jsLocation) { // Solve root site collection URL Uri url = new Uri(siteUrl); Uri rootUrl = new Uri(String.Format("{0}://{1}:{2}", url.Scheme, url.DnsSafeHost, url.Port)); //Open connection to root site collection string realm = TokenHelper.GetRealmFromTargetUrl(rootUrl); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, rootUrl.Authority, realm).AccessToken; using (var ctxRoot = TokenHelper.GetClientContextWithAccessToken(rootUrl.ToString(), token)) { // Upload JavaScript to Style Folder jsFolder; string folder = JSLocationFolderName; if (!ctxRoot.Web.FolderExists(folder)) { jsFolder = ctxRoot.Web.Folders.Add(folder); } else { jsFolder = ctxRoot.Web.Folders.GetByUrl(folder); } // Load Folder instance ctxRoot.Load(jsFolder); ctxRoot.ExecuteQuery(); // Uplaod JS file to folder FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(jsLocation); newFile.Url = UrlUtility.EnsureTrailingSlash(jsFolder.ServerRelativeUrl) + JSFileName; // Right now we override this in each upload, could be optimized newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = jsFolder.Files.Add(newFile); ctxRoot.Load(uploadFile); ctxRoot.ExecuteQuery(); } }
/// <summary> /// Adds the publishing page. /// </summary> /// <param name="web">The web.</param> /// <param name="pageName">Name of the page.</param> /// <param name="pageTemplateName">Name of the page template/layout excluded the .aspx file extension.</param> /// <param name="title">The title of the target publishing page.</param> /// <param name="publish">Should the page be published or not?</param> /// <param name="folder">The target folder for the page, within the Pages library.</param> /// <param name="startDate">Start date for scheduled publishing.</param> /// <param name="endDate">End date for scheduled publishing.</param> /// <param name="schedule">Defines whether to define a schedule or not.</param> /// <exception cref="System.ArgumentNullException">Thrown when key or pageName is a zero-length string or contains only white space</exception> /// <exception cref="System.ArgumentException">Thrown when key or pageName is null</exception> public static void AddPublishingPage(this Web web, string pageName, string pageTemplateName, string title = null, bool publish = false, Folder folder = null, DateTime?startDate = null, DateTime?endDate = null, Boolean schedule = false) { if (string.IsNullOrEmpty(pageName)) { throw (title == null) ? new ArgumentNullException(nameof(pageName)) : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, nameof(pageName)); } if (string.IsNullOrEmpty(pageTemplateName)) { throw (title == null) ? new ArgumentNullException(nameof(pageTemplateName)) : new ArgumentException(CoreResources.Exception_Message_EmptyString_Arg, nameof(pageTemplateName)); } if (string.IsNullOrEmpty(title)) { title = pageName; } // Fix page name, if needed pageName = pageName.ReplaceInvalidUrlChars("-"); var context = web.Context as ClientContext; var site = context.Site; context.Load(site, s => s.ServerRelativeUrl); context.ExecuteQueryRetry(); // Load reference Page Layout var pageFromPageLayout = context.Site.RootWeb.GetFileByServerRelativeUrl($"{UrlUtility.EnsureTrailingSlash(site.ServerRelativeUrl)}_catalogs/masterpage/{pageTemplateName}.aspx"); var pageLayoutItem = pageFromPageLayout.ListItemAllFields; context.Load(pageLayoutItem); context.ExecuteQueryRetry(); // Create the publishing page var publishingWeb = PublishingWeb.GetPublishingWeb(context, web); context.Load(publishingWeb); // Configure the publishing page var pageInformation = new PublishingPageInformation { Name = !pageName.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) ? $"{pageName}.aspx" : pageName, PageLayoutListItem = pageLayoutItem }; // Handle target folder, if any if (folder != null) { pageInformation.Folder = folder; } var page = publishingWeb.AddPublishingPage(pageInformation); // Get parent list of item, this way we can handle all languages var pagesLibrary = page.ListItem.ParentList; context.Load(pagesLibrary); context.ExecuteQueryRetry(); var pageItem = page.ListItem; pageItem["Title"] = title; pageItem.Update(); // Checkin the page file, if needed web.Context.Load(pageItem, p => p.File.CheckOutType); web.Context.ExecuteQueryRetry(); if (pageItem.File.CheckOutType != CheckOutType.None) { pageItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn); } // Publish the page, if required if (publish) { pageItem.File.Publish(string.Empty); if (pagesLibrary.EnableModeration) { pageItem.File.Approve(string.Empty); // Setup scheduling, if required if (schedule && startDate.HasValue) { page.StartDate = startDate.Value; page.EndDate = endDate ?? new DateTime(2050, 01, 01); page.Schedule(string.Empty); } } } context.ExecuteQueryRetry(); }
public void SeattleMasterPageIsUnchanged() { using (var context = TestCommon.CreateClientContext()) { var web = context.Web; //need to get the server relative url context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQuery(); //Use the existing context to directly get a copy of the seattle master page string masterpageGalleryServerRelativeUrl = UrlUtility.Combine(UrlUtility.EnsureTrailingSlash(web.ServerRelativeUrl), "_catalogs/masterpage/"); var serverRelativeUrlOfSeattle = UrlUtility.Combine(masterpageGalleryServerRelativeUrl, builtInMasterSeattle); FileInformation seattle = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, serverRelativeUrlOfSeattle); Assert.IsNotNull(seattle); //Compute a hash of the file var hashAlgorithm = HashAlgorithm.Create(); byte[] hash = hashAlgorithm.ComputeHash(seattle.Stream); //Convert to a hex string for human consumption string hex = BitConverter.ToString(hash); //Check against last known hash Assert.AreEqual(knownHashOfSeattle, hex); } }
public RemoteRepository(string serviceUrl, ICredentials credentials = null) : base(UrlUtility.EnsureTrailingSlash(serviceUrl), credentials) { }
public RemoteEnvironmentManager(string serviceUrl, ICredentials credentials = null) : base(UrlUtility.EnsureTrailingSlash(serviceUrl), credentials) { }