private void ProcessClassificationsForJournalReport(StoreDriverDeliveryEventArgsImpl argsImpl)
        {
            ClassificationSummary classificationSummary = this.GetClassificationSummary(argsImpl);

            if (classificationSummary != null && classificationSummary.IsValid && classificationSummary.IsClassified)
            {
                using (ItemAttachment itemAttachment = this.TryOpenFirstAttachment(argsImpl.ReplayItem) as ItemAttachment)
                {
                    if (itemAttachment != null)
                    {
                        using (MessageItem itemAsMessage = itemAttachment.GetItemAsMessage(StoreObjectSchema.ContentConversionProperties))
                        {
                            if (itemAsMessage != null)
                            {
                                ClassificationApplicationAgent.diag.TraceDebug <string>(0L, "Promote banner for recipient {0} on embedded message of journal report", argsImpl.MailRecipient.Email.ToString());
                                itemAsMessage[ItemSchema.IsClassified]              = classificationSummary.IsClassified;
                                itemAsMessage[ItemSchema.Classification]            = classificationSummary.DisplayName;
                                itemAsMessage[ItemSchema.ClassificationDescription] = classificationSummary.RecipientDescription;
                                itemAsMessage[ItemSchema.ClassificationGuid]        = classificationSummary.ClassificationID.ToString();
                                itemAsMessage[ItemSchema.ClassificationKeep]        = classificationSummary.RetainClassificationEnabled;
                                itemAsMessage.Save(SaveMode.NoConflictResolution);
                                itemAttachment.Save();
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
        private Attachment14Data CreateAttachment14Data(IAttachment attachment)
        {
            Attachment14Data attachment14Data = new Attachment14Data();

            attachment14Data.DisplayName       = attachment.Name;
            attachment14Data.EstimatedDataSize = attachment.Size;
            attachment14Data.IsInline          = attachment.IsInline;
            attachment14Data.FileReference     = HttpUtility.UrlEncode(base.Item.Id + ":" + attachment.Id);
            attachment14Data.Id = EntitySyncItemId.GetAttachmentId(attachment.Id);
            FileAttachment fileAttachment = attachment as FileAttachment;
            ItemAttachment itemAttachment = attachment as ItemAttachment;

            if (fileAttachment != null)
            {
                attachment14Data.Method          = 1;
                attachment14Data.ContentId       = fileAttachment.ContentId;
                attachment14Data.ContentLocation = fileAttachment.ContentLocation;
                if (fileAttachment.Content != null)
                {
                    attachment14Data.EstimatedDataSize = (long)fileAttachment.Content.Length;
                }
            }
            else
            {
                if (itemAttachment == null)
                {
                    throw new ConversionException(string.Format("Attachment type \"{0}\" is not supported.", attachment.GetType().FullName));
                }
                attachment14Data.Method = 5;
            }
            return(attachment14Data);
        }
Exemplo n.º 3
0
        public override IAttachment Read(string attachmentId)
        {
            IList <AttachmentId> attachmentIds = IdConverter.GetAttachmentIds(attachmentId);
            IAttachment          result;

            using (IItem item = this.BindToParentItem())
            {
                using (DisposeGuard disposeGuard = default(DisposeGuard))
                {
                    IItem      item2      = item;
                    Attachment attachment = null;
                    for (int i = 0; i < attachmentIds.Count; i++)
                    {
                        attachment = IrmUtils.GetAttachmentCollection(item2).Open(attachmentIds[i]);
                        disposeGuard.Add <Attachment>(attachment);
                        if (i < attachmentIds.Count - 1)
                        {
                            if (!(attachment is ItemAttachment))
                            {
                                throw new CorruptDataException(Strings.ErrorAllButLastNestedAttachmentMustBeItemAttachment);
                            }
                            ItemAttachment itemAttachment = attachment as ItemAttachment;
                            item2 = itemAttachment.GetItem();
                            disposeGuard.Add <IItem>(item2);
                        }
                    }
                    StorageTranslator <IAttachment, IAttachment> attachmentTranslator = this.GetAttachmentTranslator(attachment.AttachmentType, false);
                    IAttachment attachment2 = attachmentTranslator.ConvertToEntity(attachment);
                    attachment2.Id = attachmentId;
                    result         = attachment2;
                }
            }
            return(result);
        }
Exemplo n.º 4
0
 public Signal Unpack(MessageItem mailMessage)
 {
     this.itemAttach        = new Dictionary <Guid, byte[]>();
     this.messageItemAttach = new Dictionary <Guid, MessageItem>();
     foreach (AttachmentHandle handle in mailMessage.AttachmentCollection.GetHandles())
     {
         using (Attachment attachment = mailMessage.AttachmentCollection.Open(handle))
         {
             StreamAttachment streamAttachment = attachment as StreamAttachment;
             if (streamAttachment != null)
             {
                 byte[] value = Unpacker.ReadBytes(streamAttachment.GetContentStream(PropertyOpenMode.ReadOnly));
                 this.itemAttach.Add(new Guid(streamAttachment.FileName), value);
             }
             else
             {
                 ItemAttachment itemAttachment = attachment as ItemAttachment;
                 if (itemAttachment != null)
                 {
                     MessageItem itemAsMessage = itemAttachment.GetItemAsMessage();
                     string      contentId     = itemAttachment.ContentId;
                     if (contentId != null)
                     {
                         this.messageItemAttach.Add(new Guid(contentId), itemAsMessage);
                     }
                 }
             }
         }
     }
     return(this.ReadSignal(mailMessage));
 }
Exemplo n.º 5
0
        //gavdcodeend 15

        //gavdcodebegin 16
        static void CreateAndSendEmailWithAttachment(ExchangeService ExService)
        {
            EmailMessage newEmail = new EmailMessage(ExService)
            {
                Subject = "Email with Attachments",
                Body    = "This is an email with attachments"
            };

            newEmail.ToRecipients.Add("*****@*****.**");

            newEmail.Attachments.AddFileAttachment(@"C:\Temporary\file_01.jpg");
            newEmail.Attachments.AddFileAttachment("SecondAttachment.jpg",
                                                   @"C:\Temporary\file_01.jpg");

            byte[] attBytes = File.ReadAllBytes(@"C:\Temporary\file_01.jpg");
            newEmail.Attachments.AddFileAttachment("ThirdAttachment.jpg", attBytes);

            ItemAttachment <EmailMessage> emailAttachment =
                newEmail.Attachments.AddItemAttachment <EmailMessage>();

            emailAttachment.Name         = "Attached email";
            emailAttachment.Item.Subject = "Attached email Subject";
            emailAttachment.Item.Body    = "Attached email Body";
            emailAttachment.Item.ToRecipients.Add("*****@*****.**");

            newEmail.SendAndSaveCopy();
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,ImageData,ContentType,ItemId")] ItemAttachment itemAttachment)
        {
            if (id != itemAttachment.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(itemAttachment);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ItemAttachmentExists(itemAttachment.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ItemId"] = new SelectList(_context.Item, "Id", "Description", itemAttachment.ItemId);
            return(View(itemAttachment));
        }
 public void Put(int id, [FromBody] ItemAttachment attachment)
 {
     // TODO: Add data validation
     attachment.ID = id;
     db.ItemAttachments.Update(attachment);
     db.SaveChanges();
 }
Exemplo n.º 8
0
        public void Test_MessageWithEventAttachmentDeserialization()
        {
            string serializedMessage = @"{
              ""@odata.type"": ""#Microsoft.Graph.Message"",
              ""id"": ""msgId"",
              ""subject"": ""message with attachs"",
              ""isRead"": ""true"",
              ""attachments"": [
                {
                  ""@odata.type"": ""#Microsoft.Graph.ItemAttachment"",
                  ""id"": ""itemAttachment=="",
                  ""item"":{
                    ""id"": ""attachmentitemId"",
                    ""changeKey"": ""ck=="",
                    ""subject"": ""attachment item subject"",
                    ""@odata.type"": ""#Microsoft.Graph.Event"",
                    ""attendees"": [
                      {
                        ""emailAddress"":{
                          ""address"": ""*****@*****.**""
                        }
                      },
                      {
                        ""emailAddress"": {
                          ""address"": ""*****@*****.**""
                        }
                      }
                    ],
                    ""body"": {
                      ""Content"": ""this is event"",
                      ""ContentType"": ""Html""
                    },
                    ""start"":{
                      ""dateTime"": ""2019-01-01T12:00:00"",
                      ""TimeZone"": ""Pacific Standard Time""
                    },
                    ""end"": {
                      ""dateTime"": ""2019-01-01T04:00:00"",
                      ""TimeZone"": ""Pacific Standard Time""
                    }
                  }
                }
              ]
            }";

            Message msg = this.Convert <Message>(serializedMessage);

            Assert.AreEqual(
                1,
                msg.Attachments.Count);
            ItemAttachment messageAttach      = (ItemAttachment)msg.Attachments[0];
            Event          messageAttachEvent = (Event)messageAttach.Item;

            Assert.AreEqual(
                2,
                messageAttachEvent.Attendees.Count);

            Assert.IsNotNull(messageAttachEvent.Start.DateTime);
            Assert.IsNotNull(messageAttachEvent.End.DateTime);
        }
        private void MnuDisplayAsItem_Click(object sender, EventArgs e)
        {
            // Don't do anything if a content row is not selected
            if (this.ContentsGrid.SelectedRows.Count == 0)
            {
                return;
            }

            Attachment attach = this.ContentsGrid.SelectedRows[0].Cells[ColNameAttachmentObj].Value as Attachment;

            // If we can't get the attachment object bail out
            if (attach == null)
            {
                return;
            }

            ItemAttachment itemAttachment = attach as ItemAttachment;

            if (itemAttachment == null)
            {
                // Warn the user that an ItemAttachment is required?
                return;
            }

            if (itemAttachment.Item == null)
            {
                DebugLog.WriteVerbose("Cannot display ItemAttachment.Item because ItemAttachment.Item is NULL.");
                ErrorDialog.ShowWarning("Cannot display ItemAttachment.Item because ItemAttachment.Item is NULL.");
                return;
            }

            this.PropertyDetailsGrid.LoadObject(itemAttachment.Item);
        }
Exemplo n.º 10
0
        public void Test_InnerPropertyTracking()
        {
            ItemAttachment itemAttachment = new ItemAttachment()
            {
                Name = "Item attach",
                Item = new Event()
                {
                    Subject   = "Lets meet?",
                    Attendees = new List <Attendee>()
                    {
                        new Attendee()
                        {
                            EmailAddress = new EmailAddress()
                            {
                                Address = "*****@*****.**"
                            }
                        }
                    },

                    Body = new ItemBody()
                    {
                        ContentType = BodyType.Html,
                        Content     = "Meeting!"
                    }
                }
            };

            Assert.AreEqual(
                2,
                itemAttachment.GetChangedProperties().Count());

            Assert.AreEqual(
                3,
                itemAttachment.Item.GetChangedProperties().Count());
        }
Exemplo n.º 11
0
        public static void Pack(Signal signal, MessageItem mailMessage)
        {
            List <Item> list = new List <Item>();

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8))
                {
                    binaryWriter.Write(1);
                    list = signal.WriteObject(binaryWriter);
                    using (TextWriter textWriter = mailMessage.Body.OpenTextWriter(BodyFormat.TextPlain))
                    {
                        textWriter.Write(Convert.ToBase64String(memoryStream.ToArray()));
                    }
                }
            }
            foreach (Item item in list)
            {
                ExchangeItem exchangeItem = item as ExchangeItem;
                if (exchangeItem != null)
                {
                    if (exchangeItem.Item.IsNew)
                    {
                        throw new ArgumentException("Item must be saved in order to attach.");
                    }
                    using (ItemAttachment itemAttachment = mailMessage.AttachmentCollection.AddExistingItem(exchangeItem.Item))
                    {
                        itemAttachment.ContentId = exchangeItem.AttachContentId.ToString();
                        itemAttachment.Save();
                    }
                }
            }
        }
        public void Delete(int id)
        {
            ItemAttachment attachment = new ItemAttachment();

            attachment.ID = id;
            db.ItemAttachments.Remove(attachment);
            db.SaveChanges();
        }
Exemplo n.º 13
0
        public void Test_InnerPropertyListTracking()
        {
            DateTime startTime = DateTimeHelper.GetFormattedDateTime();
            DateTime endTime   = DateTimeHelper.GetFormattedDateTime(2);
            string   timeZone  = "Central European Standard Time";

            Message msg = new Message();

            msg.Subject = "Test item attachment";
            ItemAttachment attach = new ItemAttachment()
            {
                Name = "Event Item",
                Item = new Event()
                {
                    Attendees = new List <Attendee>()
                    {
                        new Attendee()
                        {
                            EmailAddress = new EmailAddress()
                            {
                                Address = "*****@*****.**"
                            }
                        }
                    },
                    Body = new ItemBody()
                    {
                        ContentType = BodyType.Html,
                        Content     = "Lets meet up"
                    },

                    Start = new DateTimeTimeZone()
                    {
                        DateTime = startTime.ToString(),
                        TimeZone = timeZone.ToString()
                    },

                    End = new DateTimeTimeZone()
                    {
                        DateTime = endTime.ToString(),
                        TimeZone = timeZone
                    }
                }
            };

            msg.Attachments.Add(attach);

            Assert.AreEqual(
                2,
                msg.GetChangedProperties().Count());

            Assert.AreEqual(
                2,
                msg.Attachments[0].GetChangedProperties().Count());

            Assert.AreEqual(
                4,
                ((ItemAttachment)msg.Attachments[0]).Item.GetChangedProperties().Count());
        }
Exemplo n.º 14
0
        private AttachmentResponse GetAttachmentsFromExchangeServerUsingEWSManagedApi(AttachmentRequest request)
        {
            var attachmentsProcessedCount = 0;
            var attachmentNames           = new List <string>();

            // Creo un oggetto di tipo ExchangeService
            ExchangeService service = new ExchangeService();

            //imposto il token di autenticazione ricevuto dall'add-in
            service.Credentials = new OAuthCredentials(request.attachmentToken);
            //imposto la url del server Exchange
            service.Url = new Uri(request.ewsUrl);

            // Richiede gli allegati al server
            var getAttachmentsResponse = service.GetAttachments(
                request.attachments.Select(a => a.id).ToArray(),
                null,
                new PropertySet(BasePropertySet.FirstClassProperties,
                                ItemSchema.MimeContent));

            if (getAttachmentsResponse.OverallResult == ServiceResult.Success)
            {
                foreach (var attachmentResponse in getAttachmentsResponse)
                {
                    attachmentNames.Add(attachmentResponse.Attachment.Name);

                    if (attachmentResponse.Attachment is FileAttachment)
                    {
                        //mette il contenuto dell'allegato in uno stream
                        FileAttachment fileAttachment = attachmentResponse.Attachment as FileAttachment;
                        Stream         s = new MemoryStream(fileAttachment.Content);

                        // Qui è possibile processare il contenuto dell'allegato
                    }

                    if (attachmentResponse.Attachment is ItemAttachment)
                    {
                        //mette il contenuto dell'allegato in uno stream
                        ItemAttachment itemAttachment = attachmentResponse.Attachment as ItemAttachment;
                        Stream         s = new MemoryStream(itemAttachment.Item.MimeContent.Content);

                        // Qui è possibile processare il contenuto dell'allegato
                    }

                    attachmentsProcessedCount++;
                }
            }

            // La risposta contiene il nome ed il numero degli allegati che sono stati
            // processati dal servizio
            var response = new AttachmentResponse();

            response.attachmentNames      = attachmentNames.ToArray();
            response.attachmentsProcessed = attachmentsProcessedCount;

            return(response);
        }
Exemplo n.º 15
0
 public void Post([FromBody] ItemAttachment attachment)
 {
     // TODO: Add data validation
     using (var dataContext = new APIDBContext())
     {
         dataContext.ItemAttachments.Add(attachment);
         dataContext.SaveChanges();
     }
 }
Exemplo n.º 16
0
        private static void RenderAttachment(TextWriter output, AttachmentWellInfo attachmentInfoObject, UserContext userContext, ArrayList previousAttachmentDisplayNames)
        {
            ItemAttachment itemAttachment = null;
            Item           item           = null;
            string         value          = null;

            try
            {
                if (attachmentInfoObject.AttachmentType == AttachmentType.EmbeddedMessage)
                {
                    itemAttachment = (ItemAttachment)attachmentInfoObject.OpenAttachment();
                    item           = itemAttachment.GetItemAsReadOnly(new PropertyDefinition[]
                    {
                        TaskSchema.TaskType
                    });
                }
                if (item != null)
                {
                    value = Utilities.HtmlEncode(AttachmentUtility.TrimAttachmentDisplayName(AttachmentUtility.GetEmbeddedAttachmentDisplayName(item), previousAttachmentDisplayNames, true));
                }
                else
                {
                    value = Utilities.HtmlEncode(AttachmentUtility.TrimAttachmentDisplayName(attachmentInfoObject.AttachmentName, previousAttachmentDisplayNames, false));
                }
            }
            catch (ObjectNotFoundException)
            {
                return;
            }
            finally
            {
                if (item != null)
                {
                    item.Dispose();
                    item = null;
                }
                if (itemAttachment != null)
                {
                    itemAttachment.Dispose();
                    itemAttachment = null;
                }
            }
            output.Write("<span id=\"spnAtmt\" tabindex=\"-1\">");
            output.Write(value);
            long size = attachmentInfoObject.Size;

            if (size > 0L)
            {
                output.Write(userContext.DirectionMark);
                output.Write(" ");
                output.Write(LocalizedStrings.GetHtmlEncoded(6409762));
                Utilities.RenderSizeWithUnits(output, size, true);
                output.Write(userContext.DirectionMark);
                output.Write(LocalizedStrings.GetHtmlEncoded(-1023695022));
            }
            output.Write("</span>");
        }
Exemplo n.º 17
0
 public void Put(int id, [FromBody] ItemAttachment attachment)
 {
     // TODO: Add data validation
     attachment.ID = id;
     using (var dataContext = new APIDBContext())
     {
         dataContext.ItemAttachments.Update(attachment);
         dataContext.SaveChanges();
     }
 }
        /// <summary>
        /// CRUD operation for item attachments
        /// </summary>
        /// <param name="exchangeService"></param>
        public static void CreateReadUpdateDeleteItemAttachment(ExchangeService exchangeService)
        {
            DateTime startTime = TestHelpers.GetFormattedDateTime();
            DateTime endTime   = TestHelpers.GetFormattedDateTime(2);
            string   timeZone  = "Central European Standard Time";

            Message msg = new Message(exchangeService);

            msg.Subject = "Test item attachment";

            ItemAttachment attach = new ItemAttachment()
            {
                Name = "Attached message",
                Item = new Message()
                {
                    Body = new ItemBody()
                    {
                        ContentType = BodyType.HTML,
                        Content     = "Lets meet up"
                    },
                    ToRecipients = new List <Recipient>()
                    {
                        new Recipient()
                        {
                            EmailAddress = new EmailAddress()
                            {
                                Address = "*****@*****.**"
                            }
                        }
                    }
                }
            };

            msg.Attachments.Add(attach);
            msg.Save(WellKnownFolderName.Inbox);

            AttachmentId attachId = new AttachmentId(
                msg.Attachments[0].Id,
                msg.ItemId,
                AppConfig.MailboxA);

            Attachment attachment = exchangeService.GetAttachment(attachId);

            Assert.IsInstanceOfType(
                attachment,
                typeof(ItemAttachment));

            attachment = exchangeService.GetAttachment(attachId,
                                                       new ExpandQuery("Microsoft.OutlookServices.ItemAttachment/Item"));

            ItemAttachment itemAttachment = (ItemAttachment)attachment;

            Assert.IsNotNull(itemAttachment.Item);
            Assert.IsInstanceOfType(itemAttachment.Item, typeof(Message));
        }
Exemplo n.º 19
0
        public void Delete(int id)
        {
            ItemAttachment attachment = new ItemAttachment();

            attachment.ID = id;
            using (var dataContext = new APIDBContext())
            {
                dataContext.ItemAttachments.Remove(attachment);
                dataContext.SaveChanges();
            }
        }
Exemplo n.º 20
0
        public static void LoadItemsAttachmentsListLv(Item oItem, ref ListView oListView)
        {
            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("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 oItem.Attachments)
            {
                oItem.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                oAttachment.Load();
                if (oAttachment is ItemAttachment)
                {
                    ItemAttachment oItemAttachment = oAttachment as ItemAttachment;

                    // Load attachment into memory so we can get to the item properties (such as subject).
                    oItem.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                    oItemAttachment.Load();

                    oListItem = new ListViewItem(oAttachment.Id, 0);

                    oListItem.SubItems.Add(oItemAttachment.ContentId);
                    oListItem.SubItems.Add(oItemAttachment.ContentLocation);
                    oListItem.SubItems.Add(oItemAttachment.ContentType);
                    oListItem.SubItems.Add(oItemAttachment.Name);
                    oListItem.SubItems.Add(oItemAttachment.IsInline.ToString());



                    oListItem.Tag = iAttachmentCount;
                    oListView.Items.AddRange(new ListViewItem[] { oListItem });
                    oListItem = null;
                }

                if (oAttachment is FileAttachment)
                {
                }
            }
            iAttachmentCount++;
        }
        public EWSIncomingItemAttachment(ItemAttachment attachment)
        {
            _attachment = attachment;
            Logger.DebugFormat("Loading attachment");
            var additionalProperties = new PropertySet {
                ItemSchema.MimeContent
            };

            _attachment.Load(additionalProperties);

            Logger.DebugFormat("Attachment name is {0}", _attachment.Name);
        }
Exemplo n.º 22
0
 internal static void CreateAttachment(IItem parentItem, Attachment16Data attachmentData)
 {
     AirSyncDiagnostics.TraceDebug <byte>(ExTraceGlobals.RequestsTracer, null, "CreateAttachment with AttachMethod:{0}", attachmentData.Method);
     if (attachmentData.Method == 1)
     {
         if (attachmentData.Content == null)
         {
             throw new ConversionException(string.Format(" Attachment content can not be null.", new object[0]));
         }
         IStreamAttachment streamAttachment = parentItem.IAttachmentCollection.CreateIAttachment(AttachmentType.Stream) as IStreamAttachment;
         AttachmentHelper.CopyCommonAttachmentProperties(streamAttachment, attachmentData);
         using (Stream contentStream = streamAttachment.GetContentStream())
         {
             contentStream.Write(attachmentData.Content, 0, attachmentData.Content.Length);
         }
         streamAttachment.Save();
     }
     else
     {
         if (attachmentData.Method != 5)
         {
             throw new ConversionException(string.Format("UnSupported Value '{0}' for Attachment Method. Only 1 & 5 is supported AttachemntType", attachmentData.Method));
         }
         ItemAttachment itemAttachment = parentItem.IAttachmentCollection.CreateIAttachment(AttachmentType.EmbeddedMessage) as ItemAttachment;
         AttachmentHelper.CopyCommonAttachmentProperties(itemAttachment, attachmentData);
         using (Stream stream = new MemoryStream(attachmentData.Content))
         {
             stream.Seek(0L, SeekOrigin.Begin);
             InboundConversionOptions inboundConversionOptions = AirSyncUtility.GetInboundConversionOptions();
             inboundConversionOptions.ClearCategories = false;
             try
             {
                 using (Item item = itemAttachment.GetItem())
                 {
                     ItemConversion.ConvertAnyMimeToItem(item, stream, inboundConversionOptions);
                     item.Save(SaveMode.NoConflictResolution);
                 }
             }
             catch (ExchangeDataException innerException)
             {
                 throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidMIME, innerException, false);
             }
             catch (ConversionFailedException innerException2)
             {
                 throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidMIME, innerException2, false);
             }
         }
         itemAttachment.Save();
     }
     AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.RequestsTracer, null, "AttachmentHelper:CreateAttachments:: AttachmentCreated successful. AttachmentCount:{0}", parentItem.IAttachmentCollection.Count);
 }
Exemplo n.º 23
0
        /// <summary>
        /// Demonstrates three ways to get file attachments and how to get an item attachment.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void GetAttachments(ExchangeService service)
        {
            // Return a single item.
            ItemView view = new ItemView(1);

            string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";

            // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
            FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

            if (results.TotalCount > 0)
            {
                EmailMessage email = results.Items[0] as EmailMessage;

                // Request all the attachments on the email message. This results in a GetItem operation call to EWS.
                email.Load(new PropertySet(EmailMessageSchema.Attachments));

                foreach (Attachment attachment in email.Attachments)
                {
                    if (attachment is FileAttachment)
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;

                        // Load the file attachment into memory. This gives you access to the attachment content, which
                        // is a byte array that you can use to attach this file to another item. This results in a GetAttachment operation
                        // call to EWS.
                        fileAttachment.Load();
                        Console.WriteLine("Load a file attachment with a name = " + fileAttachment.Name);

                        // Load attachment contents into a file. This results in a GetAttachment operation call to EWS.
                        fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);

                        // Put attachment contents into a stream.
                        using (FileStream theStream = new FileStream("C:\\temp\\Stream_" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            //This results in a GetAttachment operation call to EWS.
                            fileAttachment.Load(theStream);
                        }
                    }
                    else // Attachment is an item attachment.
                    {
                        ItemAttachment itemAttachment = attachment as ItemAttachment;

                        // Load the item attachment properties. This results in a GetAttachment operation call to EWS.
                        itemAttachment.Load();
                        Console.WriteLine("Loaded an item attachment with Subject = " + itemAttachment.Item.Subject);
                    }
                }
            }
        }
Exemplo n.º 24
0
        // TODO: Figure out how to implement this
        public void AddAttachment(IMailItem mailItem)
        {
#if false
            var itemProvider = mailItem as MailItemProvider;

            var itemAttachment = new ItemAttachment
            {
                Item = new Item {
                    Id = itemProvider.Handle.Id
                },
                Name = "Item Attachment!!!",
            };

            Util.PostAsync <ItemAttachment>(Uri + "/attachments", itemAttachment).Wait();
#endif
        }
        // Token: 0x06001988 RID: 6536 RVA: 0x000953D4 File Offset: 0x000935D4
        internal Stream GetItemAttachmentStream(Attachment attachment, HttpContext httpContext)
        {
            OwaContext  owaContext  = OwaContext.Get(httpContext);
            UserContext userContext = owaContext.UserContext;
            OutboundConversionOptions outboundConversionOptions = Utilities.CreateOutboundConversionOptions(userContext);
            Stream         stream         = Streams.CreateTemporaryStorageStream();
            string         text           = null;
            ItemAttachment itemAttachment = attachment as ItemAttachment;

            using (Item item = itemAttachment.GetItem(StoreObjectSchema.ContentConversionProperties))
            {
                try
                {
                    if (ItemConversion.IsItemClassConvertibleToMime(item.ClassName))
                    {
                        ItemConversion.ConvertItemToMime(item, stream, outboundConversionOptions);
                        text = ".eml";
                    }
                    else if (ObjectClass.IsCalendarItemCalendarItemOccurrenceOrRecurrenceException(item.ClassName))
                    {
                        (item as CalendarItemBase).ExportAsICAL(stream, "UTF-8", outboundConversionOptions);
                        text = ".ics";
                    }
                    else if (ObjectClass.IsContact(item.ClassName))
                    {
                        Contact.ExportVCard(item as Contact, stream, outboundConversionOptions);
                        text = ".vcf";
                    }
                    else
                    {
                        ItemConversion.ConvertItemToMsgStorage(item, stream, outboundConversionOptions);
                    }
                }
                catch (Exception)
                {
                    stream = this.GetContentsReplacementStream(-1706159495);
                    text   = ".txt";
                }
            }
            if (text != null)
            {
                this.fileName             = this.GetConvertedItemFileName(this.fileName, text);
                this.encodedfileNameBytes = this.GetEncodedString(this.fileName);
            }
            stream.Position = 0L;
            return(stream);
        }
Exemplo n.º 26
0
        // TODO: Figure out how to implement this
        public void AddAttachment(IMailItem mailItem)
        {
#if false
            var itemProvider = mailItem as MailItemProvider;

            var msgFetcher = _outlookClient.Me.Messages.GetById(_message.Id);

            var itemAttachment = new ItemAttachment
            {
                Item = itemProvider.Handle as Message,

                Name = "Item Attachment!!!",
            };

            Util.Synchronize(async() => await msgFetcher.Attachments.AddAttachmentAsync(itemAttachment));
#endif
        }
        public async Task <IActionResult> Create([Bind("Id,ImageData,Link,ContentType,ItemId,ItemAttachmentTypeId")] ItemAttachment itemAttachment, IFormFile image)
        {
            var slug = _context.Item.FirstOrDefault(i => i.Id == itemAttachment.ItemId).Slug;

            if (ModelState.IsValid)
            {
                itemAttachment.ContentType = _imageService.RecordContentType(image);
                itemAttachment.ImageData   = await _imageService.EncodeFileAsync(image);

                _context.Add(itemAttachment);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Details", "Items", new { slug }));
            }
            ViewData["ItemId"] = new SelectList(_context.Item, "Id", "Name", itemAttachment.ItemId);
            return(RedirectToAction("Details", "Items", new { slug }));
        }
        public void TestPropertyTrackingWithInnerProperties()
        {
            ItemAttachment itemAttachment = new ItemAttachment()
            {
                Name = "Item attach",
                Item = new Event()
                {
                    Subject   = "Event subject",
                    Attendees = new List <Attendee>()
                    {
                        new Attendee()
                        {
                            EmailAddress = new EmailAddress()
                            {
                                Address = "*****@*****.**"
                            }
                        }
                    },

                    Body = new ItemBody()
                }
            };

            Assert.AreEqual(
                2,
                itemAttachment.GetChangedProperies().Count);

            Assert.AreEqual(
                3,
                itemAttachment.Item.GetChangedProperies().Count);

            Assert.IsTrue(
                ItemAttachmentObjectSchema.Item.ChangeTrackable);

            itemAttachment.ResetChangeTracking();

            Assert.AreEqual(
                0,
                itemAttachment.GetChangedProperies().Count);

            Assert.AreEqual(
                0,
                itemAttachment.Item.GetChangedProperies().Count);
        }
Exemplo n.º 29
0
        public EmailAttachDTO(object attach, bool loadContent = true)
        {
            byte[] content = null;
            if (attach.GetType() == typeof(FileAttachment))
            {
                FileAttachment fAttach = (FileAttachment)attach;
                if (loadContent)
                {
                    if (fAttach.Content is null)
                    {
                        fAttach.Load();
                    }
                    content = fAttach.Content;
                }

                cargar_datos(fAttach.Id, fAttach.Name, fAttach.ContentType, fAttach.Size, content, fAttach.IsInline);
            }
            else if (attach.GetType() == typeof(ItemAttachment))
            {
                ItemAttachment iAttach = (ItemAttachment)attach;
                if (loadContent)
                {
                    iAttach.Load(ItemSchema.MimeContent);
                    if (iAttach.Item is object && iAttach.Item.GetType() == typeof(EmailMessage))
                    {
                        EmailMessage mAttach = (EmailMessage)iAttach.Item;
                        if (loadContent)
                        {
                            content = mAttach.MimeContent.Content;
                        }
                        cargar_datos(iAttach.Id, iAttach.Name + ".eml", iAttach.ContentType, iAttach.Size, content, iAttach.IsInline);
                    }
                    else
                    {
                        cargar_datos(iAttach.Id, iAttach.Name, iAttach.ContentType, iAttach.Size, null, iAttach.IsInline);
                    }
                }
                else
                {
                    cargar_datos(iAttach.Id, iAttach.Name, iAttach.ContentType, iAttach.Size, null, iAttach.IsInline);
                }
            }
        }
Exemplo n.º 30
0
        //gavdcodeend 16

        //gavdcodebegin 17
        static void GetAttachments(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Email with Attachments"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Inbox, myFilter, myView);

            ItemId myEmailId = null;

            foreach (Item oneItem in findResults)
            {
                myEmailId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    ItemSchema.Attachments);
            EmailMessage emailWithAttachments =
                EmailMessage.Bind(ExService, myEmailId, myPropSet);

            foreach (Attachment oneAttachment in emailWithAttachments.Attachments)
            {
                if (oneAttachment is FileAttachment) // Attachment is a File
                {
                    FileAttachment myAttachment = oneAttachment as FileAttachment;

                    FileStream attStream = new FileStream(@"C:\Temporary\Attch_" +
                                                          myAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    myAttachment.Load(attStream);
                    attStream.Close();
                    attStream.Dispose();
                }
                else // Attachment is an Item
                {
                    ItemAttachment itemAttachment = oneAttachment as ItemAttachment;
                    itemAttachment.Load();
                    Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
                }
            }
        }
Exemplo n.º 31
0
        // TODO: Figure out how to implement this
        public void AddAttachment(IMailItem mailItem)
        {
            #if false
            var itemProvider = mailItem as MailItemProvider;

            var itemAttachment = new ItemAttachment
            {
                Item = new Item { Id = itemProvider.Handle.Id },
                Name = "Item Attachment!!!",
            };

               Util.PostAsync<ItemAttachment>(Uri + "/attachments", itemAttachment).Wait();
            #endif
        }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContactGroup"/> class.
 /// </summary>
 /// <param name="parentAttachment">The parent attachment.</param>
 internal ContactGroup(ItemAttachment parentAttachment)
     : base(parentAttachment)
 {
 }
Exemplo n.º 33
0
    // Call this function when play press the pegs. check if in item selection mode
    public void SetSelectionMode(bool mode)
    {
        if(mode)
        {
            // get the Peg attach script from the current selected peg
            PegAttach = PegAttachObject.GetComponent<ItemAttachment>();

        } else
        {
            //Exit Item selection mode and reset pegattach
            ItemSelectionMode = false;
            PegAttach= null;
        }

            // Remove the seleced item from the inventory
            if(!eventSystem.IsPointerOverGameObject(-1) && from != null && PegAttach == null)
            {

                from.GetComponent<Image>().color = Color.white;
                from.ClearSlot(); // remove item from slot

                //Reset objects
                to = null;
                from = null;

                emptySlots++;
            }else if (!eventSystem.IsPointerOverGameObject(-1) && from != null && PegAttach != null)
            {

                PegAttach.ItemAttach(from.Items.Peek());

                from.GetComponent<Image>().color = Color.white;
                from.ClearSlot(); // remove item from slot

                //Reset objects
                to = null;
                from = null;
                emptySlots++;
                //				Debug.Log("Did not Click on the UI " + eventSystem.name);
            }
    }
Exemplo n.º 34
0
        // TODO: Figure out how to implement this
        public void AddAttachment(IMailItem mailItem)
        {
            #if false
            var itemProvider = mailItem as MailItemProvider;

            var msgFetcher = _outlookClient.Me.Messages.GetById(_message.Id);

            var itemAttachment = new ItemAttachment
            {
                Item = itemProvider.Handle as Message,

                Name = "Item Attachment!!!",
            };

               Util.Synchronize(async () => await msgFetcher.Attachments.AddAttachmentAsync(itemAttachment));
            #endif
        }