示例#1
0
        public static ReplyTemplate Find(MailboxSession session, RuleAction.OOFReply ruleAction)
        {
            ReplyTemplate result;

            try
            {
                if (ruleAction.ReplyTemplateMessageEntryID == null)
                {
                    result = ReplyTemplate.FindByTemplateGuid(session, ruleAction);
                }
                else
                {
                    StoreObjectId messageId   = StoreObjectId.FromProviderSpecificId(ruleAction.ReplyTemplateMessageEntryID);
                    MessageItem   messageItem = MessageItem.Bind(session, messageId, new PropertyDefinition[]
                    {
                        ItemSchema.ReplyTemplateId
                    });
                    messageItem.OpenAsReadWrite();
                    ReplyTemplate.Tracer.TraceDebug <IExchangePrincipal, ByteArray>(0L, "Mailbox:{0}: Found reply template by entry Id. Entry id={1}", session.MailboxOwner, new ByteArray(ruleAction.ReplyTemplateMessageEntryID));
                    ReplyTemplate.TracerPfd.TracePfd <int, IExchangePrincipal, ByteArray>(0L, "PFD IWO {0} Mailbox:{1}: Found reply template by entry Id. Entry id={2}", 31639, session.MailboxOwner, new ByteArray(ruleAction.ReplyTemplateMessageEntryID));
                    result = new ReplyTemplate(messageItem);
                }
            }
            catch (ObjectNotFoundException)
            {
                ReplyTemplate.Tracer.TraceDebug <IExchangePrincipal, ByteArray>(0L, "Mailbox:{0}: Found no reply template by entry Id. Entry id={1}", session.MailboxOwner, new ByteArray(ruleAction.ReplyTemplateMessageEntryID));
                result = ReplyTemplate.FindByTemplateGuid(session, ruleAction);
            }
            return(result);
        }
示例#2
0
 public void CreateOrUpdateSharingBinding(SharingBindingData bindingData)
 {
     Util.ThrowOnNullArgument(bindingData, "bindingData");
     Util.ThrowOnNullArgument(bindingData.LocalFolderId, "bindingData.LocalFolderId");
     object[] rawBindingQueryInFolder = this.GetRawBindingQueryInFolder(bindingData.LocalFolderId);
     if (rawBindingQueryInFolder != null)
     {
         ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, SharingBindingData>((long)this.GetHashCode(), "{0}: updating binding message {1}", this.mailboxSession.MailboxOwner, bindingData);
         SharingBindingData sharingBindingData = this.CreateDataObjectFromItem(rawBindingQueryInFolder);
         if (SharingBindingData.EqualContent(sharingBindingData, bindingData))
         {
             return;
         }
         using (Item item = MessageItem.Bind(this.mailboxSession, sharingBindingData.Id, SharingBindingManager.QueryBindingColumns))
         {
             this.SaveBindingMessage(item, bindingData);
             return;
         }
     }
     ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, SharingBindingData>((long)this.GetHashCode(), "{0}: creating binding message {1}", this.mailboxSession.MailboxOwner, bindingData);
     using (Item item2 = MessageItem.CreateAssociated(this.mailboxSession, bindingData.LocalFolderId))
     {
         item2[BindingItemSchema.SharingInstanceGuid] = Guid.NewGuid();
         this.SaveBindingMessage(item2, bindingData);
     }
 }
示例#3
0
        public string GetItemContent(MailboxSession itemStore, StoreId itemId)
        {
            if (itemId == null)
            {
                SingleInstanceItemHandler.Tracer.TraceDebug <SingleInstanceItemHandler, IExchangePrincipal>((long)this.GetHashCode(), "{0}: Item not found in {1}", this, itemStore.MailboxOwner);
                return(null);
            }
            SingleInstanceItemHandler.Tracer.TraceDebug <SingleInstanceItemHandler, IExchangePrincipal>((long)this.GetHashCode(), "{0}: Item found in '{1}'", this, itemStore.MailboxOwner);
            string result;

            try
            {
                using (Item item = MessageItem.Bind(itemStore, itemId))
                {
                    using (TextReader textReader = item.Body.OpenTextReader(BodyFormat.TextPlain))
                    {
                        result = textReader.ReadToEnd();
                    }
                }
            }
            catch (ObjectNotFoundException)
            {
                SingleInstanceItemHandler.Tracer.TraceDebug <SingleInstanceItemHandler, IExchangePrincipal>((long)this.GetHashCode(), "{0}: Item no longer found in {1}", this, itemStore.MailboxOwner);
                result = null;
            }
            return(result);
        }
示例#4
0
        public bool TryGetQueryFilter(out QueryFilter filter)
        {
            MailboxSession mailboxSession = base.Session as MailboxSession;

            if (mailboxSession == null)
            {
                throw new InvalidOperationException(ServerStrings.ExOutlookSearchFolderDoesNotHaveMailboxSession);
            }
            VersionedId versionedId = OutlookSearchFolder.FindAssociatedMessageId(mailboxSession, (Guid)this[InternalSchema.OutlookSearchFolderClsId]);

            if (versionedId == null)
            {
                filter = null;
                return(false);
            }
            bool result;

            using (MessageItem messageItem = MessageItem.Bind(mailboxSession, versionedId))
            {
                bool        flag;
                StoreId[]   array;
                Restriction restriction = OutlookSearchFolder.ReadOutlookSearchFolderDefinitionBlob(messageItem, out flag, out array);
                filter = FilterRestrictionConverter.CreateFilter(mailboxSession, mailboxSession.Mailbox.MapiStore, restriction, true);
                result = true;
            }
            return(result);
        }
        // Token: 0x0600025C RID: 604 RVA: 0x00008ED4 File Offset: 0x000070D4
        private void Initialize(MailboxSession mailboxSession, StoreObjectId id, PropertyDefinition[] properties)
        {
            bool flag = false;

            try
            {
                AnchorUtil.ThrowOnNullArgument(mailboxSession, "dataProvider");
                AnchorUtil.ThrowOnNullArgument(id, "id");
                AnchorUtil.ThrowOnNullArgument(properties, "properties");
                this.Message = MessageItem.Bind(mailboxSession, id, properties);
                flag         = true;
            }
            catch (ArgumentException ex)
            {
                base.AnchorContext.Logger.Log(MigrationEventType.Error, ex, "Encountered an argument exception when trying to find message with id={0}", new object[]
                {
                    id.ToString()
                });
                throw new ObjectNotFoundException(ServerStrings.ExItemNotFound, ex);
            }
            finally
            {
                if (!flag)
                {
                    this.Dispose();
                }
            }
        }
示例#6
0
 private void EnsureMessage()
 {
     if (this.message == null)
     {
         this.message = MessageItem.Bind(this.session, this.id, ExMailComplianceItem.MailDataColumns);
     }
 }
示例#7
0
        public void LoadMailboxMessage(string internetMessageId)
        {
            MailboxSession session = (MailboxSession)this.storeSession;

            try
            {
                this.context.BeginTrackLatency(LatencyComponent.StoreDriverDeliveryRpc);
                IEnumerable <IStorePropertyBag> source = AllItemsFolderHelper.FindItemsFromInternetId(session, internetMessageId, ItemQueryType.NoNotifications, new PropertyDefinition[]
                {
                    ItemSchema.Id
                });
                if (source.Count <IStorePropertyBag>() != 1)
                {
                    throw new UnexpectedMessageCountException(string.Format("The number of messages found was unexpected. Count: {0}", source.Count <IStorePropertyBag>()));
                }
                IStorePropertyBag storePropertyBag = source.First <IStorePropertyBag>();
                StoreObjectId     objectId         = ((VersionedId)storePropertyBag[ItemSchema.Id]).ObjectId;
                this.messageItem = MessageItem.Bind(session, objectId);
                if (this.messageItem == null)
                {
                    throw new System.Data.ObjectNotFoundException("The requested message was not loaded.");
                }
                this.messageItem.OpenAsReadWrite();
            }
            catch (Microsoft.Exchange.Data.Storage.ObjectNotFoundException innerException)
            {
                throw new System.Data.ObjectNotFoundException("The requested message was not loaded.", innerException);
            }
            finally
            {
                TimeSpan additionalLatency = this.context.EndTrackLatency(LatencyComponent.StoreDriverDeliveryRpc);
                this.context.AddRpcLatency(additionalLatency, "Load message");
            }
        }
        private Item BindToItemWithItemClass(StoreObjectId id, ICollection <PropertyDefinition> properties)
        {
            switch (id.ObjectType)
            {
            case StoreObjectType.Message:
                return(MessageItem.Bind(this.folder.Session, id, properties));

            case StoreObjectType.MeetingRequest:
                return(MeetingRequest.Bind(this.folder.Session, id, properties));

            case StoreObjectType.MeetingResponse:
                return(MeetingResponse.Bind(this.folder.Session, id, properties));

            case StoreObjectType.MeetingCancellation:
                return(MeetingCancellation.Bind(this.folder.Session, id, properties));

            case StoreObjectType.Contact:
                return(Contact.Bind(this.folder.Session, id, properties));

            case StoreObjectType.DistributionList:
                return(DistributionList.Bind(this.folder.Session, id, properties));

            case StoreObjectType.Task:
                return(Task.Bind(this.folder.Session, id, true, properties));

            case StoreObjectType.Post:
                return(PostItem.Bind(this.folder.Session, id, properties));

            case StoreObjectType.Report:
                return(ReportMessage.Bind(this.folder.Session, id, properties));
            }
            return(Item.Bind(this.folder.Session, id, properties));
        }
        // Token: 0x06000A14 RID: 2580 RVA: 0x00042548 File Offset: 0x00040748
        internal void Update(Guid externalDirectoryOrganizationId, string mailboxOwnerLegacyDN, string settings, StoreObjectId settingsFolderId)
        {
            VersionedId versionedId = null;
            string      text        = SystemMailbox.FormatItemSubject(externalDirectoryOrganizationId, mailboxOwnerLegacyDN);
            QueryFilter seekFilter  = new ComparisonFilter(ComparisonOperator.Equal, ItemSchema.Subject, text);

            lock (this.systemMailboxMutex)
            {
                if (!this.isDisposed)
                {
                    this.ConnectSystemMailboxSession();
                    try
                    {
                        using (Folder folder = Folder.Bind(this.systemMailboxSession, settingsFolderId))
                        {
                            using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, SystemMailbox.sortBySubject, SystemMailbox.updatingUserSettingsProperties))
                            {
                                IStorePropertyBag[] propertyBags;
                                if (queryResult.SeekToCondition(SeekReference.OriginBeginning, seekFilter) && queryResult.SeekToCondition(SeekReference.OriginCurrent, SystemMailbox.SettingsItemClassFilter) && 0 < (propertyBags = queryResult.GetPropertyBags(1)).Length)
                                {
                                    versionedId = (VersionedId)propertyBags[0].TryGetProperty(ItemSchema.Id);
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(settings))
                        {
                            if (versionedId != null)
                            {
                                this.systemMailboxSession.Delete(DeleteItemFlags.SoftDelete, new StoreId[]
                                {
                                    versionedId
                                });
                                SystemMailbox.Tracer.TraceDebug <string, StoreObjectId>((long)this.GetHashCode(), "Notification disabled {0} under folder {1}", text, settingsFolderId);
                            }
                        }
                        else
                        {
                            using (Item item = (versionedId != null) ? MessageItem.Bind(this.systemMailboxSession, versionedId) : MessageItem.Create(this.systemMailboxSession, settingsFolderId))
                            {
                                if (versionedId == null)
                                {
                                    item.ClassName           = "IPM.Configuration.UserCalendarNotification";
                                    item[ItemSchema.Subject] = text;
                                }
                                item[ItemSchema.TextBody] = settings;
                                item.Save(SaveMode.ResolveConflicts);
                                SystemMailbox.Tracer.TraceDebug <string, StoreObjectId>((long)this.GetHashCode(), "Notification settings of user {0} have been saved under folder {1}", text, settingsFolderId);
                            }
                        }
                    }
                    finally
                    {
                        this.DisconnectSystemMailboxSession();
                    }
                }
            }
        }
示例#10
0
        private Item BindToItemWithItemClass(StoreObjectId id, string itemClass, PropertyDefinition[] properties)
        {
            Item result;

            if (ObjectClass.IsReport(itemClass))
            {
                result = ReportMessage.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsMessage(itemClass, false))
            {
                result = MessageItem.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsPost(itemClass))
            {
                result = PostItem.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsCalendarItem(itemClass))
            {
                result = CalendarItem.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsMeetingRequest(itemClass))
            {
                result = MeetingRequest.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsMeetingResponse(itemClass))
            {
                result = MeetingResponse.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsMeetingCancellation(itemClass))
            {
                result = MeetingCancellation.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsContact(itemClass))
            {
                result = Contact.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsTask(itemClass))
            {
                Task task = Task.Bind(this.mailboxSession, id, true, properties);
                task.SuppressRecurrenceAdjustment = true;
                result = task;
            }
            else if (ObjectClass.IsDistributionList(itemClass))
            {
                result = DistributionList.Bind(this.mailboxSession, id, properties);
            }
            else if (ObjectClass.IsGenericMessage(itemClass))
            {
                result = MessageItem.Bind(this.mailboxSession, id, properties);
            }
            else
            {
                result = Item.Bind(this.mailboxSession, id, properties);
            }
            return(result);
        }
        protected override void InternalSave(ConfigurableObject instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            UnifiedPolicyNotificationBase unifiedPolicyNotificationBase = instance as UnifiedPolicyNotificationBase;

            if (unifiedPolicyNotificationBase == null)
            {
                throw new NotSupportedException("Save: " + instance.GetType().FullName);
            }
            switch (unifiedPolicyNotificationBase.ObjectState)
            {
            case ObjectState.New:
                using (Folder folder = Folder.Bind(base.MailboxSession, base.MailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox)))
                {
                    using (MessageItem messageItem = MessageItem.CreateAssociated(base.MailboxSession, folder.Id))
                    {
                        this.SetNotificationMessage(messageItem, unifiedPolicyNotificationBase);
                        messageItem.Save(SaveMode.NoConflictResolutionForceSave);
                        messageItem.Load();
                        unifiedPolicyNotificationBase.StoreObjectId = messageItem.Id;
                    }
                    return;
                }
                break;

            case ObjectState.Unchanged:
                return;

            case ObjectState.Changed:
                break;

            case ObjectState.Deleted:
                goto IL_FE;

            default:
                return;
            }
            if (unifiedPolicyNotificationBase.StoreObjectId == null)
            {
                throw new ArgumentException("notification.StoreObjectId is null when saving for an update.");
            }
            using (MessageItem messageItem2 = MessageItem.Bind(base.MailboxSession, unifiedPolicyNotificationBase.StoreObjectId))
            {
                this.SetNotificationMessage(messageItem2, unifiedPolicyNotificationBase);
                messageItem2.Save(SaveMode.NoConflictResolutionForceSave);
                messageItem2.Load();
                return;
            }
IL_FE:
            throw new InvalidOperationException(ServerStrings.ExceptionObjectHasBeenDeleted);
        }
示例#12
0
        private void UpdateAssociatedSearchFolderLastUsedTime()
        {
            VersionedId versionedId = OutlookSearchFolder.FindAssociatedMessageId((MailboxSession)base.Session, (Guid)this[InternalSchema.OutlookSearchFolderClsId]);

            if (versionedId != null)
            {
                using (MessageItem messageItem = MessageItem.Bind(base.Session, versionedId))
                {
                    int num = OutlookSearchFolder.ConvertUtcDateTimeToRTime(ExDateTime.UtcNow);
                    messageItem[MessageItemSchema.AssociatedSearchFolderLastUsedTime] = num;
                    messageItem.Save(SaveMode.NoConflictResolution);
                    return;
                }
            }
            ExTraceGlobals.StorageTracer.Information <string>((long)this.GetHashCode(), "OutlookSearchFolder::UpdateAssociatedSearchFolderLastUsedTime. Failed to update the last used time of the search folder in its associated message. Associated message not found. SearchFolder DisplayName = {0}.", base.DisplayName);
        }
示例#13
0
        public TData CreateOrUpdate(TData subscriptionData, bool throwIfConflict)
        {
            this.CheckDisposed("CreateOrUpdate");
            Util.ThrowOnNullArgument(subscriptionData, "subscriptionData");
            TData tdata = default(TData);

            try
            {
                if (subscriptionData.Id == null)
                {
                    ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, TKey>((long)this.GetHashCode(), "{0}: creating subscription {1}", this.mailboxSession.MailboxOwner, subscriptionData.Key);
                    using (MessageItem messageItem = MessageItem.Create(this.mailboxSession, this.folder.Id))
                    {
                        messageItem.ClassName = this.itemClass;
                        this.SaveSubscriptionData(messageItem, subscriptionData);
                        messageItem.Load();
                        this.ResolveConflictAfterCreation(subscriptionData.Key, messageItem.Id);
                        goto IL_11B;
                    }
                }
                ExTraceGlobals.SharingTracer.TraceDebug <IExchangePrincipal, VersionedId, TData>((long)this.GetHashCode(), "{0}: updating subscription ItemId={1}, Data={2}", this.mailboxSession.MailboxOwner, subscriptionData.Id, subscriptionData);
                using (Item item = MessageItem.Bind(this.mailboxSession, subscriptionData.Id, this.itemProperties))
                {
                    this.SaveSubscriptionData(item, subscriptionData);
                }
                IL_11B :;
            }
            catch (SharingConflictException)
            {
                tdata = this.GetExisting(subscriptionData.Key);
                if (tdata == null || !tdata.LocalFolderId.Equals(subscriptionData.LocalFolderId))
                {
                    this.Rollback(subscriptionData);
                }
                if (throwIfConflict)
                {
                    throw;
                }
            }
            TData result;

            if ((result = tdata) == null)
            {
                result = subscriptionData;
            }
            return(result);
        }
示例#14
0
        private void CreateOrHijackAssociatedMessage(VersionedId associatedMessageId, SearchFolderCriteria criteria)
        {
            MailboxSession mailboxSession = (MailboxSession)base.Session;
            MessageItem    messageItem    = null;

            try
            {
                if (associatedMessageId == null)
                {
                    messageItem = MessageItem.CreateAssociated(base.Session, mailboxSession.SafeGetDefaultFolderId(DefaultFolderType.CommonViews));
                }
                else
                {
                    messageItem = MessageItem.Bind(base.Session, associatedMessageId);
                }
                messageItem[InternalSchema.ItemClass] = "IPM.Microsoft.WunderBar.SFInfo";
                messageItem[InternalSchema.AssociatedSearchFolderId] = ((Guid)this[InternalSchema.OutlookSearchFolderClsId]).ToByteArray();
                messageItem[InternalSchema.DisplayName] = this[FolderSchema.DisplayName];
                messageItem[ItemSchema.Subject]         = this[FolderSchema.DisplayName];
                ExtendedFolderFlags?valueAsNullable = base.GetValueAsNullable <ExtendedFolderFlags>(FolderSchema.ExtendedFolderFlags);
                if (valueAsNullable != null)
                {
                    messageItem[InternalSchema.AssociatedSearchFolderFlags] = valueAsNullable.Value;
                }
                int num = OutlookSearchFolder.ConvertUtcDateTimeToRTime(ExDateTime.UtcNow);
                messageItem[InternalSchema.AssociatedSearchFolderLastUsedTime] = num;
                messageItem[InternalSchema.AssociatedSearchFolderExpiration]   = num;
                messageItem[InternalSchema.AssociatedSearchFolderTemplateId]   = 1;
                messageItem[InternalSchema.AssociatedSearchFolderTag]          = 0;
                this.WriteOutlookSearchFolderDefinitionBlob(messageItem, criteria);
                messageItem[InternalSchema.AssociatedSearchFolderStorageType] = 72;
                messageItem.Save(SaveMode.FailOnAnyConflict);
            }
            finally
            {
                if (messageItem != null)
                {
                    messageItem.Dispose();
                    messageItem = null;
                }
            }
        }
        protected override IEnumerable <T> InternalFindPaged <T>(QueryFilter filter, ObjectId rootId, bool deepSearch, SortBy sortBy, int pageSize)
        {
            if (filter != null && !(filter is FalseFilter))
            {
                throw new NotSupportedException("filter");
            }
            if (sortBy != null)
            {
                throw new NotSupportedException("sortBy");
            }
            if (rootId != null && !(rootId is MailboxStoreObjectId))
            {
                throw new NotSupportedException("rootId: " + rootId.GetType().FullName);
            }
            if (!typeof(MailMessage).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()))
            {
                throw new NotSupportedException("FindPaged: " + typeof(T).FullName);
            }
            MailboxStoreObjectId messageId = rootId as MailboxStoreObjectId;

            if (messageId != null)
            {
                MailMessage mailMessage = new MailMessage();
                try
                {
                    using (MessageItem messageItem = MessageItem.Bind(base.MailboxSession, messageId.StoreObjectId, mailMessage.Schema.AllDependentXsoProperties))
                    {
                        mailMessage.LoadDataFromXso(messageId.MailboxOwnerId, messageItem);
                        mailMessage.SetRecipients(messageItem.Recipients);
                    }
                }
                catch (ObjectNotFoundException)
                {
                    yield break;
                }
                yield return((T)((object)mailMessage));
            }
            yield break;
        }
示例#16
0
        public static DelegateRuleType GetDelegateRuleType(MailboxSession session)
        {
            DelegateRuleType result = DelegateRuleType.ForwardAndDelete;
            FolderSaveResult folderSaveResult;

            byte[] freeBusyMsgId = FreeBusyUtil.GetFreeBusyMsgId(session, out folderSaveResult);
            if (freeBusyMsgId != null && freeBusyMsgId.Length > 0)
            {
                try
                {
                    using (MessageItem messageItem = MessageItem.Bind(session, StoreObjectId.FromProviderSpecificId(freeBusyMsgId), FreeBusyUtil.FreeBusyMessageProperties))
                    {
                        result = FreeBusyUtil.GetDelegateRuleType(messageItem);
                    }
                }
                catch (ObjectNotFoundException)
                {
                    ExTraceGlobals.CalendarLoggingTracer.TraceDebug((long)session.GetHashCode(), "FreeBusyUtil::GetDelegateRuleType. No FreeBusyMessage");
                }
            }
            return(result);
        }
示例#17
0
        internal void Save(MailboxSession session)
        {
            MessageItem messageItem = null;

            try
            {
                if (this.NavigationNodeId == null)
                {
                    messageItem = MessageItem.CreateAssociated(session, session.GetDefaultFolderId(DefaultFolderType.CommonViews));
                    messageItem[StoreObjectSchema.ItemClass] = "IPM.Microsoft.WunderBar.Link";
                }
                else
                {
                    messageItem = MessageItem.Bind(session, this.NavigationNodeId);
                }
                this.UpdateMessage(messageItem);
                messageItem.Save(SaveMode.NoConflictResolution);
                this.ClearDirty();
                this.isNew = false;
            }
            catch (StorageTransientException ex)
            {
                ExTraceGlobals.CoreCallTracer.TraceDebug <string>((long)this.GetHashCode(), "NavigationNode.Save. Unable to save navigation node. Exception: {0}.", ex.Message);
            }
            catch (StoragePermanentException ex2)
            {
                ExTraceGlobals.CoreCallTracer.TraceDebug <string>((long)this.GetHashCode(), "NavigationNode.Save. Unable to get save navigation node. Exception: {0}.", ex2.Message);
            }
            finally
            {
                if (messageItem != null)
                {
                    messageItem.Dispose();
                    messageItem = null;
                }
            }
        }
        private UnifiedPolicyNotificationBase GetNotificationFromStoreId(StoreId storeId)
        {
            UnifiedPolicyNotificationBase unifiedPolicyNotificationBase = null;

            using (MessageItem messageItem = MessageItem.Bind(base.MailboxSession, storeId))
            {
                WorkItemBase workItemBase = null;
                using (Stream stream = messageItem.PropertyBag.OpenPropertyStream(MessageItemSchema.UnifiedPolicyNotificationData, PropertyOpenMode.ReadOnly))
                {
                    if (stream.Length > 0L)
                    {
                        byte[] array = new byte[stream.Length];
                        stream.Position = 0L;
                        stream.Read(array, 0, array.Length);
                        workItemBase = WorkItemBase.Deserialize(array);
                    }
                }
                unifiedPolicyNotificationBase               = UnifiedPolicyNotificationFactory.Create(workItemBase, base.MailboxSession.MailboxOwner.ObjectId);
                workItemBase.WorkItemId                     = storeId.ToBase64String();
                workItemBase.HasPersistentBackUp            = true;
                unifiedPolicyNotificationBase.StoreObjectId = messageItem.Id;
            }
            return(unifiedPolicyNotificationBase);
        }
示例#19
0
 internal StreamLogItem(Referenced <MailboxSession> mailboxSession, StoreId messageId, StoreId folderId, string subject, string attachmentName)
 {
     if (mailboxSession == null || mailboxSession.Value == null)
     {
         throw new ArgumentNullException("mailboxSession");
     }
     if (folderId == null)
     {
         throw new ArgumentNullException("folderId");
     }
     if (messageId == null)
     {
         this.messageItem         = MessageItem.Create(mailboxSession, folderId);
         this.messageItem.IsDraft = false;
     }
     else
     {
         this.messageItem = MessageItem.Bind(mailboxSession, messageId, null);
     }
     this.messageItem.Subject   = subject;
     this.messageItem.ClassName = "IPM.Note.Microsoft.Exchange.Search.Log";
     this.attachmentName        = attachmentName;
     this.mailboxSession        = mailboxSession.Reacquire();
 }
示例#20
0
 private byte[] GetMimeData(StoreObjectId itemId, out string[] recipients)
 {
     recipients = null;
     byte[] result;
     using (MessageItem messageItem = MessageItem.Bind(this.mailboxSession, itemId, StoreObjectSchema.ContentConversionProperties))
     {
         List <string> list = new List <string>(messageItem.Recipients.Count);
         foreach (RecipientBase recipientBase in messageItem.Recipients)
         {
             Participant participant = recipientBase.Participant;
             if (participant != null)
             {
                 string valueOrDefault = participant.GetValueOrDefault <string>(ParticipantSchema.SmtpAddress);
                 list.Add(valueOrDefault);
             }
         }
         OutboundConversionOptions options = new OutboundConversionOptions(this.mailboxSession.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid), this.mailboxSession.ServerFullyQualifiedDomainName)
         {
             IsSenderTrusted = true,
             RecipientCache  = null,
             ClearCategories = true,
             Limits          =
             {
                 MimeLimits = MimeLimits.Unlimited
             },
             AllowPartialStnefConversion = true
         };
         using (PooledMemoryStream pooledMemoryStream = new PooledMemoryStream(6))
         {
             ItemConversion.ConvertItemToMime(messageItem, pooledMemoryStream, options);
             recipients = list.ToArray();
             result     = pooledMemoryStream.ToArray();
         }
     }
     return(result);
 }
示例#21
0
        private static ReplyTemplate FindByTemplateGuid(MailboxSession session, RuleAction.OOFReply ruleAction)
        {
            MessageItem messageItem = null;

            try
            {
                using (Folder folder = Folder.Bind(session, DefaultFolderType.Inbox))
                {
                    byte[] replyTemplateEntryIdFromTemplateGuid = ReplyTemplate.GetReplyTemplateEntryIdFromTemplateGuid(folder, ruleAction.ReplyTemplateGuid);
                    if (replyTemplateEntryIdFromTemplateGuid != null)
                    {
                        StoreObjectId storeObjectId = StoreObjectId.FromProviderSpecificId(replyTemplateEntryIdFromTemplateGuid);
                        messageItem = MessageItem.Bind(session, storeObjectId, new PropertyDefinition[]
                        {
                            ItemSchema.ReplyTemplateId
                        });
                        messageItem.OpenAsReadWrite();
                        ReplyTemplate.Tracer.TraceDebug <IExchangePrincipal, Guid, byte[]>(0L, "Mailbox:{0}: Found reply template by GUID. GUID={1}, Entry Id={2}", session.MailboxOwner, ruleAction.ReplyTemplateGuid, storeObjectId.GetBytes());
                    }
                    else
                    {
                        ReplyTemplate.Tracer.TraceDebug <IExchangePrincipal, Guid>(0L, "Mailbox:{0}: Found no reply template by GUID. GUID={1}", session.MailboxOwner, ruleAction.ReplyTemplateGuid);
                        messageItem = null;
                    }
                }
            }
            catch (ObjectNotFoundException)
            {
                return(null);
            }
            if (messageItem != null)
            {
                return(new ReplyTemplate(messageItem));
            }
            return(null);
        }
示例#22
0
        // Token: 0x06001589 RID: 5513 RVA: 0x0007F070 File Offset: 0x0007D270
        internal override Command.ExecutionState ExecuteCommand()
        {
            MessageItem      clientMessage    = null;
            Item             item             = null;
            MessageItem      messageItem      = null;
            VersionedId      versionedId      = null;
            CalendarItemBase calendarItemBase = null;

            try
            {
                base.ValidateBody();
                StoreObjectId defaultFolderId = base.MailboxSession.GetDefaultFolderId(DefaultFolderType.Drafts);
                clientMessage = MessageItem.Create(base.MailboxSession, defaultFolderId);
                base.ParseMimeToMessage(clientMessage);
                clientMessage.Save(SaveMode.NoConflictResolution);
                clientMessage.Load();
                versionedId = clientMessage.Id;
                clientMessage.Dispose();
                clientMessage = MessageItem.Bind(base.MailboxSession, versionedId);
                item          = base.GetSmartItem();
                RmsTemplate            rmsTemplate = null;
                bool                   isReplyAll  = false;
                SendMailBase.IrmAction irmAction   = base.GetIrmAction(delegate(RightsManagedMessageItem originalRightsManagedItem)
                {
                    if (originalRightsManagedItem == null)
                    {
                        throw new ArgumentNullException("originalRightsManagedItem");
                    }
                    isReplyAll = this.IsIrmReplyAll(originalRightsManagedItem, clientMessage);
                }, ref item, out rmsTemplate);
                Microsoft.Exchange.Data.Storage.BodyFormat bodyFormat = clientMessage.Body.Format;
                MeetingMessage meetingMessage = item as MeetingMessage;
                string         text;
                if ((base.ReplaceMime || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage) && meetingMessage != null && !meetingMessage.IsDelegated() && (meetingMessage is MeetingCancellation || meetingMessage is MeetingRequest))
                {
                    text = string.Empty;
                }
                else
                {
                    using (TextReader textReader = clientMessage.Body.OpenTextReader(bodyFormat))
                    {
                        text = textReader.ReadToEnd();
                    }
                    Body body = (irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseInlineOriginalBody || irmAction == SendMailBase.IrmAction.ReusePublishingLicenseInlineOriginalBody) ? ((RightsManagedMessageItem)item).ProtectedBody : item.Body;
                    if (body.Format == Microsoft.Exchange.Data.Storage.BodyFormat.TextHtml)
                    {
                        if (bodyFormat == Microsoft.Exchange.Data.Storage.BodyFormat.TextPlain)
                        {
                            XmlDocument  xmlDocument  = new SafeXmlDocument();
                            XmlNode      xmlNode      = xmlDocument.CreateElement("PRE");
                            XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("STYLE");
                            xmlAttribute.Value = "word-wrap:break-word; font-size:10.0pt; font-family:Tahoma; color:black";
                            xmlNode.Attributes.Append(xmlAttribute);
                            xmlNode.InnerText = text;
                            text = xmlNode.OuterXml;
                        }
                        bodyFormat = Microsoft.Exchange.Data.Storage.BodyFormat.TextHtml;
                    }
                }
                ReplyForwardConfiguration replyForwardConfiguration = new ReplyForwardConfiguration(bodyFormat);
                replyForwardConfiguration.ConversionOptionsForSmime = AirSyncUtility.GetInboundConversionOptions();
                replyForwardConfiguration.AddBodyPrefix(text);
                if (item is MessageItem)
                {
                    MessageItem messageItem2 = (MessageItem)item;
                    if (!messageItem2.IsReplyAllowed)
                    {
                        base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "ReplyNotAllowed");
                        AirSyncPermanentException ex = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.MessageReplyNotAllowed, null, false);
                        throw ex;
                    }
                    if (isReplyAll)
                    {
                        messageItem = messageItem2.CreateReplyAll(defaultFolderId, replyForwardConfiguration);
                    }
                    else
                    {
                        messageItem = messageItem2.CreateReply(defaultFolderId, replyForwardConfiguration);
                    }
                    if (irmAction == SendMailBase.IrmAction.CreateNewPublishingLicense || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseInlineOriginalBody || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage)
                    {
                        messageItem = base.GetRightsManagedReplyForward(messageItem, irmAction, rmsTemplate);
                    }
                }
                else if (item is CalendarItem)
                {
                    CalendarItem item2 = (CalendarItem)item;
                    calendarItemBase = base.GetCalendarItemBaseToReplyOrForward(item2);
                    messageItem      = calendarItemBase.CreateReply(defaultFolderId, replyForwardConfiguration);
                }
                if (messageItem == null)
                {
                    base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "ReplyFailed");
                    throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.MailSubmissionFailed, null, false);
                }
                base.CopyMessageContents(clientMessage, messageItem, true, (irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage) ? item : null);
                base.SendMessage(messageItem);
            }
            finally
            {
                if (clientMessage != null)
                {
                    if (versionedId != null)
                    {
                        base.MailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                        {
                            versionedId
                        });
                    }
                    clientMessage.Dispose();
                }
                if (item != null)
                {
                    item.Dispose();
                }
                if (messageItem != null)
                {
                    messageItem.Dispose();
                }
                if (calendarItemBase != null)
                {
                    calendarItemBase.Dispose();
                }
            }
            return(Command.ExecutionState.Complete);
        }
示例#23
0
        private bool WriteToInitiationMessage(MailboxSession session, StoreObjectId storeId, string initMessageId)
        {
            ConflictResolutionResult conflictResolutionResult = null;

            try
            {
                for (int i = 0; i < 5; i++)
                {
                    using (MessageItem messageItem = MessageItem.Bind(session, storeId, NdrOofHandler.PropertiesNeededToUpdateInitiation))
                    {
                        messageItem.OpenAsReadWrite();
                        string         ndrOofValue     = (string)messageItem[MessageItemSchema.ApprovalDecisionMakersNdred];
                        ApprovalStatus?valueAsNullable = messageItem.GetValueAsNullable <ApprovalStatus>(MessageItemSchema.ApprovalStatus);
                        if (valueAsNullable == null)
                        {
                            NdrOofHandler.diag.TraceDebug <string>((long)this.GetHashCode(), "Invalid approval status property in initation message {0}. Ignored", initMessageId);
                            return(false);
                        }
                        if ((valueAsNullable & (ApprovalStatus.Approved | ApprovalStatus.Rejected)) != (ApprovalStatus)0)
                        {
                            NdrOofHandler.diag.TraceDebug <string>((long)this.GetHashCode(), "There is already a decision for {0}, there is no need to handle NDR or OOF", initMessageId);
                            return(false);
                        }
                        int num;
                        int num2;
                        int num3;
                        if (!NdrOofHandler.TryParseNdrOofProperty(ndrOofValue, out num, out num2, out num3))
                        {
                            NdrOofHandler.diag.TraceDebug <string>((long)this.GetHashCode(), "Invalid ndr/oof property in initation message {0}. Ignored", initMessageId);
                            return(false);
                        }
                        int num4;
                        int num5;
                        this.GetNdrOrOofCountInMessage(out num4, out num5);
                        num2 += num4;
                        num3 += num5;
                        messageItem[MessageItemSchema.ApprovalDecisionMakersNdred] = NdrOofHandler.FormatNdrOofProperty(num, num2, num3);
                        if (num3 + num2 == num)
                        {
                            if (num3 == 0)
                            {
                                messageItem[MessageItemSchema.ApprovalStatus] = (valueAsNullable.Value | ApprovalStatus.Ndred);
                            }
                            else
                            {
                                messageItem[MessageItemSchema.ApprovalStatus] = (valueAsNullable.Value | ApprovalStatus.Oofed);
                            }
                        }
                        conflictResolutionResult = messageItem.Save(SaveMode.ResolveConflicts);
                        if (SaveResult.IrresolvableConflict != conflictResolutionResult.SaveStatus)
                        {
                            NdrOofHandler.diag.TraceDebug <string>((long)this.GetHashCode(), "Saved initiation message '{0}' successfully.", initMessageId);
                            return(true);
                        }
                        NdrOofHandler.diag.TraceDebug <string, int, SaveResult>((long)this.GetHashCode(), "Saving message: '{0}' try {1}, resulted in an update conflict ({2}).", initMessageId, i, conflictResolutionResult.SaveStatus);
                    }
                }
            }
            catch (ObjectNotFoundException arg)
            {
                NdrOofHandler.diag.TraceDebug <string, ObjectNotFoundException>((long)this.GetHashCode(), "Initiation Message '{0}' is no longer there {1}", initMessageId, arg);
                return(false);
            }
            NdrOofHandler.diag.TraceDebug <string, SaveResult>((long)this.GetHashCode(), "Saving message failed after all retries. Init MessageId={0}, Save status={1}", initMessageId, conflictResolutionResult.SaveStatus);
            return(false);
        }
示例#24
0
        private VersionedId UpdateRetryable(MailboxSession itemStore, bool getExisting, SingleInstanceItemHandler.ContentUpdater updater)
        {
            List <object[]> list        = this.QueryItems(itemStore);
            VersionedId     versionedId = this.GetMostRecentItem(list);

            if (versionedId == null)
            {
                try
                {
                    using (Folder folder = Folder.Bind(itemStore, this.defaultFolder))
                    {
                        using (Item item = MessageItem.Create(itemStore, folder.Id))
                        {
                            item.ClassName = this.messageClass;
                            using (TextWriter textWriter = item.Body.OpenTextWriter(BodyFormat.TextPlain))
                            {
                                textWriter.Write(updater(null));
                            }
                            ConflictResolutionResult conflictResolutionResult = item.Save(SaveMode.ResolveConflicts);
                            if (conflictResolutionResult.SaveStatus == SaveResult.IrresolvableConflict)
                            {
                                throw new SaveConflictException(ServerStrings.ExSaveFailedBecauseOfConflicts(item.Id), conflictResolutionResult);
                            }
                            item.Load();
                            versionedId = item.Id;
                        }
                    }
                    SingleInstanceItemHandler.Tracer.TraceDebug <SingleInstanceItemHandler, VersionedId, IExchangePrincipal>((long)this.GetHashCode(), "{0}: Created new item itemId={1} on mailbox {2}", this, versionedId, itemStore.MailboxOwner);
                    goto IL_1CD;
                }
                catch (ObjectNotFoundException ex)
                {
                    SingleInstanceItemHandler.Tracer.TraceError <SingleInstanceItemHandler, IExchangePrincipal, ObjectNotFoundException>((long)this.GetHashCode(), "{0}: bind to folder failed on mailbox {1}. Exception={2}", this, itemStore.MailboxOwner, ex);
                    throw new SingleInstanceItemHandlerPermanentException(Strings.FailedToGetItem(this.messageClass, this.defaultFolder.ToString()), ex);
                }
            }
            using (Item item2 = MessageItem.Bind(itemStore, versionedId))
            {
                string existingContent = null;
                if (getExisting)
                {
                    using (TextReader textReader = item2.Body.OpenTextReader(BodyFormat.TextPlain))
                    {
                        existingContent = textReader.ReadToEnd();
                    }
                }
                using (TextWriter textWriter2 = item2.Body.OpenTextWriter(BodyFormat.TextPlain))
                {
                    textWriter2.Write(updater(existingContent));
                }
                ConflictResolutionResult conflictResolutionResult2 = item2.Save(SaveMode.ResolveConflicts);
                if (conflictResolutionResult2.SaveStatus == SaveResult.IrresolvableConflict)
                {
                    throw new SaveConflictException(ServerStrings.ExSaveFailedBecauseOfConflicts(item2.Id), conflictResolutionResult2);
                }
            }
            SingleInstanceItemHandler.Tracer.TraceDebug <SingleInstanceItemHandler, VersionedId, IExchangePrincipal>((long)this.GetHashCode(), "{0}: Updated item itemId={1} on mailbox {2}", this, versionedId, itemStore.MailboxOwner);
IL_1CD:
            using (IEnumerator <object[]> enumerator = list.GetEnumerator())
            {
                List <VersionedId> list2 = new List <VersionedId>();
                for (;;)
                {
                    bool flag = enumerator.MoveNext();
                    if ((!flag || list2.Count == 100) && list2.Count > 0)
                    {
                        try
                        {
                            itemStore.Delete(DeleteItemFlags.HardDelete, list2.ToArray());
                        }
                        catch (ObjectNotFoundException)
                        {
                            SingleInstanceItemHandler.Tracer.TraceError <SingleInstanceItemHandler, IExchangePrincipal>((long)this.GetHashCode(), "{0}: ObjectNotFoundException encountred while trying to delete duplicate item on mailbox {1}", this, itemStore.MailboxOwner);
                        }
                        list2.Clear();
                    }
                    if (!flag)
                    {
                        break;
                    }
                    VersionedId versionedId2 = (VersionedId)enumerator.Current[0];
                    if (versionedId != versionedId2)
                    {
                        list2.Add(versionedId2);
                        SingleInstanceItemHandler.Tracer.TraceDebug <SingleInstanceItemHandler, VersionedId, IExchangePrincipal>((long)this.GetHashCode(), "{0}: Deleting extra item {1} on mailbox {2}", this, versionedId2, itemStore.MailboxOwner);
                    }
                }
            }
            return(versionedId);
        }
示例#25
0
 public IMessageItem BindToMessage(IStoreSession session, StoreId storeId, ICollection <PropertyDefinition> propsToReturn = null)
 {
     return(MessageItem.Bind((StoreSession)session, storeId, propsToReturn));
 }
        internal ExternalUserCollection(MailboxSession session)
        {
            this.data = new List <ExternalUser>();
            byte[]       entryId      = null;
            StoreSession storeSession = null;
            bool         flag         = false;

            try
            {
                if (storeSession != null)
                {
                    storeSession.BeginMapiCall();
                    storeSession.BeginServerHealthCall();
                    flag = true;
                }
                if (StorageGlobals.MapiTestHookBeforeCall != null)
                {
                    StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod());
                }
                entryId = session.Mailbox.MapiStore.GetLocalDirectoryEntryId();
            }
            catch (MapiPermanentException ex)
            {
                throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotLookupEntryId, ex, storeSession, this, "{0}. MapiException = {1}.", new object[]
                {
                    string.Format("Unable to lookup Local Directory EntryID", new object[0]),
                    ex
                });
            }
            catch (MapiRetryableException ex2)
            {
                throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotLookupEntryId, ex2, storeSession, this, "{0}. MapiException = {1}.", new object[]
                {
                    string.Format("Unable to lookup Local Directory EntryID", new object[0]),
                    ex2
                });
            }
            finally
            {
                try
                {
                    if (storeSession != null)
                    {
                        storeSession.EndMapiCall();
                        if (flag)
                        {
                            storeSession.EndServerHealthCall();
                        }
                    }
                }
                finally
                {
                    if (StorageGlobals.MapiTestHookAfterCall != null)
                    {
                        StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod());
                    }
                }
            }
            StoreObjectId messageId = StoreObjectId.FromProviderSpecificId(entryId, StoreObjectType.Message);

            this.directoryMessage = MessageItem.Bind(session, messageId, new PropertyDefinition[]
            {
                InternalSchema.LocalDirectory
            });
            try
            {
                this.directoryMessage.OpenAsReadWrite();
                try
                {
                    using (Stream stream = this.directoryMessage.OpenPropertyStream(InternalSchema.LocalDirectory, PropertyOpenMode.ReadOnly))
                    {
                        long length = stream.Length;
                        using (BinaryReader binaryReader = new BinaryReader(stream))
                        {
                            while (stream.Position < length)
                            {
                                ExternalUser item;
                                if (ExternalUserCollection.TryReadEntry(binaryReader, out item) && !this.Contains(item))
                                {
                                    this.data.Add(item);
                                }
                            }
                        }
                    }
                }
                catch (ObjectNotFoundException)
                {
                }
                catch (EndOfStreamException)
                {
                }
            }
            catch (StoragePermanentException)
            {
                if (this.directoryMessage != null)
                {
                    this.directoryMessage.Dispose();
                }
                throw;
            }
            catch (StorageTransientException)
            {
                if (this.directoryMessage != null)
                {
                    this.directoryMessage.Dispose();
                }
                throw;
            }
            StorageGlobals.TraceConstructIDisposable(this);
            this.disposeTracker = this.GetDisposeTracker();
        }
示例#27
0
        public static StoreObjectId Recreate(MailboxSession session, Guid searchFolderClsId)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (searchFolderClsId == Guid.Empty)
            {
                throw new ArgumentException("Guid is empty", "searchFolderClsId");
            }
            using (Folder folder = Folder.Bind(session, DefaultFolderType.SearchFolders))
            {
                using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, null, null, new PropertyDefinition[]
                {
                    InternalSchema.OutlookSearchFolderClsId
                }))
                {
                    for (;;)
                    {
                        object[][] rows = queryResult.GetRows(10000);
                        for (int i = 0; i < rows.Length; i++)
                        {
                            if (rows[i][0] is Guid && ((Guid)rows[i][0]).Equals(searchFolderClsId))
                            {
                                goto Block_9;
                            }
                        }
                        if (rows.Length <= 0)
                        {
                            goto Block_11;
                        }
                    }
Block_9:
                    throw new ObjectExistedException(ServerStrings.ExSearchFolderAlreadyExists(searchFolderClsId));
                    Block_11 :;
                }
            }
            VersionedId versionedId = OutlookSearchFolder.FindAssociatedMessageId(session, searchFolderClsId);

            if (versionedId == null)
            {
                throw new ObjectNotFoundException(ServerStrings.ExSearchFolderNoAssociatedItem(searchFolderClsId));
            }
            StoreObjectId objectId;

            using (MessageItem messageItem = MessageItem.Bind(session, versionedId))
            {
                bool                 deepTraversal;
                StoreId[]            folderScope;
                Restriction          restriction          = OutlookSearchFolder.ReadOutlookSearchFolderDefinitionBlob(messageItem, out deepTraversal, out folderScope);
                QueryFilter          searchQuery          = FilterRestrictionConverter.CreateFilter(session, session.Mailbox.MapiStore, restriction, true);
                SearchFolderCriteria searchFolderCriteria = new SearchFolderCriteria(searchQuery, folderScope);
                searchFolderCriteria.DeepTraversal = deepTraversal;
                string valueOrDefault = messageItem.GetValueOrDefault <string>(InternalSchema.DisplayName, string.Empty);
                using (OutlookSearchFolder outlookSearchFolder = OutlookSearchFolder.Create(session, valueOrDefault))
                {
                    outlookSearchFolder[InternalSchema.OutlookSearchFolderClsId] = searchFolderClsId;
                    FolderSaveResult folderSaveResult = outlookSearchFolder.Save();
                    if (folderSaveResult.OperationResult != OperationResult.Succeeded)
                    {
                        throw folderSaveResult.ToException(ServerStrings.ExCannotCreateFolder(folderSaveResult));
                    }
                    outlookSearchFolder.Load(null);
                    outlookSearchFolder.ApplyContinuousSearch(searchFolderCriteria);
                    objectId = outlookSearchFolder.Id.ObjectId;
                }
            }
            return(objectId);
        }
        private Command.ExecutionState ForwardUsingXso(StoreObjectId smartId)
        {
            Item             smartItem        = base.GetSmartItem(smartId);
            MessageItem      messageItem      = null;
            VersionedId      versionedId      = null;
            MessageItem      messageItem2     = null;
            CalendarItemBase calendarItemBase = null;

            try
            {
                StoreObjectId defaultFolderId = base.MailboxSession.GetDefaultFolderId(DefaultFolderType.Drafts);
                messageItem = MessageItem.Create(base.MailboxSession, defaultFolderId);
                base.ParseMimeToMessage(messageItem);
                messageItem.Save(SaveMode.NoConflictResolution);
                messageItem.Load();
                versionedId = messageItem.Id;
                messageItem.Dispose();
                messageItem = MessageItem.Bind(base.MailboxSession, versionedId);
                RmsTemplate            rmsTemplate = null;
                SendMailBase.IrmAction irmAction   = base.GetIrmAction(delegate(RightsManagedMessageItem originalRightsManagedItem)
                {
                    if (originalRightsManagedItem == null)
                    {
                        throw new ArgumentNullException("originalRightsManagedItem");
                    }
                    if (!originalRightsManagedItem.UsageRights.IsUsageRightGranted(ContentRight.Forward))
                    {
                        throw new AirSyncPermanentException(StatusCode.IRM_OperationNotPermitted, false)
                        {
                            ErrorStringForProtocolLogger = "sfcEOperationNotPermitted"
                        };
                    }
                }, ref smartItem, out rmsTemplate);
                Microsoft.Exchange.Data.Storage.BodyFormat bodyFormat = messageItem.Body.Format;
                MeetingMessage meetingMessage = smartItem as MeetingMessage;
                string         text;
                if ((base.ReplaceMime || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage) && meetingMessage != null && !meetingMessage.IsDelegated() && (meetingMessage is MeetingRequest || meetingMessage is MeetingCancellation))
                {
                    text = string.Empty;
                }
                else
                {
                    using (TextReader textReader = messageItem.Body.OpenTextReader(bodyFormat))
                    {
                        text = textReader.ReadToEnd();
                    }
                    Body body = (irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseInlineOriginalBody || irmAction == SendMailBase.IrmAction.ReusePublishingLicenseInlineOriginalBody) ? ((RightsManagedMessageItem)smartItem).ProtectedBody : smartItem.Body;
                    if (body.Format == Microsoft.Exchange.Data.Storage.BodyFormat.TextHtml)
                    {
                        if (bodyFormat == Microsoft.Exchange.Data.Storage.BodyFormat.TextPlain)
                        {
                            XmlDocument  xmlDocument  = new SafeXmlDocument();
                            XmlNode      xmlNode      = xmlDocument.CreateElement("PRE");
                            XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("STYLE");
                            xmlAttribute.Value = "word-wrap:break-word; font-size:10.0pt; font-family:Tahoma; color:black";
                            xmlNode.Attributes.Append(xmlAttribute);
                            xmlNode.InnerText = text;
                            text = xmlNode.OuterXml;
                        }
                        bodyFormat = Microsoft.Exchange.Data.Storage.BodyFormat.TextHtml;
                    }
                }
                ReplyForwardConfiguration replyForwardConfiguration = new ReplyForwardConfiguration(bodyFormat);
                replyForwardConfiguration.ConversionOptionsForSmime = AirSyncUtility.GetInboundConversionOptions();
                replyForwardConfiguration.AddBodyPrefix(text);
                if (base.Version >= 120)
                {
                    if (smartItem is MessageItem)
                    {
                        messageItem2 = ((MessageItem)smartItem).CreateForward(defaultFolderId, replyForwardConfiguration);
                        if (irmAction == SendMailBase.IrmAction.CreateNewPublishingLicense || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseInlineOriginalBody || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage)
                        {
                            messageItem2 = base.GetRightsManagedReplyForward(messageItem2, irmAction, rmsTemplate);
                        }
                    }
                    else if (smartItem is CalendarItem)
                    {
                        CalendarItem calendarItem = (CalendarItem)smartItem;
                        calendarItemBase = base.GetCalendarItemBaseToReplyOrForward(calendarItem);
                        messageItem2     = calendarItemBase.CreateForward(defaultFolderId, replyForwardConfiguration);
                        if (!calendarItem.IsMeeting)
                        {
                            BodyConversionUtilities.CopyBody(messageItem, messageItem2);
                        }
                    }
                    if (messageItem2 == null)
                    {
                        base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "ForwardFailed");
                        throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.MailSubmissionFailed, null, false);
                    }
                    if (base.ReplaceMime || irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage)
                    {
                        RightsManagedMessageItem rightsManagedMessageItem = messageItem2 as RightsManagedMessageItem;
                        if (rightsManagedMessageItem != null)
                        {
                            rightsManagedMessageItem.ProtectedAttachmentCollection.RemoveAll();
                        }
                        else
                        {
                            messageItem2.AttachmentCollection.RemoveAll();
                        }
                    }
                    base.CopyMessageContents(messageItem, messageItem2, false, (irmAction == SendMailBase.IrmAction.CreateNewPublishingLicenseAttachOriginalMessage) ? smartItem : null);
                    base.SendMessage(messageItem2);
                }
                else if (smartItem is MessageItem)
                {
                    using (ItemAttachment itemAttachment = messageItem.AttachmentCollection.AddExistingItem(smartItem))
                    {
                        MessageItem messageItem3 = (MessageItem)smartItem;
                        itemAttachment.FileName = messageItem3.Subject + itemAttachment.FileExtension;
                        itemAttachment.Save();
                    }
                    base.SendMessage(messageItem);
                }
                else if (smartItem is CalendarItem)
                {
                    CalendarItem calendarItem2 = (CalendarItem)smartItem;
                    messageItem2 = calendarItem2.CreateForward(defaultFolderId, replyForwardConfiguration);
                    if (messageItem2 == null)
                    {
                        base.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "ForwardFailed2");
                        throw new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.MailSubmissionFailed, null, false);
                    }
                    if (!calendarItem2.IsMeeting)
                    {
                        BodyConversionUtilities.CopyBody(messageItem, messageItem2);
                    }
                    base.CopyMessageContents(messageItem, messageItem2, false, null);
                    base.SendMessage(messageItem2);
                }
            }
            finally
            {
                if (messageItem != null)
                {
                    if (versionedId != null)
                    {
                        base.MailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                        {
                            versionedId
                        });
                    }
                    messageItem.Dispose();
                }
                if (smartItem != null)
                {
                    smartItem.Dispose();
                }
                if (messageItem2 != null)
                {
                    messageItem2.Dispose();
                }
                if (calendarItemBase != null)
                {
                    calendarItemBase.Dispose();
                }
            }
            return(Command.ExecutionState.Complete);
        }
        // Token: 0x06000A3A RID: 2618 RVA: 0x0004380C File Offset: 0x00041A0C
        public void HandleEvent(MapiEvent mapiEvent, MailboxSession itemStore, StoreObject item)
        {
            if (MailboxData.GetFromCache(mapiEvent.MailboxGuid) == null)
            {
                using (MailboxData.CachedStateWriter cachedStateWriter = new MailboxData.CachedStateWriter(mapiEvent.MailboxGuid))
                {
                    if (cachedStateWriter.Get() == null)
                    {
                        MailboxData mailboxData = new MailboxData(itemStore);
                        cachedStateWriter.Set(mailboxData);
                    }
                }
            }
            MessageItem messageItem = item as MessageItem;

            if (messageItem == null)
            {
                return;
            }
            int?valueAsNullable = messageItem.GetValueAsNullable <int>(ItemSchema.InternetMessageIdHash);

            if (valueAsNullable == null)
            {
                return;
            }
            string valueOrDefault = messageItem.GetValueOrDefault <string>(ItemSchema.InternetMessageId, null);

            if (string.IsNullOrEmpty(valueOrDefault))
            {
                return;
            }
            int?valueAsNullable2 = messageItem.GetValueAsNullable <int>(MessageItemSchema.TextMessageDeliveryStatus);

            if (valueAsNullable2 == null)
            {
                return;
            }
            List <IStorePropertyBag> list = new List <IStorePropertyBag>(1);

            using (Folder folder = Folder.Bind(itemStore, DefaultFolderType.SentItems))
            {
                using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, new SortBy[]
                {
                    new SortBy(ItemSchema.InternetMessageIdHash, SortOrder.Ascending)
                }, new PropertyDefinition[]
                {
                    ItemSchema.InternetMessageIdHash,
                    ItemSchema.Id,
                    ItemSchema.InternetMessageId,
                    MessageItemSchema.TextMessageDeliveryStatus
                }))
                {
                    if (!queryResult.SeekToCondition(SeekReference.OriginBeginning, new ComparisonFilter(ComparisonOperator.Equal, ItemSchema.InternetMessageIdHash, valueAsNullable)))
                    {
                        return;
                    }
                    bool flag = false;
                    while (!flag)
                    {
                        IStorePropertyBag[] propertyBags = queryResult.GetPropertyBags(1);
                        if (propertyBags == null || 0 >= propertyBags.Length)
                        {
                            break;
                        }
                        for (int i = 0; i < propertyBags.Length; i++)
                        {
                            int?num = propertyBags[i].TryGetProperty(ItemSchema.InternetMessageIdHash) as int?;
                            if (num == null)
                            {
                                break;
                            }
                            if (num.Value != valueAsNullable)
                            {
                                flag = true;
                                break;
                            }
                            string a = propertyBags[i].TryGetProperty(ItemSchema.InternetMessageId) as string;
                            if (string.Equals(a, valueOrDefault))
                            {
                                list.Add(propertyBags[i]);
                            }
                        }
                    }
                }
            }
            foreach (IStorePropertyBag storePropertyBag in list)
            {
                int?num2 = storePropertyBag.TryGetProperty(MessageItemSchema.TextMessageDeliveryStatus) as int?;
                if (num2 == null || !(num2 >= valueAsNullable2))
                {
                    VersionedId versionedId = storePropertyBag.TryGetProperty(ItemSchema.Id) as VersionedId;
                    if (versionedId != null && versionedId.ObjectId != null)
                    {
                        using (MessageItem messageItem2 = MessageItem.Bind(itemStore, versionedId.ObjectId))
                        {
                            messageItem2.OpenAsReadWrite();
                            messageItem2.SetProperties(TextMessageDeliveryStatusProcessor.propertyDeliveryStatus, new object[]
                            {
                                valueAsNullable2
                            });
                            messageItem2.Save(SaveMode.ResolveConflicts);
                        }
                    }
                }
            }
        }
 // Token: 0x0600010A RID: 266 RVA: 0x0000677A File Offset: 0x0000497A
 public void ProcessBodyTag()
 {
     ExWatson.SendReportOnUnhandledException(delegate()
     {
         List <IStorePropertyBag> propertyBagList = new List <IStorePropertyBag>(100);
         ExDateTime toProcessDate   = ExDateTime.UtcNow.Subtract(TimeSpan.FromDays(15.0));
         int indexTrackingCounter   = 0;
         bool trackingCheckRequired = true;
         string text  = null;
         string text2 = null;
         string text3 = null;
         bool flag    = false;
         try
         {
             using (MailboxSession session = MailboxSession.OpenAsAdmin(this.principal, CultureInfo.InvariantCulture, "Client=TBA;Action=Conversation Assistant"))
             {
                 text = session.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString();
                 AllItemsFolderHelper.RunQueryOnAllItemsFolder <bool>(session, AllItemsFolderHelper.SupportedSortBy.ReceivedTime, delegate(QueryResult queryResults)
                 {
                     bool flag2 = false;
                     int num    = 0;
                     while (!flag2)
                     {
                         IStorePropertyBag[] propertyBags = queryResults.GetPropertyBags(50);
                         if (propertyBags.Length <= 0)
                         {
                             break;
                         }
                         foreach (IStorePropertyBag storePropertyBag2 in propertyBags)
                         {
                             num++;
                             if (num >= 10000)
                             {
                                 BodyTagProcessor.Tracer.TraceDebug <string>(0L, "Skip querying as we have reached our maximum limit of emails we want to process for {0}", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString());
                                 flag2 = true;
                                 break;
                             }
                             string text5 = storePropertyBag2.TryGetProperty(StoreObjectSchema.ItemClass) as string;
                             if (!string.IsNullOrEmpty(text5) && ObjectClass.IsMessage(text5, false))
                             {
                                 if (!(BodyTagProcessor.GetProperty <ExDateTime>(storePropertyBag2, ItemSchema.ReceivedTime, ExDateTime.MinValue) >= toProcessDate))
                                 {
                                     flag2 = true;
                                     break;
                                 }
                                 if (trackingCheckRequired && !(storePropertyBag2.TryGetProperty(ItemSchema.ConversationIndexTracking) is PropertyError))
                                 {
                                     indexTrackingCounter++;
                                     if (indexTrackingCounter >= 10)
                                     {
                                         BodyTagProcessor.Tracer.TraceDebug <string>(0L, "Not processing BodyTag for mailbox {0}", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString());
                                         flag2 = true;
                                         break;
                                     }
                                 }
                                 if (storePropertyBag2.TryGetProperty(ItemSchema.BodyTag) is PropertyError || storePropertyBag2.TryGetProperty(ItemSchema.BodyTag) == null)
                                 {
                                     propertyBagList.Add(storePropertyBag2);
                                 }
                             }
                         }
                         trackingCheckRequired = false;
                     }
                     return(true);
                 }, new PropertyDefinition[]
                 {
                     ItemSchema.Id,
                     StoreObjectSchema.ItemClass,
                     ItemSchema.ReceivedTime,
                     ItemSchema.BodyTag,
                     ItemSchema.ConversationIndexTracking
                 });
                 if (propertyBagList.Count == 0 || indexTrackingCounter >= 10)
                 {
                     string text4 = (propertyBagList.Count == 0) ? " 0 messages to process" : " IndexTrackingCounter reached its limit";
                     Globals.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_BodyTagProcessingSkipped, null, new object[]
                     {
                         text,
                         text4
                     });
                     return;
                 }
                 Globals.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_TotalNumberOfItemsForBodyTagProcessing, null, new object[]
                 {
                     propertyBagList.Count,
                     text
                 });
                 foreach (IStorePropertyBag storePropertyBag in propertyBagList)
                 {
                     try
                     {
                         using (MessageItem messageItem = MessageItem.Bind(session, storePropertyBag[ItemSchema.Id] as StoreId))
                         {
                             if (!(messageItem is RightsManagedMessageItem))
                             {
                                 messageItem.OpenAsReadWrite();
                                 messageItem[ItemSchema.BodyTag] = messageItem.Body.CalculateBodyTag();
                                 messageItem.Save(SaveMode.ResolveConflicts);
                             }
                         }
                     }
                     catch (ObjectNotFoundException)
                     {
                         BodyTagProcessor.Tracer.TraceDebug <object, string>(0L, "ObjectNotFound exception thrown while processing item - {0} in mailbox - {1}", storePropertyBag[ItemSchema.Id], text);
                     }
                     catch (AccessDeniedException)
                     {
                         BodyTagProcessor.Tracer.TraceDebug <object, string>(0L, "AccessDenied exception thrown while processing item - {0} in mailbox - {1}", storePropertyBag[ItemSchema.Id], text);
                     }
                     catch (CorruptDataException)
                     {
                         BodyTagProcessor.Tracer.TraceDebug <object, string>(0L, "Corrupt data exception thrown while processing item - {0} in mailbox - {1}", storePropertyBag[ItemSchema.Id], text);
                     }
                     catch (VirusException)
                     {
                         BodyTagProcessor.Tracer.TraceDebug <object, string>(0L, "Virus exception thrown while processing item - {0} in mailbox - {1}", storePropertyBag[ItemSchema.Id], text);
                     }
                     catch (PropertyErrorException)
                     {
                         BodyTagProcessor.Tracer.TraceDebug <object, string>(0L, "PropertyErrorException thrown while processing item - {0} in mailbox - {1}", storePropertyBag[ItemSchema.Id], text);
                     }
                     catch (StoragePermanentException ex)
                     {
                         if (!(ex.InnerException is MapiExceptionCallFailed))
                         {
                             throw;
                         }
                         BodyTagProcessor.Tracer.TraceDebug <object, string>(0L, "MapiExceptionCallFailed thrown while processing item - {0} in mailbox - {1}", storePropertyBag[ItemSchema.Id], text);
                     }
                 }
             }
             Globals.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_BodyTagProcessingSucceeded, null, new object[]
             {
                 text
             });
         }
         catch (ObjectNotFoundException ex2)
         {
             flag  = true;
             text2 = ex2.Message;
             text3 = ex2.StackTrace;
         }
         catch (CorruptDataException ex3)
         {
             flag  = true;
             text2 = ex3.Message;
             text3 = ex3.StackTrace;
         }
         catch (QuotaExceededException ex4)
         {
             flag  = true;
             text2 = ex4.Message;
             text3 = ex4.StackTrace;
         }
         catch (MessageSubmissionExceededException ex5)
         {
             flag  = true;
             text2 = ex5.Message;
             text3 = ex5.StackTrace;
         }
         catch (ConnectionFailedPermanentException ex6)
         {
             flag  = true;
             text2 = ex6.Message;
             text3 = ex6.StackTrace;
         }
         catch (MailboxUnavailableException ex7)
         {
             flag  = true;
             text2 = ex7.Message;
             text3 = ex7.StackTrace;
         }
         catch (StorageTransientException ex8)
         {
             flag  = true;
             text2 = ex8.Message;
             text3 = ex8.StackTrace;
         }
         catch (StoragePermanentException ex9)
         {
             if (!(ex9.InnerException is MapiExceptionJetErrorLogDiskFull))
             {
                 throw;
             }
             flag  = true;
             text2 = ex9.Message;
             text3 = ex9.StackTrace;
         }
         finally
         {
             if (flag)
             {
                 Globals.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_BodyTagProcessingFailed, null, new object[]
                 {
                     text,
                     text2 ?? "<null>",
                     text3 ?? "<null>"
                 });
             }
         }
     }, delegate(object exception)
     {
         Exception ex = exception as Exception;
         if (ex != null)
         {
             Globals.Logger.LogEvent(InfoWorkerEventLogConstants.Tuple_BodyTagProcessingFailed, null, new object[]
             {
                 this.principal.MailboxInfo.PrimarySmtpAddress.ToString(),
                 ex.Message ?? "<null>",
                 ex.StackTrace ?? "<null>"
             });
         }
         return(true);
     }, ReportOptions.None);
 }