Search code examples
c#if-statementexchangewebservices

Why doesn't this if statement work properly


This code is designed to perform a cleanup after a mailbox rehydration (from Symantec Enterprise Vault). We take a snapshot index of the MessageId and ConversationId of all items in the mailbox before the rehydration.

After the rehydration this code

    if (string.Equals(item.ItemClass, "IPM.Note.EnterpriseVault.Shortcut", StringComparison.InvariantCulture) || ((existingIds.Any(x => x.ConversationId == item.ConversationId.ToString()) == false || (item.ItemClass == "IPM.Appointment" && existingIds.Any(x => x.MessageId == item.Id.ToString()) == false) && item.DateTimeReceived < snapshotDate)))
    {
        item.Delete(DeleteMode.HardDelete);
    }

should delete

  1. Any items which have an ItemClass of "IPM.Note.EnterpriseVault.Shortcut"
  2. Any items which have an ItemClass of "IPM.Appointment" where the Id is not in the existingIds list of MessageIds, unless they were received after the `snapshotDate
  3. Any other items where the ConversationId is not in the existingIds list, unless they were received after the snapshotDate.

After running this code a user reported having lost some email that was received after the snapshotDate so it seems I have got the if statement wrong! :( Could somebody tell me please what I have got wrong (or a way that I can break this down to understand it better) and what this code will actually have done so I can let the user know what has been lost. I know lofical ORs are notoriously hard to get write and I think I have made a mistake with the brackets somewhere but I just can't see it.


Solution

  • I would recommend you to split if check into local functions it will be much easier to debug.

     if (IsShourtcut(item) || NotExistingAppItment(item) || ExistingConversation(item) && IsReceivedBeforSnapshot(item)) 
        {
                // to delete 
        }
    
    bool IsShourtcut(Item item) => string.Equals(item.ItemClass, "IPM.Note.EnterpriseVault.Shortcut", StringComparison.InvariantCulture);
    bool NotExistingAppItment(Item item) => item.ItemClass == "IPM.Appointment" && existingIds.All(x => x.MessageId != item.Id.ToString());
    bool ExistingConversation(Item item) => existingIds.All(x => x.ConversationId != item.ConversationId.ToString();
    bool IsReceivedBeforSnapshot(Item item) => item.DateTimeReceived < snapshotDate;