/// <summary> /// Adds a file to a SharePoint list. Uses SharePoint server and login detailed in <c>AppSettings</c> /// </summary> /// <param name="fileName">File to be added</param> /// <param name="SPList">Sharepoint list to be added to. This list must be preexisting</param> public static void addToSpList(string fileName, string SPList) { string SPServer = ConfigurationManager.AppSettings["SPServer"]; string USER = ConfigurationManager.AppSettings["user"]; string PSWD = ConfigurationManager.AppSettings["password"]; string DOMAIN = ConfigurationManager.AppSettings["domain"]; //Create server context ClientContext context = new ClientContext(SPServer); //Authenticate sharepoint site NetworkCredential credentials = new NetworkCredential(USER, PSWD, DOMAIN); context.Credentials = credentials; Web web = context.Web; //Create file to add FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(fileName); newFile.Url = Path.GetFileName(fileName); //Get destination SP document list List list = web.Lists.GetByTitle(SPList); //Add file to SP Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newFile); //Load file context.Load(uploadFile); //Execute context into SP context.ExecuteQuery(); }
/// <summary> /// Creates the document. /// </summary> /// <param name="memoryStream">The memory stream.</param> /// <param name="claimId">The claim id.</param> public void CreateDocument(MemoryStream memoryStream, string caseId, string claimId, string filename) { //return; try { if (_ctx != null) { var list = _ctx.Web.Lists.GetByTitle(LibraryName); _ctx.Load(list); string file = string.Format("{1:yyyy-MM-dd_hh-mm-ss-tt}_{0}", filename, DateTime.Now); string uploadLocation = string.Format("{0}/{1}/{2}", "http://dev8spt", LibraryName.Replace(" ", ""), file); FileCreationInformation fileCreationInformation = new FileCreationInformation(); fileCreationInformation.Content = memoryStream.ToArray(); fileCreationInformation.Overwrite = true; fileCreationInformation.Url = uploadLocation; FileCollection documentFiles = list.RootFolder.Files; _ctx.Load(documentFiles); Microsoft.SharePoint.Client.File newFile = documentFiles.Add(fileCreationInformation); _ctx.Load(newFile); ListItem docitem = newFile.ListItemAllFields; _ctx.Load(docitem); _ctx.ExecuteQuery(); docitem[CaseIdKey] = caseId; docitem[PrimaryKey] = claimId; docitem.Update(); _ctx.ExecuteQuery(); } else { throw new Exception("Context Doesn't Exsist"); } } catch (Exception ee) { throw ee; } finally { ConnectionClose(); } }
/// <summary> /// Uploads used CSS and site logo to host web /// </summary> /// <param name="web"></param> public void UploadAndSetLogoToSite(Web web, string pathToLogo) { // Load for basic properties web.Context.Load(web); web.Context.ExecuteQuery(); // Instance to site assets List assetLibrary = web.Lists.GetByTitle("Site Assets"); web.Context.Load(assetLibrary, l => l.RootFolder); // Use CSOM to upload the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(pathToLogo); newFile.Url = "pnp.png"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); // Set custom image as the logo web.SiteLogoUrl = web.ServerRelativeUrl + "/SiteAssets/pnp.png"; web.Update(); web.Context.ExecuteQuery(); }
/// <summary> /// Differentiated to keep the button click clean. Creates the folder structure for Style Library /// </summary> /// <param name="clientContext"></param> private void DeployJStoContosoFoldersInStyleLibrary(ClientContext clientContext) { List styleLib = clientContext.Web.GetListByTitle("Style Library"); Folder rootFolder = styleLib.RootFolder; if (!rootFolder.FolderExists("Contoso")) { rootFolder.Folders.Add("Contoso"); clientContext.ExecuteQuery(); } Folder contosoFolder = rootFolder.ResolveSubFolder("Contoso"); if (!contosoFolder.FolderExists("Scripts")) { contosoFolder.Folders.Add("Scripts"); clientContext.ExecuteQuery(); } Folder contosoScriptFolder = contosoFolder.ResolveSubFolder("Scripts"); // Get the file stream var fileBytes = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/UserProfileData.js"))); // Use CSOM to upload the file to specific folder FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = fileBytes; newFile.Url = UrlUtility.Combine(contosoScriptFolder.ServerRelativeUrl, "UserProfileData.js"); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = contosoScriptFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); }
public void uploadCSVFile(ClientContext ctx, string libraryName, string filePath, string fn) { Web web = ctx.Web; FileCreationInformation newFile = new FileCreationInformation(); newFile.Overwrite = true; newFile.Content = System.IO.File.ReadAllBytes(filePath); newFile.Url = System.IO.Path.GetFileName(filePath); List docs = web.Lists.GetByTitle(libraryName); // Add file to the library. Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile); sp.ListItem item = uploadFile.ListItemAllFields; item["Title"] = "ITL"; item["Project"] = "project"; item["_x0023_Records"] = "RECORDS"; item["Target_x0020_List"] = "Target"; item["_x0023_Records"] = 22; uploadFile.ListItemAllFields.Update(); ctx.Load(uploadFile); ctx.ExecuteQuery(); }
private static void AddFiles(ClientContext context, Folder folder, int count) { DateTime date = DateTime.Now; try { for (int index = 0; index < count; index++) { date = date.AddHours(1); if (index % 100 == 0) { Console.WriteLine("index = {0},Date: {1}", index, date.Ticks); context.ExecuteQuery(); } var info = new FileCreationInformation { Content = System.Text.Encoding.Default.GetBytes("1"), Url = date.ToString("yyyyMMddHHmmss") + ".txt", }; var file = folder.Files.Add(info); //file.ListItemAllFields["UniqueNumber"] = Guid.NewGuid().ToString(); file.ListItemAllFields.Update(); } context.ExecuteQuery(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private File UploadFileWithSpecialCharacters(Folder folder, string fileName, System.IO.Stream stream, bool overwriteIfExists) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("Filename is required"); } // Create the file var newFileInfo = new FileCreationInformation() { ContentStream = stream, Url = fileName, Overwrite = overwriteIfExists }; var file = folder.Files.Add(newFileInfo); folder.Context.Load(file); folder.Context.ExecuteQueryRetry(); return(file); }
public bool uploadFile(Folder folder, string filePathSource) { try { _context.Load(folder); _context.ExecuteQuery(); if (!System.IO.File.Exists(filePathSource)) { throw new System.IO.FileNotFoundException("File not found.", filePathSource); } // Prepara la informacion del documento a subir var newFile = new FileCreationInformation() { Content = System.IO.File.ReadAllBytes(filePathSource), Url = System.IO.Path.GetFileName(filePathSource), Overwrite = true }; File file = folder.Files.Add(newFile); // Commit folder.Update(); _context.ExecuteQuery(); return(true); } catch (Exception ex) { return(false); } }
private void UpdateDBtoSP() { string fileToUpload = @"C:\Program Files (x86)\Hewlett Packard Enterprise\DC OSS RateCard\RATECARD_DB.accdb"; string sharePointSite = "https://hpe.sharepoint.com/teams/PDT/"; string documentLibraryName = "RateCard"; using (ClientContext clientContext = new ClientContext(sharePointSite)) { SecureString passWord = new SecureString(); foreach (char c in userPassword.ToCharArray()) { passWord.AppendChar(c); } clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord); Web web = clientContext.Web; FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(fileToUpload); newFile.Url = "https://hpe.sharepoint.com/teams/PDT/RateCard/RATECARD_DB.accdb"; newFile.Overwrite = true; Boolean replaceExistingFiles = true; List docs = web.Lists.GetByTitle(documentLibraryName); Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile); clientContext.ExecuteQuery(); } }
/// <summary> /// Uploads used CSS and site logo to host web /// </summary> /// <param name="web"></param> private void UploadAssetsToHostWeb(Web web) { // Instance to site assets List assetLibrary = web.Lists.GetByTitle("Site Assets"); web.Context.Load(assetLibrary, l => l.RootFolder); // Get the path to the file which we are about to deploy string cssFile = System.Web.Hosting.HostingEnvironment.MapPath( string.Format("~/{0}", "resources/contoso.css")); // Use CSOM to upload the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(cssFile); newFile.Url = "contoso.css"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); // Get the path to the file which we are about to deploy string logoFile = System.Web.Hosting.HostingEnvironment.MapPath( string.Format("~/{0}", "resources/99x.png")); // Use CSOM to upload the file in newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(logoFile); newFile.Url = "99x.png"; newFile.Overwrite = true; uploadFile = assetLibrary.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); }
public static void UploadDocument(string siteURL, string documentListName, string documentListURL, string DocuSetFolder, string documentName, FileStream documentStream, string status, string version, string contentID, string newFileName) { using (ClientContext clientContext = new ClientContext(siteURL)) { //Get Document List Microsoft.SharePoint.Client.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName); var fileCreationInformation = new FileCreationInformation(); fileCreationInformation.ContentStream = documentStream; //Allow owerwrite of document fileCreationInformation.Overwrite = true; //Upload URL fileCreationInformation.Url = siteURL + documentListURL + DocuSetFolder + newFileName; Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add( fileCreationInformation); //Update the metadata for a field uploadFile.ListItemAllFields["ContentTypeId"] = contentID; uploadFile.ListItemAllFields["Mechanical_x0020_Status"] = status; uploadFile.ListItemAllFields["Mechanical_x0020_Version"] = version; uploadFile.ListItemAllFields["Comments"] = "Autogenerated upload"; uploadFile.ListItemAllFields.Update(); clientContext.ExecuteQuery(); } }
private bool UploadTemplateToSharePoint(SharePointListStructure list) { var featureID = Guid.NewGuid(); // Get the List template Gallery Folder var listTemplateGallery = web.Lists.GetByTitle("List Template Gallery"); var listFolder = listTemplateGallery.RootFolder; FileCreationInformation fileCreationInformation = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(list.ListPhysicalPath), Overwrite = true, Url = "_catalogs/lt/" + list.ListName + ".stp", }; var file = listFolder.Files.Add(fileCreationInformation); file.Update(); clientContext.Load(file); try { clientContext.ExecuteQuery(); } catch { return(false); } return(true); }
/// <summary> /// Another valid approach for large files /// </summary> /// <param name="ctx"></param> /// <param name="library"></param> /// <param name="filePath"></param> public void UploadDocumentContentStream(ClientContext ctx, string libraryName, string filePath) { Web web = ctx.Web; // Ensure that target library exists, create if is missing if (!LibraryExists(ctx, web, libraryName)) { CreateLibrary(ctx, web, libraryName); } using (FileStream fs = new FileStream(filePath, FileMode.Open)) { FileCreationInformation flciNewFile = new FileCreationInformation(); // This is the key difference for the first case - using ContentStream property flciNewFile.ContentStream = fs; flciNewFile.Url = System.IO.Path.GetFileName(filePath); flciNewFile.Overwrite = true; List docs = web.Lists.GetByTitle(libraryName); Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile); ctx.Load(uploadFile); ctx.ExecuteQuery(); } }
private void Seeding() { FileCreationInformation _file = new FileCreationInformation(); _file.Content = System.IO.File.ReadAllBytes(sourcePath); _file.Overwrite = true; _file.Url = System.IO.Path.GetFileName(sourcePath); File uploadfile = oList.RootFolder.Files.Add(_file); //Add Data. var newItem1 = uploadfile.ListItemAllFields; newItem1["Title"] = $"Project Doc {Guid.NewGuid()}"; newItem1["DocDescription"] = "A12345"; newItem1["DocType"] = "Business requirement"; // Leader FieldLookupValue lv = new FieldLookupValue(); lv.LookupId = 1; newItem1["ProjectList"] = lv; newItem1.Update(); //context.Load(uploadfile); context.ExecuteQuery(); }
static void UploadExcelFileToSharepoint(ClientContext clientContext, String FileLocation) //this is used to upload the excel to sharepoint { try { List list = clientContext.Web.Lists.GetByTitle(Constant.RootFolder); clientContext.Load(list); clientContext.ExecuteQuery(); Folder Root = list.RootFolder; clientContext.Load(Root); clientContext.ExecuteQuery(); int last = FileLocation.LastIndexOf("\\"); String Filename = FileLocation.Substring(last + 1); FileCreationInformation NewFile = new FileCreationInformation(); NewFile.Content = System.IO.File.ReadAllBytes(FileLocation); NewFile.Url = Filename; NewFile.Overwrite = true; File fileToUpload = Root.Files.Add(NewFile); clientContext.Load(fileToUpload); clientContext.ExecuteQuery(); } catch (Exception ex) { LogClass.RecordException(ex); throw new Exception(ex.Message); } Console.WriteLine("\n\n\nUploading successfully completed............."); }
public void CreateWebPartPage(string FileName, string PageTitle) { clientContext.Load(sitePages.RootFolder, f => f.ServerRelativeUrl); clientContext.ExecuteQuery(); var sitePagesUrl = sitePages.RootFolder.ServerRelativeUrl; var newWebPartPageUrl = sitePagesUrl + "/" + FileName; var currentPageFile = hostWeb.GetFileByServerRelativeUrl(newWebPartPageUrl); clientContext.Load(currentPageFile, f => f.Exists); clientContext.ExecuteQuery(); if (currentPageFile.Exists) { currentPageFile.DeleteObject(); clientContext.ExecuteQuery(); } var newPage = new FileCreationInformation { Url = FileName, Overwrite = true, Content = Encoding.UTF8.GetBytes(Properties.Resources.WebPartPageTemplate) }; var newWebPartPageFile = sitePages.RootFolder.Files.Add(newPage); //ListItem newWebPartPageItem = newWebPartPageFile.ListItemAllFields; //newWebPartPageItem["Title"] = PageTitle; //newWebPartPageItem.Update(); clientContext.ExecuteQuery(); CreateTopNavNode(PageTitle, FileName, false); }
public void Submit(string filename, string email, int year, int month) { using (var serverContext = ServerApplicationContext.CreateContext()) { using (var workspace = serverContext.Application.CreateDataWorkspace()) { var entried = workspace.ApplicationData.WorkTimeSet.Where(x => x.UserId == email && x.WorkDate.Year == year && x.WorkDate.Month == month).Select(x => x.WorkDate).Execute().ToList(); var holidays = HolidyManager.GenerateHoliday(year); foreach (var day in Enumerable.Range(1, DateTime.DaysInMonth(year, month))) { var targetDay = new DateTime(year, month, day); if (targetDay.DayOfWeek == DayOfWeek.Sunday || targetDay.DayOfWeek == DayOfWeek.Saturday) { continue; } if (holidays.ContainsKey(targetDay)) { continue; } if (!entried.Contains(targetDay)) { throw new ApplicationException(targetDay.ToString("d") + "の入力がありません。"); } } } } Export(filename, email, year, month); using (var serverContext = ServerApplicationContext.CreateContext()) { var appWebContext = serverContext.Application.SharePoint; using (var ctx = appWebContext.GetAppWebClientContext()) { var list = ctx.Web.Lists.GetByTitle("WorkTimeSheet"); var rootFolder = list.RootFolder; ctx.Load(rootFolder, x => x.Folders, x => x.ServerRelativeUrl); ctx.ExecuteQuery(); var subFolderName = year.ToString("0000") + month.ToString("00"); var subFolder = list.RootFolder.Folders.Where(x => x.Name == subFolderName).FirstOrDefault(); if (subFolder == null) { subFolder = rootFolder.Folders.Add(rootFolder.ServerRelativeUrl + "/" + subFolderName); ctx.Load(subFolder); ctx.ExecuteQuery(); } using (var st = new FileStream(filename, FileMode.Open)) { var info = new FileCreationInformation(); info.ContentStream = st; info.Overwrite = true; info.Url = subFolder.ServerRelativeUrl + "/" + email.Replace("@", "_") + ".xlsx"; var file = subFolder.Files.Add(info); ctx.ExecuteQuery(); } } } }
public static void AddFilesToLibrary(List library, ClientContext context, int count) { var folder = library.RootFolder; DateTime date = DateTime.Now; try { for (int index = 0; index < count; index++) { date = date.AddHours(1); if (index % 100 == 0) { Console.WriteLine("Add {0} files finished", index); context.ExecuteQuery(); } var info = new FileCreationInformation { Content = System.Text.Encoding.Default.GetBytes("1"), Url = date.ToString("yyyyMMddHHmmss") + ".txt", }; var file = folder.Files.Add(info); file.ListItemAllFields.Update(); } context.ExecuteQuery(); } catch (Exception e) { logger.ErrorFormat("An error occurred while add files to library, error: {0}", e.ToString()); } if (context.HasPendingRequest) { context.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 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(); }
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(); }
public static File UploadFile(string fileName, string folderName, byte[] fileBytes) { ClientContext ctx = ConnectToSharePoint(); List spList = ctx.Web.Lists.GetByTitle("Documents"); ctx.Load(spList); ctx.ExecuteQuery(); FileCreationInformation fileInfo = new FileCreationInformation() { ContentStream = new System.IO.MemoryStream(fileBytes), Url = fileName, Overwrite = true }; ListItem liFolder = FindFolder(folderName); Folder folder = liFolder.Folder; File newFile = folder.Files.Add(fileInfo); ctx.Load(newFile); ctx.ExecuteQuery(); return(newFile); }
private void OnChanged(List siteAssetsLibrary, Folder parentFolder, System.IO.FileInfo source) { //Copies file to another directory. ShouldProcessReason _process; var filePath = source.FullName; var fileName = System.IO.Path.GetFileName(filePath); if (this.ShouldProcess( string.Format("Uploading {0} timestamp {1}", fileName, source.LastWriteTime), string.Format("Uploading {0} timestamp {1}", fileName, source.LastWriteTime), string.Format("Caption {0}", fileName), out _process)) { LogVerbose("---------------- Now uploading file {0}", filePath); // upload each file to library in host web byte[] fileContent = System.IO.File.ReadAllBytes(filePath); FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.Content = fileContent; fileInfo.Overwrite = true; fileInfo.Url = fileName; File newFile = parentFolder.Files.Add(fileInfo); // commit changes to library this.ClientContext.Load(newFile, nf => nf.ServerRelativeUrl, nf => nf.Length); this.ClientContext.ExecuteQueryRetry(); } }
private string UploadToSharePoint(byte[] convertedByteArray, Stream reqData, string baseFileName, string watermarkedLibrary) { string siteUrl = ""; //reqData.SiteAbsoluteUrl; //Insert Credentials ClientContext context = new ClientContext(siteUrl); //SecureString passWord = new SecureString(); //foreach (var c in "mypassword") passWord.AppendChar(c); //context.Credentials = new SharePointOnlineCredentials("myUserName", passWord); Web site = context.Web; string newFileName = baseFileName.Split('.')[0] + DateTime.Now.ToString("yyyyMMdd") + "." + baseFileName.Split('.')[1]; //System.IO.File.WriteAllBytes("Foo.txt", convertedByteArray); FileCreationInformation newFile = new FileCreationInformation(); newFile.ContentStream = new MemoryStream(convertedByteArray); //convertedByteArray;// System.IO.File.WriteAllBytes("", convertedByteArray); newFile.Url = System.IO.Path.GetFileName(newFileName); newFile.Overwrite = true; Microsoft.SharePoint.Client.List docs = site.Lists.GetByTitle(watermarkedLibrary); Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile); context.Load(uploadFile); context.ExecuteQuery(); //Return the URL of the new uploaded file string convertedFileLocation = ""; // reqData.WebServerRelativeUrl + "/" + watermarkedLibrary + "/" + newFileName; return(convertedFileLocation); }
protected void btnScenario_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { Site site = clientContext.Site; clientContext.Load(site, s => s.Url); clientContext.ExecuteQuery(); String webPartGalleryUrl = site.Url.TrimEnd('/') + "/_catalogs/wp"; var folder = site.RootWeb.GetList(webPartGalleryUrl).RootFolder; //var folder = clientContext.Site.RootWeb.Lists.GetByTitle("Web Part Gallery").RootFolder; clientContext.Load(folder); clientContext.ExecuteQuery(); //upload the "userprofileinformation.webpart" file using (var stream = System.IO.File.OpenRead( Server.MapPath("~/userprofileinformation.webpart"))) { FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = stream; fileInfo.Overwrite = true; fileInfo.Url = "userprofileinformation.webpart"; File file = folder.Files.Add(fileInfo); // Let's update the group for just uploaded web part ListItem webpartItem = file.ListItemAllFields; webpartItem["Group"] = "Add-in Script Part"; webpartItem.Update(); clientContext.ExecuteQuery(); } lblStatus.Text = string.Format("Add-in script part has been added to web part gallery. You can find 'User Profile Information' script part under 'Add-in Script Part' group in the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString()); } }
/// <summary> /// Another valid approach for large files /// </summary> /// <param name="ctx"></param> /// <param name="library"></param> /// <param name="filePath"></param> public void UploadDocumentContentStream(ClientContext ctx, string libraryName, string filePath) { Web web = ctx.Web; // Ensure that target library exists, create if is missing if (!LibraryExists(ctx, web, libraryName)) { CreateLibrary(ctx, web, libraryName); } using (FileStream fs = new FileStream(filePath, FileMode.Open)) { FileCreationInformation flciNewFile = new FileCreationInformation(); // This is the key difference for the first case - using ContentStream property flciNewFile.ContentStream = fs; flciNewFile.Url = System.IO.Path.GetFileName(filePath); flciNewFile.Overwrite = true; List docs = web.Lists.GetByTitle(libraryName); Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile); ctx.Load(uploadFile); ctx.ExecuteQuery(); } }
public int UploadFileViaContentStream(ClientContext context, string sLibraryName, string sLocalFilePath) { try { Web web = context.Web; using (FileStream fs = new FileStream(sLocalFilePath, FileMode.Open)) { FileCreationInformation flciNewFile = new FileCreationInformation(); flciNewFile.ContentStream = fs; flciNewFile.Url = System.IO.Path.GetFileName(sLocalFilePath); flciNewFile.Overwrite = true; List docs = web.Lists.GetByTitle(sLibraryName); Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile); context.Load(uploadFile); context.Load(uploadFile.ListItemAllFields); context.ExecuteQuery(); return(uploadFile.ListItemAllFields.Id); } } catch (Exception ex) { throw ex; } }
private void uploadThemeFile(ClientContext context, string listName, string folderUrl, string filePath, bool add, out string name) { if (string.IsNullOrEmpty(filePath)) { name = string.Empty; return; } string path = HostingEnvironment.MapPath(filePath); List list = context.Web.Lists.GetByTitle(listName); Folder dest = list.RootFolder.Folders.GetByUrl(folderUrl); if (add) { FileCreationInformation fci = new FileCreationInformation(); name = path.Substring(path.LastIndexOf("\\") + 1); fci.Url = name; fci.Content = System.IO.File.ReadAllBytes(path); fci.Overwrite = true; Microsoft.SharePoint.Client.File fileToUpload = dest.Files.Add(fci); context.Load(fileToUpload); context.ExecuteQuery(); //fileToUpload.CheckIn(string.Empty, CheckinType.MajorCheckIn); //fileToUpload.Publish(string.Empty); } else { //delete the file name = path.Substring(path.LastIndexOf("\\") + 1); dest.Files.GetByUrl(name).DeleteObject(); context.ExecuteQuery(); } }
public static void UploadFileToSharepoint(ClientContext ctx, FileStream fs, string fileName, string contentType) { var newFile = new FileCreationInformation(); //use this method to account for files > 2 MB in size fs.Seek(0, SeekOrigin.Begin); newFile.ContentStream = fs; newFile.Overwrite = true; newFile.Url = fileName; Folder uploadFolder = ctx.Web.GetFolderByServerRelativeUrl(FolderRelativeUrl); var uploadFile = uploadFolder.Files.Add(newFile); Log("Uploading " + fileName); ctx.ExecuteQuery(); if (contentType != "") { uploadFile.ListItemAllFields.ParseAndSetFieldValue("ContentType0", contentType); uploadFile.ListItemAllFields.Update(); Log("Setting metadata on " + fileName); ctx.Load(uploadFile); ctx.ExecuteQuery(); } Log("Upload of " + fileName + " Complete"); }
/// <summary> /// This method will upload uiconfigforspo.js into sharepoint catalog site collection /// </summary> /// <param name="filePath"></param> /// <param name="clientUrl"></param> public void UploadConfigFileToSPO(string filePath, string clientUrl) { using (ClientContext clientContext = spoAuthorization.GetClientContext(clientUrl)) { var web = clientContext.Web; var newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(filePath), Overwrite = true, //The root at which the uiconfigforspo.js needs to be uploaded Url = Path.Combine("SiteAssets/Matter Center Assets/Common Assets/Scripts/", Path.GetFileName(filePath)) }; //The document library names under which the uiconfigforspo.js has to be uploaded var docs = web.Lists.GetByTitle("Site Assets"); Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); //After uploading the file to sharepoint site collection, delete the file from the app root if(!filePath.EndsWith("config.js")) { System.IO.File.Delete(filePath); } } }
/// <summary> /// Creates Pages in the given web and Library using the passed client context /// </summary> /// <param name="context"></param> /// <param name="web"></param> /// <summary> /// creates a pages using a single definition file /// </summary> /// <param name="context"></param> /// <param name="def"></param> public override void Process(ClientContext context, bool add, string def) { XmlDocument doc = new XmlDocument(); doc.LoadXml(System.IO.File.ReadAllText(def)); XmlNodeList pages = doc.SelectNodes("Pages/Page"); if (add) { foreach (XmlNode page in pages) { //get the destination list name from ListName attribute List dest = context.Web.Lists.GetByTitle(page.Attributes[Constants.PageAttributeNames.ListName].Value); FileCreationInformation info = new FileCreationInformation(); info.Content = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(page.Attributes[Constants.PageAttributeNames.ContentPath].Value)); info.Url = page.Attributes[Constants.PageAttributeNames.Title].Value; File added = dest.RootFolder.Files.Add(info); added.ListItemAllFields["ContentTypeId"] = page.Attributes[Constants.PageAttributeNames.ContentTypeId].Value; added.ListItemAllFields["Title"] = page.Attributes[Constants.PageAttributeNames.Title].Value; } } else { foreach (XmlNode page in pages) { //get the destination list name from ListName attribute List dest = context.Web.Lists.GetByTitle(page.Attributes[Constants.PageAttributeNames.ListName].Value); File file = dest.RootFolder.Files.GetByUrl(page.Attributes[Constants.PageAttributeNames.Title].Value); file.DeleteObject(); } } context.ExecuteQuery(); }
void UploadTempDoc(List list, string path) { path = Server.MapPath(path); if (!System.IO.File.Exists(path)) { //Create a file to write to using (StreamWriter sw = System.IO.File.CreateText(path)) { sw.WriteLine("Temp doc"); } } using (FileStream fs = new FileStream(path, FileMode.Open)) { FileCreationInformation flciNewFile = new FileCreationInformation(); flciNewFile.ContentStream = fs; flciNewFile.Url = System.IO.Path.GetFileName(path); flciNewFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(flciNewFile); list.Context.Load(uploadFile); list.Context.ExecuteQuery(); } }
public SPOFile AddFile(byte[] content, bool overwrite, string leafName, Dictionary <string, object> fieldValues) { FileCreationInformation fci = new FileCreationInformation(); fci.Content = content; fci.Overwrite = overwrite; fci.Url = leafName; File file = _folder.Files.Add(fci); ListItem item = file.ListItemAllFields; if (fieldValues != null) { foreach (string fieldName in fieldValues.Keys) { item[fieldName] = fieldValues[fieldName]; } } item.Update(); _folder.Context.ExecuteQuery(); SPOFile.LoadFile(SPOSiteContext.CurrentSiteContext.Context, file); return(new SPOFile(file)); }
protected void DeploySandboxSolution_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { // get the solution gallery var solutionGallery = clientContext.Web.Lists.GetByTitle("Solution Gallery"); clientContext.Load(solutionGallery); clientContext.ExecuteQuery(); // get the file from the server path in the provider site var filePath = Server.MapPath("~/PreventDeleteSites.wsp"); var file = new FileStream(filePath, FileMode.Open); // create the FileCreationInformation object and prepare // to upload it to the solution gallery var fileCI = new FileCreationInformation() { ContentStream = file, Url = "PreventDeleteSites.wsp", Overwrite = true }; // upload the solution to the gallery var uploadedFile = solutionGallery.RootFolder.Files.Add(fileCI); clientContext.Load(uploadedFile); clientContext.ExecuteQuery(); } }
public static File UploadFile(ClientContext ctx, string list, byte[] file, string url) { Folder folder; var fileCreationInformation = new FileCreationInformation { Content = file, Overwrite = true }; if (ctx.Web.ServerRelativeUrl != "/") { url = ctx.Web.ServerRelativeUrl + url; } fileCreationInformation.Url = url; if (!string.IsNullOrEmpty(list)) { var library = ctx.Web.Lists.GetByTitle(list); folder = library.RootFolder; } else { folder = ctx.Web.RootFolder; } var uploadFile = folder.Files.Add(fileCreationInformation); ctx.ExecuteQueryRetry(); return(uploadFile); }
static void Main(string[] args) { string UserName = "******"; Console.WriteLine("Enter Your Password"); SecureString password = GetPassword(); ClientContext clientContext = new ClientContext("https://acuvatehyd.sharepoint.com/teams/Info"); clientContext.Credentials = new SharePointOnlineCredentials(UserName, password); Web web = clientContext.Web; var newfile = @"D:/My Code/SharePoint/SharePointPractice/Sharepoint10-08-2018/Information.txt"; //newfile.Url = "Information"; FileCreationInformation fileCreation = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(newfile), Overwrite = true, Url = Path.Combine("rajeshDocument/Rajesh/", Path.GetFileName(newfile)) }; //var docs = web.Lists.GetByTitle("rajeshDocument"); //var subfolder = docs.RootFolder.Folders.Where(folder => folder.Name == "Rajesh"); var list = clientContext.Web.Lists.GetByTitle("rajeshDocument"); var uploadFile = list.RootFolder.Files.Add(fileCreation); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); Console.WriteLine("Uploaded Successfully"); Console.ReadLine(); }
protected override void DeployModelInternal(object modelHost, DefinitionBase model) { var list = modelHost.WithAssertAndCast<List>("modelHost", value => value.RequireNotNull()); var webPartPageModel = model.WithAssertAndCast<WebPartPageDefinition>("model", value => value.RequireNotNull()); //if (!string.IsNullOrEmpty(webPartPageModel.FolderUrl)) // throw new NotImplementedException("FolderUrl for the web part page model is not supported yet"); var context = list.Context; // #SPBug // it turns out that there is no support for the web part page creating via CMOM // we we need to get a byte array to 'hack' this pages out.. // http://stackoverflow.com/questions/6199990/creating-a-sharepoint-2010-page-via-the-client-object-model // http://social.technet.microsoft.com/forums/en-US/sharepointgeneralprevious/thread/6565bac1-daf0-4215-96b2-c3b64270ec08 var file = new FileCreationInformation(); var pageContent = string.Empty; if (!string.IsNullOrEmpty(webPartPageModel.CustomPageLayout)) pageContent = webPartPageModel.CustomPageLayout; else pageContent = GetWebPartTemplateContent(webPartPageModel); var fileName = GetSafeWebPartPageFileName(webPartPageModel); file.Url = fileName; file.Content = Encoding.UTF8.GetBytes(pageContent); file.Overwrite = webPartPageModel.NeedOverride; var newFile = list.RootFolder.Files.Add(file); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = newFile, ObjectType = typeof(File), ObjectDefinition = webPartPageModel, ModelHost = list }); context.Load(newFile); context.ExecuteQuery(); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = newFile, ObjectType = typeof(File), ObjectDefinition = webPartPageModel, ModelHost = list }); }
protected void btnScenario1_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { if (clientContext != null) { Web web = clientContext.Web; List assetLibrary = web.Lists.GetByTitle("Site Assets"); clientContext.Load(assetLibrary, l => l.RootFolder); // Get the path to the file which we are about to deploy string file = System.Web.Hosting.HostingEnvironment.MapPath(string.Format("~/{0}", "CSS/contoso.css")); // Use CSOM to uplaod the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(file); newFile.Url = "contoso.css"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); // Now, apply a reference to the CSS URL via a custom action string actionName = "ContosoCSSLink"; // Clean up existing actions that we may have deployed var existingActions = web.UserCustomActions; clientContext.Load(existingActions); // Execute our uploads and initialzie the existingActions collection clientContext.ExecuteQuery(); // Clean up existing custom action with same name, if it exists foreach (var existingAction in existingActions) { if (existingAction.Name.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) existingAction.DeleteObject(); } clientContext.ExecuteQuery(); // Build a custom action to write a link to our new CSS file UserCustomAction cssAction = web.UserCustomActions.Add(); cssAction.Location = "ScriptLink"; cssAction.Sequence = 100; cssAction.ScriptBlock = @"document.write('<link rel=""stylesheet"" href=""" + assetLibrary.RootFolder.ServerRelativeUrl + @"/contoso.css"" />');"; cssAction.Name = actionName; // Apply cssAction.Update(); clientContext.ExecuteQuery(); lblStatus.Text = string.Format("Custom CSS 'contoso.css' has been applied to the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString()); } } }
public override SPDGFile AddFile(string url, byte[] content, bool overWrite) { FileCreationInformation fci=new FileCreationInformation(); fci.Content = content; fci.Url = url; fci.Overwrite = overWrite; var file=_folder.Files.Add(fci); _context.Load(file); _context.Load(file.ListItemAllFields, SPDGClientListItem.IncludeExpression); _context.ExecuteQuery(); return new SPDGClientFile(file, _context); }
protected override async Task OnProvisioningAsync() { var fci = new FileCreationInformation() { ContentStream = ContentStream, Overwrite = OverwriteExisting, Url = await HarshUrl.EnsureServerRelative(Folder.Value, FileName), }; AddedFile = Folder.Value.Files.Add(fci); await ClientContext.ExecuteQueryAsync(); }
/// <summary> /// Creates Matter Landing Page on matter creation /// </summary> /// <param name="clientContext">Client Context</param> /// <param name="client">Client object containing Client data</param> /// <param name="matter">Matter object containing Matter data</param> /// <returns>true if success else false</returns> internal static string CreateMatterLandingPage(ClientContext clientContext, Client client, Matter matter) { string response = string.Empty; if (null != clientContext && null != client && null != matter) { try { using (clientContext) { Uri uri = new Uri(client.ClientUrl); Web web = clientContext.Web; FileCreationInformation objFileInfo = new FileCreationInformation(); List sitePageLib = null; //// Create Matter Landing Web Part Page objFileInfo.Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, Constants.AspxExtension); response = CreateWebPartPage(sitePageLib, clientContext, objFileInfo, matter, web); if (Constants.TRUE == response) { //// Configure All Web Parts string[] webParts = ConfigureXMLCodeOfWebParts(client, matter, clientContext, sitePageLib, objFileInfo, uri, web); Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, ConfigurationManager.AppSettings["MatterLandingPageRepository"].Replace(Constants.SPACE, string.Empty), Constants.Backslash, objFileInfo.Url)); clientContext.Load(file); clientContext.ExecuteQuery(); LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition webPartDefinition = null; string[] zones = { Constants.HeaderZone, Constants.TopZone, Constants.RightZone, Constants.TopZone, Constants.RightZone, Constants.RightZone, Constants.FooterZone, Constants.RightZone, Constants.RightZone }; AddWebPart(clientContext, limitedWebPartManager, webPartDefinition, webParts, zones); } else { response = Constants.FALSE; } } } catch (Exception ex) { ////Generic Exception MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["ErrorMessage"], "creating Matter Landing page")); MatterProvisionHelperFunction.DisplayAndLogError(errorFilePath, "Message: " + ex.Message + "\nStacktrace: " + ex.StackTrace); throw; } return response; } else { return string.Format(CultureInfo.InvariantCulture, Constants.ServiceResponse, string.Empty, Constants.MessageNoInputs); } }
protected void btnScenario_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { //Grab the web part gallery folder for uploading var folder = clientContext.Web.Lists.GetByTitle("Web Part Gallery").RootFolder; clientContext.Load(folder); clientContext.ExecuteQuery(); //open the "scenario2.webpart" file ListItem item; using (var fileReadingStream = System.IO.File.OpenRead( Server.MapPath("~/scenario2.webpart"))) { using (var workingCopy = new MemoryStream()) { //read the file into an in memory stream for editing fileReadingStream.CopyTo(workingCopy); LabHelper.SetJsLink(workingCopy, this.Request); //Reset the stream position for use during the upload workingCopy.Position = 0; //Use the FileCreationInformation to upload the new file FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = workingCopy; fileInfo.Overwrite = true; fileInfo.Url = "scenario2.webpart"; File file = folder.Files.Add(fileInfo); //Get the list item associated with the newly uploaded file item = file.ListItemAllFields; clientContext.Load(file.ListItemAllFields); clientContext.ExecuteQuery(); } } // Let's update the group for the uploaded web part var list = clientContext.Web.Lists.GetByTitle("Web Part Gallery"); if (item == null) { lblStatus.Text = "Oh dear something went wrong while uploading the webpart"; return; } list.GetItemById(item.Id); item["Group"] = "App Script Part"; item.Update(); clientContext.ExecuteQuery(); lblStatus.Text = string.Format("App script part has been added to web part gallery. You can find 'User Profile Information' script part under 'App Script Part' group in the <a href='{0}'>host web</a>.", spContext.SPHostUrl); } }
public int CreateWebPartPage(ClientContext clientContext, string pageName, string layout, string masterpagelistName, string listName, string pageTitle) { int response = -1; if (null != clientContext && !string.IsNullOrWhiteSpace(pageName) && !string.IsNullOrWhiteSpace(layout) && !string.IsNullOrWhiteSpace(masterpagelistName) && !string.IsNullOrWhiteSpace(listName)) { try { //// Find Default Layout from Master Page Gallery to create Web Part Page Web web = clientContext.Web; ListItemCollection collection = spList.GetData(clientContext, masterpagelistName); clientContext.Load(collection, listItemCollectionProperties => listItemCollectionProperties.Include(listItemProperties => listItemProperties.Id, listItemProperties => listItemProperties.DisplayName)); clientContext.ExecuteQuery(); ListItem fileName = null; foreach (ListItem findLayout in collection) { if (findLayout.DisplayName.Equals(layout, StringComparison.OrdinalIgnoreCase)) { fileName = findLayout; break; } } FileCreationInformation objFileInfo = new FileCreationInformation(); objFileInfo.Url = pageName; Microsoft.SharePoint.Client.File fileLayout = fileName.File; clientContext.Load(fileLayout); clientContext.ExecuteQuery(); ClientResult<Stream> filedata = fileLayout.OpenBinaryStream(); List sitePageLib = web.Lists.GetByTitle(listName); clientContext.Load(sitePageLib); clientContext.ExecuteQuery(); StreamReader reader = new StreamReader(filedata.Value); objFileInfo.Content = System.Text.Encoding.ASCII.GetBytes(reader.ReadToEnd()); Microsoft.SharePoint.Client.File matterLandingPage = sitePageLib.RootFolder.Files.Add(objFileInfo); ListItem matterLandingPageDetails = matterLandingPage.ListItemAllFields; // Update the title of the page matterLandingPageDetails[ServiceConstants.TITLE] = pageTitle; matterLandingPageDetails.Update(); clientContext.Load(matterLandingPageDetails, matterLandingPageProperties => matterLandingPageProperties[ServiceConstants.TITLE], matterLandingPageProperties => matterLandingPageProperties.Id); clientContext.ExecuteQuery(); response = matterLandingPageDetails.Id; } catch (Exception) { response = -1; } } return response; }
protected override void DeployModelInternal(object modelHost, DefinitionBase model) { var listModelHost = modelHost.WithAssertAndCast<ListModelHost>("modelHost", value => value.RequireNotNull()); var list = listModelHost.HostList; var publishingPageModel = model.WithAssertAndCast<PublishingPageDefinition>("model", value => value.RequireNotNull()); var context = list.Context; // #SPBug // it turns out that there is no support for the web part page creating via CMOM // we we need to get a byte array to 'hack' this pages out.. // http://stackoverflow.com/questions/6199990/creating-a-sharepoint-2010-page-via-the-client-object-model // http://social.technet.microsoft.com/forums/en-US/sharepointgeneralprevious/thread/6565bac1-daf0-4215-96b2-c3b64270ec08 var file = new FileCreationInformation(); var pageContent = PublishingPageTemplates.RedirectionPageMarkup; // TODO, need to be fixed // add new page var fileName = publishingPageModel.FileName; if (!fileName.EndsWith(".aspx")) fileName += ".aspx"; file.Url = fileName; file.Content = Encoding.UTF8.GetBytes(pageContent); file.Overwrite = publishingPageModel.NeedOverride; // just root folder is supported yet //if (!string.IsNullOrEmpty(publishingPageModel.FolderUrl)) // throw new NotImplementedException("FolderUrl for the web part page model is not supported yet"); context.Load(list.RootFolder.Files.Add(file)); context.ExecuteQuery(); // update properties var newPage = list.QueryAndGetItemByFileName(fileName); // TODO // gosh, how we are supposed to get Master Page gallery with publishing template having just list here? // no SPWeb.ParentSite/Site -> RootWeb.. //newPage["PublishingPageContent"] = "Yea!"; //newPage["PublishingPageLayout"] = "/auto-tests/csom-application/_catalogs/masterpage/ArticleLinks.aspx"; newPage.Update(); context.ExecuteQuery(); }
public void Initialize() { clientContext = TestCommon.CreateClientContext(); documentLibrary = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, DocumentLibraryName, false); folder = documentLibrary.RootFolder.CreateFolder(FolderName); var fci = new FileCreationInformation(); fci.Content = System.IO.File.ReadAllBytes(TestFilePath1); fci.Url = folder.ServerRelativeUrl + "/office365.png"; fci.Overwrite = true; file = folder.Files.Add(fci); clientContext.Load(file); clientContext.ExecuteQuery(); }
/// <summary> /// Upload file to library /// </summary> /// <param name="list">List to be processed - can be root web or sub site</param> /// <param name="filePath">Path to source location like c:\fuu.txt</param> public static void UploadDocumentToLibrary(this List list, string filePath) { using (FileStream fs = new FileStream(filePath, FileMode.Open)) { FileCreationInformation flciNewFile = new FileCreationInformation(); // This is the key difference for the first case - using ContentStream property flciNewFile.ContentStream = fs; flciNewFile.Url = System.IO.Path.GetFileName(filePath); flciNewFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(flciNewFile); list.Context.Load(uploadFile); list.Context.ExecuteQuery(); } }
/// <summary> /// Uploads site logo to host web /// </summary> /// <param name="web"></param> public static void UploadLogoToHostWeb(Web web) { // Instance to site assets List assetLibrary = web.Lists.GetByTitle("Site Assets"); web.Context.Load(assetLibrary, l => l.RootFolder); // Get the path to the file which we are about to deploy string logoFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources/garagelogo.png"); // Use CSOM to uplaod the file in FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(logoFile); newFile.Url = "garagelogo.png"; newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = assetLibrary.RootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQuery(); }
protected void btnScenario_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { var folder = clientContext.Site.RootWeb.Lists.GetByTitle("Web Part Gallery").RootFolder; clientContext.Load(folder); clientContext.ExecuteQuery(); //upload the "userprofileinformation.webpart" file using (var stream = System.IO.File.OpenRead( Server.MapPath("~/userprofileinformation.webpart"))) { FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = stream; fileInfo.Overwrite = true; fileInfo.Url = "userprofileinformation.webpart"; File file = folder.Files.Add(fileInfo); clientContext.ExecuteQuery(); } // Let's update the group for just uploaded web part var list = clientContext.Site.RootWeb.Lists.GetByTitle("Web Part Gallery"); CamlQuery camlQuery = CamlQuery.CreateAllItemsQuery(100); Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(camlQuery); clientContext.Load(items); clientContext.ExecuteQuery(); foreach (var item in items) { // Just random group name to differentiate it from the rest if (item["FileLeafRef"].ToString().ToLowerInvariant() == "userprofileinformation.webpart") { item["Group"] = "Add-in Script Part"; item.Update(); clientContext.ExecuteQuery(); } } lblStatus.Text = string.Format("Add-in script part has been added to web part gallery. You can find 'User Profile Information' script part under 'Add-in Script Part' group in the <a href='{0}'>host web</a>.", spContext.SPHostUrl.ToString()); } }
/// <summary> /// This has limitation of roughly 2 MB as the file size due the way information is sent to the server /// </summary> /// <param name="ctx"></param> /// <param name="libraryName"></param> /// <param name="filePath"></param> /// <param name="createLibraryIfNotExists"></param> public void UploadDocumentContent(ClientContext ctx, string libraryName, string filePath) { Web web = ctx.Web; // Ensure that target library exists, create if is missing if (!LibraryExists(ctx, web, libraryName)) { CreateLibrary(ctx, web, libraryName); } FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = System.IO.File.ReadAllBytes(filePath); newFile.Url = System.IO.Path.GetFileName(filePath); // Get instances to the given library List docs = web.Lists.GetByTitle(libraryName); // Add file to the library Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile); ctx.Load(uploadFile); ctx.ExecuteQuery(); }
/// <summary> /// Deploy workflow template to the template library /// </summary> /// <param name="solutionPath">Path to the workflow template (wsp)</param> public void DeployWorkflowSolution(string solutionPath) { // get the file from the server path in the provider site using (var file = new FileStream(solutionPath, FileMode.Open)) { // create the FileCreationInformation object and prepare // to upload it to the solution gallery var fileCI = new FileCreationInformation() { ContentStream = file, Url = Path.GetFileName(solutionPath), Overwrite = true, }; // upload the solution to the gallery var uploadedFile = templateLibrary.RootFolder.Files.Add(fileCI); clientContext.Load(uploadedFile); clientContext.ExecuteQuery(); } logger.WriteMessage("Workflow solution " + Path.GetFileName(solutionPath) + " is deployed."); }
protected void btnAddToGallery_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPHost()) { var folder = clientContext.Web.Lists.GetByTitle("Web Part Gallery").RootFolder; clientContext.Load(folder); clientContext.ExecuteQuery(); //upload the "OneDrive for Business Usage Guidelines.docx" using (var stream = System.IO.File.OpenRead(Server.MapPath("~/MyPicWebPart.dwp"))) { FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = stream; fileInfo.Overwrite = true; fileInfo.Url = "MyPicWebPart.dwp"; folder.Files.Add(fileInfo); clientContext.ExecuteQuery(); imgWPG.ImageUrl = "~/Images/Yes.png"; } } }
private void LayoutRoot_Drop(object sender, DragEventArgs e) { message.Text = "Item Dropped!"; FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[]; ClientContext clientContext = new ClientContext("http://jakesharepointsaturday.sharepoint.com/TeamSite"); _site = clientContext.Web; _list = _site.Lists.GetByTitle("Important Documents"); foreach (FileInfo file in droppedFiles) { byte[] contents = GetContentsOfFile(file); FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = contents; newFile.Url = file.Name; Microsoft.SharePoint.Client.File uploadFile = _list.RootFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQueryAsync(SuccessCallback, FailedCallback); } }
public void UploadDocument(string listName, string documentListURL, string documentName, byte[] documentStream) { _ctx = null; Web web = Ctx.Web; List list = web.Lists.GetByTitle(listName); Ctx.Load(list); Ctx.ExecuteQuery(); var folder = list.RootFolder; Ctx.Load(folder); Ctx.ExecuteQuery(); string target = folder.ServerRelativeUrl + "/" + documentName; FileCreationInformation fci = new FileCreationInformation(); fci.Overwrite = true; fci.Url = target; fci.Content = documentStream; File uploadedFile = folder.Files.Add(fci); uploadedFile.ListItemAllFields["Title"] = documentName; uploadedFile.ListItemAllFields.Update(); Ctx.ExecuteQuery(); Ctx.Load(uploadedFile); Ctx.ExecuteQuery(); //return uploadedFile; }
public void Initialize() { clientContext = TestCommon.CreateClientContext(); documentLibrary = clientContext.Web.GetListByTitle(DocumentLibraryName); if (documentLibrary == null) { documentLibrary = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, DocumentLibraryName, false); } clientContext.Load(documentLibrary.RootFolder.Folders); clientContext.ExecuteQueryRetry(); foreach (Folder existingFolder in documentLibrary.RootFolder.Folders) { if (string.Equals(existingFolder.Name, FolderName, StringComparison.InvariantCultureIgnoreCase)) { folder = existingFolder; break; } } if (folder == null) { folder = documentLibrary.RootFolder.CreateFolder(FolderName); } var fci = new FileCreationInformation(); fci.Content = System.IO.File.ReadAllBytes(TestFilePath1); fci.Url = folder.ServerRelativeUrl + "/office365.png"; fci.Overwrite = true; file = folder.Files.Add(fci); clientContext.Load(file); clientContext.ExecuteQueryRetry(); }
public override void DeployModel(object modelHost, DefinitionBase model) { var folderModelHost = modelHost.WithAssertAndCast<FolderModelHost>("modelHost", value => value.RequireNotNull()); var definition = model.WithAssertAndCast<PublishingPageLayoutDefinition>("model", value => value.RequireNotNull()); var folder = folderModelHost.CurrentListFolder; var list = folderModelHost.CurrentList; ContentType siteContentType = null; if (!string.IsNullOrEmpty(definition.AssociatedContentTypeId)) { siteContentType = folderModelHost.HostSite.RootWeb.AvailableContentTypes.GetById(definition.AssociatedContentTypeId); folderModelHost.HostSite.Context.Load(siteContentType); folderModelHost.HostSite.Context.ExecuteQueryWithTrace(); } var context = folder.Context; var pageName = GetSafePageFileName(definition); var currentPageFile = GetCurrentPage(list, folder, pageName); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioning, Object = currentPageFile, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); ModuleFileModelHandler.WithSafeFileOperation(list, currentPageFile, f => { var file = new FileCreationInformation(); file.Url = pageName; file.Content = Encoding.UTF8.GetBytes(definition.Content); file.Overwrite = definition.NeedOverride; return folder.Files.Add(file); }, newFile => { var newFileItem = newFile.ListItemAllFields; context.Load(newFileItem); context.ExecuteQueryWithTrace(); var site = folderModelHost.HostSite; var currentPageLayoutItem = FindPageLayoutItem(site, definition.FileName); var currentPageLayoutItemContext = currentPageLayoutItem.Context; var publishingFile = currentPageLayoutItem.File; currentPageLayoutItemContext.Load(currentPageLayoutItem); currentPageLayoutItemContext.Load(currentPageLayoutItem, i => i.DisplayName); currentPageLayoutItemContext.Load(publishingFile); currentPageLayoutItemContext.ExecuteQueryWithTrace(); newFileItem[BuiltInInternalFieldNames.Title] = definition.Title; newFileItem["MasterPageDescription"] = definition.Description; newFileItem[BuiltInInternalFieldNames.ContentTypeId] = BuiltInPublishingContentTypeId.PageLayout; if (!string.IsNullOrEmpty(definition.PreviewImageUrl)) { var urlValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext { Value = definition.PreviewImageUrl, Context = context }).Value; var urlFieldValue = new FieldUrlValue { Url = urlValue }; if (!string.IsNullOrEmpty(definition.PreviewImageDescription)) urlFieldValue.Description = definition.PreviewImageDescription; newFileItem["PublishingPreviewImage"] = urlFieldValue; } if (siteContentType != null) { newFileItem["PublishingAssociatedContentType"] = String.Format(";#{0};#{1};#", siteContentType.Name, siteContentType.Id.ToString()); } newFileItem.Update(); context.ExecuteQueryWithTrace(); }); currentPageFile = GetCurrentPage(folderModelHost.CurrentList, folder, pageName); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = currentPageFile, ObjectType = typeof(File), ObjectDefinition = definition, ModelHost = modelHost }); context.ExecuteQueryWithTrace(); }
/// <summary> /// Deploys a new masterpage /// </summary> /// <param name="web">The web to process</param> /// <param name="sourceFilePath">The path to the source file</param> /// <param name="title">The title of the masterpage</param> /// <param name="description">The description of the masterpage</param> /// <param name="uiVersion"></param> /// <param name="defaultCSSFile"></param> /// <param name="folderPath"></param> public static void DeployMasterPage(this Web web, string sourceFilePath, string title, string description, string uiVersion = "15", string defaultCSSFile = "", string folderPath = "") { 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); Log.Info(Constants.LOGGING_SOURCE, CoreResources.BrandingExtension_DeployMasterPage, 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.ExecuteQueryRetry(); // Create folder if does not exists if (!String.IsNullOrEmpty(folderPath)) { web.EnsureFolder(rootFolder, folderPath); } // 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, folderPath, fileName); newFile.Overwrite = true; File uploadFile = rootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQueryRetry(); 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); if (masterPageGallery.EnableModeration) { listItem.File.Publish(string.Empty); } } web.Context.Load(listItem); web.Context.ExecuteQueryRetry(); }
/// <summary> /// Private method to support all kinds of file uploads to the master page gallery /// </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> /// <param name="itemContentTypeId">Content type id for the item.</param> /// <param name="folderHierarchy">Folder hierarchy where the file will be uploaded</param> private static void DeployMasterPageGalleryItem(this Web web, string sourceFilePath, string title, string description, string associatedContentTypeID, string itemContentTypeId, string folderHierarchy = "") { 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); Log.Info(Constants.LOGGING_SOURCE, CoreResources.BrandingExtension_DeployPageLayout, 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.ExecuteQueryRetry(); // Create folder structure inside master page gallery, if does not exists // For e.g.: _catalogs/masterpage/contoso/ web.EnsureFolder(rootFolder, folderHierarchy); 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, folderHierarchy, fileName); newFile.Overwrite = true; File uploadFile = rootFolder.Files.Add(newFile); web.Context.Load(uploadFile); web.Context.ExecuteQueryRetry(); // 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"] = itemContentTypeId; // 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); if (masterPageGallery.EnableModeration) { listItem.File.Publish(string.Empty); } } web.Context.ExecuteQueryRetry(); }
private static void SetDocumentAsTemplate(ClientContext cc, Web web) { ContentType ct = web.ContentTypes.GetById("0x0101009189AB5D3D2647B580F011DA2F356FB3"); cc.Load(ct); cc.ExecuteQuery(); // Get instance to the _cts folder created for the each of the content types string ctFolderServerRelativeURL = "_cts/" + ct.Name; Folder ctFolder = web.GetFolderByServerRelativeUrl(ctFolderServerRelativeURL); cc.Load(ctFolder); cc.ExecuteQuery(); // Load the local template document string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "template.docx"); string fileName = System.IO.Path.GetFileName(path); byte[] filecontent = System.IO.File.ReadAllBytes(path); // Uplaod file to the Office365 using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open)) { FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = filecontent; newFile.Url = ctFolderServerRelativeURL + "/" + fileName; Microsoft.SharePoint.Client.File uploadedFile = ctFolder.Files.Add(newFile); cc.Load(uploadedFile); cc.ExecuteQuery(); } ct.DocumentTemplate = fileName; ct.Update(true); cc.ExecuteQuery(); Console.WriteLine("Document template uploaded and set to the content type."); }
/// <summary> /// Differentiated to keep the button click clean. Creates the folder structure for Style Library /// </summary> /// <param name="clientContext"></param> private void DeployJStoContosoFoldersInStyleLibrary(ClientContext clientContext) { List styleLib = clientContext.Web.GetListByTitle("Style Library"); Folder rootFolder = styleLib.RootFolder; if (!rootFolder.SubFolderExists("Contoso")) { rootFolder.Folders.Add("Contoso"); clientContext.ExecuteQuery(); } Folder contosoFolder = rootFolder.ResolveSubFolder("Contoso"); if (!contosoFolder.SubFolderExists("Scripts")) { contosoFolder.Folders.Add("Scripts"); clientContext.ExecuteQuery(); } Folder contosoScriptFolder = contosoFolder.ResolveSubFolder("Scripts"); // Get the file stream var fileBytes = System.IO.File.ReadAllBytes(HostingEnvironment.MapPath(string.Format("~/{0}", "Resources/UserProfileData.js"))); // Use CSOM to upload the file to specific folder FileCreationInformation newFile = new FileCreationInformation(); newFile.Content = fileBytes; newFile.Url = UrlUtility.Combine(contosoScriptFolder.ServerRelativeUrl, "UserProfileData.js"); newFile.Overwrite = true; Microsoft.SharePoint.Client.File uploadFile = contosoScriptFolder.Files.Add(newFile); clientContext.Load(uploadFile); clientContext.ExecuteQuery(); }
/// <summary> /// Create a Web Part page of matter in its document library /// </summary> /// <param name="sitePageLib">SharePoint List of matter library</param> /// <param name="clientContext">SharePoint Client Context</param> /// <param name="objFileInfo">Object of FileCreationInformation</param> /// <param name="matter">Matter object containing Matter data</param> /// <param name="web">Web object containing Web data</param> /// <returns>true if success else false</returns> internal static string CreateWebPartPage(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Matter matter, Web web) { string response = string.Empty; //// Find Default Layout from Master Page Gallery to create Web Part Page sitePageLib = web.Lists.GetByTitle(Constants.MasterPageGallery); clientContext.Load(sitePageLib); clientContext.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = Constants.DMSRoleQuery; ListItemCollection collection = sitePageLib.GetItems(camlQuery); clientContext.Load( collection, items => items.Include( item => item.DisplayName, item => item.Id)); clientContext.ExecuteQuery(); response = WebPartsCreation(sitePageLib, clientContext, objFileInfo, matter, web, collection); return response; }