protected string GetFileUrlOfItem(string itemId) { string fileUrl = string.Empty; SPSecurity.RunWithElevatedPrivileges(() => { using (var adminSite = new SPSite(CurrentWeb.Site.ID)) { using (var adminWeb = adminSite.OpenWeb(CurrentWeb.ID)) { try { adminWeb.AllowUnsafeUpdates = true; SPList resourcesList = Utilities.GetCustomListByUrl(adminWeb, ListsName.InternalName.ResourceLibrary); SPListItem item = resourcesList.GetItemById(Convert.ToInt32(itemId)); if (item != null) { SPAttachmentCollection attachs = item.Attachments; if (attachs.Count > 0) { fileUrl = attachs.UrlPrefix + attachs[0]; } } } catch (Exception ex) { Utilities.LogToULS(ex); } } } }); return(fileUrl); }
/// <summary> /// Recebe o item que foi adicionado e copia o item para cada nova pessoa que deve receber /// </summary> /// <param name="properties"></param> private void replicarItem(SPItemEventProperties properties) { using (SPWeb web = properties.Web.Site.RootWeb) { try { web.AllowUnsafeUpdates = true; SPFieldUserValueCollection usuarios = (SPFieldUserValueCollection)properties.ListItem["Destinatario"]; List <SPUser> SPusuarios = capturarTodosUsuarios(usuarios, properties); //usuarios = capturarTodosUsuarios(usuarios, properties); foreach (SPUser usuario in SPusuarios) { SPList lstCircularesEnviadas = web.Lists["DBS.CircularesEnviadas"]; SPListItem novoItem; novoItem = lstCircularesEnviadas.Items.Add(); SPAttachmentCollection anexos = properties.ListItem.Attachments; novoItem["Title"] = (String)properties.ListItem["Title"]; novoItem["Descricao"] = properties.ListItem["Mensagem"]; novoItem["Destinatario"] = usuario; novoItem["EnviarEmail"] = (bool)properties.ListItem["EnviarEmail"]; novoItem["Ciente"] = false; novoItem["DataHoraCiente"] = null; novoItem.Update(); //Para poder incluir anexos, é necessário ter salvo previamente o novo item //Copiando os anexos: if (anexos.Count > 0) { //get the folder with the attachments for the source item SPFolder sourceItemAttachmentsFolder = properties.ListItem.Web.Folders["Lists"].SubFolders[properties.ListItem.ParentList.Title].SubFolders["Attachments"].SubFolders[properties.ListItem.ID.ToString()]; //Loop over the attachments, and add them to the target item foreach (SPFile file in sourceItemAttachmentsFolder.Files) { byte[] binFile = file.OpenBinary(); novoItem.Attachments.AddNow(file.Name, binFile); } novoItem.Update(); } //Envio o e-mail EnviarEmail(web, usuario, properties.ListItem); novoItem["EmailEnviado"] = true; novoItem.Update(); } } catch (Exception ex) { //todo: salvar em algum lugar essa exception throw ex; } finally { web.AllowUnsafeUpdates = false; } } }
public static string MontaLinksAnexo(SPAttachmentCollection anexos) { if (anexos == null) { return(string.Empty); } else { StringBuilder strSaida = new StringBuilder(); strSaida.Append("<table class='tb_anexos'>"); foreach (var anexo in anexos) { var docicon = SPUtility.MapToIcon(SPContext.Current.Web, anexo.ToString(), ""); strSaida.Append("<tr class='tb_anexos_tr'>"); strSaida.AppendFormat("<td class='tb_anexos_icon'><img border=0 src='/_layouts/images/{2}'></td><td class='tb_anexos_link'><a href=\"{0}{1}\">{1}</a></td>", anexos.UrlPrefix, anexo, docicon); strSaida.Append("</tr>"); } strSaida.Append("</table>"); return(strSaida.ToString()); } }
public SPAttachmentCollectionInstance(ObjectInstance prototype, SPAttachmentCollection attachmentCollection) : this(prototype) { if (attachmentCollection == null) { throw new ArgumentNullException("attachmentCollection"); } m_attachmentCollection = attachmentCollection; }
public void MapFrom(object listItem) { SPListItem item = (SPListItem)listItem; SPList list = item.ParentList; if (list.EnableAttachments && (bool)item["Attachments"]) { Attachments = item.Attachments; } }
private void ShowNewsField() { SPWeb web = SPContext.Current.Web; SPList myNews = web.Lists["讨论列表"]; foreach (SPListItem item in myNews.Items) { SPAttachmentCollection attach = item.Attachments; for (int i = 0; i < attach.Count; i++) { String url = attach.UrlPrefix + attach[i]; Console.WriteLine("正在下载{0}...", url); SPFile file = web.GetFile(url); FileStream fs = new FileStream(file.Name, FileMode.Create); byte[] content = file.OpenBinary(); fs.Write(content, 0, content.Length); fs.Close(); } } //获取第一个discussion的主题 foreach (SPListItem myFoleder in myNews.Folders) { Response.Write("Sethem:" + myFoleder.Name); Response.Write(myFoleder["Created"] + "---" + myFoleder["Author"] + "<br/>"); foreach (SPListItem myItem in myFoleder.ListItems) { Response.Write("Replay:" + myItem.Name + "--" + myItem["Title"] + "<br/>"); Response.Write(myItem["Created"] + "---" + myItem["Author"] + "<br/>"); } } //第一个主题,第一个回复的内容 //Response.Write(myNews.Items[1]); //foreach (SPListItem myItem in myNews.Items) //{ // Response.Write(myItem["Created"] + "---" + myItem["Author"] + "<br/>"); // Response.Write(myItem["Title"] + "---" + myItem["LastReplyBy"] + "<br/>"); //} foreach (SPField myField in myNews.Fields) { if (myField.InternalName == "Author") { Response.Write(myField.InternalName + "<--->" + myField.TypeDisplayName + "---" + myField.TypeAsString + "----" + myField.Title); } } //SPListItemCollection collListItems = myNews.Items; //GridView1.DataSource = collListItems.GetDataTable(); //GridView1.DataBind(); }
public string[] AddAttachments(SPAttachmentCollection spAttachments) { List <string> files = new List <string>(); for (int i = 0; i < spAttachments.Count; i++) { files.Add(spAttachments[i]); } return(files.ToArray()); }
public static void AttachFile(this SPListItem item, Stream fileStream, string originalleafName, bool overwrite = false, bool updateRequired = false) { SPAttachmentCollection attachments = item.Attachments; SPList list = item.ParentList; SPWeb web = list.ParentWeb; if (!list.EnableAttachments) { //throw new SPException(string.Format("The specified file can not be added to the list \"{0}\" with disabled attachments.", list.Title)); return; } string leafName = SPHelper.RemoveIllegalUrlCharacters(originalleafName); if (fileStream == null || fileStream.Length == 0) { throw new SPException("The specified file should not be empty."); } var maximumFileSize = web.Site.WebApplication.MaximumFileSize * 1024 * 1024; if (fileStream.Length > maximumFileSize) { throw new SPException(string.Format("The specified file is larger than the maximum supported file size: {0}.", SPUtility.FormatSize(maximumFileSize))); } if (overwrite) { string attachmentUrl = SPUrlUtility.CombineUrl(attachments.UrlPrefix, leafName); SPFile existingFile = web.GetFile(attachmentUrl); if (existingFile.Exists) { existingFile.SaveBinary(fileStream); return; } } BinaryReader reader = new BinaryReader(fileStream); if (updateRequired) { attachments.Add(leafName, reader.ReadBytes((int)fileStream.Length)); } else { attachments.AddNow(leafName, reader.ReadBytes((int)fileStream.Length)); } reader.Close(); }
protected void BindRepeater() { SPSecurity.RunWithElevatedPrivileges(() => { using (var adminSite = new SPSite(CurrentWeb.Site.ID)) { using (var adminWeb = adminSite.OpenWeb(CurrentWeb.ID)) { try { adminWeb.AllowUnsafeUpdates = true; var query = new SPQuery() { Query = "<Where><Eq><FieldRef Name='DisplayStatus' /><Value Type='Choice'>Hiển thị</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>", }; var list = Utilities.GetCustomListByUrl(adminWeb, ListsName.InternalName.ImageLibrary); var items = list.GetItems(query); if (items != null && items.Count > 0) { DataTable dt = items.GetDataTable(); dt.Columns.Add("FileUrl"); if (dt != null && dt.Rows.Count > 0) { int i = 0; foreach (SPListItem item in items) { SPAttachmentCollection attachs = item.Attachments; if (attachs.Count > 0) { dt.Rows[i]["FileUrl"] = WebUrl + "/Lists/" + ListsName.InternalName.ImageLibrary + "/Attachments/" + item.ID + "/" + attachs[0]; } i++; } //imgThumb.Src = dt.Rows[0]["FileUrl"].ToString(); //dvTitle.InnerText = dt.Rows[0][FieldsName.ImageLibrary.InternalName.Title].ToString(); //dt.Rows.Remove(dt.Rows[0]); } rptImg.DataSource = dt; rptImg.DataBind(); } } catch (SPException ex) { Utilities.LogToULS(ex); } } } }); }
public static IEnumerable <SPFile> GetAttachments(this SPListItem item) { SPAttachmentCollection attachments = item.Attachments; if (attachments == null || attachments.Count == 0) { return(null); } SPList list = item.ParentList; SPWeb web = list.ParentWeb; SPFolder attachmentsFolder = web.GetFolder(attachments.UrlPrefix); return(attachmentsFolder.Exists ? GetAttachments(attachmentsFolder, attachments) : null); }
protected void btnOk_click(object sender, EventArgs e) { try { if (!string.IsNullOrEmpty(Request["ListId"]) && !string.IsNullOrEmpty(Request["ItemId"])) { Guid listId = new Guid(Request["ListId"]); Int32 itemId = Convert.ToInt32(Request["ItemId"]); SPWeb webObj = SPContext.Current.Web; SPList lstObj = webObj.Lists[listId]; if (lstObj != null) { SPListItem thisItem = lstObj.GetItemById(itemId); if (thisItem != null) { if (fileUploadControl.HasFiles) { SPAttachmentCollection attach = thisItem.Attachments; HttpFileCollection uploadedFiles = Request.Files; for (int i = 0; i < uploadedFiles.Count; i++) { HttpPostedFile userPostedFile = uploadedFiles[i]; String fileName = userPostedFile.FileName; using (Stream attachmentStream = userPostedFile.InputStream) { Byte[] attachmentContent = new Byte[attachmentStream.Length]; attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length); attach.Add(fileName, attachmentContent); } } thisItem.Update(); Page.ClientScript.RegisterStartupScript(this.GetType(), "CallClosePopup", "closePopup(1);", true); } else { lblError.Text = "The file name is invalid or the file is empty. A file name cannot contain any of the following characters: \\ / : * ? \" < > | # { } % ~ &"; } } } } } catch (Exception ex) { lblError.Text = ex.Message; } }
private void ShowAttachment(int itemId) { string query = @"<Where> <Eq> <FieldRef Name='ID' /> <Value Type='Counter'>" + itemId + @"</Value> </Eq> </Where>"; SPListItemCollection items = GetDataFromList(webObj.ListName, query); if (items != null) { if (items.Count > 0) { SPListItem item = items[0]; SPAttachmentCollection attach = item.Attachments; if (attach.Count > 0) { lbAttach.Text = "附件浏览(共" + attach.Count + "个)"; StringBuilder sb = new StringBuilder(); sb.Append("<dl>"); for (int i = 0; i < attach.Count; i++) { string title = attach[i]; string url = attach.UrlPrefix + attach[i]; int k = url.IndexOf('/', 7); string hosturl = url.Substring(0, k); string weburl = SPContext.Current.Site.Url; url = url.Replace(hosturl, weburl); sb.Append(GenHtml(title, url, i)); } sb.Append("</dl>"); divAttach.Visible = true; lbAttach.Visible = true; divAttach.Style.Value = "width:" + (webObj.DispWidth + 20).ToString() + "px;height:" + webObj.DispHeight + "px;overflow-y:auto;border:1px solid #ebebeb;padding:10px;"; divAttach.InnerHtml = sb.ToString(); } else { lbAttach.Visible = false; divAttach.Visible = false; } } } }
public static string MontaLinksAnexo(SPAttachmentCollection anexos) { if (anexos == null) { return(string.Empty); } else { StringBuilder strSaida = new StringBuilder(); foreach (var anexo in anexos) { strSaida.AppendFormat("<a href=\"{0}{1}\">{1}</a><br/>", anexos.UrlPrefix, anexo); } return(strSaida.ToString()); } }
/// <summary> /// An item was updated. /// </summary> public override void ItemUpdated(SPItemEventProperties properties) { base.ItemUpdated(properties); SPListItem item = properties.List.GetItemById(properties.ListItemId); SPAttachmentCollection attachments = item.Attachments; SPList destinationList = item.Web.Lists["Contract Documents"]; for (int i = 0; i < attachments.Count; i++) { SPFile file = item.ParentList.ParentWeb.GetFile(item.Attachments.UrlPrefix + item.Attachments[i].ToString()); string destinationLocation = destinationList.RootFolder.ServerRelativeUrl + "/" + file.Name; file.MoveTo(destinationLocation, true); SPFile newFile = destinationList.ParentWeb.GetFile(destinationLocation); SPListItem newItem = newFile.Item; newItem["Contract"] = item.ID; newItem["Title"] = newItem.File.Name; newItem.Update(); } }
protected void BindRepeater() { SPSecurity.RunWithElevatedPrivileges(() => { using (var adminSite = new SPSite(CurrentWeb.Site.ID)) { using (var adminWeb = adminSite.OpenWeb(CurrentWeb.ID)) { try { adminWeb.AllowUnsafeUpdates = true; SPList iconLink = Utilities.GetCustomListByUrl(adminWeb, ListsName.InternalName.IconLinkList); SPQuery query = new SPQuery(); query.Query = "<OrderBy><FieldRef Name='IConOrder' Ascending='True' /></OrderBy>"; SPListItemCollection items = iconLink.GetItems(query); if (items != null && items.Count > 0) { DataTable dt = items.GetDataTable(); dt.Columns.Add("FileUrl"); int i = 0; foreach (SPListItem item in items) { SPAttachmentCollection attachs = item.Attachments; string fileName = attachs[0]; dt.Rows[i]["FileUrl"] = fileName; i++; } if (dt != null && dt.Rows.Count > 0) { rptLinkIcon.DataSource = dt; rptLinkIcon.DataBind(); } } } catch (SPException ex) { Utilities.LogToULS(ex); } } } }); }
protected List <MeetingItem> getList() { List <MeetingItem> MeetingItems = new List <MeetingItem>(); try { using (SPSite site = new SPSite(SPContext.Current.Web.Url)) { using (SPWeb web = site.OpenWeb()) { SPList list = (SPList)web.Lists["Meetings List"]; for (int i = 0; i < list.ItemCount; i++) { string title = Convert.ToString(list.Items[i]["Title"]); string desc = Convert.ToString(list.Items[i]["Description"]); string location = Convert.ToString(list.Items[i]["Locations"]); DateTime dateTime = Convert.ToDateTime(list.Items[i]["Event DateTime"]); SPAttachmentCollection attachments = list.Items[i].Attachments; MeetingItem myItem = new MeetingItem(title, desc, getLocation(location), dateTime, attachments); MeetingItems.Add(myItem); } } } } catch (Exception e) { Label lblError = new Label(); this.Controls.Add(lblError); if (e.InnerException != null) { lblError.Text = "An error has occured reading from the selected list. Please check the Navi properties. " + e.InnerException.ToString(); } } return(MeetingItems); }
public Job(int id, int prerequisite, string title, string operation, DateTime when, SPAttachmentCollection attachments) { this.id = id; this.prerequisite = prerequisite; this.title = title; this.operation = operation; this.when = when; this.attachments = AddAttachments(attachments); this.associatedTool = IdentifyTool(); }
protected void BindRepeater() { SPSecurity.RunWithElevatedPrivileges(() => { using (var adminSite = new SPSite(CurrentWeb.Site.ID)) { using (var adminWeb = adminSite.OpenWeb(CurrentWeb.ID)) { try { adminWeb.AllowUnsafeUpdates = true; var query = new SPQuery() { Query = "<OrderBy><FieldRef Name='" + FieldsName.VideoLibrary.InternalName.Order + "' Ascending='TRUE' /></OrderBy>", RowLimit = 10 }; var list = Utilities.GetCustomListByUrl(adminWeb, ListsName.InternalName.VideoLibrary); var items = list.GetItems(query); if (items != null && items.Count > 0) { DataTable dt = new DataTable(); dt.Columns.Add("FileUrl"); dt.Columns.Add("ImageUrl"); dt.Columns.Add("ID"); dt.Columns.Add("Title"); foreach (SPListItem item in items) { SPAttachmentCollection attachs = item.Attachments; if (attachs.Count > 1) { DataRow dr = dt.NewRow(); dr["ID"] = item.ID; dr["Title"] = item.Title; dr["ImageUrl"] = WebUrl + "/Lists/" + ListsName.InternalName.VideoLibrary + "/Attachments/" + item.ID + "/" + attachs[0]; dr["FileUrl"] = WebUrl + "/Lists/" + ListsName.InternalName.VideoLibrary + "/Attachments/" + item.ID + "/" + attachs[1]; dt.Rows.Add(dr); } } if (dt.Rows.Count > 0) { ltrVideo.Text = string.Format(@"<embed flashvars=""file={0}&image={1}&autostart=false"" allowfullscreen=""true"" allowscripaccess=""always"" id=""qn-video-div-player"" name=""qn-video-div-player"" src=""{2}/ResourcesList/player.swf"" width=""286""> </embed>", dt.Rows[0]["FileUrl"].ToString(), dt.Rows[0]["ImageUrl"].ToString(), WebUrl); } rptVideo.DataSource = dt; rptVideo.DataBind(); } } catch (SPException ex) { Utilities.LogToULS(ex); } } } }); }
private void exportUtility_ExportCompleted(object sender, ExportCompletedEventArgs e) { GlymaExportUserState userState = e.UserState as GlymaExportUserState; if (userState != null) { SPWorkItem workItem = userState.StateObject as SPWorkItem; if (workItem != null) { using (SPSite site = new SPSite(workItem.SiteId)) { using (SPWeb web = site.OpenWeb(workItem.WebId)) { try { if (e.Status == ExportStatus.Error) { WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, e.ErrorMessage); } else if (e.Status == ExportStatus.Completed) { SPList exportsList = web.Lists[workItem.ParentId]; SPListItem exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid); if (exportItem != null) { // Read the contents of the file byte[] fileContents = null; Stream fs = null; try { fs = File.OpenRead(e.FileLocation); fileContents = new byte[fs.Length]; fs.Read(fileContents, 0, (int)fs.Length); // Add the file to the ListItem SPAttachmentCollection attachments = exportItem.Attachments; string fileName = Path.GetFileName(e.FileLocation); string extention = fileName.Substring(fileName.LastIndexOf('.')); fileName = e.MapName + extention; attachments.Add(fileName, fileContents); exportItem.Update(); // Mark as completed WriteExportStatus(workItem, ExportStatus.Completed); WriteProgress(workItem, 1); if (userState.UseVerboseLogging) { LogMessage(workItem, "Export file copied to list successfully."); } } catch (Exception ex) { WriteExportStatus(workItem, ExportStatus.Error); LogMessage(workItem, "Failed reading the exported file: {0}. {1}", e.FileLocation, ex.Message); //this will append the log message } finally { if (fs != null) { fs.Close(); } } //Try delete the temporary file, don't change the status to Error if this fails but log it. try { DeleteTempFile(e.FileLocation); } catch (Exception ex) { if (workItem != null) { //the status will still be Completed but an error occurred that should be monitored. LogMessage(workItem, "Failed to delete temp export file: {0}. ", ex.Message); } } } } } finally { userState.Completed.Set(); //work item has completed } } } } } }
public MeetingItem(string title, string desc, LocationItem location, DateTime dateTime, SPAttachmentCollection attachmentsCollection) { this.title = title; this.desc = desc; this.location = location; this.dateTime = dateTime; attachments = new List <string[]>(); foreach (string fileName in attachmentsCollection) { String[] array = new String[2]; array[0] = attachmentsCollection.UrlPrefix + fileName; array[1] = fileName; attachments.Add(array); } }
protected bool Main() { bool nResult = true; DataClasses.Document document = new DataClasses.Document(); string dtIn = DateTime.Now.ToString("yyyy-MM-dd"); using (SPSite site = new SPSite(strUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["PolicyHolders"]; SPQuery query = new SPQuery(); query.RowLimit = 50; SPListItemCollection items = list.GetItems(query); foreach (SPListItem item in items) { SPAttachmentCollection attachments = item.Attachments; foreach (string fileName in attachments) { SPFile file = web.GetFile(attachments.UrlPrefix + fileName); byte[] bArray = file.OpenBinary(); document.BucketName = "pdfs"; document.CommentID = ""; document.Comments = ""; document.Content_Bytes = bArray; document.Content_Ext = "pdf"; document.Content_Size = 0; document.Content_title = item["Title"].ToString(); document.Content_Type = ""; document.DocumentId = item.ID.ToString(); document.DocumentTitle = ""; document.DownloadFilePath = fileName; document.FileId = ""; document.Mode = "initial"; document.Mongo_FileId1 = ""; document.Mongo_FileId2 = ""; document.Mongo_FileId3 = ""; document.Mongo_FileId4 = ""; document.Mongo_FileId5 = ""; document.Mongo_Meta = ""; document.NumFiles = 1; document.PHID = item["PolicyHolder_ID"].ToString(); document.PMID = ""; document.SharePoint_FileId1 = item["PolicyHolder_SocialSecurityNumbe"].ToString(); document.SharePoint_FileId2 = item["PolicyHolder_LastName"].ToString(); document.SharePoint_FileId3 = item["PolicyHolder_FirstName"].ToString(); document.SharePoint_FileId4 = item["PolicyHolder_ID"].ToString(); document.SharePoint_FileId5 = ""; document.SharePoint_Meta = ""; document.UploadFilePath = "migration"; document.Content_Date = Convert.ToDateTime(dtIn); document.DocumentDate = Convert.ToDateTime(dtIn); document.Import_Date = Convert.ToDateTime(dtIn); Handlers.DocumentHandler handler = new Handlers.DocumentHandler(document); ClearDocumentProperties(document); //document.BucketName = "pdfs"; //document.FileExt = "pdf"; //document.NumFiles = 1; //document.UploadFilePath = fileName; //document.Content = bArray; } } } } return(nResult); }
private static IEnumerable <SPFile> GetAttachments(SPFolder attachmentsFolder, SPAttachmentCollection listItemAttachments) { return(from string file in listItemAttachments select attachmentsFolder.Files[file]); }