// Token: 0x060014EB RID: 5355 RVA: 0x00079B0C File Offset: 0x00077D0C private void LoadPictureData(StreamAttachment picture) { AirSyncDiagnostics.TraceDebug(ExTraceGlobals.CommonTracer, null, "XsoPictureProperty.GetPicture(), getting picture attachment data."); Stream stream = null; try { stream = picture.GetContentStream(); if (stream.Length <= 37500L) { byte[] array = new byte[stream.Length]; int num = stream.Read(array, 0, array.Length); if (num == array.Length) { this.cachedPicture = Convert.ToBase64String(array); } } } catch (ObjectNotFoundException) { } finally { if (stream != null) { stream.Dispose(); } } }
public static void ProcessAttachment(IStoreSession session, string ewsAttachmentId, IExchangePrincipal exchangePrincipal, PropertyOpenMode openMode, WacUtilities.AttachmentProcessor attachmentProcessor) { IdConverterDependencies converterDependencies = new IdConverterDependencies.FromRawData(false, false, null, null, exchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), session as MailboxSession, session as MailboxSession, session as PublicFolderSession); using (AttachmentHandler.IAttachmentRetriever attachmentRetriever = AttachmentRetriever.CreateInstance(ewsAttachmentId, converterDependencies)) { bool flag = WacUtilities.IsIrmRestricted(attachmentRetriever.RootItem); if (openMode == PropertyOpenMode.Modify) { attachmentRetriever.RootItem.OpenAsReadWrite(); } StreamAttachment streamAttachment = attachmentRetriever.Attachment as StreamAttachment; if (streamAttachment == null) { attachmentProcessor(exchangePrincipal, attachmentRetriever.Attachment, null, flag); } else { using (Stream contentStream = streamAttachment.GetContentStream(openMode)) { bool flag2 = WacUtilities.IsContentProtected(attachmentRetriever.Attachment.FileName, contentStream); attachmentProcessor(exchangePrincipal, streamAttachment, contentStream, flag || flag2); if (openMode == PropertyOpenMode.Modify) { attachmentRetriever.RootItem.Save(SaveMode.NoConflictResolution); } } } } }
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)); }
public async Task SendClientAppointmentsInvoice(int clientId, byte[] fileBytes) { Client client = await _clientService.GetClient(clientId); if (client != null) { string clientEmail = client.User.Email; //CreateStreamAttachment, depending on appointment StreamAttachment streamAttach = new StreamAttachment(); streamAttach.Stream = new System.IO.MemoryStream(fileBytes); streamAttach.FileName = "Appointment_Invoice.pdf"; EmailModel email = new EmailModel { EmailsTo = new List <string> { clientEmail }, Subject = EmailHelper.AppointmentInvoiceSubject, Message = EmailHelper.AppointmentInvoiceMessage(client.User.UserName), StreamAttachments = new List <StreamAttachment> { streamAttach } }; await SendEmailAsync(email); } }
private SyncMetadataAttachmentStream(StreamAttachment streamAttachment, Stream contentStream, StreamBase.Capabilities streamCapabilities) : base(contentStream, true, streamCapabilities | StreamBase.Capabilities.Seekable) { ArgumentValidator.ThrowIfNull("streamAttachment", streamAttachment); ArgumentValidator.ThrowIfNull("contentStream", contentStream); this.streamAttachment = streamAttachment; this.shouldSaveOnDispose = ((streamCapabilities & StreamBase.Capabilities.Writable) == StreamBase.Capabilities.Writable); }
// Token: 0x06000034 RID: 52 RVA: 0x00003938 File Offset: 0x00001B38 private static bool TryGetCommentAttachment(MessageItem messageItem, out StreamAttachment targetAttachment) { targetAttachment = null; AttachmentCollection attachmentCollection = messageItem.AttachmentCollection; foreach (AttachmentHandle handle in attachmentCollection) { Attachment attachment = null; try { attachment = attachmentCollection.Open(handle); if ("DecisionComments.txt".Equals(attachment.FileName, StringComparison.OrdinalIgnoreCase)) { targetAttachment = (attachment as StreamAttachment); if (targetAttachment != null) { attachment = null; return(true); } ModeratedDLApplication.diag.TraceError <Attachment>(0L, "Found attachment with the correct name, but it's not a stream: {0}", attachment); } } finally { if (attachment != null) { attachment.Dispose(); attachment = null; } } } return(false); }
public static Stream GetStreamForProtectedAttachment(StreamAttachment attachment, IExchangePrincipal exchangePrincipal) { UseLicenseAndUsageRights useLicenseAndUsageRights; bool flag; return(StreamAttachment.OpenRestrictedAttachment(attachment, exchangePrincipal.MailboxInfo.OrganizationId, exchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), exchangePrincipal.Sid, exchangePrincipal.RecipientTypeDetails, out useLicenseAndUsageRights, out flag)); }
// Token: 0x0600176A RID: 5994 RVA: 0x0008B5C8 File Offset: 0x000897C8 internal MemoryStream GetSyncState(StoreObjectId parentFolderId, string syncstateName) { if (!this.parentIdToSyncstates.ContainsKey(parentFolderId)) { Dictionary <string, StoreObjectId> dictionary = new Dictionary <string, StoreObjectId>(); using (Folder folder = Folder.Bind(this.MailboxSessionForUtility, parentFolderId)) { using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, null, MailboxUtility.itemIdSubjectProperties)) { object[][] rows = queryResult.GetRows(10000); while (rows != null && rows.Length > 0) { for (int i = 0; i < rows.Length; i++) { string text = rows[i][1] as string; StoreObjectId storeOrVersionedId = MailboxUtility.GetStoreOrVersionedId(rows[i][0]); if (text != null && storeOrVersionedId != null) { dictionary[text] = storeOrVersionedId; } } rows = queryResult.GetRows(10000); } } } this.parentIdToSyncstates[parentFolderId] = dictionary; } if (!this.parentIdToSyncstates[parentFolderId].ContainsKey(syncstateName)) { return(null); } StoreObjectId storeId = this.parentIdToSyncstates[parentFolderId][syncstateName]; using (Item item = Item.Bind(this.MailboxSessionForUtility, storeId)) { IList <AttachmentHandle> handles = item.AttachmentCollection.GetHandles(); if (handles.Count > 0) { using (Attachment attachment = item.AttachmentCollection.Open(handles[0])) { StreamAttachment streamAttachment = attachment as StreamAttachment; if (streamAttachment != null) { using (Stream contentStream = streamAttachment.GetContentStream()) { MemoryStream memoryStream = MailboxUtility.bufferPool.Acquire(1000); StreamHelper.CopyStream(contentStream, memoryStream, 0, (int)contentStream.Length); return(memoryStream); } } } } } return(null); }
private StreamAttachment CreateStreamAttachment(string name) { base.OpenAsReadWrite(); StreamAttachment result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { StreamAttachment streamAttachment = base.AttachmentCollection.Create(AttachmentType.Stream) as StreamAttachment; disposeGuard.Add <StreamAttachment>(streamAttachment); streamAttachment.FileName = name; disposeGuard.Success(); result = streamAttachment; } return(result); }
public void AddImageAsAttachment(MessageItem message) { ImageAttachment.Tracer.TraceDebug <string, string>((long)this.GetHashCode(), "ImageAttachment.AddImageAsAttachment: Image Name: {0}. Image Id: {1}", this.ImageName, this.ImageId); using (StreamAttachment streamAttachment = message.AttachmentCollection.Create(AttachmentType.Stream) as StreamAttachment) { using (Stream contentStream = streamAttachment.GetContentStream()) { streamAttachment.FileName = this.ImageName; streamAttachment.ContentId = this.ImageId; streamAttachment.ContentType = this.contentType; contentStream.Write(this.bytes, 0, this.bytes.Length); streamAttachment.Save(); } } }
public void StreamAttachment() { var content = new StreamAttachment { Name = "Test", Stream = new MemoryStream(Encoding.ASCII.GetBytes("Content")), MediaType = "text/plain" }; var factory = new MailAttachmentFactory(); var candidate = factory.CreateAttachement(content); Assert.IsNotNull(candidate); Assert.AreEqual("Test", candidate.Name); }
private void DeleteAttachment(string attachmentName) { base.OpenAsReadWrite(); using (StreamAttachment streamAttachment = this.GetStreamAttachment(attachmentName)) { if (streamAttachment != null) { HierarchySyncMetadataItem.Tracer.TraceDebug <string, AttachmentId>((long)this.GetHashCode(), "HierarchySyncMetadataItem:DeleteAttachment - Removing attachment with name='{0}' and Id='{1}'", attachmentName, streamAttachment.Id); base.AttachmentCollection.Remove(streamAttachment.Id); } else { HierarchySyncMetadataItem.Tracer.TraceDebug <string>((long)this.GetHashCode(), "HierarchySyncMetadataItem:DeleteAttachment - Didn't find an stream attachment with name='{0}'", attachmentName); } } }
// Token: 0x06002C61 RID: 11361 RVA: 0x000F7264 File Offset: 0x000F5464 private Stream GetContactPictureStream(Item item, string attId, out string contentType) { contentType = string.Empty; if (item == null) { return(new MemoryStream()); } if (string.IsNullOrEmpty(attId)) { attId = RenderingUtilities.GetContactPictureAttachmentId(item); } if (string.IsNullOrEmpty(attId)) { return(new MemoryStream()); } AttachmentId id = item.CreateAttachmentId(attId); AttachmentCollection attachmentCollection = Utilities.GetAttachmentCollection(item, true, base.UserContext); Stream result; using (StreamAttachment streamAttachment = attachmentCollection.Open(id) as StreamAttachment) { if (streamAttachment == null) { throw new OwaInvalidRequestException("Attachment is not a stream attachment"); } AttachmentPolicy.Level attachmentLevel = AttachmentLevelLookup.GetAttachmentLevel(streamAttachment, base.UserContext); if (attachmentLevel == AttachmentPolicy.Level.Block) { result = new MemoryStream(); } else { contentType = AttachmentEventHandler.GetContentType(streamAttachment.FileName); if (contentType.Length == 0) { ExTraceGlobals.ContactsTracer.TraceDebug <string>((long)this.GetHashCode(), "Cannot determine image type for file: {0}", streamAttachment.FileName); result = new MemoryStream(); } else { result = streamAttachment.GetContentStream(); } } } return(result); }
private void RenameAttachment(string originalAttachmentName, string newAttachmentName) { base.OpenAsReadWrite(); using (StreamAttachment streamAttachment = this.GetStreamAttachment(originalAttachmentName)) { if (streamAttachment != null) { HierarchySyncMetadataItem.Tracer.TraceDebug <AttachmentId, string, string>((long)this.GetHashCode(), "HierarchySyncMetadataItem:RenameAttachment - Renaming attachment with Id='{0}'. Old name='{1}', new name='{2}'.", streamAttachment.Id, originalAttachmentName, newAttachmentName); streamAttachment.FileName = newAttachmentName; streamAttachment.Save(); } else { HierarchySyncMetadataItem.Tracer.TraceDebug <string>((long)this.GetHashCode(), "HierarchySyncMetadataItem:RenameAttachment - Didn't find an stream attachment with name='{0}'", originalAttachmentName); } } }
public static HierarchySyncMetadataItem.SyncMetadataAttachmentStream CreateAttachment(HierarchySyncMetadataItem item, string attachmentName, bool overrideIfExisting) { ArgumentValidator.ThrowIfNull("item", item); ArgumentValidator.ThrowIfNullOrWhiteSpace("attachmentName", attachmentName); using (StreamAttachment streamAttachment = item.GetStreamAttachment(attachmentName)) { if (streamAttachment != null) { if (!overrideIfExisting) { HierarchySyncMetadataItem.Tracer.TraceDebug(0L, "SyncMetadataAttachmentStream:CreateAttachment - Skiping creation of sync state attachment and one already exist and override was not selected"); return(null); } item.DeleteAttachment(attachmentName); } } return(HierarchySyncMetadataItem.SyncMetadataAttachmentStream.Instantate(item.CreateStreamAttachment(attachmentName), StreamBase.Capabilities.Writable)); }
// Token: 0x0600003E RID: 62 RVA: 0x00004434 File Offset: 0x00002634 private void AttachOriginalMessageToNotification(MessageItem initiationMessage, MessageItem notificationMessage, out string originalSenderDisplayname) { originalSenderDisplayname = string.Empty; if (string.IsNullOrEmpty(this.defaultAcceptedDomain)) { ModeratedDLApplication.diag.TraceDebug((long)this.GetHashCode(), "Cannot attach original message to notification without domain for content conversion."); return; } AttachmentCollection attachmentCollection = initiationMessage.AttachmentCollection; foreach (AttachmentHandle handle in attachmentCollection) { using (Attachment attachment = attachmentCollection.Open(handle)) { if ("OriginalMessage".Equals(attachment.FileName, StringComparison.OrdinalIgnoreCase)) { StreamAttachment streamAttachment = attachment as StreamAttachment; if (streamAttachment != null) { using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.ReadOnly)) { using (ItemAttachment itemAttachment = (ItemAttachment)notificationMessage.AttachmentCollection.Create(AttachmentType.EmbeddedMessage)) { using (Item item = itemAttachment.GetItem()) { InboundConversionOptions options = new InboundConversionOptions(this.defaultAcceptedDomain); ItemConversion.ConvertAnyMimeToItem(item, contentStream, options); item[MessageItemSchema.Flags] = MessageFlags.None; originalSenderDisplayname = (item.TryGetProperty(MessageItemSchema.SenderDisplayName) as string); item.Save(SaveMode.NoConflictResolution); itemAttachment[AttachmentSchema.DisplayName] = initiationMessage.Subject; itemAttachment.Save(); } } } } break; } } } }
internal static void DeleteAttachment(MessageItem message, string name) { AnchorUtil.ThrowOnNullArgument(message, "message"); AnchorUtil.ThrowOnNullOrEmptyArgument(name, "name"); List <AttachmentHandle> list = new List <AttachmentHandle>(message.AttachmentCollection.Count); foreach (AttachmentHandle attachmentHandle in message.AttachmentCollection) { AttachmentType type = AttachmentType.Stream; using (StreamAttachment streamAttachment = (StreamAttachment)message.AttachmentCollection.Open(attachmentHandle, type)) { if (streamAttachment.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) { list.Add(attachmentHandle); } } } foreach (AttachmentHandle handle in list) { message.AttachmentCollection.Remove(handle); } }
internal static AnchorAttachment GetAttachment(AnchorContext context, MessageItem message, string name, PropertyOpenMode openMode) { AnchorUtil.ThrowOnNullArgument(message, "message"); AnchorUtil.ThrowOnNullOrEmptyArgument(name, "name"); if (openMode != PropertyOpenMode.ReadOnly && openMode != PropertyOpenMode.Modify) { throw new ArgumentException("Invalid OpenMode for GetAttachment", "openMode"); } AnchorAttachment anchorAttachment = null; foreach (AttachmentHandle handle in message.AttachmentCollection) { StreamAttachment streamAttachment = null; try { AttachmentType type = AttachmentType.Stream; streamAttachment = (StreamAttachment)message.AttachmentCollection.Open(handle, type); if (streamAttachment.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) { anchorAttachment = new AnchorAttachment(context, streamAttachment, openMode); streamAttachment = null; break; } } finally { if (streamAttachment != null) { streamAttachment.Dispose(); streamAttachment = null; } } } if (anchorAttachment == null) { throw new MigrationAttachmentNotFoundException(name); } return(anchorAttachment); }
private StreamAttachment GetStreamAttachment(string name) { using (DisposeGuard disposeGuard = default(DisposeGuard)) { foreach (AttachmentHandle handle in base.AttachmentCollection) { Attachment attachment = base.AttachmentCollection.Open(handle, null); disposeGuard.Add <Attachment>(attachment); if (attachment.AttachmentType == AttachmentType.Stream && !string.IsNullOrWhiteSpace(attachment.FileName) && attachment.FileName.Equals(name, StringComparison.InvariantCultureIgnoreCase)) { StreamAttachment streamAttachment = attachment as StreamAttachment; if (streamAttachment != null) { disposeGuard.Success(); return(streamAttachment); } } attachment.Dispose(); } } return(null); }
private void RemoveSubAttachment(StreamLogItem.LogItemAttachment subAttachment, bool merge) { Stream baseStream = subAttachment.AttachmentStream.BaseStream; subAttachment.AttachmentStream.Flush(); subAttachment.AttachmentStream.Dispose(); baseStream.Dispose(); subAttachment.Attachment.Save(); subAttachment.Attachment.Load(); if (merge) { using (StreamAttachment streamAttachment = (StreamAttachment)this.MessageItem.AttachmentCollection.Open(subAttachment.Attachment.Id)) { using (GZipStream gzipStream = new GZipStream(streamAttachment.GetContentStream(), CompressionMode.Decompress)) { using (StreamReader streamReader = new StreamReader(gzipStream)) { string value; while ((value = streamReader.ReadLine()) != null) { this.AttachmentStream.WriteLine(value); } } } } } this.MessageItem.AttachmentCollection.Remove(subAttachment.Attachment.Id); this.MessageItem.Save(SaveMode.NoConflictResolutionForceSave); this.MessageItem.Load(); int id = subAttachment.Id; subAttachment.AttachmentStream.Dispose(); subAttachment.AttachmentStream = null; subAttachment.Attachment.Dispose(); subAttachment.Attachment = null; subAttachment = null; this.subAttachments.Remove(id); }
// Token: 0x060014EA RID: 5354 RVA: 0x000799E0 File Offset: 0x00077BE0 private void GetPicture() { this.cachedPicture = null; Contact contact = base.XsoItem as Contact; contact.Load(new PropertyDefinition[] { XsoPictureProperty.hasPicture }); object obj = contact.TryGetProperty(XsoPictureProperty.hasPicture); if (obj != null && obj is bool && (bool)obj) { foreach (AttachmentHandle handle in contact.AttachmentCollection) { using (Attachment attachment = contact.AttachmentCollection.Open(handle)) { StreamAttachment streamAttachment = attachment as StreamAttachment; if (streamAttachment != null) { streamAttachment.Load(new PropertyDefinition[] { XsoPictureProperty.ispictureAttach }); obj = streamAttachment.TryGetProperty(XsoPictureProperty.ispictureAttach); if (obj != null && obj is bool && (bool)obj) { AirSyncDiagnostics.TraceDebug(ExTraceGlobals.CommonTracer, null, "XsoPictureProperty.GetPicture(), picture attachment exists."); this.LoadPictureData(streamAttachment); break; } } } } } }
internal static AnchorAttachment CreateAttachment(AnchorContext context, MessageItem message, string name) { AnchorUtil.ThrowOnNullArgument(message, "message"); AnchorUtil.ThrowOnNullOrEmptyArgument(name, "name"); AttachmentType type = AttachmentType.Stream; AttachmentId attachmentId = null; foreach (AttachmentHandle handle in message.AttachmentCollection) { using (StreamAttachment streamAttachment = (StreamAttachment)message.AttachmentCollection.Open(handle, type)) { if (streamAttachment.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) { attachmentId = streamAttachment.Id; break; } } } context.Logger.Log(MigrationEventType.Information, "Creating a new attachment with name {0}", new object[] { name }); StreamAttachment streamAttachment2 = (StreamAttachment)message.AttachmentCollection.Create(type); streamAttachment2.FileName = name; if (attachmentId != null) { context.Logger.Log(MigrationEventType.Information, "Found an existing attachment with name {0} and id {1}, removing old one", new object[] { name, attachmentId.ToBase64String() }); message.AttachmentCollection.Remove(attachmentId); } return(new AnchorAttachment(context, streamAttachment2, PropertyOpenMode.Create)); }
// Token: 0x06000107 RID: 263 RVA: 0x000041B0 File Offset: 0x000023B0 public Stream GetAttachmentStream(AttachmentHandler.IAttachmentRetriever attachmentRetriever, AttachmentHandler.IAttachmentPolicyChecker policyChecker, bool asDataUri) { ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>((long)this.GetHashCode(), "AttachmentHandler.GetAttachmentStream: Getting attachment stream for id={0}", this.id); if (string.IsNullOrEmpty(this.id)) { ExTraceGlobals.AttachmentHandlingTracer.TraceDebug((long)this.GetHashCode(), "Attachment id is empty or null. returning null stream."); throw new FaultException("Id cannot be null or empty."); } Stream stream = null; ByteEncoder byteEncoder = null; Stream stream2 = null; Stream result; try { Attachment attachment = attachmentRetriever.Attachment; AttachmentPolicyLevel policy = policyChecker.GetPolicy(attachment, this.webOperationContext.IsPublicLogon); if (AudioFile.IsProtectedVoiceAttachment(attachment.FileName)) { attachment.ContentType = Utils.GetUnProtectedVoiceAttachmentContentType(attachment.FileName); stream = DRMUtils.OpenProtectedAttachment(attachment, this.callContext.AccessingADUser.OrganizationId); string fileName; if (AudioFile.TryGetNonDRMFileNameFromDRM(attachment.FileName, out fileName)) { attachment.FileName = fileName; } } string text = AttachmentUtilities.GetContentType(attachment); string fileExtension = attachment.FileExtension; OleAttachment oleAttachment = attachment as OleAttachment; if (oleAttachment != null) { stream = oleAttachment.ConvertToImage(ImageFormat.Jpeg); if (stream != null) { text = "image/jpeg"; } } if (this.IsBlocked(policy) && !attachment.IsInline && !this.IsImagePreview) { ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>((long)this.GetHashCode(), "Attachment is blocked. Returning null stream. id is {0}", this.id); result = null; } else { this.WriteResponseHeaders(text, policy, attachment); if (stream == null) { StreamAttachment streamAttachment = attachment as StreamAttachment; if (streamAttachment != null) { if (string.Equals(text, "audio/mpeg", StringComparison.OrdinalIgnoreCase)) { stream = streamAttachment.GetContentStream(PropertyOpenMode.Modify); } else { stream = streamAttachment.GetContentStream(PropertyOpenMode.ReadOnly); } } else { ItemAttachment itemAttachment = attachment as ItemAttachment; if (itemAttachment != null) { using (Item item = itemAttachment.GetItem(StoreObjectSchema.ContentConversionProperties)) { IRecipientSession adrecipientSession = item.Session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid); OutboundConversionOptions outboundConversionOptions = new OutboundConversionOptions(this.callContext.DefaultDomain.DomainName.Domain); outboundConversionOptions.ClearCategories = false; outboundConversionOptions.UserADSession = adrecipientSession; outboundConversionOptions.LoadPerOrganizationCharsetDetectionOptions(adrecipientSession.SessionSettings.CurrentOrganizationId); stream = new MemoryStream(); ItemConversion.ConvertItemToMime(item, stream, outboundConversionOptions); stream.Seek(0L, SeekOrigin.Begin); } } } } long num = 0L; long num2 = 0L; if (AttachmentUtilities.NeedToFilterHtml(text, fileExtension, policy, this.configurationContext)) { stream = AttachmentUtilities.GetFilteredStream(this.configurationContext, stream, attachment.TextCharset, attachmentRetriever.BlockStatus); } else if (this.NeedToSendPartialContent(stream, out num, out num2)) { string value = string.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", new object[] { num, num2, stream.Length }); this.webOperationContext.Headers["Accept-Ranges"] = "bytes"; this.webOperationContext.Headers["Content-Range"] = value; this.webOperationContext.ETag = this.id; this.webOperationContext.StatusCode = HttpStatusCode.PartialContent; long num3 = num2 - num + 1L; if (num3 < stream.Length) { ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <long, long, long>((long)this.GetHashCode(), "RangeBytes:{0} - Seek:{1} - SetLength:{2}", num3, num, num2 + 1L); stream.Seek(num, SeekOrigin.Begin); return(new BoundedStream(stream, true, num, num2)); } } if (asDataUri) { byteEncoder = new Base64Encoder(); stream2 = new EncoderStream(stream, byteEncoder, EncoderStreamAccess.Read); stream = new DataUriStream(stream2, text); } result = stream; } } catch (Exception ex) { if (stream != null) { stream.Dispose(); } if (stream2 != null) { stream2.Dispose(); } if (byteEncoder != null) { byteEncoder.Dispose(); } string formatString = string.Empty; if (ex is ExchangeDataException) { formatString = "Fail to sanitize HTML getting attachment. id is {0}, Exception: {1}"; } else if (ex is StoragePermanentException) { formatString = "StoragePermanentException when getting attachment. id is {0}, Exception: {1}"; } else { if (!(ex is StorageTransientException)) { throw; } formatString = "StorageTransientException when getting attachment. id is {0}, Exception: {1}"; } ExTraceGlobals.AttachmentHandlingTracer.TraceError <string, Exception>((long)this.GetHashCode(), formatString, this.id, ex); throw new CannotOpenFileAttachmentException(ex); } return(result); }
private static HierarchySyncMetadataItem.SyncMetadataAttachmentStream Instantate(StreamAttachment attachment, StreamBase.Capabilities streamCapabilities) { if (attachment == null) { HierarchySyncMetadataItem.Tracer.TraceDebug(0L, "SyncMetadataAttachmentStream:Instantate - Returning null stream as attachment was also null"); return(null); } HierarchySyncMetadataItem.SyncMetadataAttachmentStream result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { disposeGuard.Add <StreamAttachment>(attachment); PropertyOpenMode propertyOpenMode = ((streamCapabilities & StreamBase.Capabilities.Writable) == StreamBase.Capabilities.Writable) ? PropertyOpenMode.Modify : PropertyOpenMode.ReadOnly; HierarchySyncMetadataItem.Tracer.TraceDebug <PropertyOpenMode, StreamBase.Capabilities>(0L, "SyncMetadataAttachmentStream:Instantate - Getting content stream. Open Mode={0}, Stream Capabilities={1}", propertyOpenMode, streamCapabilities); Stream contentStream = attachment.GetContentStream(propertyOpenMode); disposeGuard.Add <Stream>(contentStream); HierarchySyncMetadataItem.SyncMetadataAttachmentStream syncMetadataAttachmentStream = new HierarchySyncMetadataItem.SyncMetadataAttachmentStream(attachment, contentStream, streamCapabilities); disposeGuard.Success(); result = syncMetadataAttachmentStream; } return(result); }
private Stream LoadAttachmentDocument(bool isLoadingStream, out RightsManagedMessageDecryptionStatus decryptionStatus) { decryptionStatus = RightsManagedMessageDecryptionStatus.Success; StringBuilder stringBuilder = new StringBuilder(); List <AttachmentId> list = new List <AttachmentId>(); UserContext userContext = this.owaContext.UserContext; string queryStringParameter = Utilities.GetQueryStringParameter(this.owaContext.HttpContext.Request, "ewsid", false); bool flag = string.IsNullOrEmpty(queryStringParameter); OwaStoreObjectId owaStoreObjectId; string text; if (!flag) { stringBuilder.Append("service.svc/s/GetFileAttachment?id="); stringBuilder.Append(Utilities.UrlEncode(queryStringParameter)); string canary15CookieValue = Utilities.GetCanary15CookieValue(); if (canary15CookieValue != null) { stringBuilder.Append("&X-OWA-CANARY=" + canary15CookieValue); } IdHeaderInformation idHeaderInformation = ServiceIdConverter.ConvertFromConcatenatedId(queryStringParameter, BasicTypes.Attachment, list); owaStoreObjectId = OwaStoreObjectId.CreateFromMailboxItemId(idHeaderInformation.ToStoreObjectId()); text = owaStoreObjectId.ToString(); } else { text = Utilities.GetQueryStringParameter(this.owaContext.HttpContext.Request, "id"); owaStoreObjectId = OwaStoreObjectId.CreateFromString(text); stringBuilder.Append("attachment.ashx?attach=1&id="); stringBuilder.Append(Utilities.UrlEncode(text)); } Stream result; using (Item item = Utilities.GetItem <Item>(userContext, owaStoreObjectId, new PropertyDefinition[] { ItemSchema.SentRepresentingDisplayName, ItemSchema.Subject })) { if (!Utilities.IsPublic(item) && userContext.IsIrmEnabled && isLoadingStream) { item.OpenAsReadWrite(); } if (Utilities.IsIrmRestricted(item)) { if (!userContext.IsIrmEnabled || userContext.IsBasicExperience) { decryptionStatus = RightsManagedMessageDecryptionStatus.FeatureDisabled; return(null); } RightsManagedMessageItem rightsManagedMessageItem = (RightsManagedMessageItem)item; if (!rightsManagedMessageItem.CanDecode) { decryptionStatus = RightsManagedMessageDecryptionStatus.NotSupported; return(null); } try { Utilities.IrmDecryptIfRestricted(item, userContext, true); } catch (RightsManagementPermanentException exception) { decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception); return(null); } catch (RightsManagementTransientException exception2) { decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception2); return(null); } } this.messageFrom = ItemUtility.GetProperty <string>(item, ItemSchema.SentRepresentingDisplayName, string.Empty); this.messageSubject = ItemUtility.GetProperty <string>(item, ItemSchema.Subject, string.Empty); this.messageId = text; if (flag) { Utilities.FillAttachmentIdList(item, this.owaContext.HttpContext.Request, list); } using (StreamAttachment streamAttachment = Utilities.GetAttachment(item, list, userContext) as StreamAttachment) { if (streamAttachment == null) { throw new OwaInvalidRequestException("Attachment is not a stream attachment"); } this.mimeType = (streamAttachment.ContentType ?? streamAttachment.CalculatedContentType); this.fileName = ((!string.IsNullOrEmpty(streamAttachment.DisplayName)) ? streamAttachment.DisplayName : streamAttachment.FileName); this.fileSize = streamAttachment.Size; this.documentPath = this.fileName; this.documentIdStringBuilder.Append(Convert.ToBase64String(userContext.MailboxSession.MailboxOwner.MailboxInfo.GetDatabaseGuid().ToByteArray())); this.documentIdStringBuilder.Append("-"); for (int i = 0; i < list.Count; i++) { this.documentIdStringBuilder.Append(list[i].ToBase64String()); this.documentIdStringBuilder.Append("-"); if (flag) { stringBuilder.Append("&attid"); stringBuilder.Append(i.ToString(CultureInfo.InstalledUICulture)); stringBuilder.Append("="); stringBuilder.Append(Utilities.UrlEncode(list[i].ToBase64String())); } } if (flag) { stringBuilder.Append("&attcnt="); stringBuilder.Append(list.Count); } this.documentIdStringBuilder.Append(streamAttachment.LastModifiedTime.UtcTicks); this.openLink = stringBuilder.ToString(); if (isLoadingStream) { Stream contentStream = streamAttachment.GetContentStream(); MsoIpiResult msoIpiResult = MsoIpiResult.Unknown; try { msoIpiResult = ProtectorsManager.Instance.IsProtected(this.fileName, contentStream); } catch (AttachmentProtectionException exception3) { decryptionStatus = new RightsManagedMessageDecryptionStatus(RightsManagementFailureCode.CorruptData, exception3); return(null); } if (msoIpiResult == MsoIpiResult.Protected) { this.isIrmProtected = true; contentStream.Dispose(); if (!userContext.IsIrmEnabled || userContext.IsBasicExperience) { decryptionStatus = RightsManagedMessageDecryptionStatus.FeatureDisabled; result = null; } else { UseLicenseAndUsageRights useLicenseAndUsageRights; bool flag2; Stream stream; try { stream = StreamAttachment.OpenRestrictedAttachment(streamAttachment, this.owaContext.ExchangePrincipal.MailboxInfo.OrganizationId, this.owaContext.ExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), this.owaContext.LogonIdentity.UserSid, this.owaContext.ExchangePrincipal.RecipientTypeDetails, out useLicenseAndUsageRights, out flag2); } catch (RightsManagementPermanentException exception4) { decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception4); return(null); } catch (RightsManagementTransientException exception5) { decryptionStatus = RightsManagedMessageDecryptionStatus.CreateFromException(exception5); return(null); } if (flag2 && ObjectClass.IsMessage(item.ClassName, false) && !Utilities.IsIrmRestricted(item)) { object obj = item.TryGetProperty(MessageItemSchema.IsDraft); if (obj is bool && !(bool)obj && !DrmClientUtils.IsCachingOfLicenseDisabled(useLicenseAndUsageRights.UseLicense)) { streamAttachment[AttachmentSchema.DRMRights] = useLicenseAndUsageRights.UsageRights; streamAttachment[AttachmentSchema.DRMExpiryTime] = useLicenseAndUsageRights.ExpiryTime; using (Stream stream2 = streamAttachment.OpenPropertyStream(AttachmentSchema.DRMServerLicenseCompressed, PropertyOpenMode.Create)) { DrmEmailCompression.CompressUseLicense(useLicenseAndUsageRights.UseLicense, stream2); } streamAttachment[AttachmentSchema.DRMPropsSignature] = useLicenseAndUsageRights.DRMPropsSignature; streamAttachment.Save(); item.Save(SaveMode.ResolveConflicts); } } string conversationOwnerFromPublishLicense = DrmClientUtils.GetConversationOwnerFromPublishLicense(useLicenseAndUsageRights.PublishingLicense); RmsTemplate rmsTemplate = RmsTemplate.CreateFromPublishLicense(useLicenseAndUsageRights.PublishingLicense); this.isPrintRestricted = !useLicenseAndUsageRights.UsageRights.IsUsageRightGranted(ContentRight.Print); this.isCopyRestricted = !useLicenseAndUsageRights.UsageRights.IsUsageRightGranted(ContentRight.Extract); SanitizingStringBuilder <OwaHtml> sanitizingStringBuilder = new SanitizingStringBuilder <OwaHtml>(); string str = string.Format(LocalizedStrings.GetNonEncoded(-500320626), rmsTemplate.Name, rmsTemplate.Description); sanitizingStringBuilder.Append(str); if (!string.IsNullOrEmpty(conversationOwnerFromPublishLicense)) { sanitizingStringBuilder.Append("<br>"); sanitizingStringBuilder.Append(string.Format(LocalizedStrings.GetNonEncoded(1670455506), conversationOwnerFromPublishLicense)); } this.irmInfobarMessage = sanitizingStringBuilder.ToSanitizedString <SanitizedHtmlString>(); result = stream; } } else { contentStream.Seek(0L, SeekOrigin.Begin); result = contentStream; } } else { result = null; } } } return(result); }
// Token: 0x0600003F RID: 63 RVA: 0x00004608 File Offset: 0x00002808 private bool TryWriteNotificationWithAppendedComments(DsnHumanReadableWriter notificationWriter, MessageItem rejectItem, StreamAttachment commentAttachment, ApprovalInformation info) { bool result = true; string htmlModerationBody = notificationWriter.GetHtmlModerationBody(info); Charset textCharset = commentAttachment.TextCharset; Encoding inputEncoding = null; if (textCharset == null || !textCharset.TryGetEncoding(out inputEncoding)) { return(false); } Charset charset = textCharset; if (!ModeratedDLApplication.IsEncodingMatch(info.Codepages, textCharset.CodePage)) { charset = Charset.UTF8; } BodyWriteConfiguration configuration = new BodyWriteConfiguration(BodyFormat.TextHtml, charset.Name); using (Stream stream = rejectItem.Body.OpenWriteStream(configuration)) { HtmlToHtml htmlToHtml = new HtmlToHtml(); htmlToHtml.Header = htmlModerationBody; htmlToHtml.HeaderFooterFormat = HeaderFooterFormat.Html; htmlToHtml.InputEncoding = inputEncoding; htmlToHtml.OutputEncoding = charset.GetEncoding(); try { using (Stream contentStream = commentAttachment.GetContentStream(PropertyOpenMode.ReadOnly)) { htmlToHtml.Convert(contentStream, stream); stream.Flush(); } } catch (ExchangeDataException arg) { ModeratedDLApplication.diag.TraceDebug <ExchangeDataException>(0L, "Attaching comments failed with {0}", arg); result = false; } } return(result); }
internal AnchorAttachment(AnchorContext anchorContext, StreamAttachment attachment, PropertyOpenMode openMode) : this(anchorContext, attachment.GetContentStream(openMode), attachment.LastModifiedTime, null) { this.attachment = attachment; }
// Token: 0x06000039 RID: 57 RVA: 0x00003EA4 File Offset: 0x000020A4 private void SendRejectNotification(MessageItem messageItem) { ModeratedDLApplication.diag.TraceDebug((long)this.GetHashCode(), "Entering SendRejectNotification"); if (!this.ShouldSendNotification(messageItem)) { return; } RoutingAddress routingAddress; if (!this.TryGetOriginalSender(messageItem, out routingAddress)) { return; } MailboxSession mailboxSession = (MailboxSession)messageItem.Session; messageItem.Load(ModeratedDLApplication.NotificationPropertiesFromInitMessage); string valueOrDefault = messageItem.GetValueOrDefault <string>(MessageItemSchema.AcceptLanguage, string.Empty); DsnHumanReadableWriter defaultDsnHumanReadableWriter = DsnHumanReadableWriter.DefaultDsnHumanReadableWriter; ICollection <string> moderatedRecipients = this.GetModeratedRecipients(messageItem, false); string valueOrDefault2 = messageItem.GetValueOrDefault <string>(ItemSchema.InternetReferences, string.Empty); StoreObjectId defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Outbox); using (MessageItem messageItem2 = MessageItem.Create(mailboxSession, defaultFolderId)) { StreamAttachment streamAttachment = null; try { bool flag = ModeratedDLApplication.TryGetCommentAttachment(messageItem, out streamAttachment) && streamAttachment.Size > 0L; messageItem2.ClassName = "IPM.Note.Microsoft.Approval.Reply.Reject"; bool flag2 = true; ApprovalInformation approvalInformation = null; if (flag) { approvalInformation = defaultDsnHumanReadableWriter.GetModerateRejectInformation(messageItem.Subject, moderatedRecipients, flag, valueOrDefault2, valueOrDefault); messageItem2.Subject = approvalInformation.Subject; flag2 = this.TryWriteNotificationWithAppendedComments(defaultDsnHumanReadableWriter, messageItem2, streamAttachment, approvalInformation); } if (!flag || !flag2) { approvalInformation = defaultDsnHumanReadableWriter.GetModerateRejectInformation(messageItem.Subject, moderatedRecipients, false, valueOrDefault2, valueOrDefault); messageItem2.Subject = approvalInformation.Subject; BodyWriteConfiguration configuration = new BodyWriteConfiguration(BodyFormat.TextHtml, approvalInformation.MessageCharset.Name); using (Stream stream = messageItem2.Body.OpenWriteStream(configuration)) { defaultDsnHumanReadableWriter.WriteHtmlModerationBody(stream, approvalInformation); stream.Flush(); } } if (flag && !flag2) { using (StreamAttachment streamAttachment2 = messageItem2.AttachmentCollection.Create(AttachmentType.Stream) as StreamAttachment) { streamAttachment2.FileName = defaultDsnHumanReadableWriter.GetModeratorsCommentFileName(approvalInformation.Culture); using (Stream contentStream = streamAttachment2.GetContentStream()) { using (Stream contentStream2 = streamAttachment.GetContentStream(PropertyOpenMode.ReadOnly)) { byte[] buffer = new byte[8192]; ApprovalProcessor.CopyStream(contentStream2, contentStream, buffer); } contentStream.Flush(); } streamAttachment2.Save(); } } this.StampCommonNotificationProperties(messageItem2, messageItem, new RoutingAddress[] { routingAddress }, valueOrDefault2, approvalInformation.Culture); messageItem2.SendWithoutSavingMessage(); } finally { if (streamAttachment != null) { streamAttachment.Dispose(); } } } }
private static void PopulateAttachmentProperties(IdAndSession idAndSession, Item item, Attachment attachment, ModernAttachment outAttachment) { if (outAttachment == null || attachment == null || item == null) { return; } outAttachment.Data = new ModernAttachment.AttachmentData(); outAttachment.Data.AttachmentEx = new AttachmentTypeEx(); switch (attachment.AttachmentType) { case AttachmentType.NoAttachment: break; case AttachmentType.Stream: { StreamAttachment streamAttachment = attachment as StreamAttachment; if (streamAttachment != null) { FileAttachmentType fileAttachmentType = new FileAttachmentType(); outAttachment.Data.Attachment = fileAttachmentType; fileAttachmentType.IsContactPhoto = streamAttachment.IsContactPhoto; } break; } case AttachmentType.EmbeddedMessage: { ItemAttachment itemAttachment = attachment as ItemAttachment; if (itemAttachment != null) { outAttachment.Data.Attachment = new ItemAttachmentType(); } break; } case AttachmentType.Ole: { OleAttachment oleAttachment = attachment as OleAttachment; if (oleAttachment != null) { FileAttachmentType fileAttachmentType2 = new FileAttachmentType(); outAttachment.Data.Attachment = fileAttachmentType2; fileAttachmentType2.IsContactPhoto = oleAttachment.IsContactPhoto; } break; } case AttachmentType.Reference: { ReferenceAttachment referenceAttachment = attachment as ReferenceAttachment; if (referenceAttachment != null) { UserContext userContext = UserContextManager.GetUserContext(HttpContext.Current); if (userContext != null && userContext.FeaturesManager != null && userContext.FeaturesManager.ClientServerSettings.AttachmentsFilePicker.Enabled) { ReferenceAttachmentType referenceAttachmentType = new ReferenceAttachmentType(); outAttachment.Data.Attachment = referenceAttachmentType; referenceAttachmentType.AttachLongPathName = referenceAttachment.AttachLongPathName; referenceAttachmentType.ProviderEndpointUrl = referenceAttachment.ProviderEndpointUrl; referenceAttachmentType.ProviderType = referenceAttachment.ProviderType; } else { outAttachment.Data.Attachment = new FileAttachmentType(); } } break; } default: return; } if (outAttachment.Data.Attachment == null) { outAttachment.Data.Attachment = new AttachmentType(); } IdAndSession idAndSession2; if (idAndSession == null) { idAndSession2 = new IdAndSession(item.Id, item.Session); } else { idAndSession2 = idAndSession.Clone(); } idAndSession2.AttachmentIds.Add(attachment.Id); outAttachment.Data.Attachment.AttachmentId = new AttachmentIdType(idAndSession2.GetConcatenatedId().Id); outAttachment.Data.Attachment.ContentId = (string.IsNullOrEmpty(attachment.ContentId) ? null : attachment.ContentId); outAttachment.Data.Attachment.ContentLocation = ((attachment.ContentLocation == null) ? null : attachment.ContentLocation.PathAndQuery); outAttachment.Data.Attachment.ContentType = attachment.ContentType; outAttachment.Data.Attachment.IsInline = attachment.IsInline; outAttachment.Data.Attachment.LastModifiedTime = GetModernAttachmentsCommand.Utilities.FormatExDateTime(attachment.LastModifiedTime); outAttachment.Data.Attachment.Name = attachment.DisplayName; outAttachment.Data.Attachment.Size = (int)attachment.Size; }
private static bool TryProcessUnprotectedAttachment(IExchangePrincipal exchangePrincipal, Item item, StreamAttachment streamAttachment, PropertyOpenMode openMode, WacUtilities.AttachmentProcessor attachmentProcessor) { if (openMode == PropertyOpenMode.Modify) { item.OpenAsReadWrite(); } bool result; using (Stream contentStream = streamAttachment.GetContentStream(openMode)) { bool flag = WacUtilities.IsContentProtected(streamAttachment.FileName, contentStream); if (flag) { result = false; } else { attachmentProcessor(exchangePrincipal, streamAttachment, contentStream, false); if (openMode == PropertyOpenMode.Modify) { item.Save(SaveMode.NoConflictResolution); } result = true; } } return(result); }