/// <summary> /// Downloads the image and converts it to base64 strings /// </summary> /// <param name="ClientContext">client context.</param> /// <param name="imagePath">Includes the image path.</param> public static string GetImageInBase64Format(ClientContext clientContext, string imagePath) { string result = string.Empty; try { if (null != clientContext) { Microsoft.SharePoint.Client.File userImage = clientContext.Web.GetFileByServerRelativeUrl(imagePath); ClientResult <Stream> userImageStream = userImage.OpenBinaryStream(); clientContext.Load(userImage); clientContext.ExecuteQuery(); if (userImage.Exists) { using (var newStream = new MemoryStream()) { userImageStream.Value.CopyTo(newStream); byte[] bytes = newStream.ToArray(); result = ConstantStrings.base64ImageFormat + Convert.ToBase64String(bytes); } } } } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ConstantStrings.LogTableName); } return(result); }
public Stream GetImageStream(string siteUrl, string imageUrl) { using (ClientContext clientContext = new ClientContext(siteUrl)) { try { if (!isOnPrem) { SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(username, password); clientContext.Credentials = credentials; } SharePoint.Client.Web web = clientContext.Web; clientContext.Load(web, website => website.ServerRelativeUrl); clientContext.ExecuteQuery(); Regex regex = new Regex(siteUrl, RegexOptions.IgnoreCase); string strSiteRelavtiveURL = regex.Replace(imageUrl, string.Empty); string strServerRelativeURL = CombineUrl(web.ServerRelativeUrl, strSiteRelavtiveURL); Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(strServerRelativeURL); clientContext.Load(oFile); ClientResult <Stream> stream = oFile.OpenBinaryStream(); clientContext.ExecuteQuery(); return(ReadFully(stream.Value)); } catch (Exception e) { return(null); } } }
public async Task <ActionResult> GetPhoto(string url) { try { using (var clientContext = await AuthenticationHelper.GetDemoSiteClientContextAsync()) { Match match = (new Regex(@"(?<=\.)(\w*)")).Match(url); string contentType = string.Format("image/{0}", match.Captures[match.Captures.Count - 1].Value); Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(url); clientContext.Load(file); clientContext.ExecuteQuery(); ClientResult <Stream> clientResult = file.OpenBinaryStream(); clientContext.ExecuteQuery(); using (Stream stream = clientResult.Value) { byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); return(File(data, contentType)); } } } catch { } throw new HttpException(404, "File not found"); }
/// <summary> /// returns the document stream using corresponding relative document path /// </summary> public static Stream GetStream(string id, string ext) { LLMainErr Model = new LLMainErr(); Stream fileStream = null; string fileName = ""; try { using (ClientContext ctx = GetContext()) { List olist = ctx.Web.Lists.GetByTitle(ListName); bool relativePathExist = urlDictProp.TryGetValue(Uri.EscapeDataString(id) + "." + ext, out string relativePath); //urlDictProp[id.ToString()]; if (relativePathExist) { Microsoft.SharePoint.Client.File file = ctx.Web.GetFileByServerRelativeUrl(relativePath); ctx.Load(file); ClientResult <Stream> streamX = file.OpenBinaryStream(); ctx.Load(file); ctx.ExecuteQuery(); fileStream = streamX.Value; fileStream.Seek(0, SeekOrigin.Begin); fileName = file.Name; } else { fileStream = null; } } } catch (Exception ex) { Model.Error = ex.Message; } return(fileStream); }
private MemoryStream GetFileFromStorage(string fileName, string container) { try { using (ClientContext cc = GetClientContext().Clone(GetConnectionString())) { List list = cc.Web.GetListByUrl(GetDocumentLibrary(container)); string folders = GetFolders(container); File file = null; Folder spFolder = null; if (folders.Length == 0) { spFolder = list.RootFolder; } else { spFolder = list.RootFolder; string[] parts = container.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); int startFrom = 1; if (parts[0].Equals("_catalogs", StringComparison.InvariantCultureIgnoreCase)) { startFrom = 2; } for (int i = startFrom; i < parts.Length; i++) { spFolder = spFolder.ResolveSubFolder(parts[i]); } } if (!spFolder.IsPropertyAvailable("ServerRelativeUrl")) { spFolder.Context.Load(spFolder, w => w.ServerRelativeUrl); spFolder.Context.ExecuteQueryRetry(); } var fileServerRelativeUrl = UrlUtility.Combine(spFolder.ServerRelativeUrl, fileName); file = cc.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl); cc.Load(file); cc.ExecuteQueryRetry(); MemoryStream stream = new MemoryStream(); var streamResult = file.OpenBinaryStream(); cc.ExecuteQueryRetry(); streamResult.Value.CopyTo(stream); Log.Info(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileRetrieved, fileName, GetConnectionString(), container); return(stream); } } catch (Exception ex) { Log.Error(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileNotFound, fileName, GetConnectionString(), container, ex.Message); return(null); } }
public static Stream GetFile(string itemPath, ClientContext context) { try { /* * Logic explained in example below:- * itemPath = "http://sp201601/sites/academy/SiteAssets/logo/logo.png" * the web url i.e. siteurl = "http://sp201601/sites/academy" * the relative url i.e. siterelativeurl= "/sites/academy" * */ Web web = context.Web; context.Load(web, w => w.Url, w => w.ServerRelativeUrl); context.ExecuteQuery(); string siteurl = web.Url; string siterelativeurl = web.ServerRelativeUrl; string url1 = siteurl.Substring(0, siteurl.LastIndexOf(siterelativeurl)); itemPath = itemPath.Substring(url1.Length); Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(itemPath); context.Load(oFile); ClientResult <Stream> stream = oFile.OpenBinaryStream(); context.ExecuteQuery(); return(stream.Value); } catch (Exception ex) { throw; } }
public static bool CheckFileUploadedToSharePOint(string libraryName, string folderName, string FileName) { bool isFileExists = true; using (ClientContext context = GetContextObject()) { ClientResult <Stream> stream = null; Web web = context.Web; context.Load(web, website => website.ServerRelativeUrl); context.ExecuteQuery(); var docLibs = context.LoadQuery(web.Lists.Where(l => l.BaseTemplate == 101)); context.ExecuteQuery(); try { string strServerRelativeURL = string.Concat(web.ServerRelativeUrl + "/" + libraryName + "/" + folderName, "/", FileName); Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(strServerRelativeURL); context.Load(oFile); stream = oFile.OpenBinaryStream(); context.ExecuteQuery(); } catch (Exception ex) { if (ex.Message.Contains("File Not Found")) { isFileExists = false; } } } return(isFileExists); }
private static void ReadExcelData(ClientContext clientContextobj, string FileName) { const string lstDocName = "Documents"; try { DataTable datatable = new DataTable("TempExcelDataTable"); List list = clientContextobj.Web.Lists.GetByTitle(lstDocName); clientContextobj.Load(list.RootFolder); clientContextobj.ExecuteQuery(); string fileServerRelativeUrl = list.RootFolder.ServerRelativeUrl + "/" + "xlsheet.xlsx"; SP.File fileobj = clientContextobj.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl); ClientResult <System.IO.Stream> clientresult = fileobj.OpenBinaryStream(); clientContextobj.Load(fileobj); clientContextobj.ExecuteQuery(); using (System.IO.MemoryStream mstream = new System.IO.MemoryStream()) { if (clientresult != null) { clientresult.Value.CopyTo(mstream); using (SpreadsheetDocument document = SpreadsheetDocument.Open(mstream, false)) { WorkbookPart WBPart = document.WorkbookPart; IEnumerable <Sheet> sheets = document.WorkbookPart.Workbook.GetFirstChild <DocumentFormat.OpenXml.Spreadsheet.Sheets>().Elements <Sheet>(); string relationshipId = sheets.First().Id.Value; WorksheetPart WBPart1 = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId); DocumentFormat.OpenXml.Spreadsheet.Worksheet worksheet = WBPart1.Worksheet; SheetData sheetdata = worksheet.GetFirstChild <SheetData>(); IEnumerable <Row> rows = sheetdata.Descendants <Row>(); foreach (Cell cellvalue in rows.ElementAt(0)) { string str = GetCellValue(document, cellvalue); datatable.Columns.Add(str); } foreach (Row row in rows) { if (row != null) { DataRow datarow = datatable.NewRow(); for (int i = 0; i < row.Descendants <Cell>().Count(); i++) { datarow[i] = GetCellValue(document, row.Descendants <Cell>().ElementAt(i)); } datatable.Rows.Add(datarow); } } datatable.Rows.RemoveAt(0); } } } ReadData(datatable); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadKey(); }
public MemoryStream DownloadFileById(ref string hayError, string idItem, string siteUrl, string listName) { hayError = string.Empty; MemoryStream memorySt = null; string lsRetorno = string.Empty; try { using (ClientContext context = new ClientContext(siteUrl)) { context.Credentials = credentialsSHP; CamlQuery query = new CamlQuery(); query.ViewXml = string.Format(@" <View Scope='Recursive'> <Query> <Where> <Eq><FieldRef Name='ID'/><Value Type='Number'>" + idItem + @"</Value></Eq> </Where> <RowLimit>1</RowLimit> </Query> </View>", idItem); List list = context.Web.Lists.GetByTitle(listName); ListItemCollection listItems = list.GetItems(query); context.Load(listItems); context.ExecuteQuery(); if (listItems.Count == 1) { ListItem item = listItems.First(); Microsoft.SharePoint.Client.File file = item.File; ClientResult <Stream> data = file.OpenBinaryStream(); ////Load the Stream data for the file context.Load(file); context.ExecuteQuery(); if (data != null) { using (memorySt = new MemoryStream()) { data.Value.CopyTo(memorySt); } } } else { memorySt = null; } } } catch (Exception ex) { hayError = ex.Message; } return(memorySt); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); // Credentials for getting authenticated context using auth manager of OfficeDevPnP Dll // Since its a POC, I have used direct creds. // You could use other authentication modes for getting the context for PRODUCTION ENV usage. string siteUrl = "https://nakkeerann.sharepoint.com/sites/teamsite"; string userName = "******"; string password = "******"; OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager(); // parse query parameter string filePath = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "filePath", true) == 0) .Value; try { // context using auth manager using (var clientContext = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password)) { Web web = clientContext.Site.RootWeb; Microsoft.SharePoint.Client.File file = web.GetFileByUrl(filePath); var data = file.OpenBinaryStream(); string content = null; using (MemoryStream memoryStream = new MemoryStream()) { clientContext.Load(file); clientContext.ExecuteQuery(); if (data != null && data.Value != null) { data.Value.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); // Function extracts the document content content = ExtractContentFromWordDocument(memoryStream); // Function responds back with extracted document content return(req.CreateResponse(HttpStatusCode.OK, content)); } } // Function responds back return(req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process file or no content present")); } } catch (Exception ex) { log.Info("Error Message: " + ex.Message); return(req.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } }
private void UploadFile(File srcFile, Folder targetFolder, string filename = "") { var binaryStream = srcFile.OpenBinaryStream(); _sourceContext.ExecuteQueryRetry(); if (string.IsNullOrWhiteSpace(filename)) { filename = srcFile.Name; } this.UploadFileWithSpecialCharacters(targetFolder, filename, binaryStream.Value, OverwriteIfAlreadyExists); _targetContext.ExecuteQueryRetry(); }
public static void DownloadItem(ClientContext context, Microsoft.SharePoint.Client.File file, string fullPath) { context.Load(file); context.ExecuteQuery(); ClientResult <Stream> data = file.OpenBinaryStream(); context.ExecuteQuery(); SaveStreamToFile(fullPath, data.Value); //for use in form properties formSize = (double)new System.IO.FileInfo(fullPath).Length / 1024.0; }
public SPOContentReaderWriter(File file, bool isBinary) { _file = file; _isBinary = isBinary; _stream = new MemoryStream(); var spStream = _file.OpenBinaryStream(); _file.Context.ExecuteQuery(); spStream.Value.CopyTo(_stream); _stream.Position = 0; _streamWriter = new StreamWriter(_stream); _streamReader = new StreamReader(_stream); }
/// <summary> /// Create a web part page of matter in the document library. /// </summary> /// <param name="clientContext">Client Context</param> /// <param name="pageName">Web part page name</param> /// <param name="layout">Layout for the page</param> /// <param name="listName">List/library name</param> /// <param name="masterpagelistName">master page list name</param> /// <param name="pageTitle">Page title</param> /// <returns>Web part page id</returns> public static 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 = Lists.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[Constants.TITLE] = pageTitle; matterLandingPageDetails.Update(); clientContext.Load(matterLandingPageDetails, matterLandingPageProperties => matterLandingPageProperties[Constants.TITLE], matterLandingPageProperties => matterLandingPageProperties.Id); clientContext.ExecuteQuery(); response = matterLandingPageDetails.Id; } catch (Exception) { response = -1; } } return(response); }
/// <summary> /// Check if Content of local file and server file matches. /// </summary> /// <param name="context">SP client context</param> /// <param name="localMemoryStream">Memory stream of local file</param> /// <param name="serverFileURL">Server relative URL of file with filename</param> /// <returns>True if content matched else false</returns> public static bool PerformContentCheck(ClientContext context, MemoryStream localMemoryStream, String serverFileURL) { bool isMatched = true; if (null != context && null != localMemoryStream && !string.IsNullOrWhiteSpace(serverFileURL)) { Microsoft.SharePoint.Client.File serverFile = context.Web.GetFileByServerRelativeUrl(serverFileURL); context.Load(serverFile); ClientResult <Stream> serverStream = serverFile.OpenBinaryStream(); context.ExecuteQuery(); if (null != serverFile) { using (MemoryStream serverMemoryStream = new MemoryStream()) { byte[] serverBuffer = new byte[serverFile.Length + 1]; int readCount = 0; while ((readCount = serverStream.Value.Read(serverBuffer, 0, serverBuffer.Length)) > 0) { serverMemoryStream.Write(serverBuffer, 0, readCount); } serverMemoryStream.Seek(0, SeekOrigin.Begin); localMemoryStream.Seek(0, SeekOrigin.Begin); if (serverMemoryStream.Length == localMemoryStream.Length) { byte[] localBuffer = localMemoryStream.GetBuffer(); serverBuffer = serverMemoryStream.GetBuffer(); for (long index = 0; index < serverMemoryStream.Length; index++) { if (localBuffer[index] != serverBuffer[index]) { isMatched = false; break; } } } else { isMatched = false; } } } else { isMatched = false; } } return(isMatched); }
public Stream SaveEmail(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails) { Stream result = null; try { if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken()) { ///// filename, stream Dictionary <string, Stream> collectionOfAttachments = new Dictionary <string, Stream>(); ///// full URL, relative URL string[] allAttachmentUrl = mailAttachmentDetails.FullUrl.Split(';'); ClientContext clientContext; bool attachmentFlag = mailAttachmentDetails.IsAttachmentCall; if (attachmentFlag) { foreach (string attachmentUrl in allAttachmentUrl) { if (!string.IsNullOrWhiteSpace(attachmentUrl)) { // Do not use 'using' to generate client context here since it will dispose the object before other functions get executed clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken); Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1]); ClientResult <System.IO.Stream> fileStream = file.OpenBinaryStream(); ///// Load the Stream data for the file clientContext.Load(file); clientContext.ExecuteQuery(); ///// In order to allow for multiple files with the same name, we provide a GUID tag to ensure unique keys in the dictionary string uniqueKeyWithDate = attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].Substring(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].LastIndexOf(Convert.ToChar(ConstantStrings.BackwardSlash, CultureInfo.InvariantCulture)) + 1) + ConstantStrings.DOLLAR + Guid.NewGuid(); collectionOfAttachments.Add(uniqueKeyWithDate, fileStream.Value); } } } result = MailHelperFunctions.GenerateEmail(collectionOfAttachments, allAttachmentUrl, attachmentFlag); } else { result = BriefcaseHelperFunction.ReturnErrorFile(TextConstants.MessageNoInputs); } } catch (Exception exception) { Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); result = BriefcaseHelperFunction.ReturnErrorFile(string.Concat(ConstantStrings.ServiceResponse, exception.HResult, exception.Message)); } return(result); }
static void GetChanges(ClientContext SPClientContext, string ListId, TraceWriter log) { Web spWeb = SPClientContext.Web; List myList = spWeb.Lists.GetByTitle(ConfigurationManager.AppSettings["whListName"]); SPClientContext.Load(myList); SPClientContext.ExecuteQuery(); ChangeQuery myChangeQuery = GetChangeQueryNew(ListId); var allChanges = myList.GetChanges(myChangeQuery); SPClientContext.Load(allChanges); SPClientContext.ExecuteQuery(); foreach (Change oneChange in allChanges) { if (oneChange is ChangeItem) { int myItemId = (oneChange as ChangeItem).ItemId; log.Info($"---- Changed ItemId : " + myItemId); ListItem myItem = myList.GetItemById(myItemId); Microsoft.SharePoint.Client.File myFile = myItem.File; ClientResult <System.IO.Stream> myFileStream = myFile.OpenBinaryStream(); SPClientContext.Load(myFile); SPClientContext.ExecuteQuery(); byte[] myFileBytes = ConvertStreamToByteArray(myFileStream); TextAnalyzeOCRResult myResult = GetAzureTextAnalyzeOCR(myFileBytes).Result; log.Info($"---- Text Analyze OCR Result : " + JsonConvert.SerializeObject(myResult)); myItem["Language"] = myResult.language; string myText = string.Empty; for (int oneLine = 0; oneLine < myResult.regions[0].lines.Count(); oneLine++) { for (int oneWord = 0; oneWord < myResult.regions[0].lines[oneLine].words.Count(); oneWord++) { myText += myResult.regions[0].lines[oneLine].words[oneWord].text + " "; } } myItem["OCRText"] = myText; myItem.Update(); SPClientContext.ExecuteQuery(); log.Info($"---- Text Analyze OCR added to SharePoint Item"); } } }
public SPOContentReaderWriter(File file, bool isBinary) { _file = file; _isBinary = isBinary; _stream = new MemoryStream(); var spStream = _file.OpenBinaryStream(); _file.Context.ExecuteQueryRetry(); spStream.Value.CopyTo(_stream); _stream.Position = 0; _streamWriter = new StreamWriter(_stream); _streamReader = new StreamReader(_stream); }
public void ProcessRequest(HttpContext context) { try { string imageUrl = context.Request.QueryString["url"]; if (!string.IsNullOrEmpty(imageUrl)) { if (HttpContext.Current.Cache[imageUrl] != null) { byte[] data = HttpContext.Current.Cache[imageUrl] as byte[]; context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(data); } else { //This code could be replaced with the O365 Files Api var demoSiteCollectionUrl = ConfigurationManager.AppSettings["DemoSiteCollectionUrl"]; var token = HttpContext.Current.Session["SPsessionCache"].ToString(); using (var clientContext = TokenHelper.GetClientContextWithAccessToken(demoSiteCollectionUrl, token)) { Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(imageUrl); clientContext.Load(file); clientContext.ExecuteQuery(); ClientResult <Stream> clientResult = file.OpenBinaryStream(); clientContext.ExecuteQuery(); using (Stream stream = clientResult.Value) { byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); HttpContext.Current.Cache[imageUrl] = data; context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(data); } } } context.Response.Flush(); } } catch { context.Response.End(); } }
/// <summary> /// Get file information from Sharepoint. /// </summary> /// <param name="documentUrl">Document Url.</param> /// <returns>Returns file information object.</returns> public Stream GetFile() { using (ClientContext clientContext = GetContextObject()) { Web web = clientContext.Web; clientContext.Load(web, website => website.ServerRelativeUrl); clientContext.ExecuteQuery(); Regex regex = new Regex(SiteUrl, RegexOptions.IgnoreCase); string strSiteRelavtiveURL = regex.Replace(FileUrl, string.Empty); string strServerRelativeURL = CombineUrl(web.ServerRelativeUrl, strSiteRelavtiveURL); Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(strServerRelativeURL); clientContext.Load(oFile); ClientResult <Stream> stream = oFile.OpenBinaryStream(); clientContext.ExecuteQuery(); return(this.ReadFully(stream.Value)); } }
/// <summary> /// Breaks, assigns user permission and create Web Parts layout in Matter Landing Page /// </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> /// <param name="collection">ListItemCollection object consist of items in Master Page Library</param> /// <returns>true or exception value</returns> internal static string WebPartsCreation(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Matter matter, Web web, ListItemCollection collection) { ListItem fileName = null; foreach (ListItem findLayout in collection) { if (findLayout.DisplayName.Equals(Constants.DefaultLayout, StringComparison.OrdinalIgnoreCase)) { fileName = findLayout; break; } } Microsoft.SharePoint.Client.File fileLayout = fileName.File; clientContext.Load(fileLayout); clientContext.ExecuteQuery(); ClientResult <Stream> filedata = fileLayout.OpenBinaryStream(); sitePageLib = web.Lists.GetByTitle(ConfigurationManager.AppSettings["MatterLandingPageRepository"]); clientContext.Load(sitePageLib); clientContext.ExecuteQuery(); StreamReader reader = new StreamReader(filedata.Value); objFileInfo.Content = System.Text.Encoding.ASCII.GetBytes(reader.ReadToEnd()); int matterLandingPageId = AddMatterLandingPageFile(sitePageLib, clientContext, objFileInfo, matter.MatterName); BreakItemPermission(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], matter.CopyPermissionsFromParent, matterLandingPageId); List <string> responsibleAttorneyList = matter.TeamInfo.ResponsibleAttorneys.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList <string>(); List <string> attorneyList = matter.TeamInfo.Attorneys.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList <string>(); List <string> blockedUserList = matter.TeamInfo.BlockedUploadUsers.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList <string>(); if (0 < responsibleAttorneyList.Count) { AssignUserPermissionsToItem(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], responsibleAttorneyList, ConfigurationManager.AppSettings["FullControl"], matterLandingPageId); } if (0 < attorneyList.Count) { AssignUserPermissionsToItem(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], attorneyList, ConfigurationManager.AppSettings["Contribute"], matterLandingPageId); } if (0 < blockedUserList.Count) { AssignUserPermissionsToItem(clientContext, ConfigurationManager.AppSettings["MatterLandingPageRepository"], blockedUserList, ConfigurationManager.AppSettings["Read"], matterLandingPageId); } return(Constants.TRUE); }
private static Stream GetProvisioningJobStreamFromSharePoint(ClientContext context, ListItem jobItem) { jobItem.ParentList.RootFolder.EnsureProperty(f => f.ServerRelativeUrl); Microsoft.SharePoint.Client.File jobFile = jobItem.ParentList.ParentWeb.GetFileByServerRelativeUrl( String.Format("{0}/{1}", jobItem.ParentList.RootFolder.ServerRelativeUrl, (String)jobItem["FileLeafRef"])); context.Load(jobFile, jf => jf.ServerRelativeUrl); var jobFileStream = jobFile.OpenBinaryStream(); context.ExecuteQueryRetry(); MemoryStream mem = new MemoryStream(); jobFileStream.Value.CopyTo(mem); mem.Position = 0; return(mem); }
private static List <Tuple <string, Stream> > GetXmlFilesFromList() { List <Tuple <string, Stream> > inputFileStreams = new List <Tuple <string, Stream> >(); // XML files (item1=Name, item2=Data) spClient.ClientContext spCtx = LoginCsom(); spClient.Web myWeb = spCtx.Web; spClient.FolderCollection myFolders = myWeb.Folders; spClient.List myList = spCtx.Web.Lists.GetByTitle(SpListName); spClient.ListItemCollection allItems = myList.GetItems(spClient.CamlQuery.CreateAllItemsQuery()); spCtx.Load(myWeb); spCtx.Load(myFolders); spCtx.Load(allItems); spCtx.ExecuteQuery(); foreach (spClient.ListItem oneItem in allItems) { spClient.AttachmentCollection allAttachments = oneItem.AttachmentFiles; spCtx.Load(allAttachments); spCtx.ExecuteQuery(); foreach (spClient.Attachment oneAttachment in allAttachments) { spClient.File myXmlFile = myWeb.GetFileByServerRelativeUrl(oneAttachment.ServerRelativeUrl); spClient.ClientResult <Stream> myXmlData = myXmlFile.OpenBinaryStream(); spCtx.Load(myXmlFile); spCtx.ExecuteQuery(); using (MemoryStream mStream = new MemoryStream()) { if (myXmlData != null) { myXmlData.Value.CopyTo(mStream); byte[] myBinFile = mStream.ToArray(); MemoryStream xmlStream = new MemoryStream(myBinFile); inputFileStreams.Add(Tuple.Create(myXmlFile.Name, (Stream)xmlStream)); } } } } return(inputFileStreams); }
/// <summary> /// Create a Web Part page for web dashboard /// </summary> /// <param name="clientContext">SharePoint Client Context</param> /// <returns>array of bytes for the page content</returns> internal static byte[] CreateWebPartPage(ClientContext clientContext) { try { //// Find Default Layout from Master Page Gallery to create Web Part Page List sitePageLib = clientContext.Web.Lists.GetByTitle("Master Page Gallery"); clientContext.Load(sitePageLib); clientContext.ExecuteQuery(); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = Constants.QueryAll; ListItemCollection collection = sitePageLib.GetItems(camlQuery); clientContext.Load( collection, items => items.Include( item => item.DisplayName, item => item.Id).Where(item => item.DisplayName == "DefaultLayout" || item.DisplayName == "BlankWebPartPage")); clientContext.ExecuteQuery(); if (0 < collection.Count) { ListItem fileName = collection[0]; Microsoft.SharePoint.Client.File fileLayout = fileName.File; clientContext.Load(fileLayout); clientContext.ExecuteQuery(); ClientResult <Stream> filedata = fileLayout.OpenBinaryStream(); clientContext.ExecuteQuery(); StreamReader reader = new StreamReader(filedata.Value); return(System.Text.Encoding.ASCII.GetBytes(reader.ReadToEnd())); } else { return(Encoding.UTF8.GetBytes(Constants.ErrorMessage)); } } catch (Exception) { return(Encoding.UTF8.GetBytes(Constants.ErrorMessage)); } }
static void Main(string[] args) { string SiteUrl = "https://abc.sharepoint.com/sites/s01"; var pwd = "password"; var username = "******"; var authManager = new AuthenticationManager(); ClientContext context = authManager.GetSharePointOnlineAuthenticatedContextTenant(SiteUrl, username, pwd); context.Load(context.Site, x => x.ServerRelativeUrl); context.ExecuteQuery(); File fs = context.Site.RootWeb.GetFileByServerRelativeUrl(context.Site.ServerRelativeUrl + "/Shared Documents/Book1.xlsx"); context.Load(fs); context.ExecuteQuery(); var attInfo = new AttachmentCreationInformation(); attInfo.FileName = fs.Name; var data = fs.OpenBinaryStream(); ListItem item = context.Web.Lists.GetByTitle("ckkk").GetItemById(2); context.Load(item); context.ExecuteQuery(); attInfo.ContentStream = data.Value; var att = item.AttachmentFiles.Add(attInfo); context.Load(att); context.ExecuteQuery(); Console.ReadKey(); }
private void AddFile(string strfileref, Microsoft.SharePoint.Client.File file, ClientContext clientContext) { //var clientContext = getClientContext(); ClientResult <Stream> data = file.OpenBinaryStream(); clientContext.Load(file); clientContext.ExecuteQuery(); //FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, strfileref); if (data != null) { byte[] bytFile; using (MemoryStream memoryStream = new MemoryStream()) { data.Value.CopyTo(memoryStream); bytFile = memoryStream.GetBuffer(); memoryStream.Flush(); } if (chkFolders.Checked) { string QualifiedFileName = tmpDirLocation + strfileref.Substring(strfileref.IndexOf(libName)); string filePath = QualifiedFileName.TrimEnd(file.Name.ToCharArray()); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } WriteToFile(bytFile, QualifiedFileName); } else { string QualifiedFileName = tmpDirLocation + "\\" + file.Name; QualifiedFileName = checkFileName(QualifiedFileName, file.Name); WriteToFile(bytFile, QualifiedFileName); } } }
public static void DownloadAllFileFromSharePoint(List <string> groupList) { using (ClientContext clientContext = GetContextObject()) { ClientResult <Stream> stream = null; Web web = clientContext.Web; clientContext.Load(web, website => website.ServerRelativeUrl); clientContext.ExecuteQuery(); Regex regex = new Regex(Configuration.SiteUrl, RegexOptions.IgnoreCase); string strSiteRelavtiveURL = regex.Replace(Configuration.FileUrl, string.Empty); foreach (string fileName in groupList) { try { string strServerRelativeURL = string.Concat(web.ServerRelativeUrl, "/", strSiteRelavtiveURL, "/", fileName); Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(strServerRelativeURL); clientContext.Load(oFile); stream = oFile.OpenBinaryStream(); clientContext.ExecuteQuery(); Stream filestrem = ReadFully(stream.Value); string filepath = System.IO.Path.Combine(YammerdirPath, fileName); using (FileStream fileStream = System.IO.File.Create(filepath, (int)filestrem.Length)) { byte[] bytesInStream = new byte[filestrem.Length]; filestrem.Read(bytesInStream, 0, bytesInStream.Length); fileStream.Write(bytesInStream, 0, bytesInStream.Length); } } catch (Exception ex) { //if (ex.Message == "File Not Found") } } } }
public static bool CheckAllFileUploadedToSharePOint(string containerName) { bool allFileExists = true; using (ClientContext clientContext = GetContextObject()) { ClientResult <Stream> stream = null; Web web = clientContext.Web; clientContext.Load(web, website => website.ServerRelativeUrl); clientContext.ExecuteQuery(); Regex regex = new Regex(Configuration.SiteUrl, RegexOptions.IgnoreCase); string strSiteRelavtiveURL = regex.Replace(Configuration.FileUrl, string.Empty); List <string> groupList = ListBlobContainer(containerName); foreach (string fileName in groupList) { try { string strServerRelativeURL = string.Concat(web.ServerRelativeUrl, "/", strSiteRelavtiveURL, "/", fileName); Microsoft.SharePoint.Client.File oFile = web.GetFileByServerRelativeUrl(strServerRelativeURL); clientContext.Load(oFile); stream = oFile.OpenBinaryStream(); clientContext.ExecuteQuery(); } catch (Exception ex) { if (ex.Message == "File Not Found") { allFileExists = false; } } } } return(allFileExists); }
private static void ReadExcelData(ClientContext clientContext, string fileName) { bool IsError = true; string strErrorMsg = string.Empty; const string lstDocName = "Documents"; try { DataTable dataTable = new DataTable("ExcelDataTable"); List list = clientContext.Web.Lists.GetByTitle(lstDocName); clientContext.Load(list.RootFolder); clientContext.ExecuteQuery(); string fileServerRelativeUrl = list.RootFolder.ServerRelativeUrl + "/" + "ExcelFile.xlsx"; SP.File file = clientContext.Web.GetFileByServerRelativeUrl(fileServerRelativeUrl); ClientResult <System.IO.Stream> data = file.OpenBinaryStream(); clientContext.Load(file); clientContext.ExecuteQuery(); using (System.IO.MemoryStream mStream = new System.IO.MemoryStream()) { if (data != null) { data.Value.CopyTo(mStream); using (SpreadsheetDocument documnet = SpreadsheetDocument.Open(mStream, false)) { WorkbookPart workbookpart = documnet.WorkbookPart; IEnumerable <Sheet> sheets = documnet.WorkbookPart.Workbook.GetFirstChild <Sheets>().Elements <Sheet>(); string relationshipId = sheets.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)documnet.WorkbookPart.GetPartById(relationshipId); Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild <SheetData>(); IEnumerable <Row> rows = sheetData.Descendants <Row>(); foreach (Cell cell in rows.ElementAt(0)) { string str = GetCellValue(clientContext, documnet, cell); dataTable.Columns.Add(str); } foreach (Row row in rows) { if (row != null) { DataRow dataRow = dataTable.NewRow(); for (int i = 0; i < row.Descendants <Cell>().Count(); i++) { dataRow[i] = GetCellValue(clientContext, documnet, row.Descendants <Cell>().ElementAt(i)); } dataTable.Rows.Add(dataRow); } } dataTable.Rows.RemoveAt(0); } } } UpdateSPList(clientContext, dataTable, fileName); IsError = false; } catch (Exception e) { IsError = true; Console.WriteLine(e.Message); Console.WriteLine("second catch block"); } finally { if (IsError) { //Logging } } }
private static async Task <string> CreateLocalDocxFile(TraceWriter log, HttpResponseMessage response, PostData postData, ClientContext clientContext, List <string> messages, List <string> tagsFound) { // Get the document template File templateFile = null; try { templateFile = clientContext.Site.RootWeb.GetFileByServerRelativeUrl(postData.templateServerRelativeUrl); clientContext.Load(templateFile); clientContext.ExecuteQueryRetry(); } catch (Exception err) { string message = $"Error loading template file {postData.templateServerRelativeUrl}. Message was {err.Message}"; throw new Exception(message); } if (templateFile != null) { // download the template as a stream ClientResult <Stream> templatestream = templateFile.OpenBinaryStream(); clientContext.ExecuteQueryRetry(); //save the template to a local file var localDocxFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()) + ".docx"; using (Stream fileStream = new FileStream(localDocxFilePath, FileMode.Create)) { templatestream.Value.CopyTo(fileStream); } // open the local file as a WordProcessingDocument WordprocessingDocument localDocxFile = WordprocessingDocument.Open(localDocxFilePath, true); DumpTags(localDocxFile, tagsFound); // get a list of tags in the document so we can rtun to client to help troubleshooting // replace all the content controls foreach (var replacementParm in postData.plainTextParameters) { switch (replacementParm.replacementType.ToLower()) { case "plaintext": localDocxFile = InsertText(localDocxFile, replacementParm.token, replacementParm.value, log, messages); break; case "image": localDocxFile = InsertImages(localDocxFile, clientContext, replacementParm.token, replacementParm.value, log, messages); break; default: throw new Exception($"Invalid replacement type {replacementParm.replacementType}"); } } // experimantal replace all the tables foreach (var tableParm in postData.tableParameters) { localDocxFile = ReplaceTable(localDocxFile, tableParm, log, messages); } // remove the content controls IEnumerable <string> m_oEnum = new string[] { "ptIncidentSummary" }; localDocxFile = RemoveSdtBlocks(localDocxFile, m_oEnum); //save the updated document to the local file system localDocxFile.Save(); localDocxFile.Close(); // file now saved to local folder return(localDocxFilePath); } else { throw new Exception("List is not available on the site"); } }
public string SendToBriefcase(RequestObject requestObject, MailAttachmentDetails mailAttachmentDetails, bool doCheckOut) { string status = ConstantStrings.FALSE; string result = string.Empty; try { if (null != requestObject && null != mailAttachmentDetails && ValidationHelperFunctions.CheckRequestValidatorToken()) { Dictionary <string, Stream> collectionOfAttachments = new Dictionary <string, Stream>(); Dictionary <string, string> collectionOfOriginalAttachments = new Dictionary <string, string>(); string[] allAttachmentUrl = mailAttachmentDetails.FullUrl.Split(ConstantStrings.Semicolon[0]); ClientContext clientContext = null; string usersMySite = string.Empty; usersMySite = BriefcaseHelperFunction.GetPersonalURL(requestObject); if (!usersMySite.ToUpperInvariant().Contains(ServiceConstantStrings.OneDriveNotSetupUrl.ToUpperInvariant())) { foreach (string attachmentUrl in allAttachmentUrl) { if (!string.IsNullOrWhiteSpace(attachmentUrl)) { // Do not use 'using' to generate client context here since it will dispose the object before other functions get executed clientContext = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[0]), requestObject.RefreshToken); Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1]); ClientResult <System.IO.Stream> clientResultStream = file.OpenBinaryStream(); ///// Load the Stream data for the file clientContext.Load(file); clientContext.ExecuteQuery(); Guid uniqueKey = Guid.NewGuid(); collectionOfAttachments.Add(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].Substring(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].LastIndexOf(Convert.ToChar(ConstantStrings.ForwardSlash, CultureInfo.InvariantCulture)) + 1) + ConstantStrings.DOLLAR + uniqueKey, clientResultStream.Value); collectionOfOriginalAttachments.Add(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].Substring(attachmentUrl.Split(Convert.ToChar(ConstantStrings.DOLLAR, CultureInfo.InvariantCulture))[1].LastIndexOf(Convert.ToChar(ConstantStrings.ForwardSlash, CultureInfo.InvariantCulture)) + 1) + ConstantStrings.DOLLAR + uniqueKey, attachmentUrl); MailAttachmentDetails sendDocumentUrl = new MailAttachmentDetails(); sendDocumentUrl.FullUrl = attachmentUrl; if (doCheckOut) { this.CheckOutDocument(requestObject, sendDocumentUrl); } } } status = BriefcaseHelperFunction.UploadtoBriefcase(requestObject, collectionOfAttachments, collectionOfOriginalAttachments, usersMySite, allAttachmentUrl, mailAttachmentDetails.IsOverwrite); //// If error not occurred while sending documents to OneDrive if (!status.Contains(ConstantStrings.Code) && !status.Contains(ConstantStrings.Value)) { status = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, status); } } else { status = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.ErrorCodeOneDriveNotConfigured, usersMySite); } result = status; } else { result = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, 0, status); } } catch (Exception exception) { result = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName); } return(result); }