Example #1
0
        public static bool DeleteSyncStateStorage(MailboxSession mailboxSession, StoreObjectId deviceFolderId, DeviceIdentity deviceIdentity, ISyncLogger syncLogger = null)
        {
            if (syncLogger == null)
            {
                syncLogger = TracingLogger.Singleton;
            }
            ArgumentValidator.ThrowIfNull("mailboxSession", mailboxSession);
            ArgumentValidator.ThrowIfNull("folderId", deviceFolderId);
            bool result = false;

            SyncStateTypeFactory.GetInstance().RegisterInternalBuilders();
            UserSyncStateMetadata    userSyncStateMetadata    = UserSyncStateMetadataCache.Singleton.Get(mailboxSession, syncLogger);
            AggregateOperationResult aggregateOperationResult = mailboxSession.Delete(DeleteItemFlags.SoftDelete, new StoreId[]
            {
                deviceFolderId
            });

            syncLogger.Information <string>(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. Result = {0}", aggregateOperationResult.OperationResult.ToString());
            userSyncStateMetadata.TryRemove(deviceIdentity, syncLogger);
            List <DeviceSyncStateMetadata> allDevices = userSyncStateMetadata.GetAllDevices(mailboxSession, false, syncLogger);

            if (allDevices != null)
            {
                foreach (DeviceSyncStateMetadata deviceSyncStateMetadata in allDevices)
                {
                    syncLogger.Information <DeviceIdentity, DeviceIdentity>(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. Found device folder '{0}', Looking for folder '{1}'", deviceSyncStateMetadata.Id, deviceIdentity);
                    if (deviceSyncStateMetadata.Id.Equals(deviceIdentity))
                    {
                        try
                        {
                            aggregateOperationResult = mailboxSession.Delete(DeleteItemFlags.SoftDelete, new StoreId[]
                            {
                                deviceSyncStateMetadata.DeviceFolderId
                            });
                            syncLogger.Information <DeviceIdentity, DeviceIdentity, string>(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. try Deleting SyncState folder again.folderName:{0}, originalFolder:{1}, result:{2}", deviceSyncStateMetadata.Id, deviceIdentity, aggregateOperationResult.OperationResult.ToString());
                            continue;
                        }
                        catch
                        {
                            syncLogger.Information(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. Error deleting the sync state folder.");
                            continue;
                        }
                    }
                    if (deviceSyncStateMetadata.Id.IsProtocol("AirSync"))
                    {
                        result = true;
                        break;
                    }
                }
            }
            return(result);
        }
Example #2
0
        private static CalendarGroup CreateMyCalendarsGroup(MailboxSession session)
        {
            CalendarGroup calendarGroup = null;

            using (DisposeGuard disposeGuard = default(DisposeGuard))
            {
                calendarGroup = CalendarGroup.InternalCreateGroup(session, CalendarGroupType.MyCalendars);
                disposeGuard.Add <CalendarGroup>(calendarGroup);
                using (CalendarGroupEntry calendarGroupEntry = CalendarGroupEntry.Create(session, session.GetDefaultFolderId(DefaultFolderType.Calendar), FolderTreeData.MyFoldersClassId, calendarGroup.GroupName))
                {
                    calendarGroupEntry.CalendarName = ClientStrings.Calendar.ToString(session.InternalCulture);
                    ConflictResolutionResult conflictResolutionResult = calendarGroupEntry.Save(SaveMode.NoConflictResolution);
                    if (conflictResolutionResult.SaveStatus != SaveResult.Success)
                    {
                        ExTraceGlobals.StorageTracer.TraceWarning <SmtpAddress>(0L, "Unable to associate default calendar with the MyCalendars group for user: {0}. Attempting to delete default calendars group.", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress);
                        AggregateOperationResult aggregateOperationResult = session.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                        {
                            calendarGroup.Id
                        });
                        if (aggregateOperationResult.OperationResult != OperationResult.Succeeded)
                        {
                            ExTraceGlobals.StorageTracer.TraceWarning <SmtpAddress>(0L, "Unable to delete default calendar group after failing to add the default calendar to it. User: {0}", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress);
                        }
                        throw new DefaultCalendarNodeCreationException();
                    }
                }
                disposeGuard.Success();
            }
            return(calendarGroup);
        }
        internal override void ContactLinkingOperation(MailboxSession mailboxSession)
        {
            ContactsEnumerator <IStorePropertyBag> contactsEnumerator = ContactsEnumerator <IStorePropertyBag> .CreateContactsOnlyEnumerator(mailboxSession, DefaultFolderType.AllContacts, RemoveOrganizationalContacts.ContactPropertiesToEnumerate, (IStorePropertyBag propertyBag) => propertyBag, new XSOFactory());

            foreach (IStorePropertyBag storePropertyBag in contactsEnumerator)
            {
                VersionedId valueOrDefault = storePropertyBag.GetValueOrDefault <VersionedId>(ItemSchema.Id, null);
                base.PerformanceTracker.IncrementContactsRead();
                if (valueOrDefault != null && RemoveOrganizationalContacts.ShouldDeleteContact(storePropertyBag))
                {
                    try
                    {
                        mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                        {
                            valueOrDefault.ObjectId
                        });
                        base.PerformanceTracker.IncrementContactsUpdated();
                    }
                    catch (ObjectNotFoundException)
                    {
                        this.WriteWarning(base.GetErrorMessageObjectNotFound(valueOrDefault.ObjectId.ToBase64String(), typeof(Item).ToString(), mailboxSession.ToString()));
                    }
                }
            }
        }
Example #4
0
        private void DeleteNodes(Dictionary <VersionedId, NavigationNode> nodes, MailboxSession session)
        {
            List <StoreId> list  = new List <StoreId>(nodes.Count);
            List <StoreId> list2 = new List <StoreId>(nodes.Count);

            foreach (KeyValuePair <VersionedId, NavigationNode> keyValuePair in nodes)
            {
                if (keyValuePair.Value is NavigationNodeFolder)
                {
                    list.Add(keyValuePair.Key.ObjectId);
                }
                else if (keyValuePair.Value is NavigationNodeGroup)
                {
                    list2.Add(keyValuePair.Key.ObjectId);
                }
            }
            if (this.duplicateNodes != null && this.duplicateNodes.Count > 0)
            {
                foreach (KeyValuePair <VersionedId, NavigationNode> keyValuePair2 in this.duplicateNodes)
                {
                    if (keyValuePair2.Value is NavigationNodeFolder)
                    {
                        list.Add(keyValuePair2.Key.ObjectId);
                    }
                    else if (keyValuePair2.Value is NavigationNodeGroup)
                    {
                        list2.Add(keyValuePair2.Key.ObjectId);
                    }
                }
            }
            list.AddRange(list2);
            session.Delete(DeleteItemFlags.HardDelete, list.ToArray());
        }
Example #5
0
        private static SearchFolder CreateAndUpdateFilteredViewSearchFolder(MailboxSession mailboxSession, OwaSearchContext searchContext, StoreId searchFoldersRootId, SearchFolderCriteria searchFolderCriteria)
        {
            ExTraceGlobals.StorageTracer.TraceDebug <string, string>(0L, "[OwaFilterState::CreateAndUpdateFilteredViewSearchFolder] Create filtered view search folder for view filter: {0} search folder identity: {1} ", searchContext.ViewFilter.ToString(), searchContext.ClientSearchFolderIdentity);
            SearchFolder searchFolder = SearchFolder.Create(mailboxSession, searchFoldersRootId, searchContext.ClientSearchFolderIdentity, CreateMode.OpenIfExists);

            OwaFilterState.UpdateFilteredViewSearchFolder(mailboxSession, searchFolder, searchContext);
            searchContext.SearchFolderId = searchFolder.StoreObjectId;
            searchContext.IsSearchFailed = !OwaFilterState.ApplyOwaContinuousSearch(searchFolder, searchFolderCriteria, mailboxSession, searchContext);
            if (searchContext.IsSearchFailed)
            {
                ExTraceGlobals.StorageTracer.TraceError(0L, "[OwaFilterState::CreateAndUpdateFilteredViewSearchFolder] deleting searchContext.SearchFolderId: " + searchContext.SearchFolderId);
                searchContext.ViewFilterActions |= ViewFilterActions.DeleteInvalidSearchFolder;
                mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                {
                    searchContext.SearchFolderId
                });
                searchFolder.Dispose();
                searchFolder = null;
            }
            else if (OwaFilterState.LinkViewFolder(mailboxSession, searchContext.FolderIdToSearch, searchFolder, searchContext.ViewFilter))
            {
                searchContext.ViewFilterActions |= ViewFilterActions.LinkToSourceFolderSucceeded;
            }
            return(searchFolder);
        }
Example #6
0
        public static AggregateOperationResult DeleteOutlookSearchFolder(DeleteItemFlags deleteItemFlags, MailboxSession session, StoreId outlookSearchFolderId)
        {
            EnumValidator.ThrowIfInvalid <DeleteItemFlags>(deleteItemFlags);
            VersionedId versionedId;

            using (OutlookSearchFolder outlookSearchFolder = OutlookSearchFolder.Bind(session, outlookSearchFolderId))
            {
                versionedId = OutlookSearchFolder.FindAssociatedMessageId((MailboxSession)outlookSearchFolder.Session, (Guid)outlookSearchFolder[InternalSchema.OutlookSearchFolderClsId]);
            }
            StoreId[] ids;
            if (versionedId != null)
            {
                ids = new StoreId[]
                {
                    outlookSearchFolderId,
                    versionedId
                };
            }
            else
            {
                ids = new StoreId[]
                {
                    outlookSearchFolderId
                };
            }
            return(session.Delete(deleteItemFlags, ids));
        }
        // Token: 0x06000B07 RID: 2823 RVA: 0x00047AAC File Offset: 0x00045CAC
        private static void SafeDeleteItem(MailboxSession session, StoreId itemId)
        {
            Exception arg = null;

            try
            {
                session.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                {
                    itemId
                });
            }
            catch (StorageTransientException ex)
            {
                arg = ex;
            }
            catch (StoragePermanentException ex2)
            {
                arg = ex2;
            }
            catch (InvalidOperationException ex3)
            {
                arg = ex3;
            }
            UMPartnerMessageAssistant.Tracer.TraceWarning <StoreId, Exception>(0L, "UMPMA.SafeDelete({0}): Exception={1}", itemId, arg);
        }
Example #8
0
        private static TaskGroup CreateMyTasksGroup(MailboxSession session)
        {
            TaskGroup taskGroup  = TaskGroup.InternalCreateDefaultGroup(session);
            bool      flag       = TaskGroup.AddDefaultTaskFolder(session, taskGroup, DefaultFolderType.ToDoSearch, ClientStrings.ToDoSearch.ToString(session.InternalCulture));
            string    folderType = DefaultFolderType.ToDoSearch.ToString();

            if (flag)
            {
                flag       = TaskGroup.AddDefaultTaskFolder(session, taskGroup, DefaultFolderType.Tasks, ClientStrings.Tasks.ToString(session.InternalCulture));
                folderType = DefaultFolderType.Tasks.ToString();
            }
            if (!flag)
            {
                AggregateOperationResult aggregateOperationResult = session.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                {
                    taskGroup.Id
                });
                if (aggregateOperationResult.OperationResult != OperationResult.Succeeded)
                {
                    ExTraceGlobals.StorageTracer.TraceWarning <SmtpAddress>(0L, "Unable to delete default task group after failing to add the default task folder to it. User: {0}", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress);
                }
                throw new DefaultTaskNodeCreationException(folderType);
            }
            return(taskGroup);
        }
        // Token: 0x0600010F RID: 271 RVA: 0x00006A18 File Offset: 0x00004C18
        private static bool MergeDuplicateActionItems(MailboxSession session, ConversationActionItem actionItem, MailboxData mailboxData)
        {
            ActionsProcessor.Tracer.TraceDebug(0L, "{0}: Calling ActionsProcessor.MergeDuplicateActionItems", new object[]
            {
                TraceContext.Get()
            });
            ConversationId  conversationId = actionItem.ConversationId;
            int             totalActionItemCount;
            IList <StoreId> list = ConversationActionItem.QueryConversationActionsFolder(session, conversationId, 10, out totalActionItemCount);

            mailboxData.UpdateConversationActionsEnabledStatus(totalActionItemCount);
            if (list == null || list.Count <= 1)
            {
                ActionsProcessor.Tracer.TraceDebug <object, int>(0L, "{0}: No duplicates found.  Count = {1}", TraceContext.Get(), (list != null) ? list.Count : -1);
                return(false);
            }
            StoreId[] array  = new StoreId[list.Count - 1];
            bool      result = false;

            for (int i = 1; i < list.Count; i++)
            {
                if (list[i].Equals(actionItem.Id))
                {
                    result = true;
                }
                array[i - 1] = list[i];
            }
            ActionsProcessor.Tracer.TraceDebug <object, int>(0L, "{0}: Attempting to delete {1} duplicates...", TraceContext.Get(), array.Length);
            session.Delete(DeleteItemFlags.HardDelete, array);
            return(result);
        }
Example #10
0
        private static Folder CreateAndSaveFolder(MailboxSession mailboxSession, StoreObjectId containerId, CreateMode createMode, string displayName, string containerClass, Folder folderIn, ISyncLogger syncLogger = null)
        {
            if (syncLogger == null)
            {
                syncLogger = TracingLogger.Singleton;
            }
            Folder folder = null;
            bool   flag   = false;
            Folder result;

            try
            {
                if (folderIn == null)
                {
                    folder = Folder.Create(mailboxSession, containerId, StoreObjectType.Folder, displayName, createMode);
                    folder[SyncStateStorage.airsyncLockProp] = "0";
                }
                else
                {
                    folder = folderIn;
                }
                if (containerClass != null)
                {
                    folder[InternalSchema.ContainerClass] = containerClass;
                }
                StoreObjectId storeObjectId = null;
                if (!folder.IsNew)
                {
                    storeObjectId = folder.Id.ObjectId;
                }
                FolderSaveResult folderSaveResult = folder.Save();
                if (folderSaveResult.OperationResult != OperationResult.Succeeded)
                {
                    syncLogger.TraceDebug <string, FolderSaveResult>(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::CreateAndSaveFolder. Failed to create folder {0}, due to {1}.", displayName, folderSaveResult);
                    if (storeObjectId == null)
                    {
                        folder.Load(null);
                        storeObjectId = folder.StoreObjectId;
                    }
                    mailboxSession.Delete(DeleteItemFlags.SoftDelete, new StoreId[]
                    {
                        storeObjectId
                    });
                    throw folderSaveResult.ToException(ServerStrings.ExCannotCreateFolder(folderSaveResult));
                }
                folder.Load(SyncStateStorage.loggingEnabledAndCreateTimeAsArray);
                flag   = true;
                result = folder;
            }
            finally
            {
                if (!flag && folder != null)
                {
                    folder.Dispose();
                    folder = null;
                }
            }
            return(result);
        }
Example #11
0
        internal static bool RemoveElcFolder(bool userIsOnRetentionPolcyTags, MailboxSession mailboxSession, StoreId folderId, Dictionary <Guid, AdTagData> allAdTags, out UpgradeStatus status)
        {
            status = UpgradeStatus.None;
            Stack <ElcMailboxHelper.FolderNode> stack = new Stack <ElcMailboxHelper.FolderNode>(50);

            ElcMailboxHelper.FolderNode folderNode = new ElcMailboxHelper.FolderNode(folderId, null);
            stack.Push(folderNode);
            while (stack.Count > 0)
            {
                ElcMailboxHelper.FolderNode folderNode2 = stack.Peek();
                if (folderNode2.ChildCount == -1)
                {
                    using (Folder folder = Folder.Bind(mailboxSession, folderNode2.FolderId, ProvisionedFolderReader.ElcFolderProps))
                    {
                        folderNode2.ChildCount = folder.ItemCount + folder.SubfolderCount;
                        using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, null, null, ProvisionedFolderReader.ElcFolderProps))
                        {
                            for (;;)
                            {
                                object[][] rows = queryResult.GetRows(100);
                                if (rows.Length <= 0)
                                {
                                    break;
                                }
                                foreach (object[] array in rows)
                                {
                                    stack.Push(new ElcMailboxHelper.FolderNode((VersionedId)array[0], folderNode2));
                                }
                            }
                        }
                        if (ElcMailboxHelper.IsElcFolder(folder))
                        {
                            status |= ElcMailboxHelper.UpgradeElcFolder(userIsOnRetentionPolcyTags, mailboxSession, folder, allAdTags);
                            ProvisionedFolderCreator.SaveELCFolder(folder, false);
                        }
                        continue;
                    }
                }
                if (folderNode2.ChildCount == 0)
                {
                    if (folderNode2.Parent != null)
                    {
                        folderNode2.Parent.ChildCount--;
                    }
                    mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                    {
                        folderNode2.FolderId
                    });
                }
                stack.Pop();
            }
            return(folderNode.ChildCount == 0);
        }
 // Token: 0x06000CF8 RID: 3320 RVA: 0x00035B74 File Offset: 0x00033D74
 public void RemoveAll(string fileSetId, MailboxSession mailboxSession)
 {
     using (Folder folder = this.GetFolder(mailboxSession))
     {
         List <FileSetItem> allItems = this.GetAllItems(folder, fileSetId);
         if (allItems.Count > 0)
         {
             StoreId[] array = allItems.ConvertAll <StoreId>((FileSetItem fileSetItem) => fileSetItem.Id).ToArray();
             this.tracer.TraceDebug <string, string, ArrayTracer <StoreId> >((long)this.GetHashCode(), "Deleting items in folder '{0}' with fileSetId='{1}': {2}", this.folderName, fileSetId, new ArrayTracer <StoreId>(array));
             mailboxSession.Delete(DeleteItemFlags.HardDelete, array);
         }
     }
 }
 // Token: 0x06000CFD RID: 3325 RVA: 0x00035EC4 File Offset: 0x000340C4
 public void Upload(IEnumerable <string> sources, string fileSetId, MailboxSession mailboxSession, Action abortFileOperation)
 {
     using (Folder folder = this.GetFolder(mailboxSession))
     {
         List <FileSetItem> allItems = this.GetAllItems(folder, fileSetId);
         this.UploadInternal(sources, fileSetId, folder, mailboxSession, abortFileOperation);
         if (allItems.Count > 0)
         {
             StoreId[] array = allItems.ConvertAll <StoreId>((FileSetItem fileSetItem) => fileSetItem.Id).ToArray();
             this.tracer.TraceDebug <string, string, ArrayTracer <StoreId> >((long)this.GetHashCode(), "Deleting items in folder '{0}' with fileSetId='{1}' that are now outdated: {2}", this.folderName, fileSetId, new ArrayTracer <StoreId>(array));
             mailboxSession.Delete(DeleteItemFlags.HardDelete, array);
         }
     }
 }
Example #14
0
 private static void DeleteMessage(MessageItem message, MailboxSession mailboxSession, object traceObject)
 {
     message.Load();
     if (message.Id != null)
     {
         AggregateOperationResult aggregateOperationResult = mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
         {
             message.Id.ObjectId
         });
         if (OperationResult.Succeeded != aggregateOperationResult.OperationResult)
         {
             AirSyncDiagnostics.TraceDebug <MessageItem>(ExTraceGlobals.RequestsTracer, traceObject, "Failed to delete {0}", message);
         }
     }
 }
Example #15
0
        protected override bool InternalExecute()
        {
            ExchangeVersion.Current = ExchangeVersion.Latest;
            MailboxSession           mailboxIdentityMailboxSession = base.MailboxIdentityMailboxSession;
            IdAndSession             idAndSession             = base.IdConverter.ConvertFolderIdToIdAndSession(this.folderId, IdConverter.ConvertOption.IgnoreChangeKey);
            AggregateOperationResult aggregateOperationResult = mailboxIdentityMailboxSession.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
            {
                idAndSession.Id
            });

            if (aggregateOperationResult.OperationResult == OperationResult.Succeeded)
            {
                PeopleFilterGroupPriorityManager peopleFilterGroupPriorityManager = new PeopleFilterGroupPriorityManager(mailboxIdentityMailboxSession, new XSOFactory());
                mailboxIdentityMailboxSession.ContactFolders.MyContactFolders.Set(peopleFilterGroupPriorityManager.GetMyContactFolderIds());
                return(true);
            }
            return(false);
        }
Example #16
0
        public void Delete(MailboxSession itemStore)
        {
            List <object[]> results        = this.QueryItems(itemStore);
            VersionedId     mostRecentItem = this.GetMostRecentItem(results);

            if (mostRecentItem != null)
            {
                try
                {
                    itemStore.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                    {
                        mostRecentItem
                    });
                }
                catch (ObjectNotFoundException)
                {
                    SingleInstanceItemHandler.Tracer.TraceError <SingleInstanceItemHandler, VersionedId, IExchangePrincipal>((long)this.GetHashCode(), "{0}: ObjectNotFoundException encountred while trying to delete object, itemId='{1}' on mailbox {2}", this, mostRecentItem, itemStore.MailboxOwner);
                }
            }
        }
Example #17
0
 // Token: 0x06000944 RID: 2372 RVA: 0x00042AB4 File Offset: 0x00040CB4
 internal static void ClearSearchFolders(MailboxSession mailboxSession)
 {
     using (Folder folder = Utilities.SafeFolderBind(mailboxSession, DefaultFolderType.SearchFolders, new PropertyDefinition[0]))
     {
         if (folder != null)
         {
             TextFilter       textFilter       = new TextFilter(StoreObjectSchema.DisplayName, "OWA Search ", MatchOptions.Prefix, MatchFlags.Default);
             ComparisonFilter comparisonFilter = new ComparisonFilter(ComparisonOperator.LessThan, StoreObjectSchema.LastModifiedTime, DateTime.UtcNow.AddDays(-7.0));
             using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, new AndFilter(new QueryFilter[]
             {
                 comparisonFilter,
                 textFilter
             }), null, new PropertyDefinition[]
             {
                 FolderSchema.Id
             }))
             {
                 List <StoreId> list = new List <StoreId>();
                 for (;;)
                 {
                     object[][] rows = queryResult.GetRows(10000);
                     if (rows.Length <= 0)
                     {
                         break;
                     }
                     for (int i = 0; i < rows.Length; i++)
                     {
                         list.Add((StoreId)rows[i][0]);
                     }
                 }
                 if (list.Count > 0)
                 {
                     mailboxSession.Delete(DeleteItemFlags.HardDelete, list.ToArray());
                 }
             }
         }
     }
 }
Example #18
0
        public static bool DeleteSyncStateStorage(MailboxSession mailboxSession, DeviceIdentity deviceIdentity, ISyncLogger syncLogger = null)
        {
            if (syncLogger == null)
            {
                syncLogger = TracingLogger.Singleton;
            }
            ArgumentValidator.ThrowIfNull("mailboxSession", mailboxSession);
            syncLogger.Information <DeviceIdentity>(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. Need to delete folder {0}", deviceIdentity);
            SyncStateTypeFactory.GetInstance().RegisterInternalBuilders();
            UserSyncStateMetadata          userSyncStateMetadata = UserSyncStateMetadataCache.Singleton.Get(mailboxSession, syncLogger);
            List <DeviceSyncStateMetadata> allDevices            = userSyncStateMetadata.GetAllDevices(mailboxSession, false, syncLogger);
            bool result = false;

            if (allDevices != null)
            {
                foreach (DeviceSyncStateMetadata deviceSyncStateMetadata in allDevices)
                {
                    syncLogger.Information <DeviceIdentity>(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. Found syncstate folder {0}", deviceSyncStateMetadata.Id);
                    if (string.Compare(deviceSyncStateMetadata.Id.Protocol, deviceIdentity.Protocol, StringComparison.Ordinal) == 0)
                    {
                        if (deviceSyncStateMetadata.Id.Equals(deviceIdentity))
                        {
                            mailboxSession.Delete(DeleteItemFlags.SoftDelete, new StoreId[]
                            {
                                deviceSyncStateMetadata.DeviceFolderId
                            });
                            userSyncStateMetadata.TryRemove(deviceSyncStateMetadata.Id, syncLogger);
                        }
                        else
                        {
                            syncLogger.Information(ExTraceGlobals.SyncTracer, 0L, "SyncStateStorage::DeleteSyncStateStorage. found more devices with same protocol");
                            result = true;
                        }
                    }
                }
            }
            return(result);
        }
Example #19
0
        private DeletionResult DeleteMessageFromOutboxHelper(DeleteMapiMailDefinition deleteMapiMailDefinition)
        {
            DeletionResult    result = DeletionResult.Fail;
            string            domainPartOfEmailAddress = MapiMessageSubmitter.GetDomainPartOfEmailAddress(deleteMapiMailDefinition.SenderEmailAddress);
            ExchangePrincipal mailboxOwner             = ExchangePrincipal.FromProxyAddress(ADSessionSettings.RootOrgOrSingleTenantFromAcceptedDomainAutoDetect(domainPartOfEmailAddress), deleteMapiMailDefinition.SenderEmailAddress);
            QueryFilter       queryFilter = new AndFilter(new List <QueryFilter>(2)
            {
                new TextFilter(ItemSchema.InternetMessageId, deleteMapiMailDefinition.InternetMessageId, MatchOptions.FullString, MatchFlags.IgnoreCase),
                new TextFilter(StoreObjectSchema.ItemClass, deleteMapiMailDefinition.MessageClass, MatchOptions.FullString, MatchFlags.IgnoreCase)
            }.ToArray());

            using (MailboxSession mailboxSession = MailboxSession.OpenAsTransport(mailboxOwner, "Client=Monitoring;Action=MapiSubmitLAMProbe"))
            {
                using (Folder folder = Folder.Bind(mailboxSession, DefaultFolderType.Outbox))
                {
                    using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, queryFilter, null, new PropertyDefinition[]
                    {
                        ItemSchema.Id
                    }))
                    {
                        object[][] rows = queryResult.GetRows(1);
                        if (rows == null || rows.Length == 0)
                        {
                            result = DeletionResult.NoMatchingMessage;
                        }
                        else
                        {
                            mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                            {
                                ((VersionedId)rows[0][0]).ObjectId
                            });
                            result = DeletionResult.Success;
                        }
                    }
                }
            }
            return(result);
        }
 // Token: 0x060007B3 RID: 1971 RVA: 0x0003708C File Offset: 0x0003528C
 private void QueryAndDeleteMatchingItems(MailboxSession itemStore, MeetingMessage item, CalendarItemBase originalCalendarItem, byte[] itemGloblObjectId, string internetMessageId, string sentRepresenting, int itemSequenceNumber, ref OldMessageDeletion.LatestItemInfo latestInfo)
 {
     try
     {
         List <VersionedId> list = this.QueryMatchingItems(itemStore, item, itemGloblObjectId, sentRepresenting, itemSequenceNumber, ref latestInfo);
         if (item is MeetingRequest && itemSequenceNumber >= latestInfo.LatestSequenceNumber)
         {
             OldMessageDeletion.ApplyRollingHighlight((MeetingRequest)item, internetMessageId, originalCalendarItem, latestInfo);
         }
         if (list != null && list.Count != 0)
         {
             StoreId[] array = list.ToArray();
             OldMessageDeletion.Tracer.TraceDebug <object, ArrayTracer <StoreId> >((long)this.GetHashCode(), "{0}: Deleting message: {1}", TraceContext.Get(), new ArrayTracer <StoreId>(array));
             CalendarAssistant.TracerPfd.TracePfd <int, object, ArrayTracer <StoreId> >((long)this.GetHashCode(), "PFD IWC {0} {1}: Deleting message: {2}", 29847, TraceContext.Get(), new ArrayTracer <StoreId>(array));
             AggregateOperationResult aggregateOperationResult = itemStore.Delete(DeleteItemFlags.MoveToDeletedItems, array);
             OldMessageDeletion.Tracer.TraceDebug <object, OperationResult>((long)this.GetHashCode(), "{0}: Deleting items returned: {1}", TraceContext.Get(), aggregateOperationResult.OperationResult);
             CalendarAssistantPerformanceCounters.MeetingMessagesDeleted.IncrementBy((long)list.Count);
         }
     }
     catch (ObjectNotFoundException arg)
     {
         OldMessageDeletion.Tracer.TraceDebug <object, ObjectNotFoundException>((long)this.GetHashCode(), "{0}: Stopped OMD because we encountered an exception: {1}", TraceContext.Get(), arg);
     }
 }
Example #21
0
        // Token: 0x0600052E RID: 1326 RVA: 0x0001E8B4 File Offset: 0x0001CAB4
        protected override void ProcessCommand(MailboxSession mailboxSession, XmlDocument doc)
        {
            if (base.CollectionRequest.CollectionId == null)
            {
                base.Context.ProtocolLogger.SetValue(ProtocolLoggerData.Error, "InvalidURLParameters");
                throw new AirSyncPermanentException(HttpStatusCode.BadRequest, StatusCode.InvalidCombinationOfIDs, null, false);
            }
            mailboxSession.Delete(DeleteItemFlags.SoftDelete, new StoreObjectId[]
            {
                base.CollectionRequest.CollectionId
            });
            FolderIdMapping folderIdMapping = (FolderIdMapping)base.SyncState[CustomStateDatumType.IdMapping];

            folderIdMapping.Delete(new ISyncItemId[]
            {
                MailboxSyncItemId.CreateForNewItem(base.CollectionRequest.CollectionId)
            });
            XmlNode xmlNode  = doc.CreateElement("Response", "FolderHierarchy:");
            XmlNode xmlNode2 = doc.CreateElement("Status", "FolderHierarchy:");

            xmlNode2.InnerText = "1";
            doc.AppendChild(xmlNode);
            xmlNode.AppendChild(xmlNode2);
        }
Example #22
0
        // Token: 0x06000942 RID: 2370 RVA: 0x000424EC File Offset: 0x000406EC
        public Folder Execute(UserContext userContext, Folder folder, SearchScope searchScope, string searchString, bool newSearch, bool asyncSearch)
        {
            if (userContext == null)
            {
                throw new ArgumentNullException("userContext");
            }
            if (folder == null)
            {
                throw new ArgumentNullException("folder");
            }
            MailboxSession   mailboxSession   = (MailboxSession)folder.Session;
            QueryFilter      queryFilter      = SearchFilterGenerator.Execute(searchString, mailboxSession.Mailbox.IsContentIndexingEnabled, userContext.UserCulture, new PolicyTagMailboxProvider(userContext.MailboxSession), folder, searchScope, this.advancedQueryFilter);
            string           text             = (queryFilter == null) ? string.Empty : queryFilter.ToString();
            OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromStoreObject(folder);
            SearchFolder     searchFolder     = null;
            bool             flag             = false;
            Folder           result;

            try
            {
                if (userContext.SearchFolderId != null)
                {
                    if (!newSearch && userContext.LastSearchFolderId.Equals(owaStoreObjectId) && userContext.LastSearchQueryFilter.CompareTo(text) == 0 && userContext.LastSearchScope == searchScope)
                    {
                        try
                        {
                            searchFolder = SearchFolder.Bind(userContext.SearchFolderId.GetSession(userContext), userContext.SearchFolderId.StoreObjectId, FolderSearch.PrefetchProperties);
                        }
                        catch (ObjectNotFoundException)
                        {
                        }
                        if (searchFolder != null)
                        {
                            if (asyncSearch)
                            {
                                SearchPerformanceData searchPerformanceData = userContext.MapiNotificationManager.GetSearchPerformanceData(mailboxSession);
                                if (searchPerformanceData != null)
                                {
                                    searchPerformanceData.RefreshStart();
                                }
                                OwaContext.Current.SearchPerformanceData = searchPerformanceData;
                            }
                            flag = true;
                            return(searchFolder);
                        }
                    }
                    if (userContext.IsPushNotificationsEnabled)
                    {
                        userContext.MapiNotificationManager.CancelSearchNotifications(mailboxSession);
                        userContext.MapiNotificationManager.AddSearchFolderDeleteList(mailboxSession, userContext.SearchFolderId.StoreObjectId);
                    }
                    else
                    {
                        mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                        {
                            userContext.SearchFolderId.StoreObjectId
                        });
                    }
                    userContext.SearchFolderId = null;
                }
                using (Folder folder2 = Folder.Bind(mailboxSession, userContext.GetSearchFoldersId(mailboxSession).StoreObjectId))
                {
                    searchFolder = SearchFolder.Create(mailboxSession, folder2.Id.ObjectId, "OWA Search " + userContext.Key.UserContextId + " " + DateTime.UtcNow.ToString("o"), CreateMode.CreateNew);
                }
                searchFolder.Save();
                searchFolder.Load(FolderSearch.PrefetchProperties);
                userContext.SearchFolderId        = OwaStoreObjectId.CreateFromStoreObject(searchFolder);
                userContext.LastSearchFolderId    = owaStoreObjectId;
                userContext.LastSearchQueryFilter = text;
                userContext.LastSearchScope       = searchScope;
                if (queryFilter == null)
                {
                    flag   = true;
                    result = searchFolder;
                }
                else
                {
                    bool      flag2 = FolderSearch.FailNonContentIndexedSearch(folder, queryFilter);
                    bool      flag3;
                    StoreId[] folderScope;
                    if (searchScope == SearchScope.SelectedFolder || !mailboxSession.Mailbox.IsContentIndexingEnabled)
                    {
                        flag3       = false;
                        folderScope = new StoreId[]
                        {
                            folder.Id.ObjectId
                        };
                    }
                    else if (searchScope == SearchScope.SelectedAndSubfolders)
                    {
                        flag3       = true;
                        folderScope = new StoreId[]
                        {
                            folder.Id.ObjectId
                        };
                    }
                    else
                    {
                        if (searchScope != SearchScope.AllFoldersAndItems && searchScope != SearchScope.AllItemsInModule)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        flag3       = true;
                        folderScope = new StoreId[]
                        {
                            userContext.GetRootFolderId(mailboxSession)
                        };
                    }
                    if (searchScope != SearchScope.SelectedFolder)
                    {
                        if (!folder.Id.ObjectId.Equals(userContext.JunkEmailFolderId))
                        {
                            QueryFilter queryFilter2 = new ComparisonFilter(ComparisonOperator.NotEqual, StoreObjectSchema.ParentItemId, userContext.JunkEmailFolderId);
                            queryFilter = new AndFilter(new QueryFilter[]
                            {
                                queryFilter,
                                queryFilter2
                            });
                        }
                        StoreObjectId storeObjectId = userContext.GetDeletedItemsFolderId((MailboxSession)folder.Session).StoreObjectId;
                        if (!folder.Id.ObjectId.Equals(storeObjectId))
                        {
                            QueryFilter queryFilter3 = new ComparisonFilter(ComparisonOperator.NotEqual, StoreObjectSchema.ParentItemId, storeObjectId);
                            queryFilter = new AndFilter(new QueryFilter[]
                            {
                                queryFilter,
                                queryFilter3
                            });
                        }
                    }
                    ExTraceGlobals.MailDataTracer.TraceDebug((long)this.GetHashCode(), "Search\nFilter: {0}\nDeep Traversal: {1}\nFolder: {2}\nContent Indexing Enabled: {3}", new object[]
                    {
                        queryFilter,
                        flag3,
                        folder.Id,
                        mailboxSession.Mailbox.IsContentIndexingEnabled ? "Yes" : "No"
                    });
                    SearchFolderCriteria searchFolderCriteria = new SearchFolderCriteria(queryFilter, folderScope);
                    searchFolderCriteria.DeepTraversal               = flag3;
                    searchFolderCriteria.MaximumResultsCount         = new int?(1000);
                    searchFolderCriteria.FailNonContentIndexedSearch = flag2;
                    SearchPerformanceData searchPerformanceData;
                    if (!userContext.IsPushNotificationsEnabled || !asyncSearch)
                    {
                        searchPerformanceData = new SearchPerformanceData();
                        searchPerformanceData.StartSearch(searchString);
                        IAsyncResult asyncResult = searchFolder.BeginApplyOneTimeSearch(searchFolderCriteria, null, null);
                        Stopwatch    stopwatch   = Utilities.StartWatch();
                        bool         flag4       = asyncResult.AsyncWaitHandle.WaitOne(30000, false);
                        searchPerformanceData.Complete(!flag4, true);
                        if (flag4)
                        {
                            searchFolder.EndApplyOneTimeSearch(asyncResult);
                        }
                        else
                        {
                            ExTraceGlobals.MailTracer.TraceDebug((long)this.GetHashCode(), "FolderSearch.Execute. Search timed out.");
                            if (Globals.ArePerfCountersEnabled)
                            {
                                OwaSingleCounters.SearchesTimedOut.Increment();
                            }
                        }
                        Utilities.StopWatch(stopwatch, "FolderSearch.Execute (Wait for search to complete)");
                        if (Globals.ArePerfCountersEnabled)
                        {
                            PerformanceCounterManager.UpdateSearchTimePerformanceCounter(stopwatch.ElapsedMilliseconds);
                            OwaSingleCounters.TotalSearches.Increment();
                        }
                        searchFolder.Save();
                        searchFolder.Load(FolderSearch.PrefetchProperties);
                    }
                    else
                    {
                        userContext.MapiNotificationManager.InitSearchNotifications(mailboxSession, userContext.SearchFolderId.StoreObjectId, searchFolder, searchFolderCriteria, searchString);
                        searchPerformanceData = userContext.MapiNotificationManager.GetSearchPerformanceData(mailboxSession);
                    }
                    if (!flag2)
                    {
                        searchPerformanceData.SlowSearchEnabled();
                    }
                    OwaContext.Current.SearchPerformanceData = searchPerformanceData;
                    flag   = true;
                    result = searchFolder;
                }
            }
            finally
            {
                if (!flag && searchFolder != null)
                {
                    searchFolder.Dispose();
                }
            }
            return(result);
        }
        // Token: 0x060007AE RID: 1966 RVA: 0x00036C68 File Offset: 0x00034E68
        private void DeleteOldMessages(MailboxSession itemStore, MeetingMessage item, CalendarItemBase originalCalItem, out bool fullUpdateDeleted)
        {
            fullUpdateDeleted = false;
            string text = (string)Utils.SafeGetProperty(item, ItemSchema.InternetMessageId, "<null>");

            if (item is MeetingRequest || item is MeetingCancellation)
            {
                bool flag = (bool)Utils.SafeGetProperty(item, MeetingMessageSchema.HijackedMeeting, false);
                if (flag)
                {
                    CalendarAssistantLog.LogEntry(itemStore, "Message {0} has been hijacked, skipping deletion of old messages.", new object[]
                    {
                        text
                    });
                    return;
                }
            }
            int num = (int)Utils.SafeGetProperty(item, CalendarItemBaseSchema.AppointmentSequenceNumber, -1);

            if (num < 0)
            {
                OldMessageDeletion.Tracer.TraceError <object, string>((long)this.GetHashCode(), "{0}: Message does not have a sequence number, skipping {1}", TraceContext.Get(), text);
                CalendarAssistantLog.LogEntry(itemStore, "Message does not have a sequence number, skipping {0}", new object[]
                {
                    text
                });
                return;
            }
            if (OldMessageDeletion.ShouldIgnoreFolder(itemStore, item.ParentId))
            {
                return;
            }
            string text2 = (string)Utils.SafeGetProperty(item, MessageItemSchema.ReceivedRepresentingEmailAddress, string.Empty);
            string text3 = (string)Utils.SafeGetProperty(item, CalendarItemBaseSchema.OrganizerEmailAddress, string.Empty);

            byte[] array = (byte[])Utils.SafeGetProperty(item, CalendarItemBaseSchema.GlobalObjectId, null);
            if (array == null)
            {
                OldMessageDeletion.Tracer.TraceError <object, string>((long)this.GetHashCode(), "{0}: Message {1} does not have a globalObjectId, skipping the message.", TraceContext.Get(), text);
                CalendarAssistantLog.LogEntry(itemStore, "Message {0} does not have a globalObjectId, skipping the message.", new object[]
                {
                    text
                });
                return;
            }
            OldMessageDeletion.Tracer.TraceDebug <object, string, string>((long)item.GetHashCode(), "{0}: Received representing={1} sent representing={2}", TraceContext.Get(), text2, text3);
            CalendarAssistant.TracerPfd.TracePfd((long)item.GetHashCode(), "PFD IWC {0} {1}: Received representing={2} sent representing={3}", new object[]
            {
                22679,
                TraceContext.Get(),
                text2,
                text3
            });
            if (!itemStore.IsGroupMailbox() && string.Compare(text2, text3, true) == 0)
            {
                Participant participant = null;
                if (!OldMessageDeletion.IsSenderSame(item.Sender, itemStore, out participant))
                {
                    return;
                }
                AggregateOperationResult aggregateOperationResult = itemStore.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                {
                    item.Id
                });
                OldMessageDeletion.Tracer.TraceDebug <object, string, OperationResult>((long)this.GetHashCode(), "{0}: Moving the item {1} to the Deleted Items folder returned:{2}", TraceContext.Get(), text, aggregateOperationResult.OperationResult);
                return;
            }
            else
            {
                if (item.IsRepairUpdateMessage)
                {
                    RUMOldMessageDeletion.CleanUp(itemStore, item, originalCalItem, OldMessageDeletion.Tracer, out fullUpdateDeleted);
                    return;
                }
                OldMessageDeletion.LatestItemInfo latestItemInfo;
                latestItemInfo.FullUpdateDeleted      = fullUpdateDeleted;
                latestItemInfo.RollingHighlight       = (int)Utils.SafeGetProperty(item, CalendarItemBaseSchema.ChangeHighlight, 0);
                latestItemInfo.LatestOldStartTime     = ExDateTime.MinValue;
                latestItemInfo.LatestOldEndTime       = ExDateTime.MinValue;
                latestItemInfo.LatestOldLocationStr   = string.Empty;
                latestItemInfo.LatestSequenceNumber   = -1;
                latestItemInfo.LatestItemId           = item.Id;
                latestItemInfo.LatestClientSubmitTime = (ExDateTime)Utils.SafeGetProperty(item, ItemSchema.SentTime, ExDateTime.MinValue);
                this.QueryAndDeleteMatchingItems(itemStore, item, originalCalItem, array, text, text3, num, ref latestItemInfo);
                fullUpdateDeleted = latestItemInfo.FullUpdateDeleted;
                return;
            }
        }
        // Token: 0x060007AC RID: 1964 RVA: 0x00036880 File Offset: 0x00034A80
        public void PerformCleanUp(MailboxSession itemStore, StoreObject item, CalendarConfiguration mailboxConfig, CalendarItemBase originalCalItem, IEnumerable <VersionedId> duplicates)
        {
            bool flag = false;

            if (mailboxConfig.RemoveOldMeetingMessages && !(item is MeetingForwardNotification))
            {
                this.DeleteOldMessages(itemStore, (MeetingMessage)item, originalCalItem, out flag);
            }
            if (item is MeetingMessage)
            {
                bool           flag2          = false;
                MeetingMessage meetingMessage = (MeetingMessage)item;
                if (meetingMessage.IsRepairUpdateMessage)
                {
                    flag2 = (!flag || (!(meetingMessage is MeetingRequest) && !(meetingMessage is MeetingCancellation)));
                    if (flag2)
                    {
                        meetingMessage.MarkAsOutOfDate();
                        meetingMessage.IsRead = true;
                        try
                        {
                            int num = 3;
                            ConflictResolutionResult saveResults;
                            do
                            {
                                saveResults = meetingMessage.Save(SaveMode.ResolveConflicts);
                                meetingMessage.Load();
                                num--;
                            }while (num > 0 && !CalendarProcessing.CheckSaveResults(meetingMessage, saveResults, meetingMessage.InternetMessageId));
                        }
                        catch (ObjectNotFoundException arg)
                        {
                            flag2 = false;
                            OldMessageDeletion.Tracer.TraceWarning <object, ObjectNotFoundException>((long)this.GetHashCode(), "{0}: Tried to mark a RUM as Outdated, which does not exist anymore. Exception: {1}", TraceContext.Get(), arg);
                        }
                    }
                }
                if (!flag2 && item is MeetingForwardNotification)
                {
                    bool   flag3 = itemStore.IsGroupMailbox();
                    string text  = null;
                    flag2 = (mailboxConfig.RemoveForwardedMeetingNotifications || !meetingMessage.IsResponseRequested || flag3);
                    if (!flag2)
                    {
                        Participant participant = null;
                        flag2 = OldMessageDeletion.IsSenderSame(meetingMessage.From, itemStore, out participant);
                        if (participant != null)
                        {
                            text = participant.EmailAddress;
                        }
                    }
                    string text2;
                    if (flag2)
                    {
                        text2 = string.Format("Deleting MFN message as it was forwarded by the organizer. ParticipantFromEmail: {0}, Message From: {1},  From RoutingType: {2},  Mailbox owner : {3}, Mailboxconfig.RemoveMFN setting {4}, IsResponseRequested {5}, Subject: {6}, IsGroupMailbox: {7} ", new object[]
                        {
                            text ?? "unspecified",
                            meetingMessage.From,
                            (meetingMessage.From != null) ? meetingMessage.From.RoutingType : "unspecified",
                            itemStore.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString(),
                            mailboxConfig.RemoveForwardedMeetingNotifications,
                            meetingMessage.IsResponseRequested,
                            meetingMessage.Subject,
                            flag3
                        });
                    }
                    else
                    {
                        text2 = string.Format("Not deleting MFN message as it was forwarded by someone other than the organizer. ParticipantFromEmail {0}, Message From: {1}, From RoutingType: {2},  Mailbox owner : {3}, Mailboxconfig.RemoveMFN setting {4}, IsResponseRequested {5}, Subject: {6} ", new object[]
                        {
                            text ?? "unspecified",
                            meetingMessage.From,
                            (meetingMessage.From != null) ? meetingMessage.From.RoutingType : "unspecified",
                            itemStore.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString(),
                            mailboxConfig.RemoveForwardedMeetingNotifications,
                            meetingMessage.IsResponseRequested,
                            meetingMessage.Subject
                        });
                    }
                    OldMessageDeletion.Tracer.TraceDebug((long)this.GetHashCode(), text2);
                    MfnLog.LogEntry(itemStore, text2);
                }
                if (!flag2 && OldMessageDeletion.IsSelfForwardedEventAndAccepted(meetingMessage, itemStore, originalCalItem))
                {
                    flag2 = true;
                    OldMessageDeletion.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: Marked the meeting request for deletion as sent to self", new object[]
                    {
                        TraceContext.Get()
                    });
                }
                if (flag2)
                {
                    this.DeleteMessage(itemStore, item);
                }
            }
            if (duplicates != null)
            {
                foreach (VersionedId versionedId in duplicates)
                {
                    itemStore.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                    {
                        versionedId
                    });
                    OldMessageDeletion.Tracer.TraceDebug <object, VersionedId>((long)this.GetHashCode(), "{0}: Deleted a duplicate item ID: {1}.", TraceContext.Get(), versionedId);
                }
            }
        }
Example #25
0
        public static SearchFolder CreateOrOpenOwaFilteredViewSearchFolder(MailboxSession mailboxSession, OwaSearchContext searchContext, StoreId searchFoldersRootId, SearchFolderCriteria searchFolderCriteria, bool flushStaleFolders = true)
        {
            ExTraceGlobals.StorageTracer.TraceDebug <OwaViewFilter>(0L, "[OwaFilterState::CreateOrOpenOwaFilteredViewSearchFolder] Create or open the specified filtered view: {0}", searchContext.ViewFilter);
            SearchFolder searchFolder = null;
            bool         flag         = true;

            searchContext.ViewFilterActions = ViewFilterActions.None;
            try
            {
                searchContext.ClientSearchFolderIdentity = OwaFilterState.GetOwaFilteredViewSearchFolderName(mailboxSession, searchContext);
                if (searchContext.SearchFolderId == null && OwaFilterState.FilterToLinkPropertyDefinitionsMap.ContainsKey(searchContext.ViewFilter))
                {
                    StoreObjectId defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox);
                    if (defaultFolderId.Equals(searchContext.FolderIdToSearch))
                    {
                        searchContext.SearchFolderId = OwaFilterState.GetLinkedFolderIdForFilteredView(mailboxSession, searchContext.FolderIdToSearch, searchContext.ViewFilter);
                    }
                }
                if (searchContext.SearchFolderId != null)
                {
                    searchContext.ViewFilterActions |= ViewFilterActions.BindToExisting;
                    searchFolder = OwaFilterState.BindAndUpdateExistingFilteredViewSearchFolder(mailboxSession, searchContext);
                }
                if (searchFolder == null)
                {
                    searchContext.ViewFilterActions |= ViewFilterActions.FindExisting;
                    searchFolder = OwaFilterState.GetFilteredView(mailboxSession, searchContext, searchFoldersRootId, flushStaleFolders);
                }
                if (searchContext.IsSearchFailed && searchFolder != null)
                {
                    ExTraceGlobals.StorageTracer.TraceError <string, StoreId>(0L, "[OwaFilterState::CreateOrOpenOwaFilteredViewSearchFolder] deleting search folder: {0} using searchContext.SearchFolderId: {1}", searchContext.ClientSearchFolderIdentity, searchContext.SearchFolderId);
                    searchContext.ViewFilterActions |= ViewFilterActions.DeleteInvalidSearchFolder;
                    mailboxSession.Delete(DeleteItemFlags.HardDelete, new StoreId[]
                    {
                        searchContext.SearchFolderId
                    });
                    searchContext.SearchFolderId = null;
                    searchContext.IsSearchFailed = false;
                    searchFolder.Dispose();
                    searchFolder = null;
                }
                if (searchFolder == null)
                {
                    searchContext.ViewFilterActions |= ViewFilterActions.CreateFilter;
                    searchFolder = OwaFilterState.CreateAndUpdateFilteredViewSearchFolder(mailboxSession, searchContext, searchFoldersRootId, searchFolderCriteria);
                }
                ExTraceGlobals.StorageTracer.TraceDebug(0L, string.Format("{0}_{1}", searchContext.ClientSearchFolderIdentity, (int)searchContext.ViewFilterActions));
                flag = false;
            }
            finally
            {
                if (flag)
                {
                    ExTraceGlobals.StorageTracer.TraceError(0L, "[OwaFilterState::CreateOrOpenOwaFilteredViewSearchFolder] Creating/Opening of dynamic search folder failed. Setting search folder to null and disposing it");
                    if (searchFolder != null)
                    {
                        searchFolder.Dispose();
                        searchFolder = null;
                    }
                }
            }
            return(searchFolder);
        }
Example #26
0
        private static SearchFolder GetFilteredView(MailboxSession mailboxSession, OwaSearchContext searchContext, StoreId searchFoldersRootId, bool flushStaleFolders)
        {
            ExTraceGlobals.StorageTracer.TraceDebug <OwaViewFilter>(0L, "[OwaFilterState::GetFilteredView] Get the specified filtered view: {0}", searchContext.ViewFilter);
            StoreObjectId  defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox);
            OwaFilterState newFilterState  = new OwaFilterState(searchContext.FolderIdToSearch, searchContext.ViewFilter, searchContext.FromFilter);
            int            num             = 0;
            StoreObjectId  storeObjectId   = null;
            List <StoreId> list            = new List <StoreId>();
            SearchFolder   result          = null;

            using (Folder folder = Folder.Bind(mailboxSession, searchFoldersRootId))
            {
                List <object[]> list2 = new List <object[]>();
                using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, null, null, OwaFilterState.FolderQueryProperties))
                {
                    list2 = OwaFilterState.FetchRowsFromQueryResult(queryResult, 10000);
                }
                int        num2  = OwaFilterState.FilterSearchFolderPropertyIndexes[FolderSchema.Id];
                int        num3  = OwaFilterState.FilterSearchFolderPropertyIndexes[FolderSchema.SearchFolderAllowAgeout];
                int        num4  = OwaFilterState.FilterSearchFolderPropertyIndexes[StoreObjectSchema.LastModifiedTime];
                int        num5  = OwaFilterState.FilterSearchFolderPropertyIndexes[OwaFilteredViewProperties.FilteredViewLabel];
                ExDateTime other = ExDateTime.MaxValue;
                for (int i = 0; i < list2.Count; i++)
                {
                    OwaFilterState owaFilterState = OwaFilterState.ParseFromPropertyValue(list2[i][num5]);
                    if (owaFilterState != null)
                    {
                        if (OwaFilterState.AreEqual(newFilterState, owaFilterState))
                        {
                            searchContext.ViewFilterActions |= ViewFilterActions.FilterFound;
                            searchContext.SearchFolderId     = (list2[i][num2] as VersionedId).ObjectId;
                            result = OwaFilterState.BindAndUpdateExistingFilteredViewSearchFolder(mailboxSession, searchContext);
                            break;
                        }
                        if (list2[i][num3] is bool && (bool)list2[i][num3])
                        {
                            if (!owaFilterState.IsCurrentVersion && flushStaleFolders)
                            {
                                list.Add((StoreId)list2[i][num2]);
                            }
                            else
                            {
                                num++;
                                ExDateTime exDateTime = ExDateTime.MinValue;
                                if (!(list2[i][num4] is PropertyError))
                                {
                                    exDateTime = (ExDateTime)list2[i][num4];
                                }
                                if (exDateTime.CompareTo(other) < 0)
                                {
                                    StoreObjectId objectId = (list2[i][num2] as VersionedId).ObjectId;
                                    if (!defaultFolderId.Equals(owaFilterState.SourceFolderId))
                                    {
                                        other         = exDateTime;
                                        storeObjectId = objectId;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (num >= searchContext.MaximumTemporaryFilteredViewPerUser && flushStaleFolders && storeObjectId != null)
            {
                ExTraceGlobals.StorageTracer.TraceDebug <int>(0L, "[OwaFilterState::GetFilteredView] Delete LRU filtered view search folder at hitting max filtered views: {0}", searchContext.MaximumTemporaryFilteredViewPerUser);
                list.Add(storeObjectId);
            }
            if (list.Count > 0)
            {
                ExTraceGlobals.StorageTracer.TraceDebug(0L, "[OwaFilterState::GetFilteredView] deleting LRU / non current version of filtered views count: " + list.Count);
                mailboxSession.Delete(DeleteItemFlags.HardDelete, list.ToArray());
            }
            return(result);
        }
Example #27
0
        // Token: 0x06000B71 RID: 2929 RVA: 0x00049A1C File Offset: 0x00047C1C
        protected override void HandleEventInternal(MapiEvent mapiEvent, MailboxSession itemStore, StoreObject item, List <KeyValuePair <string, object> > customDataToLog)
        {
            ResourceBookingAssistantLogEntry resourceBookingAssistantLogEntry = new ResourceBookingAssistantLogEntry
            {
                MapiEventFlag = mapiEvent.EventMask.ToString(),
                MailboxGuid   = itemStore.MailboxGuid,
                TenantGuid    = itemStore.MailboxOwner.MailboxInfo.OrganizationId.GetTenantGuid(),
                DatabaseGuid  = itemStore.MailboxOwner.MailboxInfo.GetDatabaseGuid()
            };

            try
            {
                string text = (item != null) ? item.ClassName : mapiEvent.ObjectClass;
                resourceBookingAssistantLogEntry.ObjectClass = text;
                if (itemStore.GetDefaultFolderId(DefaultFolderType.Calendar) == null)
                {
                    ResourceBookingAssistant.Tracer.TraceDebug <object, Guid>((long)this.GetHashCode(), "{0}: Mailbox: {1} - Calendar folder does not exist. Skipping processing.", TraceContext.Get(), mapiEvent.MailboxGuid);
                    resourceBookingAssistantLogEntry.IsCalendarFolderNotAvailable = true;
                }
                else
                {
                    CachedState cachedState = AssistantsService.CachedObjectsList.GetCachedState(mapiEvent.MailboxGuid);
                    bool        flag        = ResourceCheck.DetailedCheckForAutomatedBooking(mapiEvent, itemStore, item, cachedState);
                    resourceBookingAssistantLogEntry.IsAutomatedBooking = flag;
                    if (flag)
                    {
                        if (item == null)
                        {
                            ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: HandleEvent was passed a null item.", new object[]
                            {
                                TraceContext.Get()
                            });
                        }
                        else
                        {
                            ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: Automatic Booking is on.", new object[]
                            {
                                TraceContext.Get()
                            });
                            if (item is MeetingMessage)
                            {
                                MeetingMessage meetingMessage = item as MeetingMessage;
                                resourceBookingAssistantLogEntry.MeetingSender            = meetingMessage.Sender.EmailAddress;
                                resourceBookingAssistantLogEntry.MeetingInternetMessageId = meetingMessage.InternetMessageId;
                                if (meetingMessage.IsDelegated())
                                {
                                    ResourceBookingAssistant.Tracer.TraceDebug <object, string>((long)this.GetHashCode(), "{0}: Deleting delegated meeting message: ID={1}", TraceContext.Get(), item.Id.ToString());
                                    itemStore.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                                    {
                                        meetingMessage.Id
                                    });
                                    RbaLog.LogEntry(itemStore, meetingMessage, EvaluationResults.Delete);
                                    resourceBookingAssistantLogEntry.IsDelegatedMeetingRequest = true;
                                    return;
                                }
                            }
                            cachedState.LockForRead();
                            CalendarConfiguration calendarConfiguration;
                            try
                            {
                                calendarConfiguration = (cachedState.State[0] as CalendarConfiguration);
                            }
                            finally
                            {
                                cachedState.ReleaseReaderLock();
                            }
                            bool flag2 = false;
                            try
                            {
                                if (item is MeetingRequest)
                                {
                                    flag2 = (item as MeetingRequest).IsOrganizer();
                                }
                                else if (item is MeetingCancellation)
                                {
                                    flag2 = (item as MeetingCancellation).IsOrganizer();
                                }
                            }
                            catch (ObjectNotFoundException innerException)
                            {
                                ResourceBookingAssistant.Tracer.TraceDebug <object, string>((long)this.GetHashCode(), "{0}: Object Not Found. ID={1}", TraceContext.Get(), item.Id.ToString());
                                throw new TransientMailboxException(innerException);
                            }
                            resourceBookingAssistantLogEntry.IsOrganizer = flag2;
                            if (!ObjectClass.IsOfClass(text, "IPM.Schedule.Meeting") || flag2)
                            {
                                if (calendarConfiguration.DeleteNonCalendarItems && (mapiEvent.EventMask & MapiEventTypeFlags.NewMail) != (MapiEventTypeFlags)0)
                                {
                                    ResourceBookingAssistant.Tracer.TraceError((long)this.GetHashCode(), "{0}: Deleting a non-meeting message", new object[]
                                    {
                                        TraceContext.Get()
                                    });
                                    if (item is MessageItem)
                                    {
                                        RbaLog.LogEntry(itemStore, item as MessageItem, EvaluationResults.Delete);
                                    }
                                    itemStore.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                                    {
                                        item.Id
                                    });
                                    resourceBookingAssistantLogEntry.DeleteNonMeetingMessage = true;
                                }
                            }
                            else
                            {
                                ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: Message is the right class", new object[]
                                {
                                    TraceContext.Get()
                                });
                                if (!(item is MeetingMessage))
                                {
                                    ResourceBookingAssistant.Tracer.TraceError((long)this.GetHashCode(), "{0}: Unexpected: Message class matched, but is not the correct object type. Ignoring message.", new object[]
                                    {
                                        TraceContext.Get()
                                    });
                                }
                                else
                                {
                                    ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: Message is MeetingMessage", new object[]
                                    {
                                        TraceContext.Get()
                                    });
                                    resourceBookingAssistantLogEntry.IsMeetingMessage = true;
                                    MeetingMessage   meetingMessage   = item as MeetingMessage;
                                    CalendarItemBase calendarItemBase = null;
                                    DateTime         utcNow           = DateTime.UtcNow;
                                    resourceBookingAssistantLogEntry.StartProcessingTime = utcNow;
                                    for (int i = 0; i < 2; i++)
                                    {
                                        IEnumerable <VersionedId> duplicates;
                                        Exception ex;
                                        bool      calendarItem = CalendarAssistant.GetCalendarItem(meetingMessage, ResourceBookingAssistant.Tracer, ref calendarItemBase, false, out duplicates, out ex);
                                        resourceBookingAssistantLogEntry.AddExceptionToLog(ex);
                                        if (!calendarItem)
                                        {
                                            break;
                                        }
                                        if (calendarItemBase == null)
                                        {
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, VersionedId>((long)this.GetHashCode(), "{0}: Original CalendarItem for message {1} is null", TraceContext.Get(), meetingMessage.Id);
                                        }
                                        StoreObjectValidationError[] array = meetingMessage.Validate();
                                        if (array != null && array.Length > 0)
                                        {
                                            ResourceBookingAssistant.Tracer.TraceError <object, StoreObjectValidationError>((long)this.GetHashCode(), "{0}: mtgMessage did not validate, {1}", TraceContext.Get(), array[0]);
                                            resourceBookingAssistantLogEntry.IsMeetingMessageInvalid = true;
                                            throw new SkipException(Strings.descSkipExceptionFailedValidateCalItem);
                                        }
                                        string text2 = string.Empty;
                                        try
                                        {
                                            this.calProcessor.ProcessMeetingMessage(itemStore, meetingMessage, ref calendarItemBase, calendarConfiguration, duplicates, false);
                                            text2 = meetingMessage.Id.ToString();
                                            resourceBookingAssistantLogEntry.IsMeetingMessageProcessed = true;
                                            resourceBookingAssistantLogEntry.MeetingMessageId          = text2;
                                            bool flag3 = false;
                                            if (meetingMessage is MeetingRequest)
                                            {
                                                flag3 = (meetingMessage as MeetingRequest).IsOrganizer();
                                            }
                                            else if (meetingMessage is MeetingCancellation)
                                            {
                                                flag3 = (meetingMessage as MeetingCancellation).IsOrganizer();
                                            }
                                            else if (meetingMessage is MeetingResponse)
                                            {
                                                flag3 = true;
                                            }
                                            resourceBookingAssistantLogEntry.IsOrganizer = flag3;
                                            resourceBookingAssistantLogEntry.IsDelegatedMeetingRequest = meetingMessage.IsDelegated();
                                            if (calendarItemBase == null)
                                            {
                                                if (flag3)
                                                {
                                                    RbaLog.LogEntry(itemStore, meetingMessage, EvaluationResults.IgnoreOrganizer);
                                                }
                                                else if (resourceBookingAssistantLogEntry.IsDelegatedMeetingRequest)
                                                {
                                                    RbaLog.LogEntry(itemStore, meetingMessage, EvaluationResults.IgnoreDelegate);
                                                }
                                            }
                                            if (calendarItemBase == null && meetingMessage is MeetingCancellation)
                                            {
                                                ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: Deleting a meeting cancellation without correlated calendar item found", new object[]
                                                {
                                                    TraceContext.Get()
                                                });
                                                itemStore.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                                                {
                                                    meetingMessage.Id
                                                });
                                                RbaLog.LogEntry(itemStore, meetingMessage, EvaluationResults.Delete);
                                                resourceBookingAssistantLogEntry.DeleteCanceledMeeting = true;
                                            }
                                            if (calendarItemBase != null)
                                            {
                                                StoreObjectValidationError[] array2 = calendarItemBase.Validate();
                                                if (array2 != null && array2.Length > 0)
                                                {
                                                    ResourceBookingAssistant.Tracer.TraceError <object, StoreObjectValidationError>((long)this.GetHashCode(), "{0}: calendar item did not validate, {1}", TraceContext.Get(), array2[0]);
                                                    throw new SkipException(Strings.descSkipExceptionFailedValidateCalItem);
                                                }
                                                ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: About to process request", new object[]
                                                {
                                                    TraceContext.Get()
                                                });
                                                EvaluationResults evaluationResults = EvaluationResults.None;
                                                BookingRoles      bookingRoles      = BookingRoles.NoRole;
                                                ResourceBookingProcessing.ProcessRequest(mapiEvent, itemStore, meetingMessage, ref calendarItemBase, calendarConfiguration, out evaluationResults, out bookingRoles);
                                                resourceBookingAssistantLogEntry.IsResourceBookingRequestProcessed = true;
                                                resourceBookingAssistantLogEntry.EvaluationResult = evaluationResults.ToString();
                                                resourceBookingAssistantLogEntry.BookingRole      = bookingRoles.ToString();
                                            }
                                            break;
                                        }
                                        catch (CorruptDataException ex2)
                                        {
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, string, CorruptDataException>((long)this.GetHashCode(), "{0}: The calendar item found was corrupted, so we could not do Resource Booking processing for message ID={1}, skipping event. Exception={2}", TraceContext.Get(), text2, ex2);
                                            throw new SkipException(ex2);
                                        }
                                        catch (ADTransientException arg)
                                        {
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, string, ADTransientException>((long)this.GetHashCode(), "{0}: There was an tranisent AD error processing the calendar item during Resource Booking processing for message ID={1}, cleaning things up and retrying. Exception={2}", TraceContext.Get(), text2, arg);
                                            throw;
                                        }
                                        catch (ObjectNotFoundException innerException2)
                                        {
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, string>((long)this.GetHashCode(), "{0}: Object Not Found. ID={1}", TraceContext.Get(), text2);
                                            throw new TransientMailboxException(innerException2);
                                        }
                                        catch (SaveConflictException ex3)
                                        {
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, string, SaveConflictException>((long)this.GetHashCode(), "{0}: There was an error saving the calendar item during Resource Booking processing for message ID={1}, cleaning things up and retrying.Exception={2}", TraceContext.Get(), text2, ex3);
                                            resourceBookingAssistantLogEntry.AddExceptionToLog(ex3);
                                        }
                                        catch (OccurrenceCrossingBoundaryException ex4)
                                        {
                                            resourceBookingAssistantLogEntry.AddExceptionToLog(ex4);
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, string>((long)this.GetHashCode(), "{0}: Found an overlapping occurrence while processing message ID={1}. Cleaning things up and retrying", TraceContext.Get(), text2);
                                            if (ex4.OccurrenceInfo == null)
                                            {
                                                ResourceBookingAssistant.Tracer.TraceError((long)this.GetHashCode(), "{0}: Unexpected: Handling OccurrenceCrossingBoundaryException, the OccurrenceInfo is null", new object[]
                                                {
                                                    TraceContext.Get()
                                                });
                                                break;
                                            }
                                            VersionedId versionedId = ex4.OccurrenceInfo.VersionedId;
                                            AggregateOperationResult aggregateOperationResult = meetingMessage.Session.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                                            {
                                                versionedId
                                            });
                                            ResourceBookingAssistant.Tracer.TraceDebug <object, OperationResult>((long)this.GetHashCode(), "{0}: Deleting the occurrence when handling an OccurrenceCrossingBoundaryException, returned:{2}", TraceContext.Get(), aggregateOperationResult.OperationResult);
                                        }
                                        finally
                                        {
                                            ResourceBookingAssistant.Tracer.TraceDebug((long)this.GetHashCode(), "{0}: In finally block.", new object[]
                                            {
                                                TraceContext.Get()
                                            });
                                            if (calendarItemBase != null)
                                            {
                                                calendarItemBase.Dispose();
                                                calendarItemBase = null;
                                            }
                                            DateTime utcNow2  = DateTime.UtcNow;
                                            TimeSpan timeSpan = utcNow2.Subtract(utcNow);
                                            ResourceBookingPerfmon.AverageResourceBookingProcessingTime.IncrementBy((long)timeSpan.TotalMilliseconds);
                                            ResourceBookingPerfmon.AverageResourceBookingProcessingTimeBase.Increment();
                                            resourceBookingAssistantLogEntry.StartProcessingTime = utcNow;
                                            resourceBookingAssistantLogEntry.StopProcessingTime  = utcNow2;
                                            ResourceBookingAssistant.TracerPfd.TracePfd <int, object, string>((long)this.GetHashCode(), "PFD IWR {0} {1}: Finished processing message. MeetingMessageID = {2}", 20247, TraceContext.Get(), text2);
                                        }
                                        i++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex5)
            {
                resourceBookingAssistantLogEntry.AddExceptionToLog(ex5);
                throw ex5;
            }
            finally
            {
                customDataToLog.AddRange(resourceBookingAssistantLogEntry.FormatCustomData());
            }
        }
Example #28
0
        public void Remove()
        {
            base.ThrowIfCannotActAsOwner();
            StoreObjectId nodeId = (StoreObjectId)base.GetParameter("srcNId");
            NavigationNodeGroupSection navigationNodeGroupSection = (NavigationNodeGroupSection)base.GetParameter("GS");
            NavigationNodeCollection   navigationNodeCollection   = NavigationNodeCollection.TryCreateNavigationNodeCollection(base.UserContext, base.UserContext.MailboxSession, navigationNodeGroupSection);
            List <OwaStoreObjectId>    list           = new List <OwaStoreObjectId>();
            NavigationNode             navigationNode = navigationNodeCollection.FindNavigationNodeByNodeId(nodeId);

            if (navigationNode == null)
            {
                base.RenderPartialFailure(-289549140, OwaEventHandlerErrorCode.NotSet);
            }
            else
            {
                OperationResult operationResult = (OperationResult)0;
                if (navigationNodeGroupSection != NavigationNodeGroupSection.First)
                {
                    List <NavigationNodeFolder> list2 = new List <NavigationNodeFolder>();
                    if (navigationNode is NavigationNodeFolder)
                    {
                        list2.Add(navigationNode as NavigationNodeFolder);
                    }
                    else if (navigationNode is NavigationNodeGroup)
                    {
                        NavigationNodeGroup navigationNodeGroup = navigationNode as NavigationNodeGroup;
                        foreach (NavigationNodeFolder item in navigationNodeGroup.Children)
                        {
                            list2.Add(item);
                        }
                    }
                    foreach (NavigationNodeFolder navigationNodeFolder in list2)
                    {
                        if (navigationNodeFolder.IsValid)
                        {
                            OwaStoreObjectId owaStoreObjectId = OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder);
                            MailboxSession   mailboxSession   = owaStoreObjectId.IsArchive ? ((MailboxSession)owaStoreObjectId.GetSession(base.UserContext)) : base.UserContext.MailboxSession;
                            if (navigationNodeFolder.IsFolderInSpecificMailboxSession(mailboxSession))
                            {
                                if (Utilities.IsSpecialFolderForSession(mailboxSession, navigationNodeFolder.FolderId))
                                {
                                    throw new OwaEventHandlerException("Cannot delete default folders.", LocalizedStrings.GetNonEncoded(-1164567320), true);
                                }
                                if (operationResult == (OperationResult)0)
                                {
                                    operationResult = OperationResult.Succeeded;
                                }
                                AggregateOperationResult aggregateOperationResult = mailboxSession.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                                {
                                    navigationNodeFolder.FolderId
                                });
                                if (aggregateOperationResult.OperationResult == OperationResult.Succeeded)
                                {
                                    list.Add(OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder));
                                }
                                else
                                {
                                    operationResult = OperationResult.PartiallySucceeded;
                                }
                            }
                        }
                    }
                    if (operationResult != (OperationResult)0 && list.Count == 0)
                    {
                        operationResult = OperationResult.Failed;
                    }
                    if (operationResult == OperationResult.Failed)
                    {
                        base.RenderPartialFailure(1041829989, OwaEventHandlerErrorCode.NotSet);
                    }
                    else if (operationResult == OperationResult.PartiallySucceeded)
                    {
                        base.RenderPartialFailure(995407892, OwaEventHandlerErrorCode.NotSet);
                    }
                }
                else
                {
                    NavigationNodeFolder navigationNodeFolder2 = navigationNode as NavigationNodeFolder;
                    if (navigationNodeFolder2 != null && navigationNodeFolder2.IsFilteredView)
                    {
                        OwaStoreObjectId owaStoreObjectId2 = OwaStoreObjectId.CreateFromNavigationNodeFolder(base.UserContext, navigationNodeFolder2);
                        using (SearchFolder searchFolder = SearchFolder.Bind(owaStoreObjectId2.GetSession(base.UserContext), owaStoreObjectId2.StoreObjectId, FolderList.FolderTreeQueryProperties))
                        {
                            searchFolder[FolderSchema.SearchFolderAllowAgeout] = true;
                            searchFolder.DisplayName = Utilities.GetRandomNameForTempFilteredView(base.UserContext);
                            searchFolder.Save();
                        }
                    }
                }
                if (operationResult == (OperationResult)0 || operationResult == OperationResult.Succeeded)
                {
                    if (navigationNodeCollection.RemoveFolderOrGroupByNodeId(nodeId) != null)
                    {
                        navigationNodeCollection.Save(base.UserContext.MailboxSession);
                    }
                }
                else if (operationResult == OperationResult.PartiallySucceeded)
                {
                    foreach (OwaStoreObjectId owaStoreObjectId3 in list)
                    {
                        navigationNodeCollection.RemoveFolderByLegacyDNandId(owaStoreObjectId3.MailboxOwnerLegacyDN ?? base.UserContext.MailboxOwnerLegacyDN, owaStoreObjectId3.StoreObjectId);
                    }
                    navigationNodeCollection.Save(base.UserContext.MailboxSession);
                }
            }
            NavigationTreeDirtyFlag navigationTreeDirtyFlag = NavigationTreeDirtyFlag.None;

            if (navigationNodeGroupSection == NavigationNodeGroupSection.First)
            {
                navigationTreeDirtyFlag = NavigationTreeDirtyFlag.Favorites;
            }
            else
            {
                if (list.Count > 0)
                {
                    List <FolderTreeNode> list3 = FolderTreeNode.CreateDeletedNodesWithDirtyCheck(base.UserContext, list, out navigationTreeDirtyFlag);
                    this.Writer.Write("<div id=tn>");
                    foreach (FolderTreeNode folderTreeNode in list3)
                    {
                        folderTreeNode.RenderUndecoratedNode(this.Writer);
                    }
                    this.Writer.Write("</div>");
                }
                switch (navigationNodeGroupSection)
                {
                case NavigationNodeGroupSection.Calendar:
                    navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Calendar;
                    break;

                case NavigationNodeGroupSection.Contacts:
                    navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Contact;
                    break;

                case NavigationNodeGroupSection.Tasks:
                    navigationTreeDirtyFlag |= NavigationTreeDirtyFlag.Task;
                    break;
                }
            }
            RenderingUtilities.RenderNavigationTreeDirtyFlag(this.Writer, base.UserContext, navigationTreeDirtyFlag, (NavigationModule[])base.GetParameter("cms"));
        }
Example #29
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);
        }
Example #30
0
        private static ApprovalRequestUpdater.Result FindAndUpdateExistingApprovalRequest(MessageItem updateMessage, int decision, string decisionMaker, ExDateTime decisionTime, string messageId)
        {
            bool   updated = false;
            string local;
            string domain;

            if (!FindMessageUtils.TryParseMessageId(messageId, out local, out domain))
            {
                return(ApprovalRequestUpdater.Result.InvalidUpdateMessage);
            }
            ApprovalRequestUpdater.diag.TraceDebug <string>(0L, "Update approval request: messageid={0}", messageId);
            MessageStatus messageStatus = StorageExceptionHandler.RunUnderExceptionHandler(ApprovalRequestUpdater.MessageConverterInstance, delegate
            {
                MailboxSession mailboxSession = (MailboxSession)updateMessage.Session;
                StoreObjectId storeObjectId   = null;
                for (int i = 0; i < 25; i++)
                {
                    string internetMessageId  = ApprovalRequestWriter.FormatApprovalRequestMessageId(local, i, domain, false);
                    IStorePropertyBag[] array = AllItemsFolderHelper.FindItemsFromInternetId(mailboxSession, internetMessageId, new PropertyDefinition[]
                    {
                        ItemSchema.Id
                    });
                    if (array != null && array.Length > 0)
                    {
                        ApprovalRequestUpdater.diag.TraceDebug <int>(0L, "Found {0} to update, picking the first.", array.Length);
                        storeObjectId = ((VersionedId)array[0][ItemSchema.Id]).ObjectId;
                        break;
                    }
                }
                if (storeObjectId != null)
                {
                    using (MessageItem messageItem = MessageItem.Bind(mailboxSession, storeObjectId))
                    {
                        if (ApprovalRequestUpdater.VerifyAndUpdateApprovalRequest(mailboxSession, updateMessage.Sender, decision, decisionMaker, decisionTime, messageItem))
                        {
                            ConflictResolutionResult conflictResolutionResult = messageItem.Save(SaveMode.ResolveConflicts);
                            if (conflictResolutionResult.SaveStatus != SaveResult.Success)
                            {
                                ApprovalRequestUpdater.diag.TraceDebug <string, SaveResult>(0L, "Saving message: {0}, resulted in an update conflict ({1}). Ignored", messageId, conflictResolutionResult.SaveStatus);
                            }
                            AggregateOperationResult aggregateOperationResult = mailboxSession.Delete(DeleteItemFlags.MoveToDeletedItems, new StoreId[]
                            {
                                storeObjectId
                            });
                            if (aggregateOperationResult.OperationResult != OperationResult.Succeeded)
                            {
                                ApprovalRequestUpdater.diag.TraceDebug <string, OperationResult>(0L, "Delete message: {0}, resulted in failure {1} Ignored", messageId, aggregateOperationResult.OperationResult);
                            }
                            updated = true;
                        }
                    }
                }
            });

            if (!updated)
            {
                ApprovalRequestUpdater.diag.TraceDebug <string>(0L, "Couldn't find message: {0}, ignored", messageId);
                return(ApprovalRequestUpdater.Result.NotFound);
            }
            if (MessageStatus.Success != messageStatus)
            {
                ApprovalRequestUpdater.diag.TraceDebug <string, string>(0L, "Message ({0}) processing was not successful ({1}), ignoring..", messageId, (messageStatus.Exception == null) ? "NULL exception" : messageStatus.Exception.Message);
                return(ApprovalRequestUpdater.Result.SaveConflict);
            }
            return(ApprovalRequestUpdater.Result.UpdatedSucessfully);
        }