public static void UploadControlTemplateJS(ClientContext ctx, List materpagelist, string remoteFolderURL, string fileName) { string romoteFileURL = string.Format("{0}/Display%20Templates/Content%20Web%20Parts/{1}", remoteFolderURL, fileName); FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCase CBS Webpart/" + fileName); newFile.Url = romoteFileURL; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = materpagelist.RootFolder.Files.Add(newFile); ctx.Load(uploadFile); ctx.ExecuteQuery(); var listItem = uploadFile.ListItemAllFields; if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } listItem["Title"] = fileName.Substring(0, fileName.IndexOf(".js")); listItem["ContentTypeId"] = "0x0101002039C03B61C64EC4A04F5361F385106601"; listItem["TargetControlType"] = ";#Content Web Parts;#"; listItem["DisplayTemplateLevel"] = "Control"; listItem["TemplateHidden"] = "0"; listItem["UIVersion"] = "15"; listItem.Update(); uploadFile.CheckIn("", CheckinType.MajorCheckIn); ctx.ExecuteQuery(); }
private void UploadControlTemplateJS(ClientContext clientContext, Web web, List list, string controlContentTypeId, string jsURL, string serverRelatedURL) { string fileURL = string.Format("Scripts/{0}", jsURL); string romoteFileURL = string.Format("{0}/_catalogs/masterpage/Display%20Templates/Content%20Web%20Parts/{1}", serverRelatedURL, jsURL); FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(string.Format("~/{0}", fileURL))); newFile.Url = romoteFileURL; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); var listItem = uploadFile.ListItemAllFields; if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } listItem["Title"] = jsURL.Split('.')[0]; listItem["ContentTypeId"] = controlContentTypeId; listItem["DisplayTemplateLevel"] = "Control"; listItem["TargetControlType"] = ";#Content Web Parts;#"; listItem["DisplayTemplateLevel"] = "Control"; listItem["TemplateHidden"] = "0"; listItem["UIVersion"] = "15"; listItem.Update(); uploadFile.CheckIn("", CheckinType.MajorCheckIn); clientContext.Load(listItem); clientContext.ExecuteQuery(); }
private static bool CheckOutIfNeeded(Web web, File targetFile) { var checkedOut = false; try { web.Context.Load(targetFile, f => f.CheckOutType, f => f.ListItemAllFields.ParentList.ForceCheckout); web.Context.ExecuteQueryRetry(); if (targetFile.ListItemAllFields.ServerObjectIsNull.HasValue && !targetFile.ListItemAllFields.ServerObjectIsNull.Value && targetFile.ListItemAllFields.ParentList.ForceCheckout) { if (targetFile.CheckOutType == CheckOutType.None) { targetFile.CheckOut(); } checkedOut = true; } } catch (ServerException ex) { // Handling the exception stating the "The object specified does not belong to a list." if (ex.ServerErrorCode != -2146232832) { throw; } } return(checkedOut); }
private void UploadItemTemplateJS(ClientContext clientContext, Web web, List list, string controlContentTypeId, string serverRelatedURL) { string fileURL = "Scripts/HomePageHeroItemTemplate.js"; string romoteFileURL = string.Format("{0}/_catalogs/masterpage/Display%20Templates/Content%20Web%20Parts/HomePageHeroItemTemplate.js", serverRelatedURL); FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(string.Format("~/{0}", fileURL))); newFile.Url = romoteFileURL; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); var listItem = uploadFile.ListItemAllFields; if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } listItem["ContentTypeId"] = controlContentTypeId; listItem["DisplayTemplateLevel"] = "Control"; listItem["TargetControlType"] = ";#Content Web Parts;#"; listItem["DisplayTemplateLevel"] = "Item"; listItem["TemplateHidden"] = "0"; listItem["UIVersion"] = "15"; listItem["ManagedPropertyMapping"] = "'Title':'Title','Tag Line':'brandingTagLineOWSTEXT', 'Left Caption Background Color'{Left Caption Background Color}:'brandingLeftCaptionBGColorOWSTEXT', 'Left Caption Background Opacity'{Left Caption Background Opacity}:'brandingLeftCaptionBGOpacityOWSTEXT', 'HeroImage'{HeroImage}:'brandingHeroImageOWSIMGE','Hero URL Link'{Hero URL Link}:'brandingLinkURLOWSTEXT', 'Right Caption Title'{Right Caption Title}:'brandingRightCaptionTitleOWSTEXT', 'Right Caption Description'{Right Caption Description}:'brandingRightCaptionDescriptionOWSMTXT', 'Sort Order'{Sort Order}:'brandingSortOrderOWSNMBR'"; listItem.Update(); uploadFile.CheckIn("", CheckinType.MajorCheckIn); clientContext.Load(listItem); clientContext.ExecuteQuery(); }
public static void UploadPageLayout(ClientContext ctx, string sourcePath, string targetListTitle, string targetUrl) { using (FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read)) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); using (MemoryStream ms = new MemoryStream()) { ms.Write(data, 0, data.Length); var newfile = new FileCreationInformation(); newfile.Content = ms.ToArray(); newfile.Url = targetUrl; newfile.Overwrite = true; List docs = ctx.Web.Lists.GetByTitle(targetListTitle); Microsoft.SharePoint.Client.File uploadedFile = docs.RootFolder.Files.Add(newfile); uploadedFile.CheckOut(); uploadedFile.CheckIn("Data storage model", CheckinType.MajorCheckIn); uploadedFile.Publish("Data storage model layout."); ctx.Load(uploadedFile); ctx.ExecuteQuery(); } } }
private void UploadMasterpages(ClientContext clientContext, Web web, List list, string controlContentTypeId, string masterPageURL, string serverRelatedURL) { string fileURL = string.Format("Masterpages/{0}", masterPageURL); string remoteFileURL = string.Format("{0}/_catalogs/masterpage/{1}", serverRelatedURL, masterPageURL); FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(string.Format("~/{0}", fileURL))); newFile.Url = remoteFileURL; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); var listItem = uploadFile.ListItemAllFields; if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } listItem["ContentTypeId"] = controlContentTypeId; listItem["UIVersion"] = Convert.ToString(15); listItem.Update(); uploadFile.CheckIn("", CheckinType.MajorCheckIn); listItem.File.Publish(""); clientContext.Load(listItem); clientContext.ExecuteQuery(); }
// Meta data (Update the meta data on an uploaded file) private void AddMetaData(ClientContext context, DataRow datarow, String strDestination) { // Get a list item for the file we just added Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(strDestination); file.CheckOut(); ListItem listitem = file.ListItemAllFields; context.Load(listitem); // Iterate the mappings in the import settings and apply foreach (ImportMapping importmapping in importsettings.ImportMappings) { try { // If the import mapping does not require any formatting then just apply directly. if (importmapping.FormatType == ImportMapping.FormatTypes.None) { listitem[importmapping.InternalName] = datarow[importmapping.DataColumn]; } } catch { // Do nothing, just keep trying any other mappings } } listitem.Update(); file.CheckIn(string.Empty, CheckinType.OverwriteCheckIn); context.ExecuteQuery(); }
private bool CheckOutIfNeeded(Web web, Microsoft.SharePoint.Client.File targetFile) { var checkedOut = false; try { if (targetFile.ListItemAllFields.ServerObjectIsNull.HasValue && !targetFile.ListItemAllFields.ServerObjectIsNull.Value && targetFile.ListItemAllFields.ParentList.ForceCheckout) { if (targetFile.CheckOutType == CheckOutType.None) { targetFile.CheckOut(); } checkedOut = true; } } catch (ServerException ex) { // Handling the exception stating the "The object specified does not belong to a list." if (ex.ServerErrorCode != -2146232832) { throw; } } return(checkedOut); }
/// <summary> /// Can be used ot deploy page layouts to master page gallyery. /// <remarks>Should be only used with root web of site collection where publishing features are enabled.</remarks> /// </summary> /// <param name="web">Web as the root site of the publishign site collection</param> /// <param name="sourceFilePath">Full path to the file which will be uploaded</param> /// <param name="title">Title for the page layout</param> /// <param name="description">Description for the page layout</param> /// <param name="associatedContentTypeID">Assocated content type ID</param> public static void DeployPageLayout(this Web web, string sourceFilePath, string title, string description, string associatedContentTypeID) { // Get the path to the file which we are about to deploy List masterPageGallery = web.GetCatalog(116); Folder rootFolder = masterPageGallery.RootFolder; web.Context.Load(masterPageGallery); web.Context.Load(rootFolder); web.Context.ExecuteQuery(); string fileName = Path.GetFileName(sourceFilePath); var fileBytes = System.IO.File.ReadAllBytes(sourceFilePath); // Use CSOM to upload the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = fileBytes; newFile.Url = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); // Check out the file if needed if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } } // Get content type for ID to assign assocated content type information ContentType associatedCt = web.GetContentTypeById(associatedContentTypeID); var listItem = uploadFile.ListItemAllFields; listItem["Title"] = title; listItem["MasterPageDescription"] = description; // set the item as page layout listItem["ContentTypeId"] = "0x01010007FF3E057FA8AB4AA42FCB67B453FFC100E214EEE741181F4E9F7ACC43278EE811"; // Set teh associated content type ID property listItem["PublishingAssociatedContentType"] = ";#" + associatedCt.Name + ";#" + associatedCt.Id + ";#"; listItem["UIVersion"] = Convert.ToString(15); listItem.Update(); // Check in the page layout if needed if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { uploadFile.CheckIn("", CheckinType.MajorCheckIn); listItem.File.Publish(""); } web.Context.ExecuteQuery(); }
public static void DeployMasterPage(this Web web, string sourceFilePath, string title, string description, string uiVersion = "15", string defaultCSSFile = "") { // Get the path to the file which we are about to deploy List masterPageGallery = web.GetCatalog(116); Folder rootFolder = masterPageGallery.RootFolder; web.Context.Load(masterPageGallery); web.Context.Load(rootFolder); web.Context.ExecuteQuery(); // Get the file name from the provided path string fileName = Path.GetFileName(sourceFilePath); var fileBytes = System.IO.File.ReadAllBytes(sourceFilePath); // Use CSOM to upload the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = fileBytes; newFile.Url = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); var listItem = uploadFile.ListItemAllFields; if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } } listItem["Title"] = title; listItem["MasterPageDescription"] = description; // Set content type as master page listItem["ContentTypeId"] = "0x01010500B45822D4B60B7B40A2BFCC0995839404"; listItem["UIVersion"] = uiVersion; listItem.Update(); if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { uploadFile.CheckIn("", CheckinType.MajorCheckIn); listItem.File.Publish(""); } web.Context.Load(listItem); web.Context.ExecuteQuery(); }
public string CheckOutDocument(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails) { string returnFlag = ConstantStrings.FALSE; if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken()) { string result = ConstantStrings.FALSE; ClientContext clientContext; try { using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(mailAttachmentDetails.FullUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken)) { Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(mailAttachmentDetails.FullUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].TrimEnd(ConstantStrings.Semicolon[0])); clientContext.Load(file); clientContext.ExecuteQuery(); if (file.CheckOutType == CheckOutType.None) { file.CheckOut(); result = string.Concat(ConstantStrings.TRUE, ConstantStrings.Comma, ConstantStrings.Space, file.Name); } else { result = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ServiceConstantStrings.AlreadyCheckOut); } clientContext.ExecuteQuery(); returnFlag = result; } } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); returnFlag = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message)); } } else { returnFlag = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, TextConstants.InvalidParametersMessage); } return(returnFlag); }
public static void DeployMasterPage(this Web web, string sourceFilePath, string title, string description, string uiVersion = "15", string defaultCSSFile = "") { if (string.IsNullOrEmpty(sourceFilePath)) { throw new ArgumentNullException("sourceFilePath"); } if (!System.IO.File.Exists(sourceFilePath)) { throw new FileNotFoundException("File for param sourceFilePath not found.", sourceFilePath); } string fileName = Path.GetFileName(sourceFilePath); LoggingUtility.Internal.TraceInformation((int)EventId.DeployMasterPage, "Deploying masterpage '{0}' to '{1}'.", fileName, web.Context.Url); // Get the path to the file which we are about to deploy List masterPageGallery = web.GetCatalog((int)ListTemplateType.MasterPageCatalog); Folder rootFolder = masterPageGallery.RootFolder; web.Context.Load(masterPageGallery); web.Context.Load(rootFolder); web.Context.ExecuteQuery(); // Get the file name from the provided path var fileBytes = System.IO.File.ReadAllBytes(sourceFilePath); // Use CSOM to upload the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = fileBytes; newFile.Url = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); var listItem = uploadFile.ListItemAllFields; if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } } listItem["Title"] = title; listItem["MasterPageDescription"] = description; // Set content type as master page listItem["ContentTypeId"] = Constants.MASTERPAGE_CONTENT_TYPE; listItem["UIVersion"] = uiVersion; listItem.Update(); if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { uploadFile.CheckIn(string.Empty, CheckinType.MajorCheckIn); listItem.File.Publish(string.Empty); } web.Context.Load(listItem); web.Context.ExecuteQuery(); }
/// <summary> /// Can be used to deploy page layouts to master page gallery. /// <remarks>Should be only used with root web of site collection where publishing features are enabled.</remarks> /// </summary> /// <param name="web">Web as the root site of the publishing site collection</param> /// <param name="sourceFilePath">Full path to the file which will be uploaded</param> /// <param name="title">Title for the page layout</param> /// <param name="description">Description for the page layout</param> /// <param name="associatedContentTypeID">Associated content type ID</param> public static void DeployPageLayout(this Web web, string sourceFilePath, string title, string description, string associatedContentTypeID) { if (string.IsNullOrEmpty(sourceFilePath)) { throw new ArgumentNullException("sourceFilePath"); } if (!System.IO.File.Exists(sourceFilePath)) { throw new FileNotFoundException("File for param sourceFilePath file does not exist", sourceFilePath); } string fileName = Path.GetFileName(sourceFilePath); LoggingUtility.Internal.TraceInformation((int)EventId.DeployPageLayout, "Deploying page layout '{0}' to '{1}'.", fileName, web.Context.Url); // Get the path to the file which we are about to deploy List masterPageGallery = web.GetCatalog((int)ListTemplateType.MasterPageCatalog); Folder rootFolder = masterPageGallery.RootFolder; web.Context.Load(masterPageGallery); web.Context.Load(rootFolder); web.Context.ExecuteQuery(); var fileBytes = System.IO.File.ReadAllBytes(sourceFilePath); // Use CSOM to upload the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = fileBytes; newFile.Url = UrlUtility.Combine(rootFolder.ServerRelativeUrl, fileName); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = rootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); // Check out the file if needed if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { if (uploadFile.CheckOutType == CheckOutType.None) { uploadFile.CheckOut(); } } // Get content type for ID to assign associated content type information ContentType associatedCt = web.GetContentTypeById(associatedContentTypeID); var listItem = uploadFile.ListItemAllFields; listItem["Title"] = title; listItem["MasterPageDescription"] = description; // set the item as page layout listItem["ContentTypeId"] = Constants.PAGE_LAYOUT_CONTENT_TYPE; // Set the associated content type ID property listItem["PublishingAssociatedContentType"] = string.Format(";#{0};#{1};#", associatedCt.Name, associatedCt.Id); listItem["UIVersion"] = Convert.ToString(15); listItem.Update(); // Check in the page layout if needed if (masterPageGallery.ForceCheckout || masterPageGallery.EnableVersioning) { uploadFile.CheckIn(string.Empty, CheckinType.MajorCheckIn); listItem.File.Publish(string.Empty); } web.Context.ExecuteQuery(); }
public static void AddPublishingPage(PublishingPage page, ClientContext ctx, Web web) { SPPublishing.PublishingPage publishingPage = web.GetPublishingPage(page.FileName + ".aspx"); RemovePublishingPage(publishingPage, page, ctx, web); web.AddPublishingPage(page.FileName, page.Layout, page.Title, false); //DO NOT Publish here or it will fail if library doesn't enable Minor versions (PnP bug) publishingPage = web.GetPublishingPage(page.FileName + ".aspx"); Microsoft.SharePoint.Client.File pageFile = publishingPage.ListItem.File; pageFile.CheckOut(); if (page.Properties != null && page.Properties.Count > 0) { ctx.Load(pageFile, p => p.Name, p => p.CheckOutType); //need these values in SetFileProperties ctx.ExecuteQuery(); pageFile.SetFileProperties(page.Properties, false); } if (page.WebParts != null && page.WebParts.Count > 0) { Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager mgr = pageFile.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared); ctx.Load(mgr); ctx.ExecuteQuery(); AddWebpartsToPublishingPage(page, ctx, mgr); } List pagesLibrary = publishingPage.ListItem.ParentList; ctx.Load(pagesLibrary); ctx.ExecuteQueryRetry(); ListItem pageItem = publishingPage.ListItem; web.Context.Load(pageItem, p => p.File.CheckOutType); web.Context.ExecuteQueryRetry(); if (pageItem.File.CheckOutType != CheckOutType.None) { pageItem.File.CheckIn(String.Empty, CheckinType.MajorCheckIn); } if (page.Publish && pagesLibrary.EnableMinorVersions) { pageItem.File.Publish(String.Empty); if (pagesLibrary.EnableModeration) { pageItem.File.Approve(String.Empty); } } if (page.WelcomePage) { SetWelcomePage(web, pageFile); } ctx.ExecuteQuery(); }
public static bool AddFileToSPLib(string fullFileName, string webUrl, string libName) { try { SPAccount account = Global.SPAccounts().FirstOrDefault(s => s.SPSite.ToLower() == webUrl.ToLower()); if (account == null) { Global.WriteLog("There is no SPAccount entry for " + webUrl + " in the setting xml file.", EventLogEntryType.Error); return(false); } SecureString securePassword = new SecureString(); foreach (var passwordChar in account.Password) { securePassword.AppendChar(passwordChar); } using (context = new ClientContext(webUrl)) { context.Credentials = new SharePointOnlineCredentials(account.UserName, securePassword); context.Load(context.Web, w => w.Title); context.ExecuteQuery(); Microsoft.SharePoint.Client.ListCollection collList = context.Web.Lists; context.LoadQuery(collList.Include( list => list.Title, list => list.Id, list => list.Hidden, list => list.BaseType)); context.Load(collList); context.ExecuteQuery(); var targetList = collList.FirstOrDefault(l => l.Title.ToLower() == libName.ToLower()); string fileName = System.IO.Path.GetFileName(fullFileName); fileName = Global.CleanInvalidCharacters(fileName); context.Load(targetList); context.ExecuteQuery(); context.Load(targetList.RootFolder); context.ExecuteQuery(); Microsoft.SharePoint.Client.File currentFile = null; var tempcurrentFile = CheckIfItemAlreadyExistByDisplayName(fileName, targetList); if (tempcurrentFile != null && tempcurrentFile.Count() != 0) { currentFile = tempcurrentFile.FirstOrDefault().File; if (targetList.ForceCheckout) { currentFile.CheckOut(); } } using (FileStream fs = new FileStream(fullFileName, FileMode.Open)) { string targetLocation = targetList.RootFolder.ServerRelativeUrl + "/" + fileName; Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, targetLocation, fs, true); } if (targetList.ForceCheckout) { currentFile.CheckIn("Updated on " + DateTime.Now, CheckinType.MajorCheckIn); } return(true); } } catch (Exception ex) { if (!ex.Message.Contains("it is being used by another process")) { Global.WriteLog(string.Format("Can not add the file {0} in the SP lib {1}. Reason: ", fullFileName, libName, ex.Message), EventLogEntryType.Error); } return(false); } }
public override void ProvisionObjects(Web web, ProvisioningTemplate template) { Log.Info(Constants.LOGGING_SOURCE_FRAMEWORK_PROVISIONING, CoreResources.Provisioning_ObjectHandlers_Pages); var context = web.Context as ClientContext; if (!web.IsPropertyAvailable("ServerRelativeUrl")) { context.Load(web, w => w.ServerRelativeUrl); context.ExecuteQueryRetry(); } foreach (var page in template.PublishingPages) { var url = String.Format("{0}/Pages/{1}.aspx", web.ServerRelativeUrl, page.PageName); if (!url.ToLower().StartsWith(web.ServerRelativeUrl.ToLower())) { url = UrlUtility.Combine(web.ServerRelativeUrl, url); } var exists = true; Microsoft.SharePoint.Client.File file = null; try { file = web.GetFileByServerRelativeUrl(url); web.Context.Load(file); web.Context.ExecuteQuery(); } catch (ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { exists = false; } } if (exists) { if (page.Overwrite) { file.DeleteObject(); web.Context.ExecuteQueryRetry(); web.AddPublishingPage(page.PageName, page.PageLayoutName, page.Title, page.Content, page.Properties, page.Publish); } //if (file.CheckOutType == CheckOutType.None) //{ // file.CheckOut(); //} } else { web.AddPublishingPage(page.PageName, page.PageLayoutName, page.Title, page.Content, page.Properties, page.Publish); } if (page.WelcomePage) { if (!web.IsPropertyAvailable("RootFolder")) { web.Context.Load(web.RootFolder); web.Context.ExecuteQueryRetry(); } var rootFolderRelativeUrl = url.Substring(web.RootFolder.ServerRelativeUrl.Length); web.SetHomePage(rootFolderRelativeUrl); } // Check out the file if needed if (page.WebParts != null & page.WebParts.Any()) { if (!exists) { file = web.GetFileByServerRelativeUrl(url); web.Context.Load(file); web.Context.ExecuteQuery(); } file.CheckOut(); var existingWebParts = web.GetWebParts(url); foreach (var webpart in page.WebParts) { if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == webpart.Title) == null) { WebPartEntity wpEntity = new WebPartEntity(); wpEntity.WebPartTitle = webpart.Title; wpEntity.WebPartIndex = (int)webpart.Order; wpEntity.WebPartZone = webpart.Zone; if (!string.IsNullOrWhiteSpace(webpart.ListUrl)) { var list = web.GetListByUrl(webpart.ListUrl); var contents = String.Format(webpart.Contents, list.Id, list.Title); wpEntity.WebPartXml = contents.Trim(new[] { '\n', ' ' }); } else { wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] { '\n', ' ' }); } //wpEntity.WebPartXml = webpart.Contents.ToParsedString().Trim(new[] {'\n', ' '}); web.AddWebPartToWebPartPage(url, wpEntity); } } file.CheckIn("", CheckinType.MajorCheckIn); file.Publish(""); } } }
public static void SetSupportCaseContent(ClientContext ctx, string pageName, string url, string queryurl) { List pages = ctx.Web.Lists.GetByTitle("Pages"); ctx.Load(pages.RootFolder, f => f.ServerRelativeUrl); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.File file = ctx.Web.GetFileByServerRelativeUrl(pages.RootFolder.ServerRelativeUrl + "/" + pageName + ".aspx"); ctx.Load(file); ctx.ExecuteQuery(); file.CheckOut(); LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); string quicklaunchmenuFormat = @"<div><a href='{0}/{1}'>Sample Home Page</a></div> <br /> <div style='font-weight:bold'>CSR Dashboard</div> <div class='cdsm_mainmenu'> <ul> <li><a href='{0}/CSRInfo/{1}'>My CSR Info</a></li> <li><a href='{0}/CallQueue/{1}'>Call Queue</a></li> <li> <span class='collapse_arrow'></span> <span><a href='{0}/CustomerDashboard/{1}'>Customer Dashboard</a></span> <ul> <li><a href='{0}/CustomerDashboard/Orders{1}'>Recent Orders</a></li> <li><a class='current' href='#'>Support Cases</a></li> <li><a href='{0}/CustomerDashboard/Notes{1}'>Notes</a></li> </ul> </li> </ul> </div> <div class='cdsm_submenu'> </div>"; string quicklaunchmenu = string.Format(quicklaunchmenuFormat, url, queryurl); string qlwebPartXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><webParts><webPart xmlns=\"http://schemas.microsoft.com/WebPart/v3\"><metaData><type name=\"Microsoft.SharePoint.WebPartPages.ScriptEditorWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" /><importErrorMessage>Cannot import this Web Part.</importErrorMessage></metaData><data><properties><property name=\"Content\" type=\"string\"><![CDATA[" + quicklaunchmenu + "]]></property><property name=\"ChromeType\" type=\"chrometype\">None</property></properties></data></webPart></webParts>"; WebPartDefinition qlWpd = limitedWebPartManager.ImportWebPart(qlwebPartXml); WebPartDefinition qlWpdNew = limitedWebPartManager.AddWebPart(qlWpd.WebPart, "SupportCasesZoneLeft", 0); ctx.Load(qlWpdNew); //Customer Dropdown List Script Web Part string dpwebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/CustomerDropDownlist.webpart"); WebPartDefinition dpWpd = limitedWebPartManager.ImportWebPart(dpwebPartXml); WebPartDefinition dpWpdNew = limitedWebPartManager.AddWebPart(dpWpd.WebPart, "SupportCasesZoneTop", 0); ctx.Load(dpWpdNew); //Support Case CBS Info Web Part string cbsInfoWebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCaseCBSWebPartInfo.webpart"); WebPartDefinition cbsInfoWpd = limitedWebPartManager.ImportWebPart(cbsInfoWebPartXml); WebPartDefinition cbsInfoWpdNew = limitedWebPartManager.AddWebPart(cbsInfoWpd.WebPart, "SupportCasesZoneMiddle", 0); ctx.Load(cbsInfoWpdNew); //Support Case Content By Search Web Part string cbswebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCase CBS Webpart/SupportCaseCBS.webpart"); WebPartDefinition cbsWpd = limitedWebPartManager.ImportWebPart(cbswebPartXml); WebPartDefinition cbsWpdNew = limitedWebPartManager.AddWebPart(cbsWpd.WebPart, "SupportCasesZoneMiddle", 1); ctx.Load(cbsWpdNew); //Support Cases App Part string appPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/SupportCaseAppPart.webpart"); WebPartDefinition appPartWpd = limitedWebPartManager.ImportWebPart(appPartXml); WebPartDefinition appPartdNew = limitedWebPartManager.AddWebPart(appPartWpd.WebPart, "SupportCasesZoneBottom", 0); ctx.Load(appPartdNew); //Get Host Web Query String and show support case list web part string querywebPartXml = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Assets/GetHostWebQueryStringAndShowList.webpart"); WebPartDefinition queryWpd = limitedWebPartManager.ImportWebPart(querywebPartXml); WebPartDefinition queryWpdNew = limitedWebPartManager.AddWebPart(queryWpd.WebPart, "SupportCasesZoneBottom", 1); ctx.Load(queryWpdNew); file.CheckIn("Data storage model", CheckinType.MajorCheckIn); file.Publish("Data storage model"); ctx.Load(file); ctx.ExecuteQuery(); }
/// <summary> /// Uploads the document to matter library. /// </summary> /// <param name="requestObject">Request Object containing SharePoint App Token</param> /// <param name="sourceUrl">URL of the source document</param> /// <param name="documentStream">Content stream of the document</param> /// <param name="versionInfo">The version information.</param> /// <param name="comments">The comments.</param> /// <param name="retainCheckOut">retain check out option</param> /// <returns>Content Type List for the Request Object containing SharePoint App Token</returns> internal static string UploadtoMatter(RequestObject requestObject, string sourceUrl, Stream documentStream, int versionInfo, string comments, bool retainCheckOut) { string status = ConstantStrings.FALSE; string result = ConstantStrings.FALSE; try { if (null != requestObject) { ClientContext clientContext; if (!string.IsNullOrWhiteSpace(sourceUrl) && null != documentStream) { string[] sourceUrlParts = sourceUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture)); if (2 == sourceUrlParts.Length) { using (clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(sourceUrlParts[0]), requestObject.RefreshToken)) { Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(sourceUrlParts[1]); string documentLibraryName = BriefcaseHelperFunction.getLibraryName(clientContext, file); string contentType = string.Empty; contentType = BriefcaseContentTypeHelperFunctions.ContentTypeByName(requestObject, clientContext, file.Name, sourceUrl, 1, contentType, documentLibraryName); string listContentType = BriefcaseContentTypeHelperFunctions.GetContentTypeList(requestObject, clientContext, sourceUrl, contentType, 1, documentLibraryName); status = BriefcaseContentTypeHelperFunctions.GetContentTypeList(requestObject, clientContext, sourceUrl, contentType, 2, documentLibraryName); FileSaveBinaryInformation fileSaveBinaryInformation = new FileSaveBinaryInformation(); fileSaveBinaryInformation.ContentStream = documentStream; file.SaveBinary(fileSaveBinaryInformation); // Check if file is already checked out if (file.CheckOutType == CheckOutType.None) { file.CheckOut(); } // Check the type of Check in to be performed switch (versionInfo) { case 0: file.CheckIn(comments, CheckinType.MinorCheckIn); break; case 1: file.CheckIn(comments, CheckinType.MajorCheckIn); break; case 2: file.CheckIn(comments, CheckinType.OverwriteCheckIn); break; } // Load the Stream data for the file clientContext.ExecuteQuery(); status = BriefcaseContentTypeHelperFunctions.GetContentTypeList(requestObject, clientContext, sourceUrl, listContentType, 2, documentLibraryName); // Check whether we need to retain checkout if (retainCheckOut) { file.CheckOut(); clientContext.ExecuteQuery(); } status = string.Concat(ConstantStrings.TRUE, ConstantStrings.Comma, ConstantStrings.Space, file.ServerRelativeUrl); } } result = status; } else { status = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, TextConstants.MissingParametersMessage); result = status; } } } catch (Exception exception) { status = string.Concat(ConstantStrings.FALSE, ConstantStrings.Comma, ConstantStrings.Space, ServiceUtility.RemoveEscapeCharacter(exception.Message)); result = status; } return(result); }
static void Main(string[] args) { try { //Get site URL and credentials values from config Uri siteUri = new Uri(ConfigurationManager.AppSettings["SourceSite"].ToString()); //Connect to SharePoint Online using (ClientContext clientContext = new ClientContext(siteUri.ToString())) { SecureString passWord = new SecureString(); foreach (char c in ConfigurationManager.AppSettings["DestinationPassword"].ToCharArray()) { passWord.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials("*****@*****.**", passWord); if (clientContext != null) { //Source list List sourceList = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["SourceList"]); //Destination library List destinationLibrary = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings["DestinationLibrary"]); // try to get all the list items // could get in sections if it exceeds List View Threshold CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>"; ListItemCollection listItems = sourceList.GetItems(camlQuery); FieldCollection listFields = sourceList.Fields; clientContext.Load(sourceList); clientContext.Load(listFields); clientContext.Load(listItems); clientContext.ExecuteQuery(); // Download attachments for each list item and then upload to new list item foreach (ListItem item in listItems) { string attachmentURL = siteUri + "/Lists/" + ConfigurationManager.AppSettings["SourceList"].ToString() + "/Attachments/" + item["ID"]; Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(attachmentURL); clientContext.Load(folder); try { clientContext.ExecuteQuery(); } catch (ServerException ex) { Console.WriteLine(ex.Message); Console.WriteLine("No Attachment for ID " + item["ID"].ToString()); } FileCollection attachments = folder.Files; clientContext.Load(attachments); clientContext.ExecuteQuery(); // write each file to local disk foreach (SP.File file in folder.Files) { if (clientContext.HasPendingRequest) { clientContext.ExecuteQuery(); } var fileRef = file.ServerRelativeUrl; var fileInfo = SP.File.OpenBinaryDirect(clientContext, fileRef); using (var memory = new MemoryStream()) { byte[] buffer = new byte[1024 * 64]; int nread = 0; while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0) { memory.Write(buffer, 0, nread); } memory.Seek(0, SeekOrigin.Begin); // at this point you have the contents of your file in memory // save to computer Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, string.Format("/{0}/{1}", ConfigurationManager.AppSettings["AttachmentLibrary"], System.IO.Path.GetFileName(file.Name)), memory, true); } // this call avoids potential problems if any requests are still pending if (clientContext.HasPendingRequest) { clientContext.ExecuteQuery(); } SP.File newFile = clientContext.Web.GetFileByServerRelativeUrl(string.Format("/{0}/{1}", ConfigurationManager.AppSettings["AttachmentLibrary"], System.IO.Path.GetFileName(file.Name))); clientContext.Load(newFile); clientContext.ExecuteQuery(); //check out to make sure not to create multiple versions newFile.CheckOut(); FieldLookupValue applicationName = item["Source"] as FieldLookupValue; // app name may be null if (applicationName == null) { applicationName = new FieldLookupValue(); } applicationName.LookupId = Convert.ToInt32(item["ID"]); ListItem newItem = newFile.ListItemAllFields; newItem["From_x0020_Source"] = applicationName; newItem.Update(); // use OverwriteCheckIn type to make sure not to create multiple versions newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn); // Clear requests if any if pending if (clientContext.HasPendingRequest) { clientContext.ExecuteQuery(); } } Console.WriteLine("All list items and attachments copied over. Press any key to close"); Console.ReadKey(); } } } } catch (Exception ex) { Console.WriteLine("Failed: " + ex.Message); Console.WriteLine("Stack Trace: " + ex.StackTrace); Console.ReadKey(); } }
private static bool CheckOutIfNeeded(Web web, File targetFile) { var checkedOut = false; try { web.Context.Load(targetFile, f => f.CheckOutType, f => f.ListItemAllFields.ParentList.ForceCheckout); web.Context.ExecuteQueryRetry(); if (targetFile.CheckOutType == CheckOutType.None) { targetFile.CheckOut(); } checkedOut = true; } catch (ServerException ex) { // Handling the exception stating the "The object specified does not belong to a list." if (ex.ServerErrorCode != -2146232832) { throw; } } return checkedOut; }
public void Upload() { try { using (context = new MSC.ClientContext(sharePointSite)) { SecureString s = new SecureString(); //s. MSC.SharePointOnlineCredentials cred = new MSC.SharePointOnlineCredentials(ConfigurationManager.AppSettings["UsrName"], getPassword(ConfigurationManager.AppSettings["PassWord"])); context.Credentials = cred; var list = context.Web.Lists.GetByTitle(documentLibraryName); context.Load(list); var root = list.RootFolder; context.Load(root); context.ExecuteQuery(); // ADDITION string SourceDocPath = ConfigurationManager.AppSettings["SourceDocsPath"]; DirectoryInfo dInfo = new DirectoryInfo(SourceDocPath); FileInfo[] ListofFiles = dInfo.GetFiles(); List <linkIdentifier> listofLinks = new List <linkIdentifier>(); XmlDocument doc = new XmlDocument(); doc.Load("Links.xml"); XmlNodeList listXml = doc.GetElementsByTagName("link"); foreach (XmlNode n1 in listXml) { linkIdentifier id = new linkIdentifier(); id.rowIndex = Convert.ToInt32(n1["rowIndex"].InnerText); id.colIndex = Convert.ToInt32(n1["colIndex"].InnerText); id.SheetName = n1["SheetName"].InnerText; listofLinks.Add(id); } foreach (FileInfo fileInstance in ListofFiles) { bool IsgoodLink = false; string path = fileInstance.FullName; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook wb = excel.Workbooks.Open(path); //***********************LINK CHECK***************************************** //Read the first cell foreach (linkIdentifier identifier in listofLinks) { Worksheet excelSheet = wb.Sheets[identifier.SheetName]; string test = excelSheet.Cells[identifier.rowIndex, identifier.colIndex].Formula; test = test.Split(',')[0].TrimEnd("\"".ToCharArray()); String[] pathList = test.Split('/'); try { if (test.Contains(".aspx")) { //LinkCheck(test); IsgoodLink = CheckLink(pathList, cred); } else { IsgoodLink = CheckLink(pathList, cred); } } catch (MSC.ServerException e) { if (e.ServerErrorTypeName == "System.IO.FileNotFoundException") { IsgoodLink = false; } wb.Close(); IsgoodLink = false; } if (IsgoodLink == false) { Console.WriteLine("File {0} is having deadlinks.", fileInstance.Name); wb.Close(); return; } } wb.Close(); //***********************LINK CHECK***************************************** string tempdir = fileInstance.Name; tempdir = tempdir.Substring("2019.craft ".Length); tempdir = tempdir.Trim(' '); tempdir = tempdir.Remove((tempdir.Length - ".xlsm".Length)); String ParentDirectoryName = tempdir.Split('-')[0]; ParentDirectoryName = ParentDirectoryName.Trim(); string ChildDirectoryName = tempdir.Split('-')[1]; ChildDirectoryName = ChildDirectoryName.Trim(); try { MSC.ListItemCreationInformation information = new MSC.ListItemCreationInformation(); string targetFolder = ConfigurationManager.AppSettings["RootFolder"]; if (ConfigurationManager.AppSettings["Testing"] == "1") { targetFolder = ConfigurationManager.AppSettings["RootFolderTest"]; } ; information.FolderUrl = list.RootFolder.ServerRelativeUrl + targetFolder + ParentDirectoryName; MSC.Folder parentFolder = list.RootFolder.Folders.Add(information.FolderUrl); context.Load(parentFolder); context.ExecuteQuery(); information.FolderUrl = information.FolderUrl + "/" + ChildDirectoryName; MSC.Folder childDirectory = list.RootFolder.Folders.Add(information.FolderUrl); context.Load(childDirectory); context.ExecuteQuery(); if (IsgoodLink) { string filePath = fileInstance.FullName; FileStream documentStream = System.IO.File.OpenRead(filePath); byte[] info = new byte[documentStream.Length]; documentStream.Read(info, 0, (int)documentStream.Length); string fileURL = information.FolderUrl + "/" + fileInstance.Name; MSC.FileCreationInformation fileCreationInformation = new MSC.FileCreationInformation(); fileCreationInformation.Overwrite = true; fileCreationInformation.Content = info; fileCreationInformation.Url = fileURL; try { Microsoft.SharePoint.Client.File f = context.Web.GetFileByServerRelativeUrl(fileURL); context.Load(f); context.ExecuteQuery(); f.CheckOut(); } catch (Microsoft.SharePoint.Client.ServerException ex) { if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException") { Console.WriteLine("File is not found for Checkout"); } } Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(fileCreationInformation); uploadFile.CheckIn("Improvement Plan", MSC.CheckinType.MajorCheckIn); context.Load(uploadFile, w => w.MajorVersion, w => w.MinorVersion); context.ExecuteQuery(); Console.WriteLine("Document {0} is uploaded and checked in into SharePoint", fileURL); } } catch (Exception e) { Console.WriteLine(e.Message); } } } } catch (Exception ex) { new EventLog().WriteEntry(ex.Message, EventLogEntryType.Error); return; } }
//Update Documents public string UpdateDocument(DocRepositoryBO objDocRepo) { int DocItemID = 0; try { #region Document/file upload ClientContext ctx = new ClientContext(this.objAuth.SiteURL); ctx.RequestTimeout = 50000; //1000000; ctx.Credentials = GetO365Credentials(this.objAuth.UserName, this.objAuth.UserPassword); Web web = ctx.Web; Microsoft.SharePoint.Client.File uploadFile = web.GetFileByServerRelativeUrl(objDocRepo.FilePath); if (uploadFile.CheckOutType != CheckOutType.Online) { uploadFile.CheckOut(); } if (objDocRepo != null) { using (FileStream fs = new FileStream(objDocRepo.FilePath, FileMode.Open)) { FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = fs; fileInfo.Url = Path.GetFileName(objDocRepo.FilePath); fileInfo.Overwrite = true; Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle(objDocRepo.DocumentLibraryName); uploadFile = docs.RootFolder.Files.Add(fileInfo); ctx.Load(uploadFile, f => f.ListItemAllFields); ListItem item = uploadFile.ListItemAllFields; if (objDocRepo.Title != null) { item["Title"] = objDocRepo.DocName.Trim(); } if (objDocRepo.DocType != null) { item["DocumentType"] = objDocRepo.DocType.Trim(); } item["DocumentName"] = objDocRepo.DocName; item["DocumentNumber"] = objDocRepo.DocNumber; item["Stage"] = objDocRepo.Stage; item["Category"] = objDocRepo.Category; item["ReqId"] = objDocRepo.ReqID; item.Update(); if (ctx.HasPendingRequest) { ctx.ExecuteQueryAsync() .Wait(); } DocItemID = item.Id; } } #endregion } catch (Exception ex) { return("Error:" + ex.Message); } return(DocItemID.ToString()); }