public int FillAppWebNotesWith1G() { using (var ctx = SharePointContext.CreateUserClientContextForSPAppWeb()) { List notesList = ctx.Web.Lists.GetByTitle("Notes"); int maxNum = 100; for (int i = 0; i < maxNum; i++) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = notesList.AddItem(itemCreateInfo); newItem["Title"] = "Note " + i.ToString() + "."; newItem["FTCAM_Description"] = "Description " + i.ToString() + "."; newItem.Update(); ctx.ExecuteQuery(); var file = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Assets/SampleData.rar"); var filestream = System.IO.File.OpenRead(file); var info = new AttachmentCreationInformation { FileName = "SampleData.rar", ContentStream = filestream }; newItem.AttachmentFiles.Add(info); ctx.ExecuteQuery(); filestream.Close(); } return(maxNum); } }
public static void SaveAttchments(FileStream fsAttachment, string NewTitle) { using (ClientContext ctx = new ClientContext(_serverURL)) { SecureString passWord = new SecureString(); foreach (char c in _userPasswordAdmin) { passWord.AppendChar(c); } ctx.Credentials = new SharePointOnlineCredentials(_userNameAdmin, passWord); List oList = ctx.Web.Lists.GetByTitle("BotTestAttachments"); ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem oListItem = oList.AddItem(itemCreateInfo); oListItem["Title"] = NewTitle; oListItem.Update(); ctx.ExecuteQuery(); ListItem item = oList.GetItemById(oListItem.Id); AttachmentCreationInformation attInfo = new AttachmentCreationInformation(); attInfo.FileName = fsAttachment.Name; attInfo.ContentStream = fsAttachment; item.AttachmentFiles.Add(attInfo); item.Update(); ctx.ExecuteQuery(); } }
/// <summary> /// FileStream を指定して、 /// リストアイテムに添付ファイルを追加します。 /// </summary> /// <param name="this">リストアイテム</param> /// <param name="fs">FileStream</param> /// <returns>リストアイテムを返します。</returns> public static SP.ListItem AddAttachmentFile(this SP.ListItem @this, FileStream fs) { var af = new AttachmentCreationInformation() { ContentStream = fs, FileName = fs.Name, }; @this.AttachmentFiles.Add(af); return(@this); }
public static void attachFile(ListItem item, ClientContext ctx, String filepath) { var attInfo = new AttachmentCreationInformation(); attInfo.FileName = Path.GetFileName(filepath); attInfo.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filepath)); Attachment att = item.AttachmentFiles.Add(attInfo); //Add to File ctx.Load(att); ctx.ExecuteQuery(); }
public void SaveAttachment(ClientContext ctx, ListItem item, string fileName, byte[] attachment) { var attachmentInfo = new AttachmentCreationInformation { FileName = fileName }; using (var fileStream = new System.IO.MemoryStream(attachment)) { attachmentInfo.ContentStream = fileStream; item.AttachmentFiles.Add(attachmentInfo); ctx.ExecuteQueryWithIncrementalRetry(); } }
private static void UpdateAttachments(ClientContext srccontext, ClientContext dstcontext, int srcItemID, int destItemID, string listName) { try { //getting attachment from files Web srcweb = srccontext.Web; srccontext.Load(srcweb); srccontext.ExecuteQuery(); string src = string.Format("{0}/lists/{1}/Attachments/{2}", srcweb.Url, listName, srcItemID); Folder attachmentsFolder = srcweb.GetFolderByServerRelativeUrl(src); srccontext.Load(attachmentsFolder); FileCollection attachments = attachmentsFolder.Files; srccontext.Load(attachments); srccontext.ExecuteQuery(); if (attachments.Count > 0) { foreach (Microsoft.SharePoint.Client.File attachment in attachments) { ClientResult <Stream> clientResultStream = attachment.OpenBinaryStream(); srccontext.ExecuteQuery(); var stream = clientResultStream.Value; AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation(); Byte[] buffer = new Byte[attachment.Length]; int bytesRead = stream.Read(buffer, 0, buffer.Length); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(buffer); attachFileInfo.ContentStream = stream2; attachFileInfo.FileName = attachment.Name; Web destweb = dstcontext.Web; List destlist = destweb.Lists.GetByTitle(listName); ListItem destitem = destlist.GetItemById(destItemID); dstcontext.Load(destitem); dstcontext.ExecuteQuery(); Attachment a = destitem.AttachmentFiles.Add(attachFileInfo); dstcontext.Load(a); dstcontext.ExecuteQuery(); stream2.Close(); } } } catch (Exception ex) { //Log exception } }
public void AttachFile <TItem>(TItem item, string fileName, byte[] content) where TItem : BaseItem { if (item._item != null) { var attInfo = new AttachmentCreationInformation(); attInfo.FileName = fileName; attInfo.ContentStream = new MemoryStream(content); Attachment att = item._item.AttachmentFiles.Add(attInfo); //Add to File _clientContext.Load(att); _clientContext.ExecuteQuery(); ListItem oListItem = _oList.GetItemById(item.ID.Value); _clientContext.Load(oListItem); _clientContext.ExecuteQuery(); item._item = oListItem; } }
//gavdcodeend 29 //gavdcodebegin 30 static void SpCsCsomCreateOneAttachment(ClientContext spCtx) { List myList = spCtx.Web.Lists.GetByTitle("TestList"); int listItemId = 3; ListItem myListItem = myList.GetItemById(listItemId); string myFilePath = @"C:\Temporary\Test.csv"; var myAttachmentInfo = new AttachmentCreationInformation(); myAttachmentInfo.FileName = Path.GetFileName(myFilePath); using (FileStream myFileStream = new FileStream(myFilePath, FileMode.Open)) { myAttachmentInfo.ContentStream = myFileStream; Attachment myAttachment = myListItem.AttachmentFiles.Add(myAttachmentInfo); spCtx.Load(myAttachment); spCtx.ExecuteQuery(); } }
private void AddAttachment(ProvisioningTemplate template, ListItem listitem, Model.SharePoint.InformationArchitecture.DataRowAttachment attachment, bool SkipExecuteQuery = false) { #if !SP2013 && !SP2016 listitem.AttachmentFiles.AddUsingPath(ResourcePath.FromDecodedUrl(attachment.Name), FileUtilities.GetFileStream(template, attachment.Src)); #else var attachmentCI = new AttachmentCreationInformation() { ContentStream = FileUtilities.GetFileStream(template, attachment.Src), FileName = attachment.Name }; listitem.AttachmentFiles.Add(attachmentCI); #endif if (!SkipExecuteQuery) { listitem.Context.ExecuteQueryRetry(); } else { listitem.Update(); } }
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(); }
public void AttachFileToItem <T>(int id, string filename, Stream filestream) { long fileSize = filestream.Length; string listname = EntityHelper.GetInternalNameFromEntityType(typeof(T)); using (ClientContext context = GetClientContext()) { Web web = context.Web; List currentList = web.GetListByTitle(listname); ListItem item = currentList.GetItemById(id); var attachmentInfo = new AttachmentCreationInformation { FileName = filename, ContentStream = filestream }; Attachment attachment = item.AttachmentFiles.Add(attachmentInfo); context.Load(attachment); context.ExecuteQuery(); _log.DebugFormat($"Uploaded '{filename}' to {listname}({id}). Size:{fileSize} Bytes"); } }
public bool uploadAttachment(Guid guidList, int idItem, string filePathSource) { try { if (!System.IO.File.Exists(filePathSource)) { throw new System.IO.FileNotFoundException("File not found.", filePathSource); } var list = _context.Web.Lists.GetById(guidList); var listItem = list.GetItemById(idItem); _context.Load(listItem, i => i.AttachmentFiles); _context.ExecuteQuery(); if (listItem != null) { using (System.IO.FileStream fs = new System.IO.FileStream(filePathSource, System.IO.FileMode.Open)) { var attInfo = new AttachmentCreationInformation() { FileName = System.IO.Path.GetFileName(filePathSource), ContentStream = fs }; var att = listItem.AttachmentFiles.Add(attInfo); _context.Load(att); _context.ExecuteQuery(); } } return(true); } catch (Exception ex) { return(false); } }
private void AddAttachments(ListItem item, XmlNode newNode) { AttachmentCreationInformation attInfo = new AttachmentCreationInformation(); //attachment data is in Attachments/Attachment XmlNodeList attachments = newNode.SelectNodes("Attachments/Attachment"); foreach (XmlNode attachment in attachments) { //get file attributes and file bytes if (string.IsNullOrEmpty(attachment.InnerText)) { return; } string attachmentName, attachmentExtension; int attSize; byte[] fileData; Base64Helper.GetBase64Values(attachment.InnerText, out attachmentName, out attachmentExtension, out attSize, out fileData); attInfo.FileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmssfffff"), attachmentName); attInfo.ContentStream = new MemoryStream(fileData); item.AttachmentFiles.Add(attInfo); } }
/// <summary> /// Add a discussion item (thread and/or reply) to the specified target list. /// </summary> /// <param name="targetList">The target <see cref="Microsoft.SharePoint.Client.List"/> object</param> /// <param name="itemData">A <see cref="System.Data.DataRow"/> object containing the field data for new item to be created.</param> /// <param name="parentItem">A valid <see cref="Microsoft.SharePoint.Client.ListItem"/> object if currently item is a reply; null by default</param> /// <returns><see cref="Microsoft.SharePoint.Client.ListItem"/> object of the newly created discussion item (thread/reply).</returns> /// <remarks> /// All the operations performed are also logged in the filename specified in the app.config /// </remarks> private ListItem AddDiscussionItem(List targetList, DataRow itemData, ListItem parentItem = null) { bool isReply = null != parentItem; string fallbackUserAccount = System.Configuration.ConfigurationManager.AppSettings.Get("FallbackUserAccount"); var fallbackUserValue = GetTargetUser(fallbackUserAccount); var authorUserValue = GetTargetUser(itemData["Author"].ToString()); var editorUserValue = GetTargetUser(itemData["Editor"].ToString()); ListItem newItem = null; if (!isReply) { newItem = Utility.CreateNewDiscussion(Program.SPContext, targetList, (string)itemData["Title"]); // We Do this to get the ID of the recently created item newItem.Update(); //Program.SPContext.ExecuteQuery(); Program.SPContext.Load(newItem, t => t.Id, t => t.Folder, t => t.AttachmentFiles); } else { newItem = Utility.CreateNewDiscussionReply(Program.SPContext, parentItem); // We Do this to get the ID of the recently created item newItem.Update(); //Program.SPContext.ExecuteQuery(); Program.SPContext.Load(newItem, t => t.Id, t => t.AttachmentFiles); } Program.SPContext.ExecuteQuery(); // Get the last created item ID string thisItemID = newItem.Id.ToString(); itemIdMappings[itemData["ID"].ToString()] = thisItemID; newItem["Body"] = itemData["Body"]; if (string.Equals(itemData["Attachments"], "True")) { // Perform Link correction in the body var itemFileRef = itemData["FileRef"].ToString(); string sourceListUrl = itemFileRef.Substring(0, itemFileRef.LastIndexOf("/")); if (isReply) { sourceListUrl = sourceListUrl.Substring(0, sourceListUrl.LastIndexOf("/")); } sourceListUrl = string.Format("{0}/{1}/{2}", sourceListUrl, "Attachments", itemData["ID"].ToString()); string targetListUrl = string.Format("{0}/{1}/{2}", targetList.RootFolder.ServerRelativeUrl, "Attachments", newItem.Id.ToString()); newItem["Body"] = itemData["Body"].ToString().Replace( System.Uri.EscapeUriString(sourceListUrl), System.Uri.EscapeUriString(targetListUrl)); } if (authorUserValue.LookupId != -1) { newItem["Author"] = authorUserValue; } else if (fallbackUserValue.LookupId != -1) { newItem["Author"] = fallbackUserValue; } if (editorUserValue.LookupId != -1) { newItem["Editor"] = editorUserValue; } else if (fallbackUserValue.LookupId != -1) { newItem["Editor"] = fallbackUserValue; } newItem["IsQuestion"] = itemData["IsQuestion"]; newItem["IsAnswered"] = itemData["IsAnswered"]; if (!string.IsNullOrEmpty(itemData["IsFeatured"].ToString())) { newItem["IsFeatured"] = itemData["IsFeatured"]; } if (isReply && !string.IsNullOrEmpty(itemData["ParentItemID"].ToString()) && itemIdMappings.ContainsKey(itemData["ParentItemID"].ToString())) { newItem["ParentItemID"] = itemIdMappings[itemData["ParentItemID"].ToString()]; } newItem["Created"] = itemData["Created"].ToString(); newItem["Modified"] = DateTime.Parse(itemData["Modified"].ToString()); newItem.Update(); Program.SPContext.ExecuteQuery(); if (string.Equals(itemData["Attachments"], "True")) { string attachmentDirectory = System.IO.Path.Combine(inputFileDirectory, "Attachments", itemData["ID"].ToString()); string[] attachments = System.IO.Directory.GetFiles(attachmentDirectory); LogExecutionMessage(string.Format(".. Uploading {0} attachments", attachments.Count())); foreach (string attachmentFile in attachments) { var fileInfo = new System.IO.FileInfo(attachmentFile); using (var inputStream = new System.IO.FileStream(attachmentFile, System.IO.FileMode.Open)) { try { var attachInfo = new AttachmentCreationInformation(); attachInfo.FileName = fileInfo.Name; attachInfo.ContentStream = inputStream; newItem.AttachmentFiles.Add(attachInfo); Program.SPContext.ExecuteQuery(); LogExecutionMessage(string.Format(".... attachment {0} uploaded successfully.", fileInfo.Name)); } catch (Exception) { LogExecutionMessage(string.Format(".... [ERROR] Failed to uploaded attachment {0}; skipping to the next one", fileInfo.Name)); continue; } } } } return(newItem); }
public static void tempFunc() { SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Connection"]); ClientContext ctx = new ClientContext(siteUrl); Web oWeb = ctx.Web; ctx.Load(oWeb); ctx.ExecuteQuery(); DataTable dt = new DataTable(); SqlCommand com = new SqlCommand(); com.CommandType = CommandType.StoredProcedure; com.Connection = con; com.CommandTimeout = 0; com.CommandText = @"select pbd.BlogID , mled.DownloadPath from [LearnetUsage].[dbo].[BlogDetails] pbd inner join BLOGDETAILS bd on pbd.BlogTitle=bd.title inner join MigratedListItemEmbededDocument mled on bd.BlogID=mled.DocumentParentRowID and bd.SiteCollection=mled.SiteCollection where bd.sitecollection ='R&D - Social Community' and typeOfContent='topic' and migrated='yes' and hasAttachement=1 and Filepath like '%pdf' and pbd.Segment_Channel_ID=9"; com.CommandType = CommandType.Text; SqlDataAdapter adp = new SqlDataAdapter(com); com.Connection.Open(); adp.Fill(dt); com.Connection.Close(); foreach (DataRow dr in dt.Rows) { ListItem oItem = oWeb.Lists.GetByTitle("DiscussionText").GetItemById(Convert.ToInt16(dr["BlogID"])); ctx.Load(oItem); ctx.ExecuteQuery(); string filePath = dr["DownloadPath"].ToString();// System.Web.HttpUtility.UrlDecode(dr["DownloadPath"].ToString()); FileInfo temp = new FileInfo(filePath); if (isImage(temp)) { uploadImagesForTextBlog(ctx, filePath, temp, "t"); continue; } using (System.IO.FileStream fileStream = new System.IO.FileInfo(filePath).Open(System.IO.FileMode.Open)) { try { var attachment = new AttachmentCreationInformation(); attachment.FileName = System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)); attachment.ContentStream = fileStream; // My file stream Attachment att = oItem.AttachmentFiles.Add(attachment); ctx.Load(att); ctx.ExecuteQuery(); string targetFileUrl = string.Format("{0}/Lists/DiscussionText/Attachments/{1}/{2}", ctx.Web.ServerRelativeUrl, oItem["ID"], System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1))); Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fileStream, true); } catch (Exception ex) { Console.WriteLine(ex.Message); //rollbackTransaction(oItem, ctx, ex.Message,b.rowID); } } } }
static void Main(string[] args) { //tempFunc(); //Environment.Exit(0); Console.Title = "Uploading Blog"; Console.WriteLine(string.Format("Start {0}", DateTime.Now)); //Get Collection List <KeyArea_Channel> keyAreaChannelColl = db.getKeyArea_Channel(); List <Common.ContentType> contentTypeColl = db.getContentType(); //args.[0] = "News"; //if (args.Length == 0) //{ // Console.WriteLine("Site parameter missing..."); // Environment.Exit(100); //} // List<Blog> blogUploadCollection = db.getBlogsToUpload(args[0].ToString(),args[1].ToString()); List <Blog> blogUploadCollection = db.getBlogsToUpload("Learnet", "V"); ClientContext ctx; Web oWeb; foreach (Blog b in blogUploadCollection) { //if (b.subSite == "Learnet")//|| b.ID !=15) //{ // continue; // setSiteUrlForLearnet(b); // if (siteUrl == "Not mapped to any site") // continue; //} //else //{ // siteUrl = ConfigurationManager.AppSettings["SiteUrl"]; //} string p = (string.IsNullOrEmpty(b.project) ? "" : b.project).ToLower(); //if (p == "retail" || p == "jio") // if (p != "retail") // continue; setSiteUrlForLearnet(b, "http://digitalj3.ril.com"); if (siteUrl == "Not mapped to any site") { continue; } //set Learnet site url //ONly video // if (b.categoryType.ToString() != "V") { continue; } b.project = "Hydrocarbon"; Console.WriteLine(string.Format("Uploading Blog ID {0}", b.ID)); prepareWebContext(out ctx, out oWeb); // Console.WriteLine(formatBody(b.body,ctx)); List olist = null; if (b.categoryType.ToLower() == "t") { if ((b.siteCollection.ToLower() == "hr social" && b.subSite.ToLower() == "blogs")) { olist = oWeb.Lists.GetByTitle("MyCorner"); continue; // for mycorner blog } else { if (b.siteCollection.ToLower() == "" && b.subSite.ToLower() == "fc&a") { if (b.categories.ToLower() == "mycorner") { olist = oWeb.Lists.GetByTitle("MyCorner"); continue; // for mycorner blog } } olist = oWeb.Lists.GetByTitle("DiscussionText"); } } else { olist = oWeb.Lists.GetByTitle("Discussions List"); } ListItemCreationInformation createItem = new ListItemCreationInformation(); ListItem oItem = olist.AddItem(createItem); // parse keyArea and contenttype b.keyArea = formatKeyArea(b, ref keyAreaChannelColl, ctx); b.contentType = formatContentType(b, ref contentTypeColl); //get blogComment if exist List <Blog> blogCommentCollection = null; int blogCommentCount = 0; if (b.hasComment) { blogCommentCollection = getBlogComments(b); blogCommentCount = blogCommentCollection.Count; } Console.WriteLine("Uploading blog on site"); try { insertBlogItem(blogCommentCount, b, ctx, oItem, b.typeOfContent); } catch (Exception ex) { rollbackTransaction(oItem, ctx, ex.Message, b.rowID); continue; } if (b.hasComment) { Console.WriteLine("Uploading blog comment on site"); try { insertBlogComments(blogCommentCollection, ctx, oItem, b); } catch (Exception ex) { continue; } } if (b.likeCount > 0) { Console.WriteLine("Uploading blog like on site"); foreach (string user in b.likedBy.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { User likedUser = resolveUser(user, ctx); db.blogAnalyticsCommentLike((string.IsNullOrEmpty(b.project) ? b.channel : b.project), ctx.Web.Title, Convert.ToInt16(oItem["ID"]), "LIKE", likedUser.Title, likedUser.Email, (b.published.ToString() == "01-01-0001 00:00:00" ? b.modified : b.published), b.categoryType); } } if (b.hasAttachement) { Console.WriteLine("Uploading attachment on site"); ctx.Load(oItem); ctx.ExecuteQuery(); DataRowCollection dataRows = db.getBlogAttachments(b.siteCollection, b.subSite, b.ID).Rows; foreach (DataRow dr in dataRows) { string filePath = dr["DownloadPath"].ToString();// System.Web.HttpUtility.UrlDecode(dr["DownloadPath"].ToString()); if (filePath == "") { if (dataRows.Count == 0) { Console.WriteLine("Cannot access blank path"); rollbackTransaction(oItem, ctx, "Cannot access blank path", b.rowID); return; } else { continue; } } else if (filePath.ToLower() == "na") { continue; } FileInfo temp = new FileInfo(filePath); if (isImage(temp) && (dr["AttachmentType"].ToString().ToLower().Trim() == "normal" || dr["AttachmentType"].ToString().ToLower().Trim() == "thumbnail")) { uploadImagesForTextBlog(ctx, filePath, temp, b.categoryType); continue; } using (System.IO.FileStream fileStream = new System.IO.FileInfo(filePath).Open(System.IO.FileMode.Open)) { try { var attachment = new AttachmentCreationInformation(); attachment.FileName = System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)); attachment.ContentStream = fileStream; // My file stream Attachment att = oItem.AttachmentFiles.Add(attachment); ctx.Load(att); ctx.ExecuteQuery(); } catch (Exception ex) { //string targetFileUrl = string.Format("{0}/Lists/DiscussionsList/Attachments/{1}/{2}", ctx.Web.ServerRelativeUrl, oItem["ID"], System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)),fileStream,true); //Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fileStream, true); Console.WriteLine(ex.Message); if (!ex.Message.Contains("The specified name is already in use.")) { rollbackTransaction(oItem, ctx, ex.Message, b.rowID); } } } } } } // UPDATE MIGRATED SITE STATUS Console.WriteLine("Updatint Migrated Site Status"); var siteName = (from site in blogUploadCollection select new { siteColl = site.siteCollection, subWeb = site.subSite }).Distinct().ToList(); foreach (var obj in siteName) { db.completeMigratedStatusForSite(obj.siteColl, obj.subWeb); } Console.WriteLine(string.Format("End {0}", DateTime.Now)); }
/// <summary> /// Add and send item to Sharepointlist including Media /// </summary> /// <param name="spList">guid of sharepoint list</param> /// <param name="item">the item</param> /// <param name="data">data that holds dataId and formId</param> /// <param name="dataToMark"></param> /// <param name="itemUpdated">In case of update, use this item</param> /// <returns></returns> public async Task <ListItem> AddItemToList(List spList, List <DataMapping> dataMappings, FormData data, MarkDataReqViewModel dataToMark, List <DataMapping> uniqueDataMappings, ListItemCollection allItems) { bool containsArray = false; Log.Debug($"Processing data : {data.Id}"); List <ListItem> toAdd = new List <ListItem>(); bool shouldFulfillOtherLines = false; int toCreate = -1; ListItem item = spList.AddItem(new ListItemCreationInformation()); var r = await NeedTobeUpdated(dataMappings, data, spList, uniqueDataMappings); if (r != null) { item = r; } foreach (var dataMapping in dataMappings) { string[] columnValues = await KfApiManager.TransformText(data.FormID, data.Id, dataMapping.KfColumnSelector); TOOLS.ConvertToCorrectTypeAndSet(item, dataMapping, columnValues.First()); if (columnValues.Length > 1) // if there's at least one row to add { shouldFulfillOtherLines = true; if (toCreate.Equals(-1)) { toCreate = columnValues.Length - 1; } containsArray = true; int cvc = 0; foreach (string columnValue in columnValues) { if (columnValue != columnValues.First()) { if (toCreate > 0) { var tmp_item = spList.AddItem(new ListItemCreationInformation()); foreach (var field in dataMappings) { if (item.FieldValues.ContainsKey(field.SpColumnId)) { tmp_item[field.SpColumnId] = item[field.SpColumnId]; } } TOOLS.ConvertToCorrectTypeAndSet(tmp_item, dataMapping, columnValue); toAdd.Add(tmp_item); toCreate--; } else { TOOLS.ConvertToCorrectTypeAndSet(toAdd[cvc++], dataMapping, columnValue); } } } } else if (shouldFulfillOtherLines) { foreach (var line in toAdd) { line[dataMapping.SpColumnId] = columnValues.First(); } } } toAdd.Insert(0, item); if (containsArray) { RemoveDuplicated(ref toAdd, dataMappings, spList, uniqueDataMappings, allItems); } try { lock (locky) { foreach (var add in toAdd) { add.Update(); } Context.ExecuteQuery(); dataToMark.Ids.Add(data.Id); } var x = $"{KfApiManager.KfApiUrl}/rest/v3/forms/{data.FormID}/data/{data.Id}/all_medias"; var response = await KfApiManager.HttpClient.GetAsync(x); if (response.StatusCode == System.Net.HttpStatusCode.OK) { using (var ms = new MemoryStream()) { Log.Debug($"processing media for data {data.Id}"); await response.Content.CopyToAsync(ms); ms.Seek(0, SeekOrigin.Begin); AttachmentCreationInformation pjInfo = new AttachmentCreationInformation(); pjInfo.ContentStream = ms; pjInfo.FileName = response.Content.Headers.ContentDisposition.FileName; Attachment pj = toAdd.Last().AttachmentFiles.Add(pjInfo); lock (locky) { Context.Load(pj); Context.ExecuteQuery(); } } } /* foreach (var item in items) * { * item.DeleteObject(); * }*/ Context.ExecuteQuery(); Log.Debug($"Data {data.Id} sent to Sharepoint successefully"); } catch (Exception e) { throw; } return(null); }
public void sentdatatoSPLIst(string sVoucher) { DataTable CurrentdtSPList = Session["CurrentdtSPList"] as DataTable; string login = "******"; //give your username here string password = "******"; //give your password var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } string siteUrl = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices"; ClientContext clientContext = new ClientContext(siteUrl); Microsoft.SharePoint.Client.List myList = clientContext.Web.Lists.GetByTitle("Students_Requests"); ListItemCreationInformation itemInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem myItem = myList.AddItem(itemInfo); //string refno = Create16DigitString(); myItem["Title"] = CurrentdtSPList.Rows[0]["Title"].ToString(); //myItem["RequestID"] = refno; myItem["Year"] = CurrentdtSPList.Rows[0]["Year"].ToString(); myItem["Semester"] = CurrentdtSPList.Rows[0]["Semester"].ToString(); myItem["Request"] = CurrentdtSPList.Rows[0]["Request"].ToString(); myItem["RequestNote"] = CurrentdtSPList.Rows[0]["RequestNote"].ToString(); myItem["ServiceID"] = CurrentdtSPList.Rows[0]["ServiceID"].ToString(); myItem["Fees"] = CurrentdtSPList.Rows[0]["Fees"].ToString(); //myItem["Requester"] = clientContext.Web.EnsureUser(hdf_StudentEmail.Value); myItem["Requester"] = clientContext.Web.EnsureUser(CurrentdtSPList.Rows[0]["Requester"].ToString()); myItem["StudentID"] = CurrentdtSPList.Rows[0]["StudentID"].ToString(); myItem["StudentName"] = CurrentdtSPList.Rows[0]["StudentName"].ToString(); myItem["Contact"] = CurrentdtSPList.Rows[0]["Contact"].ToString(); myItem["Finance"] = clientContext.Web.EnsureUser(CurrentdtSPList.Rows[0]["Finance"].ToString()); myItem["FinanceAction"] = CurrentdtSPList.Rows[0]["FinanceAction"].ToString(); myItem["FinanceNote"] = ""; myItem["Host"] = clientContext.Web.EnsureUser(CurrentdtSPList.Rows[0]["Host"].ToString()); myItem["HostAction"] = CurrentdtSPList.Rows[0]["HostAction"].ToString(); myItem["HostNote"] = ""; //myItem["Provider"] = ""; myItem["ProviderAction"] = CurrentdtSPList.Rows[0]["ProviderAction"].ToString(); myItem["ProviderNote"] = ""; myItem["Status"] = CurrentdtSPList.Rows[0]["Status"].ToString(); myItem["Payment_Ref"] = sVoucher; //myItem["Modified"] = DateTime.Now; //myItem["Created"] = DateTime.Now; //myItem["Created By"] = hdf_StudentEmail.Value; //myItem["Modified By"] = hdf_StudentEmail.Value; try { myItem.Update(); if (Session["filePath"] != null) { var attachment = new AttachmentCreationInformation(); //flp_Upload.SaveAs(Server.MapPath("~/Upload/" + flp_Upload.FileName)); //string FileUrl = Server.MapPath("~/Upload/" + flp_Upload.FileName); string filePath = Session["filePath"].ToString(); attachment.FileName = Path.GetFileName(filePath); attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath)); Attachment att = myItem.AttachmentFiles.Add(attachment); } var onlineCredentials = new SharePointOnlineCredentials(login, securePassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); //string FileUrls = Server.MapPath("~/Upload/" + flp_Upload.FileName); //System.IO.File.Delete(FileUrls); if (Session["filePath"] != null) { string FileUrls = Session["filePath"].ToString(); System.IO.File.Delete(FileUrls); } lbl_Msg.Text = "Request (ID# " + CurrentdtSPList.Rows[0]["Title"].ToString() + ") Generated Successfully"; lbl_Msg.Visible = true; div_msg1.Visible = true; } catch (Exception e) { Console.WriteLine(e.Message); } //Console.ReadLine(); }
// Lists are more complex to handle the libraries. // If the is not´document given we do not upload one. (Used for unit testing) private int addDocumentToList(SPOList spol, string documentPath, string filePath, List <SPOField> fields) { // Get the list List spList = context.Web.Lists.GetById(spol.Id); context.Load(spList); context.Load(spList.RootFolder); context.ExecuteQuery(); string serverRelativeUrl = spList.RootFolder.ServerRelativeUrl; string documentName = null; string documentFolder = null; if (documentPath != null) { documentName = documentPath.Split('/').Last(); documentFolder = string.Join("/", documentPath.Split('/').Reverse().Skip(1).Reverse()); } ListItemCreationInformation lici = new ListItemCreationInformation(); // Create subfolders as needed if (documentPath != null) { // Figure out which folders need to be created List <FolderCreationSpec> folderCreatíonSequence = calculateFolderCreationSequence(serverRelativeUrl, getAllFolderNames(spList), documentPath); // Create those folders foreach (FolderCreationSpec fcs in folderCreatíonSequence) { createFolder(spList, fcs.Path, fcs.Foldername); } // Set the FolderUrl for the item creation lici.FolderUrl = serverRelativeUrl; if (!string.IsNullOrEmpty(documentFolder)) { lici.FolderUrl += "/" + documentFolder; } } // Create the item ListItem newItem = spList.AddItem(lici); // Set attribute values. Default for "Title" is the document name. if (fields == null) { fields = new List <SPOField>(); } foreach (SPOField spoField in fields) { string value = convert(spoField); if (value != null) { newItem[spoField.InternalName] = value; } } if (fields.Where(n => n.Title == "Title").Count() == 0) { newItem["Title"] = documentName; } newItem.Update(); // Attach the file if (documentPath != null) { AttachmentCreationInformation attachment = new AttachmentCreationInformation() { FileName = documentName, ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath)) }; Attachment att = newItem.AttachmentFiles.Add(attachment); context.Load(att); } // Execution... context.ExecuteQuery(); return(newItem.Id); }
static void Main(string[] args) { Console.Title = "MyCorner Blog"; Console.WriteLine(string.Format("Start {0}", DateTime.Now)); //Get Collection List <KeyArea_Channel> keyAreaChannelColl = db.getKeyArea_Channel(); List <Common.ContentType> contentTypeColl = db.getContentType(); List <Blog> blogUploadCollection = db.getRecordForMyCorner(); ClientContext ctx; Web oWeb; foreach (Blog b in blogUploadCollection) { siteUrl = ConfigurationManager.AppSettings["SiteUrl"]; Console.WriteLine(string.Format("Uploading Blog ID {0}", b.ID)); prepareWebContext(out ctx, out oWeb); // Console.WriteLine(formatBody(b.body,ctx)); List olist = null; if (b.categoryType.ToLower() == "t") { olist = oWeb.Lists.GetByTitle("MyCorner"); } else { olist = oWeb.Lists.GetByTitle("Discussions List"); } ListItemCreationInformation createItem = new ListItemCreationInformation(); ListItem oItem = olist.AddItem(createItem); // parse keyArea and contenttype b.keyArea = "462"; b.contentType = "5"; //get blogComment if exist List <Blog> blogCommentCollection = null; int blogCommentCount = 0; if (b.hasComment) { blogCommentCollection = getBlogComments(b); blogCommentCount = blogCommentCollection.Count; } Console.WriteLine("Uploading blog on site"); try { insertBlogItem(blogCommentCount, b, ctx, oItem, b.typeOfContent); } catch (Exception ex) { rollbackTransaction(oItem, ctx, ex.Message, b.rowID); continue; } if (b.hasComment) { Console.WriteLine("Uploading blog comment on site"); try { insertBlogComments(blogCommentCollection, ctx, oItem, b); } catch (Exception ex) { continue; } } if (b.likeCount > 0) { Console.WriteLine("Uploading blog like on site"); foreach (string user in b.likedBy.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)) { User likedUser = resolveUser(user, ctx); db.blogAnalyticsCommentLike("Root", ctx.Web.Title, Convert.ToInt16(oItem["ID"]), "LIKE", likedUser.Title, likedUser.Email, (b.published.ToString() == "01-01-0001 00:00:00" ? b.modified : b.published), b.categoryType); } } if (b.hasAttachement) { Console.WriteLine("Uploading attachment on site"); ctx.Load(oItem); ctx.ExecuteQuery(); foreach (DataRow dr in db.getBlogAttachments(b.siteCollection, b.subSite, b.ID).Rows) { string filePath = dr["DownloadPath"].ToString();// System.Web.HttpUtility.UrlDecode(dr["DownloadPath"].ToString()); if (filePath == "") { Console.WriteLine("Cannot access blank path"); rollbackTransaction(oItem, ctx, "Cannot access blank path", b.rowID); return; } else if (filePath.ToLower() == "na") { continue; } FileInfo temp = new FileInfo(filePath); if (isImage(temp) && (dr["AttachmentType"].ToString().ToLower().Trim() == "normal" || dr["AttachmentType"].ToString().ToLower().Trim() == "thumbnail")) { uploadImagesForTextBlog(ctx, filePath, temp, b.categoryType); continue; } using (System.IO.FileStream fileStream = new System.IO.FileInfo(filePath).Open(System.IO.FileMode.Open)) { try { var attachment = new AttachmentCreationInformation(); attachment.FileName = System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)); attachment.ContentStream = fileStream; // My file stream Attachment att = oItem.AttachmentFiles.Add(attachment); ctx.Load(att); ctx.ExecuteQuery(); } catch (Exception ex) { //string targetFileUrl = string.Format("{0}/Lists/DiscussionsList/Attachments/{1}/{2}", ctx.Web.ServerRelativeUrl, oItem["ID"], System.Web.HttpUtility.UrlDecode(temp.Name.Substring(temp.Name.IndexOf("_") + 1)),fileStream,true); //Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fileStream, true); Console.WriteLine(ex.Message); rollbackTransaction(oItem, ctx, ex.Message, b.rowID); } } } } // db.udpateParseBlogItems(b.rowID, comment, "Yes"); } // UPDATE MIGRATED SITE STATUS Console.WriteLine("Updatint Migrated Site Status"); var siteName = (from site in blogUploadCollection select new { siteColl = site.siteCollection, subWeb = site.subSite }).Distinct().ToList(); foreach (var obj in siteName) { db.completeMigratedStatusForSite(obj.siteColl, obj.subWeb); } Console.WriteLine(string.Format("End {0}", DateTime.Now)); }
public void sentdatatoSPLIst() { string Dates = "<b>From:</b> " + Convert.ToDateTime(txt_From.Text).ToString("dd/MM/yyyy") + " <b>To:</b> " + Convert.ToDateTime(txt_To.Text).ToString("dd/MM/yyyy") + ""; string letterrequestStatus = "No"; if (chk_Request.Checked == true) { letterrequestStatus = "Yes"; } else { letterrequestStatus = "No"; } String requestedletters = ""; string k = ""; for (int i = 0; i < chk_Courses.Items.Count; i++) { if (chk_Courses.Items[i].Selected) { k = k + "<b>Course Code:</b> " + chk_Courses.Items[i].Text + " <b>Instructor:</b> " + chk_Courses.Items[i].Value + "<br/>"; } } requestedletters = k; int sem = 0; int Year = LibraryMOD.SeperateTerm(LibraryMOD.GetCurrentTerm(), out sem); int iYear = Year; int iSem = sem; string sSemester = LibraryMOD.GetSemesterString(iSem); string languageoption = ""; if (Session["LanguageOption"].ToString() == "True") { languageoption = "<b>Language:</b> " + ddlLanguage.SelectedItem.Text + ""; } string login = "******"; //give your username here string password = "******"; //give your password var securePassword = new SecureString(); foreach (char c in password) { securePassword.AppendChar(c); } string siteUrl = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices"; ClientContext clientContext = new ClientContext(siteUrl); Microsoft.SharePoint.Client.List myList = clientContext.Web.Lists.GetByTitle("Students_Requests"); ListItemCreationInformation itemInfo = new ListItemCreationInformation(); Microsoft.SharePoint.Client.ListItem myItem = myList.AddItem(itemInfo); string refno = Create16DigitString(); myItem["Title"] = refno; //myItem["RequestID"] = refno; myItem["Year"] = iYear; myItem["Semester"] = iSem; myItem["Request"] = "<b>Service ID:</b> " + lbl_ServiceID.Text + "<br/> <b>Service Name:</b> " + lbl_ServiceNameEn.Text + " (" + lbl_ServiceNameAr.Text + " )<br/><b>Major:</b> " + lbl_CurrentMajor.Text + "<br/><b>Excuse Dates:</b> " + Dates + "<br/><b>Re-examination letter requested:</b> " + letterrequestStatus + "<br/><b>Requested Letters:</b><br/>" + requestedletters + "<br/>" + languageoption + "<br/>"; myItem["RequestNote"] = txt_Remarks.Text.Trim(); myItem["ServiceID"] = lbl_ServiceID.Text; myItem["Fees"] = hdf_Price.Value; myItem["Requester"] = clientContext.Web.EnsureUser(hdf_StudentEmail.Value); //myItem["Requester"] = clientContext.Web.EnsureUser("*****@*****.**"); myItem["StudentID"] = lbl_StudentID.Text; myItem["StudentName"] = lbl_StudentName.Text; myItem["Contact"] = lbl_StudentContact.Text; myItem["Finance"] = clientContext.Web.EnsureUser(Session["FinanceEmail"].ToString()); myItem["FinanceAction"] = "Initiate"; myItem["FinanceNote"] = ""; myItem["Host"] = clientContext.Web.EnsureUser(Session["HostEmail"].ToString());//Session["HostEmail"].ToString(); myItem["HostAction"] = "Initiate"; myItem["HostNote"] = ""; //myItem["Provider"] = ""; myItem["ProviderAction"] = "Initiate"; myItem["ProviderNote"] = ""; myItem["Status"] = "Finance Approval Needed"; //myItem["Modified"] = DateTime.Now; //myItem["Created"] = DateTime.Now; //myItem["Created By"] = hdf_StudentEmail.Value; //myItem["Modified By"] = hdf_StudentEmail.Value; try { myItem.Update(); if (flp_Upload.HasFile) { var attachment = new AttachmentCreationInformation(); flp_Upload.SaveAs(Server.MapPath("~/Upload/" + flp_Upload.FileName)); string FileUrl = Server.MapPath("~/Upload/" + flp_Upload.FileName); string filePath = FileUrl; attachment.FileName = Path.GetFileName(filePath); attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes(filePath)); Attachment att = myItem.AttachmentFiles.Add(attachment); } var onlineCredentials = new SharePointOnlineCredentials(login, securePassword); clientContext.Credentials = onlineCredentials; clientContext.ExecuteQuery(); if (flp_Upload.HasFile) { string FileUrls = Server.MapPath("~/Upload/" + flp_Upload.FileName); System.IO.File.Delete(FileUrls); } lbl_Msg.Text = "Request (ID# " + refno + ") Generated Successfully"; lbl_Msg.Visible = true; div_msg.Visible = true; lnk_Generate.Enabled = false; } catch (Exception e) { Console.WriteLine(e.Message); } //Console.ReadLine(); }
public int FillAppWebNotesWith1G() { using (var ctx = SharePointContext.CreateUserClientContextForSPAppWeb()) { List notesList = ctx.Web.Lists.GetByTitle("Notes"); int maxNum = 100; for (int i = 0; i < maxNum; i++) { ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = notesList.AddItem(itemCreateInfo); newItem["Title"] = "Note " + i.ToString() + "."; newItem["FTCAM_Description"] = "Description " + i.ToString() + "."; newItem.Update(); ctx.ExecuteQuery(); var file = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Assets/SampleData.rar"); var filestream = System.IO.File.OpenRead(file); var info = new AttachmentCreationInformation { FileName = "SampleData.rar", ContentStream = filestream }; newItem.AttachmentFiles.Add(info); ctx.ExecuteQuery(); filestream.Close(); } return maxNum; } }
private static void MigrateContent_List(ClientContext clientContext, List listToBeReplaced, List newList) { try { ListItemCollection sourceListItems = listToBeReplaced.GetItems(CamlQuery.CreateAllItemsQuery()); FieldCollection sourceListFields = listToBeReplaced.Fields; clientContext.Load(sourceListItems, sListItems => sListItems.IncludeWithDefaultProperties(li => li.AttachmentFiles)); clientContext.Load(sourceListFields); clientContext.ExecuteQuery(); var sourceItemEnumerator = sourceListItems.GetEnumerator(); while (sourceItemEnumerator.MoveNext()) { var sourceItem = sourceItemEnumerator.Current; ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem targetItem = newList.AddItem(itemCreateInfo); object sourceModifiedDate = null; object sourceModifiledBy = null; foreach (Field sourceListField in sourceListFields) { try { //[START]Copy all except Attachments,ReadOnlyField,ContentType if (!sourceListField.ReadOnlyField && sourceListField.InternalName != "Attachments" && sourceListField.InternalName != "ContentType" && null != sourceItem[sourceListField.InternalName]) { //[START] Calendar and Event List if (listToBeReplaced.BaseTemplate.ToString().Equals("106")) { if (sourceListField.InternalName.Equals("EndDate")) { continue; } else if (sourceListField.InternalName.Equals("EventDate")) { targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName]; targetItem["EndDate"] = sourceItem["EndDate"]; targetItem.Update(); clientContext.ExecuteQuery(); //[START] [Load "Target Items" After Update, to avoid Version Conflict] targetItem = newList.GetItemById(targetItem.Id); clientContext.Load(targetItem); clientContext.ExecuteQuery(); //[END] [Load "Target Items" After Update, to avoid Version Conflict] } else if (ContainsField(newList, sourceListField.InternalName)) { targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName]; targetItem.Update(); clientContext.ExecuteQuery(); //[START] [Load "Target Items" After Update, to avoid Version Conflict] targetItem = newList.GetItemById(targetItem.Id); clientContext.Load(targetItem); clientContext.ExecuteQuery(); //[END] [Load "Target Items" After Update, to avoid Version Conflict] } } //[END] Calendar and Event List else { if (ContainsField(newList, sourceListField.InternalName)) { targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName]; targetItem.Update(); clientContext.ExecuteQuery(); //[START] [Load "Target Items" After Update, to avoid Version Conflict] targetItem = newList.GetItemById(targetItem.Id); clientContext.Load(targetItem); clientContext.ExecuteQuery(); //[END] [Load "Target Items" After Update, to avoid Version Conflict] } } } //[END]Copy all except Attachments, ReadOnlyField, ContentType //Created, Author Field if (sourceItem.FieldValues.Keys.Contains(sourceListField.InternalName)) { //Created By if (sourceListField.InternalName.Equals("Author")) { //newList.Fields.GetByInternalNameOrTitle("Author").ReadOnlyField = false; if (ContainsField(newList, sourceListField.InternalName)) { targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName]; targetItem.Update(); clientContext.ExecuteQuery(); } } //Created Date if (sourceListField.InternalName.Equals("Created")) { //newList.Fields.GetByInternalNameOrTitle("Created").ReadOnlyField = false; if (ContainsField(newList, sourceListField.InternalName)) { targetItem[sourceListField.InternalName] = sourceItem[sourceListField.InternalName]; targetItem.Update(); clientContext.ExecuteQuery(); } } //Modified Date if (sourceListField.InternalName.Equals("Modified")) { if (ContainsField(newList, sourceListField.InternalName)) { sourceModifiedDate = sourceItem["Modified"]; } } //Modified By if (sourceListField.InternalName.Equals("Editor")) { if (ContainsField(newList, sourceListField.InternalName)) { sourceModifiledBy = sourceItem["Editor"]; } } } //Created, Author Field } catch (Exception ex) { ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List - Copy Items", ex.GetType().ToString(), "Not initialized: " + sourceListField.Title); Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Copy Items, Exception Message: " + ex.Message + ", Exception Comment: Not initialized: " + sourceListField.Title); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[EXCEPTION] [MigrateContent_List] Copy Items, Exception Message: " + ex.Message + ", ExceptionComments: Not initialized: " + sourceListField.Title); Console.ForegroundColor = ConsoleColor.Gray; } } #region Copy Attachments //Copy attachments foreach (Attachment fileName in sourceItem.AttachmentFiles) { try { Microsoft.SharePoint.Client.File oAttachment = clientContext.Web.GetFileByServerRelativeUrl(fileName.ServerRelativeUrl); clientContext.Load(oAttachment); clientContext.ExecuteQuery(); FileInformation fInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, oAttachment.ServerRelativeUrl); AttachmentCreationInformation attachFileInfo = new AttachmentCreationInformation(); Byte[] buffer = new Byte[oAttachment.Length]; int bytesRead = fInfo.Stream.Read(buffer, 0, buffer.Length); MemoryStream stream = new MemoryStream(buffer); attachFileInfo.ContentStream = stream; attachFileInfo.FileName = oAttachment.Name; targetItem.AttachmentFiles.Add(attachFileInfo); targetItem.Update(); clientContext.ExecuteQuery(); stream.Dispose(); //[START] [Load "Target Items" After Update, to avoid Version Conflict] targetItem = newList.GetItemById(targetItem.Id); clientContext.Load(targetItem); clientContext.ExecuteQuery(); //[END] [Load "Target Items" After Update, to avoid Version Conflict] } catch (Exception ex) { if (!ex.Message.Equals("Version conflict.", StringComparison.CurrentCultureIgnoreCase)) { ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List - Copy Attachments", ex.GetType().ToString(), ""); Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Copy Attachments, Exception Message: " + ex.Message); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[EXCEPTION] [MigrateContent_List] Copy Attachments, Exception Message: " + ex.Message); Console.ForegroundColor = ConsoleColor.Gray; } } } #endregion //[START] [Load "Target Items" After Update, to avoid Version Conflict] targetItem = newList.GetItemById(targetItem.Id); clientContext.Load(targetItem); clientContext.ExecuteQuery(); //[END] [Load "Target Items" After Update, to avoid Version Conflict] targetItem["Modified"] = sourceModifiedDate; targetItem["Editor"] = sourceModifiledBy; targetItem.Update(); clientContext.ExecuteQuery(); } } catch (Exception ex) { ExceptionCsv.WriteException(ExceptionCsv.WebApplication, ExceptionCsv.SiteCollection, ExceptionCsv.WebUrl, "ListMigration", ex.Message, ex.ToString(), "MigrateContent_List", ex.GetType().ToString(), ""); Logger.AddMessageToTraceLogFile(Constants.Logging, "[EXCEPTION] [MigrateContent_List] Exception Message: " + ex.Message); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[EXCEPTION] [MigrateContent_List] Exception Message: " + ex.Message); Console.ForegroundColor = ConsoleColor.Gray; } }