private async void OpenAttachment(FileAttachment item) { using (new Loading(this)) { await UI.OpenAttachment(item); } }
public ProxyResponse<InsertAttachmentResult> AddAttachment(FileAttachment attachment) { OperationMethod = HttpMethod.Post; _requestPrefix = ResourceNames.InvoiceAttachment; var uri = base.GetRequestUri(string.Empty,HttpMethod.Post); return base.GetResponse<FileAttachment, InsertAttachmentResult>(uri, attachment); }
public FileShareDocument(string name, string path) { Attachment = new FileAttachment(path); var fileInfo = new FileInfo(path); CreationTime = fileInfo.CreationTime; SetACLForFile(fileInfo); Name = name; NameHashed = HashName(name); }
private async void DeleteAttachment(FileAttachment item) { if (!string.IsNullOrEmpty(item.Id)) { using (new Loading(this)) { await GraphService.DeleteEventAttachment(_eventId, item.Id); } } Items.Remove(item); UI.Publish(item); }
public CardsAddFileAttachmentRequest(ICardId card, FileAttachment attachment) : base(card, "attachments", Method.POST) { Guard.NotNull(attachment, "attachment"); Guard.NotNullOrEmpty(attachment.FilePath, "attachment.FilePath"); if (!string.IsNullOrEmpty(attachment.Name)) { Guard.LengthBetween(attachment.Name, 0, 256, "attachment.Name"); AddParameter("name", attachment.Name); } AddFile("file", attachment.FilePath); }
public void AddAttachment(string filepath) { using (var reader = new StreamReader(filepath)) { var contents = reader.ReadToEnd(); var bytes = System.Text.Encoding.Unicode.GetBytes(contents); var name = filepath.Split('\\').Last(); var fileAttachment = new FileAttachment { ContentBytes = bytes, Name = name, }; HttpUtilSync.PostItem(Uri + "/attachments", fileAttachment); } }
public void AddAttachment(string filepath) { using (var reader = new StreamReader(filepath)) { var contents = reader.ReadToEnd(); var msgFetcher = _outlookClient.Me.Messages.GetById(_message.Id); var bytes = System.Text.Encoding.Unicode.GetBytes(contents); var name = filepath.Split('\\').Last(); var fileAttachment = new FileAttachment { ContentBytes = bytes, Name = name, Size = bytes.Length }; msgFetcher.Attachments.AddAttachmentAsync(fileAttachment).GetResult(); } }
internal static async Task OpenAttachment(FileAttachment item) { DependencyService.Get <IAttachmentOpener>().Open(item); await Task.FromResult(0); }
/// <summary> /// Sends the attachment asynchronous. /// </summary> /// <param name="userId">The user identifier.</param> /// <param name="stream">The stream.</param> /// <param name="filename">The filename.</param> /// <param name="mimeType">Type of the MIME.</param> /// <param name="type">The type.</param> /// <returns></returns> public async Task <MessageResult> SendFileAttachmentAsync(string userId, Stream stream, string filename, string mimeType, string type = "file") { var attachment = (Attachment)null; switch (type) { case "image": attachment = new ImageAttachment(); break; case "video": attachment = new VideoAttachment(); break; case "audio": attachment = new AudioAttachment(); break; default: attachment = new FileAttachment(); break; } (attachment as Attachment <MediaPayload>).Payload.IsReusable = true; var result = new MessageResult(); try { using (var client = new HttpClient()) { client.Timeout = TimeSpan.FromMinutes(5); using (var content = new MultipartFormDataContent()) { var recipient = JsonConvert.SerializeObject(new Identity(userId)); var message = JsonConvert.SerializeObject(new AttachmentMessage(attachment)); content.Add(new StringContent(recipient), "recipient"); content.Add(new StringContent(message), "message"); var fileContent = new StreamContent(stream); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType); content.Add(fileContent, "filedata", filename); using (var response = await client.PostAsync($"https://graph.facebook.com/v{_apiVersion}/me/messages?access_token={_accessToken}", content)) { if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.BadRequest) { result.Success = false; result.Error = new ResultError { Code = -1, ErrorSubcode = (int)response.StatusCode, Message = response.ReasonPhrase ?? response.StatusCode.ToString(), }; } else { var returnValue = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); result.Error = CreateResultError(returnValue); if (result.Error == null) { result.RecipientId = returnValue.Value <string>("recipient_id"); result.MessageId = returnValue.Value <string>("message_id"); result.AttachmentId = returnValue.Value <string>("attachment_id"); result.Success = true; } } } } } } catch (Exception ex) { HandleException(ex, result); } return(result); }
public ActionResult AddTicketComments(TicketPresenter ticketPresenter) { if (ticketPresenter != null && ticketPresenter.TicketDetails != null && ticketPresenter.TicketDetail.TicketId > 0 && SessionData.Instance.UserInfo != null && SessionData.Instance.UserInfo.Developer != null) { if (!string.IsNullOrEmpty(ticketPresenter.CommentAttachmentId)) { var attachmentIds = ticketPresenter.CommentAttachmentId.Split(','); foreach (var attachmentId in attachmentIds) { var attachmentsids = attachmentId.Split('~'); var attachments = new FileAttachment { FileAttachmentId = Convert.ToInt32(attachmentsids[0]), FileName = attachmentsids[1] }; ticketPresenter.Comment.FileAttachments.Add(attachments); } } ticketPresenter.Comment.DeveloperId = SessionData.Instance.UserInfo.Developer.DeveloperID; ticketPresenter.Comment.TicketId = ticketPresenter.TicketDetail.TicketId; ticketPresenter.Comment.DeveloperName = SessionData.Instance.UserInfo.FirstName + SessionData.Instance.UserInfo.LastName; this.ticketService.PostComment(ticketPresenter.Comment, SessionData.Instance.UserInfo.Developer.DeveloperID); var updatedTicketInfo = this.ticketService.RetrieveTicketDetails(ticketPresenter.Comment.TicketId.ToString(), SessionData.Instance.UserInfo.Developer.DeveloperID.ToString()); if (updatedTicketInfo != null) { ticketPresenter.AssignTicketComment(updatedTicketInfo.Comments); } return this.PartialView(TicketCommentsContainer, ticketPresenter); } return this.Json(string.Empty); }
// Token: 0x06000767 RID: 1895 RVA: 0x00029340 File Offset: 0x00027540 protected override int InternalExecute(int count) { string[] array = HttpUtility.UrlDecode(base.FileReference).Split(new char[] { ':' }); if (array.Length != 2) { throw new AirSyncPermanentException(StatusCode.Sync_TooManyFolders, false) { ErrorStringForProtocolLogger = "InvalidEntityAttachemtnId" }; } StoreObjectId itemId = StoreId.EwsIdToStoreObjectId(array[0]); IEvents events = EntitySyncItem.GetEvents(this.CalendaringContainer, base.Session, itemId); if (events == null) { throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false) { ErrorStringForProtocolLogger = "EventsNotFound" }; } IAttachments attachments = events[array[0]].Attachments; if (attachments == null) { throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false) { ErrorStringForProtocolLogger = "EntityNotFound" }; } IAttachment attachment = attachments.Read(array[1], null); if (attachment == null) { throw new AirSyncPermanentException(StatusCode.Sync_ClientServerConversion, false) { ErrorStringForProtocolLogger = "EntityAttachementNotFound" }; } base.ContentType = attachment.ContentType; FileAttachment fileAttachment = attachment as FileAttachment; ItemAttachment itemAttachment = attachment as ItemAttachment; if (fileAttachment != null) { if (!base.MaxAttachmentSize.IsUnlimited && fileAttachment.Content.Length > (int)base.MaxAttachmentSize.Value.ToBytes()) { throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge); } count = ((count == -1) ? fileAttachment.Content.Length : Math.Min(count, fileAttachment.Content.Length - base.MinRange)); base.OutStream.Write(fileAttachment.Content, base.MinRange, count); return(count); } else { if (itemAttachment != null) { int result; AttachmentHelper.GetAttachment(base.Session, itemId, attachment.Id, base.OutStream, base.MinRange, count, base.MaxAttachmentSize, base.RightsManagementSupport, out result); return(result); } throw new AirSyncPermanentException(StatusCode.Sync_InvalidWaitTime, new LocalizedString(string.Format("Attachment type \"{0}\" is not supported.", attachment.GetType().FullName)), false) { ErrorStringForProtocolLogger = "UnsupportedEntityAttachementType" }; } }
/// <summary> /// Initializes a new instance of the <see cref="ExchangeEmailAttachment" /> class. /// </summary> /// <param name="attachment">The attachment retrieved from the Exchange server.</param> /// <exception cref="ArgumentNullException"><paramref name="attachment" /> is null.</exception> internal ExchangeEmailAttachment(FileAttachment attachment) { _attachment = attachment ?? throw new ArgumentNullException(nameof(attachment)); FileName = attachment.Name; }
private bool Equals(FileAttachment fa) { return(string.Equals(Filename, fa.Filename) && string.Equals(DisplayName, fa.DisplayName) && string.Equals(MimeType, fa.MimeType)); }
/// <summary> Sends a message to the channel for this webhook with an attachment. </summary> /// <returns> Returns the ID of the created message. </returns> public Task <ulong> SendFileAsync(FileAttachment attachment, string text, bool isTTS = false, IEnumerable <Embed> embeds = null, string username = null, string avatarUrl = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageComponent components = null) => WebhookClientHelper.SendFileAsync(this, attachment, text, isTTS, embeds, username, avatarUrl, allowedMentions, components, options);
private bool SetFormFromContact(Contact oContact) { bool bRet = false; ClearForm(); txtGivenName.Text = oContact.GivenName; txtMiddleName.Text = oContact.MiddleName; txtSurname.Text = oContact.Surname; txtCompanyName.Text = oContact.CompanyName; txtJobTitle.Text = oContact.JobTitle; txtNotes.Text = oContact.Body.Text; //if (oContact.HasPicture) //{ // FileAttachment oFileAttachment = null; // System.IO.Stream oStream = null; // oFileAttachment = oContact.GetContactPictureAttachment(); // oFileAttachment.Load(oStream ); // // pbContactPhoto.Image = Image.FromStream(oStream); // // For saving image: // // http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/6be416f7-c8f0-425c-879c-7954c572afc8#662c7497-3898-42dc-8bd4-3dd168724a3f // //// Stream attachment contents into a file. // //FileStream theStream = new FileStream("C:\\temp\\Stream_" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite); // //fileAttachment.Load(theStream); // //theStream.Close(); // //theStream.Dispose(); // // http://support.microsoft.com/kb/317701 //} FileAttachment oFileAttachment = null; // Note that you need to have ContactSchema.Attachments loaded you will get a general error... oFileAttachment = _Contact.GetContactPictureAttachment(); if (oFileAttachment != null) { System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream(); oFileAttachment.Load(oMemoryStream); pbContactPhoto.Image = Image.FromStream(oMemoryStream); } string sInfo = string.Empty; foreach (Attachment oAttachment in oContact.Attachments) { oFileAttachment = oAttachment as FileAttachment; sInfo += "Name: " + oAttachment.Name; sInfo += "\r\nIsInline: " + oAttachment.IsInline.ToString(); if (oFileAttachment.IsContactPhoto) { sInfo += "\r\nIsContactPhoto: True"; } else { sInfo += "\r\nIsContactPhoto: False"; } sInfo += "\r\nSize: " + oAttachment.Size.ToString(); sInfo += "\r\nId: " + oAttachment.Id; sInfo += "\r\nContentId: " + oAttachment.ContentId; sInfo += "\r\nContentLocation: " + oAttachment.ContentLocation; sInfo += "\r\nContentType: " + oAttachment.ContentType; sInfo += "\r\nLastModifiedTime: " + oAttachment.LastModifiedTime.ToString(); sInfo += "\r\nContentId: " + oAttachment.ContentId; sInfo += "\r\nContentType: " + oAttachment.ContentType; sInfo += "\r\n--------------------\r\n"; // This is another way to get at the Contact Photo if (oFileAttachment.IsContactPhoto) { // Note that you need to have ContactSchema.Attachments loaded or you will get nothing back. //System.IO.MemoryStream oMemoryStreamx = new System.IO.MemoryStream(); //oFileAttachment.Load(oMemoryStream); //pbContactPhoto.Image = Image.FromStream(oMemoryStreamx); //oMemoryStream = null; } oFileAttachment = null; this.txtAttachments.Text = sInfo; _isDirty = false; } PhysicalAddressEntry oPhysicalAddress = null; if (oContact.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Business, out oPhysicalAddress)) { txtBA_Street.Text = oPhysicalAddress.Street; txtBA_City.Text = oPhysicalAddress.City; txtBA_State.Text = oPhysicalAddress.State; txtBA_PostalCode.Text = oPhysicalAddress.PostalCode; txtBA_CountryOrRegion.Text = oPhysicalAddress.CountryOrRegion; } if (oContact.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Home, out oPhysicalAddress)) { txtHA_Street.Text = oPhysicalAddress.Street; txtHA_City.Text = oPhysicalAddress.City; txtHA_State.Text = oPhysicalAddress.State; txtHA_PostalCode.Text = oPhysicalAddress.PostalCode; txtHA_CountryOrRegion.Text = oPhysicalAddress.CountryOrRegion; } if (oContact.PhysicalAddresses.TryGetValue(PhysicalAddressKey.Other, out oPhysicalAddress)) { txtOA_Street.Text = oPhysicalAddress.Street; txtOA_City.Text = oPhysicalAddress.City; txtOA_State.Text = oPhysicalAddress.State; txtOA_PostalCode.Text = oPhysicalAddress.PostalCode; txtOA_CountryOrRegion.Text = oPhysicalAddress.CountryOrRegion; } bool bSet = false; //Makes setting values for copied lines of code easier. txtEmailAddress1_Address.Enabled = bSet; txtEmailAddress1_Name.Enabled = bSet; txtEmailAddress1_MailboxType.Enabled = bSet; txtEmailAddress1_RoutingType.Enabled = bSet; txtEmailAddress1_MailboxType.Enabled = bSet; txtEmailAddress1_Id_UniqueId.Enabled = bSet; txtEmailAddress1_Id_ChangeKey.Enabled = bSet; txtEmailAddress2_Address.Enabled = bSet; txtEmailAddress2_Name.Enabled = bSet; txtEmailAddress2_MailboxType.Enabled = bSet; txtEmailAddress2_RoutingType.Enabled = bSet; txtEmailAddress2_MailboxType.Enabled = bSet; txtEmailAddress2_Id_UniqueId.Enabled = bSet; txtEmailAddress2_Id_ChangeKey.Enabled = bSet; txtEmailAddress3_Address.Enabled = bSet; txtEmailAddress3_Name.Enabled = bSet; txtEmailAddress3_MailboxType.Enabled = bSet; txtEmailAddress3_RoutingType.Enabled = bSet; txtEmailAddress3_MailboxType.Enabled = bSet; txtEmailAddress3_Id_UniqueId.Enabled = bSet; txtEmailAddress3_Id_ChangeKey.Enabled = bSet; EmailAddress oEmailAddress = null; if (oContact.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress1, out oEmailAddress)) { txtEmailAddress1_Address.Text = oEmailAddress.Address; txtEmailAddress1_Name.Text = oEmailAddress.Name; txtEmailAddress1_MailboxType.Text = oEmailAddress.MailboxType.ToString(); txtEmailAddress1_RoutingType.Text = oEmailAddress.RoutingType; txtEmailAddress1_MailboxType.Text = oEmailAddress.MailboxType.Value.ToString(); if (oEmailAddress.Id != null) { txtEmailAddress1_Id_UniqueId.Text = oEmailAddress.Id.UniqueId; txtEmailAddress1_Id_ChangeKey.Text = oEmailAddress.Id.ChangeKey; } else { txtEmailAddress1_Id_UniqueId.Text = ""; txtEmailAddress1_Id_ChangeKey.Text = ""; } bSet = false; // Make read-only until the code can be enhanced. txtEmailAddress1_Address.Enabled = bSet; txtEmailAddress1_Name.Enabled = bSet; txtEmailAddress1_MailboxType.Enabled = bSet; txtEmailAddress1_RoutingType.Enabled = bSet; txtEmailAddress1_MailboxType.Enabled = bSet; txtEmailAddress1_Id_UniqueId.Enabled = false; txtEmailAddress1_Id_ChangeKey.Enabled = false; } if (oContact.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress2, out oEmailAddress)) { txtEmailAddress2_Address.Text = oEmailAddress.Address; txtEmailAddress2_Name.Text = oEmailAddress.Name; txtEmailAddress2_MailboxType.Text = oEmailAddress.MailboxType.ToString(); txtEmailAddress2_RoutingType.Text = oEmailAddress.RoutingType; txtEmailAddress2_MailboxType.Text = oEmailAddress.MailboxType.Value.ToString(); if (oEmailAddress.Id != null) { txtEmailAddress2_Id_UniqueId.Text = oEmailAddress.Id.UniqueId; txtEmailAddress2_Id_ChangeKey.Text = oEmailAddress.Id.ChangeKey; } else { txtEmailAddress2_Id_UniqueId.Text = ""; txtEmailAddress2_Id_ChangeKey.Text = ""; } bSet = false; // Make read-only until the code can be enhanced. txtEmailAddress2_Address.Enabled = bSet; txtEmailAddress2_Name.Enabled = bSet; txtEmailAddress2_MailboxType.Enabled = bSet; txtEmailAddress2_RoutingType.Enabled = bSet; txtEmailAddress2_MailboxType.Enabled = bSet; txtEmailAddress2_Id_UniqueId.Enabled = false; txtEmailAddress2_Id_ChangeKey.Enabled = false; } if (oContact.EmailAddresses.TryGetValue(EmailAddressKey.EmailAddress3, out oEmailAddress)) { txtEmailAddress3_Address.Text = oEmailAddress.Address; txtEmailAddress3_Name.Text = oEmailAddress.Name; txtEmailAddress3_MailboxType.Text = oEmailAddress.MailboxType.ToString(); txtEmailAddress3_RoutingType.Text = oEmailAddress.RoutingType; txtEmailAddress3_MailboxType.Text = oEmailAddress.MailboxType.Value.ToString(); if (oEmailAddress.Id != null) { txtEmailAddress3_Id_UniqueId.Text = oEmailAddress.Id.UniqueId; txtEmailAddress3_Id_ChangeKey.Text = oEmailAddress.Id.ChangeKey; } else { txtEmailAddress3_Id_UniqueId.Text = ""; txtEmailAddress3_Id_ChangeKey.Text = ""; } bSet = false; // Make read-only until the code can be enhanced. txtEmailAddress3_Address.Enabled = bSet; txtEmailAddress3_Name.Enabled = bSet; txtEmailAddress3_MailboxType.Enabled = bSet; txtEmailAddress3_RoutingType.Enabled = bSet; txtEmailAddress3_MailboxType.Enabled = bSet; txtEmailAddress3_Id_UniqueId.Enabled = false; txtEmailAddress3_Id_ChangeKey.Enabled = false; } string sValue = "Not Set"; //sValue = oContact.PostalAddressIndex.ToString(); // bool bHasValue = false; try { // [Microsoft.Exchange.WebServices.Data.ServiceObjectPropertyException] = {"This property was requested, but it wasn't returned by the server."} // Message = "This property was requested, but it wasn't returned by the server." sValue = oContact.PostalAddressIndex.ToString(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); //MessageBox.Show(ex.ToString()); } //PostalAddressIndex.ToString((PostalAddressIndexType)PostalAddressIndex.) if (sValue != "Not Set") { switch (sValue) { case "None": this.cmboPostalAddressIndex.Text = "None"; break; case "Other": this.cmboPostalAddressIndex.Text = "Other"; break; case "Home": this.cmboPostalAddressIndex.Text = "Home"; break; case "Business": this.cmboPostalAddressIndex.Text = "Business"; break; } } else { this.cmboPostalAddressIndex.Text = "Not Set"; } ////x = (int)oContact.PostalAddressIndex.Value; ////if (oContact.PostalAddressIndex != null) //if (sValue != null) //{ // switch (oContact.PostalAddressIndex.Value) // { // case PhysicalAddressIndex.None: // this.cmboPostalAddressIndex.Text = "None"; // break; // case PhysicalAddressIndex.Other: // this.cmboPostalAddressIndex.Text = "Other"; // break; // case PhysicalAddressIndex.Home: // this.cmboPostalAddressIndex.Text = "Home"; // break; // case PhysicalAddressIndex.Business: // this.cmboPostalAddressIndex.Text = "Business"; // break; // } //} //else //{ // this.cmboPostalAddressIndex.Text = "Not Set"; //} bRet = true; return(bRet); }
/// <summary> /// Method to add a file attachment to a saved draft. /// </summary> /// <param name="MessageId"></param> /// <param name="fileContent"></param> /// <returns>Success.</returns> internal async Task AddFileAttachmentAsync(string MessageId, MemoryStream fileContent, string fileName) { // Make sure we have a reference to the Outlook Services client. var outlookClient = await AuthenticationHelper.GetOutlookClientAsync("Mail"); var attachment = new FileAttachment(); attachment.ContentBytes = fileContent.ToArray(); attachment.Name = fileName; attachment.Size = fileContent.ToArray().Length; attachment.ContentType = "image/png"; try { var storedMessage = outlookClient.Me.Messages.GetById(MessageId); await storedMessage.Attachments.AddAttachmentAsync(attachment); await storedMessage.SendAsync(); Debug.WriteLine("Added attachment to message: " + MessageId); return; } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return; } }
public Example_01() { PDF pdf = new PDF(new BufferedStream( new FileStream("Example_01.pdf", FileMode.Create))); pdf.SetTitle("Hello"); pdf.SetAuthor("Eugene"); pdf.SetSubject("Example"); pdf.SetKeywords("Hello World This is a test"); pdf.SetCreator("Application Name"); String fileName = "linux-logo.png"; EmbeddedFile file1 = new EmbeddedFile( pdf, fileName, new FileStream("images/" + fileName, FileMode.Open, FileAccess.Read), false); // Don't compress images. fileName = "Example_02.cs"; EmbeddedFile file2 = new EmbeddedFile( pdf, fileName, new FileStream(fileName, FileMode.Open, FileAccess.Read), true); // Compress text files. Page page = new Page(pdf, Letter.PORTRAIT); Box flag = new Box(); flag.SetLocation(100.0f, 100.0f); flag.SetSize(190.0f, 100.0f); flag.SetColor(Color.white); flag.DrawOn(page); float[] xy = new float[] { 0f, 0f }; float sw = 7.69f; // stripe width Line stripe = new Line(0.0f, sw / 2, 190.0f, sw / 2); stripe.SetWidth(sw); stripe.SetColor(Color.oldgloryred); for (int row = 0; row < 7; row++) { stripe.PlaceIn(flag, 0.0f, row * 2 * sw); xy = stripe.DrawOn(page); } Box union = new Box(); union.SetSize(76.0f, 53.85f); union.SetColor(Color.oldgloryblue); union.SetFillShape(true); union.PlaceIn(flag, 0.0f, 0.0f); union.DrawOn(page); float h_si = 12.6f; // horizontal star interval float v_si = 10.8f; // vertical star interval Point star = new Point(h_si / 2, v_si / 2); star.SetShape(Point.STAR); star.SetRadius(3.0f); star.SetColor(Color.white); star.SetFillShape(true); for (int row = 0; row < 6; row++) { for (int col = 0; col < 5; col++) { star.PlaceIn(union, row * h_si, col * v_si); xy = star.DrawOn(page); } } star.SetLocation(h_si, v_si); for (int row = 0; row < 5; row++) { for (int col = 0; col < 4; col++) { star.PlaceIn(union, row * h_si, col * v_si); star.DrawOn(page); } } FileAttachment attachment = new FileAttachment(pdf, file1); attachment.SetLocation(100f, 300f); attachment.SetIconPushPin(); attachment.SetIconSize(24f); attachment.SetTitle("Attached File: " + file1.GetFileName()); attachment.SetDescription( "Right mouse click or double click on the icon to save the attached file."); attachment.DrawOn(page); attachment = new FileAttachment(pdf, file2); attachment.SetLocation(200f, 300f); attachment.SetIconPaperclip(); attachment.SetIconSize(24f); attachment.SetTitle("Attached File: " + file2.GetFileName()); attachment.SetDescription( "Right mouse click or double click on the icon to save the attached file."); attachment.DrawOn(page); pdf.Close(); }
static void saveFileAttachment(FileAttachment attachment, String fileName) { FileStream fs = File.Create(fileName); BinaryWriter writer = new BinaryWriter(fs); writer.Write(attachment.Data); writer.Close(); fs.Close(); var inputStream = new MemoryStream(attachment.Data); MemoryStream data = new MemoryStream(); using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(inputStream)) { zip[0].Extract(data); } data.Seek(0, SeekOrigin.Begin); var xml = Encoding.UTF8.GetString(data.ToArray()); DownloaedFile = xml.Replace("encoding=\"utf-8\"?", "encoding=\"utf-16\"?"); }
static FileAttachment getFileAttachment(String content) { FileAttachment attachment = new FileAttachment(); var memorysteam = compress(content); attachment.Data = memorysteam.ToArray(); attachment.SizeSpecified = true; attachment.Size = attachment.Data.Length; return attachment; }
private void cmsEmbededItemsAttachmentsSaveAs_Click(object sender, EventArgs e) { if (lvEmbededItemsAttachments.SelectedItems.Count > 0) { int iAttachment = 0; string SelectedFile = string.Empty; iAttachment = (int)lvEmbededItemsAttachments.SelectedItems[0].Tag; if (_Item.Attachments[iAttachment] is FileAttachment) { FileAttachment oFileAttachment = (FileAttachment)_Item.Attachments[iAttachment]; if (UserIoHelper.PickSaveFileToFolder(oFileAttachment.Name, ref SelectedFile)) { _Item.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID oFileAttachment.Load((SelectedFile)); } } //if (_Item.Attachments[iAttachment] is ItemAttachment) //{ // ItemAttachment oAttachment = (ItemAttachment)_Item.Attachments[iAttachment]; // ItemAttachment oItemAttachment = oAttachment as ItemAttachment; // oItemAttachment.Load(); // Load attachment into memory so we can get to the item properties (such as subject). // //_EwsCaller.GetItemMime( // //PropertySet oMimePropertySet = new PropertySet(ItemSchema.MimeContent); // //Item oAttachmentItem = Item.Bind(_ExchangeService, oItemAttachment.Id, oMimePropertySet); // //string sStuff = oAttachmentItem.MimeContent.ToString() ; // // string sStuff = _EwsCaller.GetItemMime(oItemAttachment.Id); // //oAttachmentItem. // //EmailMessage email = EmailMessage.Bind(es, current.Id) ; // //Attachment x = (Attachment)ItemAttachment; // // TODO: Get it working. // // Should be able to get the stream of the attachment and save it... // //oItemAttachment = _Item.Service.FileAttachmentContentHandler // //Item oxItem = (Item)oItemAttachment; // if (UserIoHelper.PickSaveFileToFolder(oItemAttachment.Item.Subject + ".msg", ref SelectedFile)) // { // byte[] MimeBytes = oItemAttachment.Item.MimeContent.Content; // System.IO.File.WriteAllBytes(SelectedFile, MimeBytes); // //PropertySet mimeSet = new PropertySet(BasePropertySet.IdOnly); // //mimeSet.Add(EmailMessageSchema.MimeContent); // //mimeSet.Add(EmailMessageSchema.Subject); // //FileAttachment fileAttachment = oItemAttachment as FileAttachment; // //FileAttachment oFileAttachment = (FileAttachment)oItemAttachment; // //MemoryStream oMemoryStream = new MemoryStream(); // //oFileAttachment.Load(oMemoryStream); // //StreamReader oStreamReader = new StreamReader(oMemoryStream); // //oMemoryStream.Seek(0, SeekOrigin.Begin); // //byte[] bytes = oMemoryStream.GetBuffer(); // //PropertySet oMimePropertySet = new PropertySet(ItemSchema.MimeContent); // //oItem.Load(oMimePropertySet); // //sReturn = oItem.MimeContent.ToString(); // //Attachment oA = (Attachment)_Item.Attachments[iAttachment]; // //FileAttachment oFA = (FileAttachment)oA; // // System.IO.File.WriteAllBytes(SelectedFile, oItemAttachment.Item.Copy(); // //oFA.Load(SelectedFile); // //FileStream theStream = new FileStream("C:\\testx\\Stream_" + SelectedFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); // //theStream.w // //theStream.Close(); // //theStream.Dispose(); // //System.IO.File.WriteAllBytes("C:\\testx\\Stream_" + SelectedFile, (bytes[])sStuff.ToCharArray()); // } // } } }
public static Task <ulong> SendFileAsync(DiscordWebhookClient client, FileAttachment attachment, string text, bool isTTS, IEnumerable <Embed> embeds, string username, string avatarUrl, AllowedMentions allowedMentions, MessageComponent components, RequestOptions options) => SendFilesAsync(client, new FileAttachment[] { attachment }, text, isTTS, embeds, username, avatarUrl, allowedMentions, components, options);
public Task AddAttachment(ICardId card, FileAttachment attachment) { return(_restClient.RequestAsync(new CardsAddFileAttachmentRequest(card, attachment))); }
public async Task <FileAttachment> UploadFile(int serviceRequestId, FileAttachment fileAttachment) { FileAttachment uploadedFileAttachment = null; using (var client = new HttpClient()) { client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json"); client.DefaultRequestHeaders.TryAddWithoutValidation("app-jwt", this.jwt); client.DefaultRequestHeaders.TryAddWithoutValidation("api-key", this.api_key); client.BaseAddress = new Uri(this.baseURL); ByteArrayContent content = new ByteArrayContent(fileAttachment.Data); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); string subUrl = "file-attachments?serviceRequestId=" + serviceRequestId + "&filename=" + fileAttachment.EscapedName + "&contentType=application/octet-stream&size=" + fileAttachment.Size; try { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; System.Net.ServicePointManager.Expect100Continue = false; HttpResponseMessage response = client.PostAsync(subUrl, (HttpContent)content).GetAwaiter().GetResult(); if (response.StatusCode == HttpStatusCode.OK) { uploadedFileAttachment = await(Task <FileAttachment>) HttpContentExtensions.ReadAsAsync <FileAttachment>(response.Content); } if (response.StatusCode == HttpStatusCode.BadRequest) { uploadedFileAttachment = await(Task <FileAttachment>) HttpContentExtensions.ReadAsAsync <FileAttachment>(response.Content); uploadedFileAttachment.Name = fileAttachment.Name; uploadedFileAttachment.Id = -1; } response.EnsureSuccessStatusCode(); var status = response.StatusCode; } catch (WebException ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.InnerException); Debug.WriteLine(ex.StackTrace); } catch (HttpRequestException socketException) { Debug.WriteLine(socketException.Message); Debug.WriteLine(socketException.InnerException); Debug.WriteLine(socketException.StackTrace); throw new MtoaConnectionException("Unable to connect to MTOA services.", socketException); } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.InnerException); Debug.WriteLine(ex.StackTrace); } return(uploadedFileAttachment); } }
public bool DownloadFromExchange(string PathDownload, string Subject, string Filter, string Sender) { //cargar credenciales string Asunto; string _stage = ""; bool _isRead; bool _attachmentFound = false; EmailMessage _message; if (pExchange != null) { //El filtro de búsqueda para obtener correos electrónicos no leídos SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(50); // Se Activa la consulta de los elementos no leídos // Este método obtiene el resultado de la llamada FindItem a EWS. Con los correos sin leer FindItemsResults <Item> findResults = pExchange.FindItems(WellKnownFolderName.Inbox, sf, view); // Recorremos los correos no leídos foreach (Item item in findResults) { try { // Recorrer los mensajes _stage = "Find in messages"; _message = EmailMessage.Bind(pExchange, item.Id); // se carga el "message" busca por Id Asunto = _message.Subject.ToString(); // sacamos el Subject } catch (Exception ex) { Console.WriteLine($"[{_stage}]: {ex.Message}"); continue; } try { if (Regex.IsMatch(_message.From.ToString(), Sender) || Sender == "") { Console.WriteLine($"-> Checking sender: {_message.From}"); if (Asunto.Contains(Subject) || Subject == "") // se comprueba en los correos no leídos el asunto { Console.WriteLine($" -> Checking subject: {Asunto}"); _isRead = false; // foreach (Attachment att in _message.Attachments) { // Recorrer los adjuntos _stage = "Find in messages"; if (att is FileAttachment) { FileAttachment fileAttachment = att as FileAttachment; // Carga el archivo adjunto en un archivo //if (Filter == fileAttachment.Name.Substring((fileAttachment.Name.ToString().Length - 3), 3)) if (Regex.IsMatch(fileAttachment.Name.ToString(), Filter) || Filter == "") { Console.Write($" -> Checking attachment: {fileAttachment.Name} ..."); // Que guarda en la dirección indicada _stage = "Save File"; fileAttachment.Load(PathDownload + fileAttachment.Name); Console.WriteLine($" Downloaded OK!!"); _attachmentFound = true; pBody += $"- File {fileAttachment.Name.ToString()} found and stored.<br>"; if (!_isRead) { _stage = "Message update is read"; _message.IsRead = true; // lo marcamos como leído _message.Update(ConflictResolutionMode.AutoResolve); // Se envía al servidor el cambio realizado _isRead = true; Console.WriteLine($" -> Marked as read."); } } } } } } else { Console.WriteLine("-> No matches"); } } catch (Exception ex) { Console.WriteLine($"[{_stage}]: {ex.Message}"); continue; } } } return(_attachmentFound); }
/// <summary> /// Gets the latests posts for all subscriptions /// </summary> /// <returns></returns> public async Task GetLatestsPosts() { //Ensure module is enabled. if (!ModuleEnabled) { Console.WriteLine("Module disabled."); return; } if (InSubLoop) { //Prevents multiple loops running at once which could cause an instagram block. Console.WriteLine("Already in loop. Skipping."); return; } else { InSubLoop = true; } try { //Unsubscribe oversubs: await UnsubscribeOverSubscriptions(); Console.WriteLine("Getting new posts!"); var getdbfeed = await FollowedAccountsContainer.Find(_ => true).ToListAsync(); //Randomize the order of the IG accounts: Random rand = new Random(); getdbfeed.OrderBy(item => rand.Next()); foreach (var dbfeed in getdbfeed) { Console.WriteLine("Checking " + dbfeed.InstagramID); try { // Get IG account: InstagramProcessor instagram = new InstagramProcessor(InstagramProcessor.AccountFinder.GetIGAccount()); //Check to see if there is any channel that is subscribed to IG accounts: if (dbfeed.SubscribedChannels.Count == 0) { //If not, delete. await this.FollowedAccountsContainer.DeleteOneAsync(x => x.InstagramID == dbfeed.InstagramID); } else //Otherwise proceed: { //Set last check as now: dbfeed.LastCheckTime = DateTime.Now; var newIGPosts = await instagram.PostsSinceDate(long.Parse(dbfeed.InstagramID), dbfeed.LastPostDate); if (newIGPosts.Length > 0 && newIGPosts[newIGPosts.Length - 1].success) { //Set the most recent posts date: dbfeed.LastPostDate = newIGPosts[newIGPosts.Length - 1].postDate; } foreach (InstagramProcessorResponse response in newIGPosts) { List <RespondChannel> invalidChannels = new List <RespondChannel>(); foreach (RespondChannel subbedGuild in dbfeed.SubscribedChannels) { if (response.success) { //Create component builder: IGComponentBuilder component = new IGComponentBuilder(response); //Create embed response: IGEmbedBuilder embed = new IGEmbedBuilder(response); if (!response.success) { //Failed to process post: Console.WriteLine("Failed to process post."); return; } else if (response.isVideo) { if (response.stream != null) { //Response with stream: using (Stream stream = new MemoryStream(response.stream)) { FileAttachment attachment = new FileAttachment(stream, "IGMedia.mp4", "An Instagram Video."); // get channel: IMessageChannel chan = null; try { chan = _client.GetChannel(ulong.Parse(subbedGuild.ChannelID)) as IMessageChannel; } catch { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } if (chan != null) { //send message await chan.SendFileAsync(attachment, embed : embed.AutoSelector(), components : component.AutoSelector()); } else { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } } } else { //Response without stream: // get channel: IMessageChannel chan = null; try { chan = _client.GetChannel(ulong.Parse(subbedGuild.ChannelID)) as IMessageChannel; } catch { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } if (chan != null) { //send message await chan.SendMessageAsync(response.contentURL.ToString(), embed : embed.AutoSelector(), components : component.AutoSelector()); } else { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } } } else { if (response.stream != null) { using (Stream stream = new MemoryStream(response.stream)) { FileAttachment attachment = new FileAttachment(stream, "IGMedia.jpg", "An Instagram Image."); // get channel: IMessageChannel chan = null; try { chan = _client.GetChannel(ulong.Parse(subbedGuild.ChannelID)) as IMessageChannel; } catch { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } if (chan != null) { //send message await chan.SendFileAsync(attachment, embed : embed.AutoSelector(), components : component.AutoSelector()); } else { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } } } else { // get channel: IMessageChannel chan = null; try { chan = _client.GetChannel(ulong.Parse(subbedGuild.ChannelID)) as IMessageChannel; } catch { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } if (chan != null) { //send message try { await chan.SendMessageAsync(embed : embed.AutoSelector(), components : component.AutoSelector()); }catch (Exception e) { Console.WriteLine("Error sending subscription message. Error: " + e); invalidChannels.Add(subbedGuild); } } else { Console.WriteLine("Cannot find channel. Removing from DB."); invalidChannels.Add(subbedGuild); } } } } else if (response.error == "NullAccount") { Console.WriteLine("Removing null account: " + dbfeed.InstagramID); invalidChannels.Add(subbedGuild); } else { //TODO: Decide if the user should be informed or not. May create spam. Console.WriteLine("Failed auto post. ID: " + dbfeed.InstagramID); var chan = _client.GetChannel(ulong.Parse(subbedGuild.ChannelID)) as IMessageChannel; string igUsername = await instagram.GetIGUsername(dbfeed.InstagramID); await chan.SendMessageAsync("Failed to get latest posts for " + igUsername + ". Use `/unsubscribe " + igUsername + "` to remove the inaccessible account."); } } //Remove all invalid channels: invalidChannels.ForEach(item => dbfeed.SubscribedChannels.RemoveAll(c => c.ChannelID.Equals(item.ChannelID))); } //Update database: await this.FollowedAccountsContainer.ReplaceOneAsync(x => x.InstagramID == dbfeed.InstagramID, dbfeed, new ReplaceOptions { IsUpsert = true }); // Wait to prevent spamming IG api: // 10 seconds await Task.Delay(10000); } } catch (Exception e) { Console.WriteLine("Failed to get updates for IG account. Error: " + e); } } } catch (Exception e) { Console.WriteLine("Error with update loop: " + e); } finally { //Always mark as done loop when exiting: InSubLoop = false; Console.WriteLine("Done."); } }
private void AttachmentDeleted(FileAttachment item) { var removed = _attachments.FirstOrDefault(x => x.Name == item.Name); _attachments.Remove(removed); OnPropertyChanged(() => HasAttachments); }
public async void CreateNewMessage() { try { // split out the different email addresses and add to collection char[] delim = { ';' }; // handle To: string[] toArray = tbToRecipients.Text.Split(delim); foreach (var to in toArray) { AddRecipToCollection(to, toRecipients); } // handle Cc: string[] ccArray = tbCC.Text.Split(delim); foreach (var cc in toArray) { AddRecipToCollection(cc, ccRecipients); } // handle Bcc: string[] bccArray = tbBcc.Text.Split(delim); foreach (var bcc in toArray) { AddRecipToCollection(bcc, bccRecipients); } // create the item body ItemBody body = new ItemBody(); body.Content = rtbBody.Text; body.ContentType = BodyType.Html; // create the message object and add the properties Microsoft.Graph.Message msg = new Microsoft.Graph.Message(); msg.Subject = tbSubject.Text; msg.Body = body; msg.ToRecipients = toRecipients; msg.CcRecipients = ccRecipients; msg.BccRecipients = bccRecipients; // set importance if (cbxImportance.Text == "Normal") { msg.Importance = Importance.Normal; } else if (cbxImportance.Text == "High") { msg.Importance = Importance.High; } else { msg.Importance = Importance.Low; } // setup the attachment collection if (dgAttachments.Rows.Count > 0) { // setup the attachments collection msg.Attachments = new MessageAttachmentsCollectionPage(); // add attachments foreach (DataGridViewRow row in dgAttachments.Rows) { if (row.Cells[0].Value != null) { // create the file attachment from the file path FileAttachment file = new FileAttachment(); byte[] array = System.IO.File.ReadAllBytes(row.Cells[0].Value.ToString()); file.ContentBytes = array; file.Name = row.Cells[1].Value.ToString(); file.ContentType = row.Cells[2].Value.ToString(); file.ContentId = row.Cells[4].Value.ToString(); file.IsInline = false; file.ODataType = row.Cells[6].Value.ToString(); // add it to the message msg.Attachments.Add(file); } } } // log the request info sdklogger.Log(graphClient.Me.SendMail(msg, true).Request().GetHttpRequestMessage().Headers.ToString()); sdklogger.Log(graphClient.Me.SendMail(msg, true).Request().GetHttpRequestMessage().RequestUri.ToString()); // send the new message await graphClient.Me.SendMail(msg, true).Request().PostAsync(); } catch (Exception ex) { sdklogger.Log("NewMessageSend Failed: "); sdklogger.Log(ex.Message); sdklogger.Log(ex.StackTrace); } finally { // close the form Close(); } }
public void SendEmailSuportCoppy(string subject, string body, List <string> receivers, string sender, string Emailhead, FileAttachment attachmentFile) { var mail = new MailMessage(); foreach (var receive in receivers) { mail.To.Add(receive); } mail.From = new MailAddress(sender, Emailhead, System.Text.Encoding.UTF8); mail.Subject = subject; mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = body; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.IsBodyHtml = true; mail.Priority = MailPriority.High; if (attachmentFile?.Content != null) { var stream = new MemoryStream(attachmentFile.Content); var attachment = new Attachment(stream, attachmentFile.Name); mail.Attachments.Add(attachment); } var smtpUser = _configuration["StmpUser"]; var stmpPassword = _configuration["StmpPassword"]; var stmpHost = _configuration["StmpHost"]; var stmpPort = Convert.ToInt32(_configuration["StmpPort"]); using (var client = new SmtpClient()) { EmailConfigs(client, smtpUser, stmpPassword, stmpHost, stmpPort, false); client.Send(mail); } }
public void AddOrChangeForm(FileAttachment newAttachment) { FormContent = newAttachment.GetResourceAsByteArray(); FileName = newAttachment.Name; }
private static void SendEmails(string subject, string body, MailAddress from, IEnumerable<MailAddress> to, HttpPostedFile[] uploadedFiles) { if(string.IsNullOrEmpty(body)) { return; } var mail = new MailMessage { From = from, // #23 - explicitly set Reply-To field ReplyToList = { from }, Subject = subject ?? string.Empty, Body = body, IsBodyHtml = body.Contains("<html") || body.Contains("<body") || body.Contains("<div") }; foreach(var address in to) { mail.To.Add(address); } // we need to load the uploaded files into memory because they're disposed when the request ends var attachments = new List<FileAttachment>(); foreach(var file in uploadedFiles ?? new HttpPostedFile[0]) { var attachment = new FileAttachment { Name = file.FileName, ContentType = file.ContentType, Bytes = new byte[file.ContentLength] }; // #86 - make sure we start reading files at their origin (in case a custom index has been tampering with them) file.InputStream.Seek(0, SeekOrigin.Begin); file.InputStream.Read(attachment.Bytes, 0, file.ContentLength); attachments.Add(attachment); } // send the mail as fire-and-forget (pass the attachments as state) ThreadPool.QueueUserWorkItem(state => { foreach(var attachment in (IEnumerable<FileAttachment>)state) { mail.Attachments.Add(new Attachment(new MemoryStream(attachment.Bytes), attachment.Name, attachment.ContentType)); } try { using(var client = new SmtpClient()) { client.Send(mail); } } catch(Exception ex) { // NOTE: we're out of the request context here, but the logging still seems to work just fine Log.Error(ex, "Email could not be sent, see exception for details."); } }, attachments); }
private void SendEmails(string subject, string body, MailAddress from, IEnumerable <MailAddress> to, HttpPostedFile[] uploadedFiles, string emailType) { if (string.IsNullOrEmpty(body)) { return; } var mail = new MailMessage { From = from, // #23 - explicitly set Reply-To field ReplyToList = { from }, Subject = subject ?? string.Empty, Body = body, IsBodyHtml = body.Contains("<html") || body.Contains("<body") || body.Contains("<div") }; foreach (var address in to) { mail.To.Add(address); } // we need to load the uploaded files into memory because they're disposed when the request ends var attachments = new List <FileAttachment>(); foreach (var file in uploadedFiles ?? new HttpPostedFile[0]) { var attachment = new FileAttachment { Name = file.FileName, ContentType = file.ContentType, Bytes = new byte[file.ContentLength] }; // #86 - make sure we start reading files at their origin (in case a custom index has been tampering with them) file.InputStream.Seek(0, SeekOrigin.Begin); file.InputStream.Read(attachment.Bytes, 0, file.ContentLength); attachments.Add(attachment); } // #23 - raise an event before sending the mail if (BeforeSendMail != null) { try { var cancelEventArgs = new FormEditorMailCancelEventArgs(mail, emailType.ToLowerInvariant()); BeforeSendMail.Invoke(this, cancelEventArgs); if (cancelEventArgs.Cancel) { Log.Info("The {0} email was not sent because an event handler for BeforeSendMail cancelled the mail delivery.", emailType); return; } } catch (Exception ex) { // an event handler failed - log error and continue Log.Error(ex, "An event handler for BeforeSendMail threw an exception."); } } // send the mail as fire-and-forget (pass the attachments as state) ThreadPool.QueueUserWorkItem(state => { foreach (var attachment in (IEnumerable <FileAttachment>)state) { mail.Attachments.Add(new Attachment(new MemoryStream(attachment.Bytes), attachment.Name, attachment.ContentType)); } try { using (var client = new SmtpClient()) { client.Send(mail); } } catch (Exception ex) { // NOTE: we're out of the request context here, but the logging still seems to work just fine Log.Error(ex, "Email could not be sent, see exception for details."); } }, attachments); }
public async Task Link(string url, [Summary(description: "The post number for the desired post in a carousel.")][MinValue(1)] int index = 1, [Summary(description: "Set to true to mark the image/video and caption as a spoiler.")] bool HasSpoilers = false) { // Check whitelist: if (!Whitelist.IsServerOnList(((Context.Guild == null) ? (0) : (Context.Guild.Id)))) { // Self-hosted whitelist notification for official bot: if (Context.Client.CurrentUser.Id == 815695225678463017) { await RespondAsync("This bot is now self-host only. Learn more about this change in the updates channel on the support server: https://discord.gg/8dkjmGSbYE", ephemeral : true); } else { await RespondAsync("This guild is not on the whitelist. The command was blocked.", ephemeral : true); } return; } //Buy more time to process posts: await DeferAsync(false); // Get IG account: InstagramProcessor instagram = new InstagramProcessor(InstagramProcessor.AccountFinder.GetIGAccount()); //Process Post: InstagramProcessorResponse response = await instagram.PostRouter(url, Context.Guild, index); if (!response.success) { //Failed to process post: await FollowupAsync(response.error, ephemeral : true); return; } //Create embed builder: IGEmbedBuilder embed = new IGEmbedBuilder(response, Context.User.Username, HasSpoilers); //Create component builder: IGComponentBuilder component = new IGComponentBuilder(response, Context.User.Id); if (response.isVideo) { if (response.stream != null) { //Response with stream: using (Stream stream = new MemoryStream(response.stream)) { FileAttachment attachment = new FileAttachment(stream, "IGMedia.mp4", "An Instagram Video.", isSpoiler: HasSpoilers); await Context.Interaction.FollowupWithFileAsync(attachment, embed : embed.AutoSelector(), components : component.AutoSelector()); } } else { //Response without stream: await FollowupAsync(response.contentURL.ToString(), embed : embed.AutoSelector(), components : component.AutoSelector()); } } else { if (response.stream != null) { using (Stream stream = new MemoryStream(response.stream)) { FileAttachment attachment = new FileAttachment(stream, "IGMedia.jpg", "An Instagram Image.", isSpoiler: HasSpoilers); await Context.Interaction.FollowupWithFileAsync(attachment, embed : embed.AutoSelector(), allowedMentions : AllowedMentions.None, components : component.AutoSelector()); } } else { await FollowupAsync(embed : embed.AutoSelector(), components : component.AutoSelector()); } } }
/// <summary> /// Search the Inbox for the first unread email with an attachment matching the specified regular expression, and if found, download the attachment to the specified directory. /// </summary> /// <param name="attachmentNamePattern">The attachment filename pattern to search for.</param> /// <param name="targetDirectory">The (writable) directory where a found attachment will be saved.</param> /// <returns>True if a matching attachment was found and downloaded. False otherwise.</returns> /// <remarks> /// If the <paramref name="targetDirectory"/> does not exist, it will be created before searching for an attachment to download. /// </remarks> /// <exception cref="ArgumentNullException">Thrown if the <paramref name="attachmentNamePattern"/> regular expression is null.</exception> public virtual bool DownloadAttachment(Regex attachmentNamePattern, string targetDirectory) { if (attachmentNamePattern == null) { throw new ArgumentNullException("attachmentNamePattern"); } //we don't know how many items we'll have to search (likely nowhere near int.MaxValue) ItemView view = new ItemView(int.MaxValue); //we want the most recently received item view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); //load the properties required to perform a search for the attachment view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead, EmailMessageSchema.HasAttachments); //build the search filter SearchFilter filter = new SearchFilter.SearchFilterCollection( LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), new SearchFilter.IsEqualTo(EmailMessageSchema.HasAttachments, true) ); //perform the search and return the results as EmailMessage objects #if NET45 var results = Inbox.FindItems(filter, view).Cast <EmailMessage>(); #elif NETSTANDARD var results = Inbox.FindItems(filter, view).Result.Cast <EmailMessage>(); #endif bool foundAttachment = false; foreach (var result in results) { //another call to EWS to actually load in this email's attachment collection #if NET45 var email = EmailMessage.Bind(exchangeService, result.Id, new PropertySet(EmailMessageSchema.Attachments)); #elif NETSTANDARD var email = EmailMessage.Bind(exchangeService, result.Id, new PropertySet(EmailMessageSchema.Attachments)).Result; #endif foreach (var attachment in email.Attachments) { if (attachmentNamePattern.IsMatch(attachment.Name)) { FileAttachment fileAttachment = attachment as FileAttachment; if (fileAttachment != null) { //save the attachment to the target directory if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } fileAttachment.Load(Path.Combine(targetDirectory, fileAttachment.Name)); //mark the email as read email.IsRead = true; email.Update(ConflictResolutionMode.AlwaysOverwrite); //get outta here! foundAttachment = true; break; } } } if (foundAttachment) { break; } } return(foundAttachment); }
public static async Task<bool> AddFileAttachmentAsync(string MessageId, MemoryStream fileContent) { // Make sure we have a reference to the Outlook Services client OutlookServicesClient outlookClient = await GetOutlookClientAsync(); var attachment = new FileAttachment(); attachment.ContentBytes = fileContent.ToArray(); attachment.Name = "fileAttachment"; attachment.Size = fileContent.ToArray().Length; try { var storedMessage = outlookClient.Me.Messages.GetById(MessageId); await storedMessage.Attachments.AddAttachmentAsync(attachment); await storedMessage.SendAsync(); Debug.WriteLine("Added attachment to message: " + MessageId); return true; } catch (ODataErrorException ex) { // GetById will throw an ODataErrorException when the // item with the specified Id can't be found in the contact store on the server. Debug.WriteLine(ex.Message); return false; } }
static void Main(string[] args) { if (args.Length < 14) { ShowUsage(); Environment.Exit(0); } ExchangeService service = null; if ((args[0] != "-CerValidation")) { ShowUsage(); Environment.Exit(0); } if ((args[1] == "No")) { ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); }; } Console.WriteLine("[+]CerValidation:{0}", args[1]); if ((args[2] != "-ExchangeVersion")) { ShowUsage(); Environment.Exit(0); } if ((args[3] == "Exchange2007_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); } else if ((args[3] == "Exchange2010")) { service = new ExchangeService(ExchangeVersion.Exchange2010); } else if ((args[3] == "Exchange2010_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); } else if ((args[3] == "Exchange2010_SP2")) { service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); } else if ((args[3] == "Exchange2013")) { service = new ExchangeService(ExchangeVersion.Exchange2013); } else if ((args[3] == "Exchange2013_SP1")) { service = new ExchangeService(ExchangeVersion.Exchange2013_SP1); } else { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]ExchangeVersion:{0}", args[3]); if (args[4] == "-u") { UserString = args[5]; Console.WriteLine("[+]User:{0}", args[5]); if ((args[6] != "-p")) { ShowUsage(); Environment.Exit(0); } PwdString = args[7]; Console.WriteLine("[+]Password:{0}", args[7]); service.Credentials = new WebCredentials(UserString, PwdString); } else if (args[4] == "-use") { if (args[5] == "the") { if (args[6] == "default") { if (args[7] == "credentials") { service.UseDefaultCredentials = true; Console.WriteLine("[+]Use the default credentials"); } } } else { ShowUsage(); Environment.Exit(0); } } else { ShowUsage(); Environment.Exit(0); } if ((args[8] == "-ewsPath")) { Console.WriteLine("[+]ewsPath:{0}", args[9]); ewsPathString = args[9]; try { service.Url = new Uri(ewsPathString); } catch (Exception e) { Console.WriteLine("{0}", e.Message); Environment.Exit(0); } } else if ((args[8] == "-AutodiscoverUrl")) { Console.WriteLine("[+]AutodiscoverUrl:{0}", args[9]); AutodiscoverUrlString = args[9]; try { service.AutodiscoverUrl(AutodiscoverUrlString, RedirectionUrlValidationCallback); Console.WriteLine("[+]ewsPath:{0}", service.Url); } catch (Exception e) { Console.WriteLine("{0}", e.Message); Environment.Exit(0); } } else { ShowUsage(); Environment.Exit(0); } if ((args[10] != "-Mode")) { ShowUsage(); Environment.Exit(0); } if ((args[11] == "ListMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FindItemsResults <Item> findResults = null; FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); if (args[13] == "Inbox") { findResults = service.FindItems(WellKnownFolderName.Inbox, view); } else if (args[13] == "Outbox") { findResults = service.FindItems(WellKnownFolderName.Outbox, view); } else if (args[13] == "DeletedItems") { findResults = service.FindItems(WellKnownFolderName.DeletedItems, view); } else if (args[13] == "Drafts") { findResults = service.FindItems(WellKnownFolderName.Drafts, view); } else if (args[13] == "SentItems") { findResults = service.FindItems(WellKnownFolderName.SentItems, view); } else if (args[13] == "JunkEmail") { findResults = service.FindItems(WellKnownFolderName.JunkEmail, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); if (item.Subject != null) { Console.WriteLine("[*]Subject:{0}", item.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments); if (item.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", item.Id); Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); item.Load(itempropertyset); if (item.Body.ToString().Length > 100) { item.Body = item.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body); } else { Console.WriteLine("[*]MessageBody:{0}", item.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListUnreadMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FindItemsResults <Item> findResults = null; FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); if (args[13] == "Inbox") { findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view); } else if (args[13] == "Outbox") { findResults = service.FindItems(WellKnownFolderName.Outbox, sf, view); } else if (args[13] == "DeletedItems") { findResults = service.FindItems(WellKnownFolderName.DeletedItems, sf, view); } else if (args[13] == "Drafts") { findResults = service.FindItems(WellKnownFolderName.Drafts, sf, view); } else if (args[13] == "SentItems") { findResults = service.FindItems(WellKnownFolderName.SentItems, sf, view); } else if (args[13] == "JunkEmail") { findResults = service.FindItems(WellKnownFolderName.JunkEmail, sf, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); EmailMessage email = EmailMessage.Bind(service, item.Id); if (email.Subject != null) { Console.WriteLine("[*]Subject:{0}", email.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments); if (email.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", email.Id); Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); email.Load(itempropertyset); if (email.Body.ToString().Length > 100) { email.Body = email.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body); } else { Console.WriteLine("[*]MessageBody:{0}", email.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } if ((args[11] == "ListFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } FolderString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); FindFoldersResults findResults = null; FolderView view = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep }; if (args[13] == "Inbox") { findResults = service.FindFolders(WellKnownFolderName.Inbox, view); } else if (args[13] == "Outbox") { findResults = service.FindFolders(WellKnownFolderName.Outbox, view); } else if (args[13] == "DeletedItems") { findResults = service.FindFolders(WellKnownFolderName.DeletedItems, view); } else if (args[13] == "Drafts") { findResults = service.FindFolders(WellKnownFolderName.Drafts, view); } else if (args[13] == "SentItems") { findResults = service.FindFolders(WellKnownFolderName.SentItems, view); } else if (args[13] == "JunkEmail") { findResults = service.FindFolders(WellKnownFolderName.JunkEmail, view); } else { ShowUsage(); Environment.Exit(0); } foreach (Folder folder in findResults.Folders) { Console.WriteLine("\r\n"); Console.WriteLine("[*]DisplayName:{0}", folder.DisplayName); Console.WriteLine("[*]Id:{0}", folder.Id); Console.WriteLine("[*]TotalCount:{0}", folder.TotalCount); } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListMailofFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); Folder Folders = Folder.Bind(service, IdString); FindItemsResults <Item> findResults = null; ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; findResults = Folders.FindItems(view); foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); if (item.Subject != null) { Console.WriteLine("[*]Subject:{0}", item.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments); if (item.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", item.Id); Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo); Console.WriteLine("[*]Size:{0}", item.Size); item.Load(itempropertyset); if (item.Body.ToString().Length > 100) { item.Body = item.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body); } else { Console.WriteLine("[*]MessageBody:{0}", item.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ListUnreadMailofFolder")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); SearchFilter sf = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); Folder Folders = Folder.Bind(service, IdString); FindItemsResults <Item> findResults = null; ItemView view = new ItemView(int.MaxValue); PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; view.PropertySet = itempropertyset; findResults = Folders.FindItems(sf, view); foreach (Item item in findResults.Items) { Console.WriteLine("\r\n"); EmailMessage email = EmailMessage.Bind(service, item.Id); if (email.Subject != null) { Console.WriteLine("[*]Subject:{0}", email.Subject); } else { Console.WriteLine("[*]Subject:<null>"); } Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments); if (email.HasAttachments) { EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; fileAttachment.Load(); Console.WriteLine(" - Attachments:{0}", fileAttachment.Name); } } Console.WriteLine("[*]ItemId:{0}", email.Id); Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated); Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived); Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent); Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc); Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo); Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo); Console.WriteLine("[*]Size:{0}", email.Size); email.Load(itempropertyset); if (email.Body.ToString().Length > 100) { email.Body = email.Body.ToString().Substring(0, 100); Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body); } else { Console.WriteLine("[*]MessageBody:{0}", email.Body); } } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "SaveAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { FileAttachment fileAttachment = attachment as FileAttachment; Console.WriteLine("[+]Attachments:{0}", fileAttachment.Name); fileAttachment.Load(fileAttachment.Name); Console.WriteLine("\r\n[+]SaveAttachment success"); } } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "AddAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); if ((args[14] != "-AttachmentFile")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]AttachmentFile:{0}", args[15]); EmailMessage message = EmailMessage.Bind(service, IdString); message.Attachments.AddFileAttachment(args[15]); message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]AddAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ClearAllAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); message.Attachments.Clear(); message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]ClearAllAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "DeleteAttachment")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); if ((args[14] != "-AttachmentFile")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]AttachmentFile:{0}", args[15]); EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments)); foreach (Attachment attachment in message.Attachments) { if (attachment.Name == args[15]) { message.Attachments.Remove(attachment); break; } } message.Update(ConflictResolutionMode.AlwaysOverwrite); Console.WriteLine("\r\n[+]DeleteAttachment success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "DeleteMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); EmailMessage message = EmailMessage.Bind(service, IdString); message.Delete(DeleteMode.SoftDelete); Console.WriteLine("\r\n[+]DeleteMail success"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "SearchMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-String")) { ShowUsage(); Environment.Exit(0); } SearchString = args[13]; Console.WriteLine("[+]SearchString:{0}", args[13]); SearchMail(service, WellKnownFolderName.Inbox, SearchString); SearchMail(service, WellKnownFolderName.Outbox, SearchString); SearchMail(service, WellKnownFolderName.DeletedItems, SearchString); SearchMail(service, WellKnownFolderName.Drafts, SearchString); SearchMail(service, WellKnownFolderName.SentItems, SearchString); SearchMail(service, WellKnownFolderName.JunkEmail, SearchString); Console.WriteLine("\r\n[+]SearchMail done"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ExportMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Folder")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Folder:{0}", args[13]); Console.WriteLine("[+]SavePath:{0}.eml", args[13]); Folder inbox = null; if (args[13] == "Inbox") { inbox = Folder.Bind(service, WellKnownFolderName.Inbox); } else if (args[13] == "Outbox") { inbox = Folder.Bind(service, WellKnownFolderName.Outbox); } else if (args[13] == "DeletedItems") { inbox = Folder.Bind(service, WellKnownFolderName.DeletedItems); } else if (args[13] == "Drafts") { inbox = Folder.Bind(service, WellKnownFolderName.Drafts); } else if (args[13] == "SentItems") { inbox = Folder.Bind(service, WellKnownFolderName.SentItems); } else if (args[13] == "JunkEmail") { inbox = Folder.Bind(service, WellKnownFolderName.JunkEmail); } else { Console.WriteLine("[!]Don't support this folder"); Environment.Exit(0); } ItemView view = new ItemView(int.MaxValue); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); FindItemsResults <Item> results = inbox.FindItems(view); int i = 0; foreach (var item in results) { i++; PropertySet props = new PropertySet(EmailMessageSchema.MimeContent); var email = EmailMessage.Bind(service, item.Id, props); string emlFileName = args[13] + ".eml"; using (FileStream fs = new FileStream(emlFileName, FileMode.Append, FileAccess.Write)) { fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length); } } Console.WriteLine("\r\n[+]ExportMail done,total number:{0}", i); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ViewMail")) { Console.WriteLine("[+]Mode:{0}", args[11]); try { if ((args[12] != "-Id")) { ShowUsage(); Environment.Exit(0); } IdString = args[13]; Console.WriteLine("[+]Id:{0}", args[13]); ViewMail(service, WellKnownFolderName.Inbox, IdString); ViewMail(service, WellKnownFolderName.Outbox, IdString); ViewMail(service, WellKnownFolderName.DeletedItems, IdString); ViewMail(service, WellKnownFolderName.Drafts, IdString); ViewMail(service, WellKnownFolderName.SentItems, IdString); ViewMail(service, WellKnownFolderName.JunkEmail, IdString); Console.WriteLine("\r\n[+]ViewMail done"); } catch (Exception e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } } else if ((args[11] == "ReadXML")) { Console.WriteLine("[+]Mode:{0}", args[11]); if ((args[12] != "-Path")) { ShowUsage(); Environment.Exit(0); } Console.WriteLine("[+]XML path:{0}", args[13]); Console.WriteLine("[+]Out path:out.xml"); StreamReader sendData = new StreamReader(args[13], Encoding.Default); byte[] sendDataByte = Encoding.UTF8.GetBytes(sendData.ReadToEnd()); sendData.Close(); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(service.Url); request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = sendDataByte.Length; request.AllowAutoRedirect = false; if (args[4] == "-use") { request.Credentials = CredentialCache.DefaultCredentials; } else { request.Credentials = new NetworkCredential(UserString, PwdString); } Stream requestStream = request.GetRequestStream(); requestStream.Write(sendDataByte, 0, sendDataByte.Length); requestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new WebException(response.StatusDescription); } Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); String receiveString = readStream.ReadToEnd(); response.Close(); readStream.Close(); StreamWriter receiveData = new StreamWriter("out.xml"); receiveData.Write(receiveString); receiveData.Close(); } catch (WebException e) { Console.WriteLine("[!]{0}", e.Message); Environment.Exit(0); } Console.WriteLine("\r\n[+]ReadXML done"); } }
private async void SendMailForm_LoadAsync(object sender, EventArgs e) { Icon = Properties.Resources.DefaultIcon; attachments = new List <FileAttachment>(); // Display the window in the center of the parent window. Location = new Point(Owner.Location.X + (Owner.Width - Width) / 2, Owner.Location.Y + (Owner.Height - Height) / 2); comboBox_Importance.SelectedIndex = 1; comboBox_BodyType.SelectedIndex = 0; if (draftItemId != "") { // Editing a draft item. button_Attachments.Enabled = false; // When sending a draft item, it must be saved to SentItems. checkBox_SaveToSentItems.Checked = true; checkBox_SaveToSentItems.Enabled = false; viewerRequestHelper = new ViewerRequestHelper(); NewEmailMessage draftItem; try { draftItem = await viewerRequestHelper.GetDraftMessageAsync(draftItemId); } catch (Exception ex) { MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); return; } if (comboBox_Importance.InvokeRequired) { comboBox_Importance.Invoke(new MethodInvoker(delegate { comboBox_Importance.SelectedIndex = (int)draftItem.Importance; })); } else { comboBox_Importance.SelectedIndex = (int)draftItem.Importance; } if (comboBox_Importance.InvokeRequired) { comboBox_Importance.Invoke(new MethodInvoker(delegate { comboBox_Importance.SelectedIndex = (int)draftItem.Importance;; })); } else { comboBox_Importance.SelectedIndex = (int)draftItem.Importance; } if (checkBox_RequestDeliveryReceipt.InvokeRequired) { checkBox_RequestDeliveryReceipt.Invoke(new MethodInvoker(delegate { checkBox_RequestDeliveryReceipt.Checked = draftItem.IsDeliveryReceiptRequested; })); } else { checkBox_RequestDeliveryReceipt.Checked = draftItem.IsDeliveryReceiptRequested; } if (checkBox_RequestReadReceipt.InvokeRequired) { checkBox_RequestReadReceipt.Invoke(new MethodInvoker(delegate { checkBox_RequestReadReceipt.Checked = draftItem.IsReadReceiptRequested; })); } else { checkBox_RequestReadReceipt.Checked = draftItem.IsReadReceiptRequested; } if (textBox_To.InvokeRequired) { textBox_To.Invoke(new MethodInvoker(delegate { textBox_To.Text = RecipientsString(draftItem.ToRecipients); })); } else { textBox_To.Text = RecipientsString(draftItem.ToRecipients); } if (textBox_Cc.InvokeRequired) { textBox_Cc.Invoke(new MethodInvoker(delegate { textBox_Cc.Text = RecipientsString(draftItem.CcRecipients); })); } else { textBox_Cc.Text = RecipientsString(draftItem.CcRecipients); } if (textBox_Bcc.InvokeRequired) { textBox_Bcc.Invoke(new MethodInvoker(delegate { textBox_Bcc.Text = RecipientsString(draftItem.BccRecipients); })); } else { textBox_Bcc.Text = RecipientsString(draftItem.BccRecipients); } if (textBox_Subject.InvokeRequired) { textBox_Subject.Invoke(new MethodInvoker(delegate { textBox_Subject.Text = draftItem.Subject; })); } else { textBox_Subject.Text = draftItem.Subject; } if (textBox_Body.InvokeRequired) { textBox_Body.Invoke(new MethodInvoker(delegate { textBox_Body.Text = draftItem.Body.Content; })); } else { textBox_Body.Text = draftItem.Body.Content; } if (comboBox_BodyType.InvokeRequired) { comboBox_BodyType.Invoke(new MethodInvoker(delegate { comboBox_BodyType.SelectedIndex = (int)draftItem.Body.ContentType; })); } else { comboBox_BodyType.SelectedIndex = (int)draftItem.Body.ContentType; } var attachList = await viewerRequestHelper.GetAllAttachmentsAsync(FolderContentType.Message, draftItemId); foreach (var attach in attachList) { Dictionary <string, string> fullAttachInfo = await viewerRequestHelper.GetAttachmentAsync(FolderContentType.Message, draftItemId, attach.Id); string tempType = ""; string tempName = ""; string tempContentBytes = ""; foreach (KeyValuePair <string, string> item in fullAttachInfo) { if (item.Key.ToLowerInvariant() == "@odata.type") { tempType = (item.Value == null) ? "" : item.Value.ToString(); } else if (item.Key.ToLowerInvariant() == "name") { tempName = (item.Value == null) ? "" : item.Value.ToString(); } else if (item.Key.ToLowerInvariant() == "contentbytes") { tempContentBytes = (item.Value == null) ? "" : item.Value.ToString(); } } if (tempType == (Util.UseMicrosoftGraphInMailboxViewer ? "#microsoft.graph.fileAttachment" : "#Microsoft.OutlookServices.FileAttachment")) { // This is a FileAttachment attachments.Add(FileAttachment.CreateFromContentBytes(tempName, tempContentBytes)); } } if (button_Attachments.InvokeRequired) { button_Attachments.Invoke(new MethodInvoker(delegate { button_Attachments.Enabled = true; })); } else { button_Attachments.Enabled = true; } } }
private async Task PostToNotebook(GraphServiceClient graphClient, string msg, FileAttachment attachment) { var accessToken = GetAccessToken().Result; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); using (var content = new MultipartFormDataContent("MyPartBoundary198374")) { var stringContent = new StringContent(msg, Encoding.UTF8, "text/html"); content.Add(stringContent, "Presentation"); var fileContent = new ByteArrayContent(attachment.ContentBytes); fileContent.Headers.ContentType = new MediaTypeHeaderValue(attachment.ContentType); content.Add(fileContent, "fileBlock1", "fileBlock1"); var requestUrl = graphClient.Users["*****@*****.**"] .Onenote .Pages .RequestUrl; using ( var message = await client.PostAsync(requestUrl, content)) { Console.WriteLine(message.ReasonPhrase); } } } }
private int LoadFileNonInlineAttachmentsLv(ItemId oItemId, ref ListView oListView) { int iAttachments = 0; oListView.Clear(); oListView.View = View.Details; oListView.GridLines = true; oListView.FullRowSelect = true; oListView.Columns.Add("Id", 70, HorizontalAlignment.Left); oListView.Columns.Add("ContentId", 70, HorizontalAlignment.Left); oListView.Columns.Add("ContentLocation", 70, HorizontalAlignment.Left); oListView.Columns.Add("ContentType", 70, HorizontalAlignment.Left); oListView.Columns.Add("Name", 140, HorizontalAlignment.Left); oListView.Columns.Add("FileName", 200, HorizontalAlignment.Left); oListView.Columns.Add("IsInline", 50, HorizontalAlignment.Left); // Exchange 2010 and later. oListView.Columns.Add("LastModifiedTime", 70, HorizontalAlignment.Left); // Exchange 2010 and later. oListView.Columns.Add("Size", 70, HorizontalAlignment.Right); // Exchange 2010 and later. ListViewItem oListItem = null; int iAttachmentCount = 0; foreach (Attachment oAttachment in _Item.Attachments) { if (oAttachment is FileAttachment) { FileAttachment oAttach = oAttachment as FileAttachment; _Item.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID oAttachment.Load(); // For Exchange 2010, check for Inline attachments using: // if (oAttachment.IsInline == false) // For earlier versions, resort to checking for ContentId not being set. // if (oAttach.ContentId.Length == 0) if (oAttachment.IsInline == false) { //ExtendedPropertyDefinition myProperty = new ExtendedPropertyDefinition( // DefaultExtendedPropertySet.PublicStrings, // "urn:schemas:contacts:propertyx", // MapiPropertyType.String); //Item item = Item.Bind( // service, // new ItemId("your id"), // new PropertySet(BasePropertySet.FirstClassProperties, myProperty)); oListItem = new ListViewItem(oAttach.Id, 0); oListItem.SubItems.Add(oAttach.ContentId); oListItem.SubItems.Add(oAttach.ContentLocation); oListItem.SubItems.Add(oAttach.ContentType); oListItem.SubItems.Add(oAttach.Name); oListItem.SubItems.Add(oAttach.FileName); oListItem.SubItems.Add(oAttach.IsInline.ToString()); // Exchange 2010 and later. oListItem.SubItems.Add(oAttachment.LastModifiedTime.ToString()); // Exchange 2010 and later. oListItem.SubItems.Add(oAttach.Size.ToString()); // Exchange 2010 and later. oListItem.Tag = iAttachmentCount; oListView.Items.AddRange(new ListViewItem[] { oListItem }); oListItem = null; iAttachments++; } } iAttachmentCount++; } return(iAttachments); }
public static EmailMessage CreateEmbeddedEmail(string body, int newsletterId) { EmailMessage message = new EmailMessage(); Hashtable addedAtt = new Hashtable(); body = template.ParseInternalLinks(body); //string currentDomain = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; //string pattern = "href=\"?([^\\\"' >]+)|src=\\\"?([^\\\"' >]+)"; string currentDomain = "http://" + System.Web.HttpContext.Current.Request.ServerVariables["SERVER_NAME"]; string pattern = "href=\"?([^\\\"' >]+)|src=\\\"?([^\\\"' >]+)|background=\\\"?([^\\\"' >]+)"; string appendNewsletter = "umbNl=" + newsletterId.ToString(); MatchCollection tags = Regex.Matches(body, pattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match tag in tags) { if (tag.Groups.Count > 0) { if (tag.Groups[1].Value.ToLower().IndexOf("http://") == -1 && tag.Groups[2].Value.ToLower().IndexOf("http://") == -1 && tag.Groups[1].Value.ToLower().IndexOf("mailto:") == -1 && tag.Groups[2].Value.ToLower().IndexOf("mailto:") == -1) { // links if (tag.Groups[1].Value != "") { if (tag.Groups[0].Value.ToLower() == "href=\"/") { if (tag.Groups[1].Value.IndexOf("?") == -1) { body = body.Replace(tag.Groups[0].Value + "\"", "href=\"" + currentDomain + tag.Groups[1].Value + "?" + appendNewsletter + "\""); } else { body = body.Replace(tag.Groups[0].Value + "\"", "href=\"" + currentDomain + tag.Groups[1].Value + "&" + appendNewsletter + "\""); } } else { if (tag.Groups[1].Value.IndexOf("?") == -1) { body = body.Replace("href=\"" + tag.Groups[1].Value + "\"", "href=\"" + currentDomain + tag.Groups[1].Value + "?" + appendNewsletter + "\""); } else { body = body.Replace("href=\"" + tag.Groups[1].Value + "\"", "href=\"" + currentDomain + tag.Groups[1].Value + "&" + appendNewsletter + "\""); } } } // src else { string imageExtextions = "jpg,jpeg,gif,png"; string image = tag.Groups[2].Value; if (image == "") { image = tag.Groups[3].Value; } string orgImage = image; string ext = image.Split(char.Parse("."))[image.Split(char.Parse(".")).Length - 1].ToLower(); bool isImage = imageExtextions.IndexOf(ext) != -1; if (isImage) { string guid = Guid.NewGuid().ToString(); FileAttachment attachment = CreateImageAttachment(image, ext, guid); if (attachment != null) { if (addedAtt.ContainsKey(image)) { body = body.Replace(image, "cid:" + addedAtt[image].ToString()); } else { message.AddRelatedAttachment(attachment); body = body.Replace(image, "cid:" + guid); addedAtt.Add(image, guid); } } else { body = body.Replace(orgImage, currentDomain + tag.Groups[2].Value); } // break; } else { body = body.Replace(orgImage, currentDomain + tag.Groups[2].Value); } } } } } message.HtmlPart = new HtmlAttachment(body); return(message); }
private void saveFileAttachment(FileAttachment attachment, String fileName) { FileStream fs = File.Create(fileName); BinaryWriter writer = new BinaryWriter(fs); writer.Write(attachment.Data); writer.Close(); fs.Close(); }
public void UploadFile(FileAttachment fileAttachment) { m_svc.UploadFile(fileAttachment); }
private FileAttachment getFileAttachment(String fileName) { FileAttachment attachment = new FileAttachment(); FileStream fs = File.OpenRead(fileName); byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); attachment.Data = data; attachment.SizeSpecified = true; attachment.Size = fs.Length; return attachment; }
protected override TfsUpdateDocument SubmitAttachmentChanges(IMigrationAction action, ConflictManager conflictMgrService) { /* * retrieve change details */ XmlDocument desc = action.MigrationActionDescription; XmlElement rootNode = desc.DocumentElement; Debug.Assert(null != rootNode); XmlNode attachmentNode = rootNode.FirstChild; string originalName = attachmentNode.Attributes["Name"].Value; string utcCreationDate = attachmentNode.Attributes["UtcCreationDate"].Value; string utcLastWriteDate = attachmentNode.Attributes["UtcLastWriteDate"].Value; string length = attachmentNode.Attributes["Length"].Value; string comment = attachmentNode.FirstChild.InnerText; int targetWorkItemId = FindTargetWorkItemId(action, conflictMgrService); string targetRevision = rootNode.Attributes["TargetRevision"].Value; /* * create operation document */ TfsUpdateDocument tfsUpdateDocument = InitializeUpdateDocument(); tfsUpdateDocument.CreateWorkItemUpdateDoc(targetWorkItemId.ToString(), targetRevision); /* * insert Connector specific comment */ WorkItem item = WorkItemStore.GetWorkItem(targetWorkItemId); Debug.Assert(null != item, "target work item does not exist"); tfsUpdateDocument.InsertConversionHistoryCommentToHistory(item.Type.Name, GenerateMigrationHistoryComment(action)); int[] fileId = FindAttachmentFileId(targetWorkItemId, originalName, utcCreationDate, utcLastWriteDate, length, comment); /* * delete attachment */ if (action.Action == WellKnownChangeActionId.DelAttachment) { if (fileId.Length == 0) { action.State = ActionState.Skipped; return(null); } else { tfsUpdateDocument.RemoveAttachment(fileId[0]); return(tfsUpdateDocument); } } /* * add attachment */ try { string sourceStoreCountString = attachmentNode.Attributes["CountInSourceSideStore"].Value; int sourceStoreCount; if (int.TryParse(sourceStoreCountString, out sourceStoreCount)) { if (sourceStoreCount <= fileId.Length) { action.State = ActionState.Skipped; return(null); } } } catch (Exception e) { TraceManager.TraceVerbose(e.ToString()); // for backward compatibility, just proceed } if (AttachmentIsOversized(length)) { MigrationConflict conflict = new FileAttachmentOversizedConflictType().CreateConflict( originalName, length, MaxAttachmentSize, targetWorkItemId.ToString(), Core.ServerName, Core.Config.Project, action); List <MigrationAction> actions; ConflictResolutionResult resolveRslt = conflictMgrService.TryResolveNewConflict(conflictMgrService.SourceId, conflict, out actions); if (!resolveRslt.Resolved) { return(null); } if (resolveRslt.ResolutionType == ConflictResolutionType.SuppressedConflictedChangeAction) { action.State = ActionState.Skipped; return(null); } if (resolveRslt.ResolutionType == ConflictResolutionType.Other) { // conflict resolved, just proceed } else { throw new NotImplementedException(); } } Guid fileGuid = Guid.NewGuid(); tfsUpdateDocument.AddAttachment(originalName, XmlConvert.ToString(fileGuid), utcCreationDate, utcLastWriteDate, length, comment); // get areaNodeUri - required by Dev10 OM Project project = item.Project; string projectNodeUri = (project.Uri).ToString(); string areaNodeUri = string.Empty; if (project.Id == item.AreaId) { areaNodeUri = Core.AreaNodeUri; } else { // Loop through the area root nodes looking for the one we're on foreach (Node node in project.AreaRootNodes) { // It could be one of the root nodes if (node.Id == item.AreaId) { areaNodeUri = node.Uri.ToString(); break; } // Now check if it is a child of the current area root node try { Node node2 = node.FindNodeInSubTree(item.AreaId); areaNodeUri = node2.Uri.ToString(); break; } catch (DeniedOrNotExistException) { // Ignore if not found, go onto the next area root node continue; } } } //Now upload the file since that has to be done before the Xml batch is executed. Debug.Assert(!string.IsNullOrEmpty(LocalWorkDir)); string filePath = Path.Combine(LocalWorkDir, fileGuid.ToString()); action.SourceItem.Download(filePath); using (var strm = File.OpenRead(filePath)) { var f = new FileAttachment(); f.AreaNodeUri = areaNodeUri; f.ProjectUri = projectNodeUri; f.FileNameGUID = fileGuid; f.LocalFile = strm; // attachment.GetFileContents(); WorkItemServer.UploadFile(f); } if (File.Exists(filePath)) { File.Delete(filePath); } return(tfsUpdateDocument); }
public void AddAttachment(ICardId card, FileAttachment attachment) { _restClient.Request(new CardsAddFileAttachmentRequest(card, attachment)); }
public Task AddAttachment(ICardId card, FileAttachment attachment) { return _restClient.RequestAsync(new CardsAddFileAttachmentRequest(card, attachment)); }
/// <summary> /// Saves the ticket. /// </summary> /// <param name="ticketPresenter">The ticket presenter.</param> /// <param name="isUpdateTicket">if set to <c>true</c> [is update ticket].</param> /// <returns> /// save details /// </returns> public ActionResult SaveTicket(TicketPresenter ticketPresenter, bool isUpdateTicket) { if (ticketPresenter != null) { if (!isUpdateTicket) { ticketPresenter.TicketDetails.CommentDescription = ticketPresenter.TicketDescription; } if (ticketPresenter.DueDate == null) { ticketPresenter.TicketDetails.DueDate = null; } else { ticketPresenter.TicketDetails.DueDate = ticketPresenter.DueDate; } ticketPresenter.TicketDetails.AddedByDeveloperId = SessionData.Instance.UserInfo.Developer.DeveloperID; ticketPresenter.TicketDetails.StatusId = ticketPresenter.SelectedStatus; ticketPresenter.TicketDetails.Priority = ticketPresenter.SelectedPriority; string developerIds = Convert.ToString(ticketPresenter.SelectedDeveloper, CultureInfo.CurrentCulture); var ticketDeveloperArray = developerIds.Split(','); foreach (var ticketDeveloper in ticketDeveloperArray) { ticketPresenter.TicketDetails.DeveloperIds.Add(ticketDeveloper); } var projectIds = Convert.ToString(ticketPresenter.SelectedProject, CultureInfo.CurrentCulture); if (projectIds != null) { var ticketProjectArray = projectIds.Split(','); foreach (var ticketProject in ticketProjectArray) { ticketPresenter.TicketDetails.ProjectIds.Add(ticketProject); } } var clientIds = Convert.ToString(ticketPresenter.SelectedClient, CultureInfo.CurrentCulture); if (clientIds != null) { var ticketClientArray = clientIds.Split(','); foreach (var ticketClient in ticketClientArray) { ticketPresenter.TicketDetails.ClientIds.Add(ticketClient); } } if (developerIds.Equals(DefaultDeveloperId)) { developerIds = null; } if (ticketPresenter.AttachmentIds != null) { var attachmentIds = ticketPresenter.AttachmentIds.Split(','); foreach (var attachmentId in attachmentIds) { var attachmentsids = attachmentId.Split('~'); var attachments = new FileAttachment { FileAttachmentId = Convert.ToInt32(attachmentsids[0]), FileName = attachmentsids[1] }; ticketPresenter.TicketDetails.FileAttachments.Add(attachments); } } if (ticketPresenter.TagIds != null) { var tagIdsArray = ticketPresenter.TagIds.Split(','); foreach (var tag in tagIdsArray) { ticketPresenter.TicketDetails.Tags.Add(tag); } } if (!isUpdateTicket) { this.ticketService.Insert(SessionData.Instance.UserInfo.Developer.DeveloperID, ticketPresenter.TicketDetails); } if (ticketPresenter.TicketId != null) { ticketPresenter.TicketDetails.TicketId = (int)ticketPresenter.TicketId; this.ticketService.UpdateTicketDetail(SessionData.Instance.UserInfo.Developer.DeveloperID, ticketPresenter.TicketDetails); } return this.Json(ticketPresenter); } return this.Json(string.Empty); }
private static FileAttachment CreateTestAttachment(bool createLargeAttachment = false) { // Create an attachment var attachmentName = string.Format("TestAttachment-{0}.txt", Guid.NewGuid().ToString()); string attachmentData = null; if (createLargeAttachment) { var builder = new StringBuilder(); builder.AppendFormat("This is a test attachment written at {0} {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); // Ensure we have an attchment of around 100k for (var cnt=0; cnt < 20240; cnt++ ) { builder.Append("This is Some Data man!"); } attachmentData = builder.ToString(); } else { attachmentData = string.Format("This is a test attachment written at {0} {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); } File.WriteAllText(attachmentName, attachmentData ); var byteData = File.ReadAllBytes(attachmentName); FileAttachment attachment = new FileAttachment(); attachment.Name = attachmentName; attachment.Description = "Test Only"; attachment.AttachmentData = byteData; attachment.AllowExistingAttachmentToBeOverwritten = true; attachment.ItemIdAttachedTo = Convert.ToInt32(TestInvoiceId); return attachment; }
private async Task<FileAttachment[]> GetInspectionOrRepairPhotosAsAttachments(string listName, int inspectionId, int roomId) { var format = "{0}lists/GetByTitle('{1}')/Items?&$Filter=(sl_inspectionID eq {2} and sl_roomID eq {3})&$select=Id,Title"; //&$select=File/TimeLastModified,File/Name var url = string.Format(format, sharePointServiceEndpointUri, listName, inspectionId, roomId); var json = await HttpGetJson(url, sharePointAccessToken); var items = JObject.Parse(json)["value"].ToArray(); var attachments = new FileAttachment[items.Length]; for (int i = 0; i < items.Length; i++) { var fileId = items[i]["Id"]; var fileName = items[i]["Title"].ToString(); var fileUrl = string.Format("{0}lists/GetByTitle('{1}')/Items({2})/File/$value", sharePointServiceEndpointUri, listName, fileId); var data = await HttpGetData(fileUrl, sharePointAccessToken); var attachment = new FileAttachment { ContentId = (i + 1).ToString("000"), Name = fileName, ContentBytes = data }; attachments[i] = attachment; } return attachments; }
private bool CanDelete(FileAttachment item) { return _isOrganizer; }
static partial void RealInstanceFactory(ref FileAttachment real, [CallerMemberName] string callerName = "");
/// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task <RestUserMessage> SendFileAsync(FileAttachment attachment, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null, Embed[] embeds = null) => ChannelHelper.SendFileAsync(this, Discord, attachment, text, isTTS, embed, allowedMentions, messageReference, components, stickers, options, embeds);
/// <inheritdoc /> async Task <IUserMessage> IMessageChannel.SendFileAsync(FileAttachment attachment, string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference, MessageComponent components, ISticker[] stickers, Embed[] embeds) => await SendFileAsync(attachment, text, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds).ConfigureAwait(false);
public void SendMessageWithAttachments() { Message message = new Message(); message.Subject = "Test Email " + DateTime.Now.ToString(); message.Categories.Add("blue"); message.Categories.Add("green"); message.CcRecipients = new List<Recipient>(); message.CcRecipients.Add(new Recipient() { EmailAddress = new EmailAddress() { Name = "CCUser1", Address = "*****@*****.**" } }); message.CcRecipients.Add(new Recipient() { EmailAddress = new EmailAddress() { Name = "CCUser2", Address = "*****@*****.**" } }); FileAttachment attachment = new FileAttachment(); attachment.ContentBytes = Convert.FromBase64String("VXNlciBOYW1lLEZpcnN0IE5hbWUsTGFzdCBOYW1lLERpc3BsYXkgTmFtZSxKb2IgVGl0bGUsRGVwYXJ0bWVudCxPZmZpY2UgTnVtYmVyLE9mZmljZSBQaG9uZSxNb2JpbGUgUGhvbmUsRmF4LEFkZHJlc3MsQ2l0eSxTdGF0ZSBvciBQcm92aW5jZSxaSVAgb3IgUG9zdGFsIENvZGUsQ291bnRyeSBvciBSZWdpb24NCmF0dWxnb0BleG9sa2Rldi5jY3NjdHAubmV0LEF0dWwsR295YWwsQXR1bCBHb3lhbCwsLCwsLCwsLCwsDQpqZWZ3aWdodEBleG9sa2Rldi5jY3NjdHAubmV0LEplZmYsV2lnaHQsSmVmZiBXaWdodCwsLCwsLCwsLCwsDQpzYWJyYWhhQGV4b2xrZGV2LmNjc2N0cC5uZXQsU2FiaXRoYSxBYnJhaGFtLFNhYml0aGEgQWJyYWhhbSwsLCwsLCwsLCwsDQpnYXJlZ2luQGV4b2xrZGV2LmNjc2N0cC5uZXQsR2FyZWdpbixBdmFneWFuLEdhcmVnaW4gQXZhZ3lhbiwsLCwsLCwsLCwsDQpkYW5hYkBleG9sa2Rldi5jY3NjdHAubmV0LERhbmEsQmlya2J5LERhbmEgQmlya2J5LCwsLCwsLCwsLCwNCmRhdnN0ZXJAZXhvbGtkZXYuY2NzY3RwLm5ldCxEYXZpZCxTdGVybGluZyxEYXZpZCBTdGVybGluZywsLCwsLCwsLCwsDQpmZXJuYW5ndkBleG9sa2Rldi5jY3NjdHAubmV0LEZlcm5hbmRvLEdhcmNpYSxGZXJuYW5kbyBHYXJjaWEsLCwsLCwsLCwsLA0KYWxpbmVAZXhvbGtkZXYuY2NzY3RwLm5ldCxBbGluZSxOYWthc2hpYW4sQWxpbmUgTmFrYXNoaWFuLCwsLCwsLCwsLCwNCnB0b3VzaWdAZXhvbGtkZXYuY2NzY3RwLm5ldCxQYXRyaWNrLFRvdXNpZ25hbnQsUGF0cmljayBUb3VzaWduYW50LCwsLCwsLCwsLCwNCm1lbmNpbmFAZXhvbGtkZXYuY2NzY3RwLm5ldCxNYXVyaWNpbyxFbmNpbmEsTWF1cmljaW8gRW5jaW5hLCwsLCwsLCwsLCwNCnJvaGl0YWdAZXhvbGtkZXYuY2NzY3RwLm5ldCxSb2hpdCxOYWdhcm1hbCxSb2hpdCBOYWdhcm1hbCwsLCwsLCwsLCwsDQp2ZW5rYXRheUBleG9sa2Rldi5jY3NjdHAubmV0LFZlbmthdCxBeXlhZGV2YXJhLFZlbmthdCBBeXlhZGV2YXJhLCwsLCwsLCwsLCwNCmRlc2luZ2hAZXhvbGtkZXYuY2NzY3RwLm5ldCxEZWVwYWssU2luZ2gsRGVlcGFrIFNpbmdoLCwsLCwsLCwsLCwNCnNoYXduYnJAZXhvbGtkZXYuY2NzY3RwLm5ldCxTaGF3bixCcmFjZXdlbGwsU2hhd24gQnJhY2V3ZWxsLCwsLCwsLCwsLCwNCmphc29uaGVuQGV4b2xrZGV2LmNjc2N0cC5uZXQsSmFzb24sSGVuZGVyc29uLEphc29uIEhlbmRlcnNvbiwsLCwsLCwsLCwsDQpzaHJlZWRwQGV4b2xrZGV2LmNjc2N0cC5uZXQsU2hyZWVkZXZpLFBhZG1hc2luaSxTaHJlZWRldmkgUGFkbWFzaW5pLCwsLCwsLCwsLCwNCmFuc2NvZ2dpQGV4b2xrZGV2LmNjc2N0cC5uZXQsRHJldyxTY29nZ2lucyxEcmV3IFNjb2dnaW5zLCwsLCwsLCwsLCwNCnBpb3RycEBleG9sa2Rldi5jY3NjdHAubmV0LFBldGVyLFB1c3praWV3aWN6LFBldGVyIFB1c3praWV3aWN6LCwsLCwsLCwsLCwNCmpvc2hnYXZAZXhvbGtkZXYuY2NzY3RwLm5ldCxKb3NoLEdhdmFudCxKb3NoIEdhdmFudCwsLCwsLCwsLCwsDQp2YXJ1bmdAZXhvbGtkZXYuY2NzY3RwLm5ldCxWYXJ1bixHdXB0YSxWYXJ1biBHdXB0YSwsLCwsLCwsLCwsDQo="); attachment.Name = "ExolkdevUsers.csv"; attachment.ContentType = "application/vnd.ms-excel"; message.Attachments.Add(attachment); client.Me.Messages.AddMessageAsync(message).Wait(); var messages = client.Me.Folders["Drafts"].Messages.ExecuteAsync(); messages.Wait(); var attachments = client.Me.Messages.GetById(messages.Result.CurrentPage[0].Id).Attachments.ExecuteAsync(); attachments.Wait(); }
public async Task<FileAttachment> AddEventAttachment(string eventId, FileAttachment attachment) { string uri = EventsFolder + eventId + "/attachments"; return await GetHttpHelper().PostItemAsync<FileAttachment>(uri, attachment); }