示例#1
0
 public static EmailMessage GenerateContentReport(SmtpAddress arbitrationAddress, SmtpAddress reportToAddress, StoreSession session, bool isArbitration)
 {
     if (arbitrationAddress.IsValidAddress && reportToAddress.IsValidAddress)
     {
         EmailMessage   emailMessage = EmailMessage.Create();
         RoutingAddress address      = GlobalConfigurationBase <MicrosoftExchangeRecipient, MicrosoftExchangeRecipientConfiguration> .Instance.Address;
         emailMessage.From = new EmailRecipient(null, (string)address);
         emailMessage.To.Add(new EmailRecipient(null, (string)reportToAddress));
         emailMessage.Subject = "Arbitration Mailbox Content Report: " + arbitrationAddress.ToString();
         using (Stream contentWriteStream = emailMessage.Body.GetContentWriteStream())
         {
             using (StreamWriter streamWriter = new StreamWriter(contentWriteStream))
             {
                 if (!isArbitration)
                 {
                     streamWriter.WriteLine("This mailbox is not an approval arbitration mailbox. This report is only generated for approval arbitration mailboxes.");
                     return(emailMessage);
                 }
                 Attachment attachment = emailMessage.Attachments.Add("formattedDetails.txt");
                 using (Stream contentWriteStream2 = attachment.GetContentWriteStream())
                 {
                     using (Folder folder = Folder.Bind((MailboxSession)session, DefaultFolderType.Inbox))
                     {
                         using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, null, new PropertyDefinition[]
                         {
                             ItemSchema.Id
                         }))
                         {
                             object[][] rows = queryResult.GetRows(10000);
                             int        num  = 0;
                             int        num2 = 0;
                             TimeSpan   t    = default(TimeSpan);
                             TimeSpan   t2   = default(TimeSpan);
                             while (rows != null && rows.Length > 0)
                             {
                                 foreach (object[] array2 in rows)
                                 {
                                     StoreObjectId objectId = ((VersionedId)array2[0]).ObjectId;
                                     using (MessageItem messageItem = MessageItem.Bind(session, objectId, ArbitrationMailboxReport.ApprovalProperties))
                                     {
                                         string         valueOrDefault   = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalRequestor);
                                         string         valueOrDefault2  = messageItem.GetValueOrDefault <string>(ItemSchema.DisplayCc);
                                         string         valueOrDefault3  = messageItem.GetValueOrDefault <string>(ItemSchema.Subject);
                                         string         valueOrDefault4  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalAllowedDecisionMakers);
                                         string         valueOrDefault5  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalDecisionMakersNdred);
                                         string         valueOrDefault6  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalRequestMessageId);
                                         string         valueOrDefault7  = messageItem.GetValueOrDefault <string>(ItemSchema.InternetMessageId);
                                         string         valueOrDefault8  = messageItem.GetValueOrDefault <string>(ItemSchema.InternetReferences);
                                         string         valueOrDefault9  = messageItem.GetValueOrDefault <string>(MessageItemSchema.ApprovalDecisionMaker);
                                         ApprovalStatus?valueAsNullable  = messageItem.GetValueAsNullable <ApprovalStatus>(MessageItemSchema.ApprovalStatus);
                                         ExDateTime?    valueAsNullable2 = messageItem.GetValueAsNullable <ExDateTime>(MessageItemSchema.ApprovalDecisionTime);
                                         ExDateTime?    valueAsNullable3 = messageItem.GetValueAsNullable <ExDateTime>(ItemSchema.ReceivedTime);
                                         ExDateTime?    valueAsNullable4 = messageItem.GetValueAsNullable <ExDateTime>(ItemSchema.RetentionDate);
                                         if (valueAsNullable3 != null)
                                         {
                                             if (valueAsNullable2 == null)
                                             {
                                                 ExDateTime utcNow = ExDateTime.UtcNow;
                                                 t2 += utcNow - valueAsNullable3.Value;
                                                 num2++;
                                             }
                                             else if (valueAsNullable3 <= valueAsNullable2)
                                             {
                                                 t += valueAsNullable2.Value - valueAsNullable3.Value;
                                                 num++;
                                             }
                                         }
                                         streamWriter.WriteLine("Initiation Message ID:" + valueOrDefault7);
                                         streamWriter.WriteLine("Original Message ID:" + valueOrDefault8);
                                         streamWriter.WriteLine("Sender:" + valueOrDefault);
                                         streamWriter.WriteLine("Moderated Recipient Addresses:" + valueOrDefault2);
                                         streamWriter.WriteLine("Message Subject:" + valueOrDefault3);
                                         streamWriter.WriteLine("Moderators:" + valueOrDefault4);
                                         streamWriter.WriteLine("Moderators (total; not delivered; away):" + valueOrDefault5);
                                         streamWriter.WriteLine("Approval Request Message ID:" + valueOrDefault6);
                                         streamWriter.WriteLine("Decision maker:" + valueOrDefault9);
                                         streamWriter.WriteLine("Decision status:" + valueAsNullable);
                                         streamWriter.WriteLine("Decision Time:" + valueAsNullable2);
                                         streamWriter.WriteLine("Received Time:" + valueAsNullable3);
                                         streamWriter.WriteLine("Expiry Time:" + valueAsNullable4);
                                         streamWriter.WriteLine();
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault7);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault8);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault2);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault3);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault4);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault5);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault6);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault9);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueAsNullable);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueOrDefault6);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueAsNullable2);
                                         ArbitrationMailboxReport.CheckAndWrite(contentWriteStream2, valueAsNullable3);
                                         Utf8Csv.EncodeEscapeAndWriteLine(contentWriteStream2, (valueAsNullable4 != null) ? valueAsNullable4.ToString() : string.Empty);
                                     }
                                 }
                                 rows = queryResult.GetRows(10000);
                             }
                             streamWriter.WriteLine("Summary:");
                             streamWriter.WriteLine("Messages with a decision:" + num);
                             if (num > 0)
                             {
                                 streamWriter.WriteLine("Average decision time:" + TimeSpan.FromSeconds(t.TotalSeconds / (double)num));
                             }
                             streamWriter.WriteLine("Messages without a decision:" + num2);
                             if (num2 > 0)
                             {
                                 streamWriter.WriteLine("Average waiting time:" + TimeSpan.FromSeconds(t2.TotalSeconds / (double)num2));
                             }
                         }
                     }
                 }
                 return(emailMessage);
             }
         }
     }
     return(null);
 }
示例#2
0
 public void Test()
 {
     Folder.Bind(_service, WellKnownFolderName.Inbox);
     Console.WriteLine("test success.");
 }
示例#3
0
        private TeamMailboxDiagnosticsInfo GetOneTeamMailboxDiagnosticsInfo(KeyValuePair <ADUser, ExchangePrincipal> entry)
        {
            TeamMailboxDiagnosticsInfo     teamMailboxDiagnosticsInfo = new TeamMailboxDiagnosticsInfo(entry.Value.MailboxInfo.DisplayName);
            MultiValuedProperty <SyncInfo> multiValuedProperty        = new MultiValuedProperty <SyncInfo>();
            bool flag  = false;
            bool flag2 = false;
            bool flag3 = false;
            TeamMailboxDiagnosticsInfo result;

            using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(entry.Value, CultureInfo.InvariantCulture, "Client=TeamMailbox;Action=GetDiagnostics;Interactive=False"))
            {
                using (UserConfiguration mailboxConfiguration = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "SiteSynchronizerConfigurations", UserConfigurationTypes.Dictionary, false))
                {
                    if (mailboxConfiguration != null)
                    {
                        teamMailboxDiagnosticsInfo.HierarchySyncInfo = GetSiteMailboxDiagnostics.GetSyncInfoFromMetadata(entry.Value.MailboxInfo.DisplayName, (entry.Key.SharePointUrl != null) ? entry.Key.SharePointUrl.AbsoluteUri : string.Empty, mailboxConfiguration);
                        if (!string.IsNullOrEmpty(teamMailboxDiagnosticsInfo.HierarchySyncInfo.LastSyncFailure))
                        {
                            flag = true;
                        }
                    }
                }
                using (Folder folder = Folder.Bind(mailboxSession, DefaultFolderType.Root))
                {
                    using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, new ExistsFilter(FolderSchema.LinkedId), null, new PropertyDefinition[]
                    {
                        FolderSchema.Id,
                        FolderSchema.DisplayName,
                        FolderSchema.LinkedUrl
                    }))
                    {
                        object[][] array = null;
                        do
                        {
                            array = queryResult.GetRows(10000);
                            for (int i = 0; i < array.Length; i++)
                            {
                                StoreObjectId objectId    = ((VersionedId)array[i][0]).ObjectId;
                                string        displayName = array[i][1] as string;
                                string        url         = array[i][2] as string;
                                using (UserConfiguration folderConfiguration = UserConfigurationHelper.GetFolderConfiguration(mailboxSession, objectId, "DocumentLibSynchronizerConfigurations", UserConfigurationTypes.Dictionary, false, false))
                                {
                                    if (folderConfiguration != null)
                                    {
                                        SyncInfo syncInfoFromMetadata = GetSiteMailboxDiagnostics.GetSyncInfoFromMetadata(displayName, url, folderConfiguration);
                                        multiValuedProperty.Add(syncInfoFromMetadata);
                                        if (!string.IsNullOrEmpty(syncInfoFromMetadata.LastSyncFailure))
                                        {
                                            flag = true;
                                        }
                                    }
                                }
                            }
                        }while (array.Length != 0);
                    }
                }
                teamMailboxDiagnosticsInfo.DocLibSyncInfos = multiValuedProperty;
                using (UserConfiguration mailboxConfiguration2 = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "TeamMailboxDocumentLastSyncCycleLog", UserConfigurationTypes.Stream, false))
                {
                    if (mailboxConfiguration2 != null)
                    {
                        using (Stream stream = mailboxConfiguration2.GetStream())
                        {
                            byte[] array2 = new byte[stream.Length];
                            stream.Read(array2, 0, array2.Length);
                            teamMailboxDiagnosticsInfo.LastDocumentSyncCycleLog = Encoding.ASCII.GetString(array2);
                        }
                    }
                }
                using (UserConfiguration mailboxConfiguration3 = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "MembershipSynchronizerConfigurations", UserConfigurationTypes.Dictionary, false))
                {
                    if (mailboxConfiguration3 != null)
                    {
                        teamMailboxDiagnosticsInfo.MembershipSyncInfo = GetSiteMailboxDiagnostics.GetSyncInfoFromMetadata(entry.Value.MailboxInfo.DisplayName, (entry.Key.SharePointUrl != null) ? entry.Key.SharePointUrl.AbsoluteUri : string.Empty, mailboxConfiguration3);
                        if (!string.IsNullOrEmpty(teamMailboxDiagnosticsInfo.MembershipSyncInfo.LastSyncFailure))
                        {
                            flag2 = true;
                        }
                    }
                }
                using (UserConfiguration mailboxConfiguration4 = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "TeamMailboxMembershipLastSyncCycleLog", UserConfigurationTypes.Stream, false))
                {
                    if (mailboxConfiguration4 != null)
                    {
                        using (Stream stream2 = mailboxConfiguration4.GetStream())
                        {
                            byte[] array3 = new byte[stream2.Length];
                            stream2.Read(array3, 0, array3.Length);
                            teamMailboxDiagnosticsInfo.LastMembershipSyncCycleLog = Encoding.ASCII.GetString(array3);
                        }
                    }
                }
                using (UserConfiguration mailboxConfiguration5 = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "MaintenanceSynchronizerConfigurations", UserConfigurationTypes.Dictionary, false))
                {
                    if (mailboxConfiguration5 != null)
                    {
                        teamMailboxDiagnosticsInfo.MaintenanceSyncInfo = GetSiteMailboxDiagnostics.GetSyncInfoFromMetadata(entry.Value.MailboxInfo.DisplayName, (entry.Key.SharePointUrl != null) ? entry.Key.SharePointUrl.AbsoluteUri : string.Empty, mailboxConfiguration5);
                        if (!string.IsNullOrEmpty(teamMailboxDiagnosticsInfo.MaintenanceSyncInfo.LastSyncFailure))
                        {
                            flag3 = true;
                        }
                    }
                }
                using (UserConfiguration mailboxConfiguration6 = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "TeamMailboxMaintenanceLastSyncCycleLog", UserConfigurationTypes.Stream, false))
                {
                    if (mailboxConfiguration6 != null)
                    {
                        using (Stream stream3 = mailboxConfiguration6.GetStream())
                        {
                            byte[] array4 = new byte[stream3.Length];
                            stream3.Read(array4, 0, array4.Length);
                            teamMailboxDiagnosticsInfo.LastMaintenanceSyncCycleLog = Encoding.ASCII.GetString(array4);
                        }
                    }
                }
                if (!flag && !flag2 && !flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.Succeeded;
                }
                else if (flag && !flag2 && !flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.DocumentSyncFailureOnly;
                }
                else if (!flag && flag2 && !flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.MembershipSyncFailureOnly;
                }
                else if (!flag && !flag2 && flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.MaintenanceSyncFailureOnly;
                }
                else if (flag && flag2 && !flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.DocumentAndMembershipSyncFailure;
                }
                else if (!flag && flag2 && flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.MembershipAndMaintenanceSyncFailure;
                }
                else if (flag && !flag2 && flag3)
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.DocumentAndMaintenanceSyncFailure;
                }
                else
                {
                    teamMailboxDiagnosticsInfo.Status = TeamMailboxSyncStatus.Failed;
                }
                result = teamMailboxDiagnosticsInfo;
            }
            return(result);
        }
示例#4
0
        // Go connect to the Calendar folder and get the calendar items
        public static bool ProcessCalendar(ExchangeService service)
        {
            Folder fldCal    = null;
            int    iOffset   = 0;
            int    iPageSize = 500;
            bool   bMore     = true;
            //List<Item> cAppts = new List<Item>();
            FindItemsResults <Item> findResults = null;

            try
            {
                // Here's where it connects to the Calendar
                fldCal = Folder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
            }
            catch (ServiceResponseException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("");
                Console.WriteLine("Could not connect to this user's mailbox or calendar.");
                Console.WriteLine(ex.Message);
                Console.ResetColor();
                return(false);
            }

            // if we're in then we get here
            // creating a view with props to request / collect
            ItemView cView = new ItemView(iPageSize, iOffset, OffsetBasePoint.Beginning);
            List <ExtendedPropertyDefinition> propSet = new List <ExtendedPropertyDefinition>();

            DoProps(ref propSet);
            cView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
            cView.OrderBy.Add(ItemSchema.LastModifiedTime, SortDirection.Descending);
            foreach (PropertyDefinitionBase pdbProp in propSet)
            {
                cView.PropertySet.Add(pdbProp);
            }

            // now go get the items. 1000 Max so must loop to get all items
            while (bMore)
            {
                findResults = fldCal.FindItems(cView);

                int i = 0;
                int n = 0;
                foreach (Appointment appt in findResults.Items)
                {
                    //cAppts.Add(item);
                    i++;
                    if (i % 5 == 0)
                    {
                        // do a progress marker that spins | / - \
                        Console.SetCursorPosition(0, Console.CursorTop);
                        Console.Write("");
                        Console.Write(cSpin[n % 4]);
                        n++;
                    }

                    try
                    {
                        if (appt.Size > 0)
                        {
                            if (bVerbose)
                            {
                                outLog.WriteLine("Calling to Process Item");
                            }
                            ProcessItem(appt);
                        }
                        else
                        {
                            DisplayAndLog("Encountered an invalid Appointment. Continuing...");
                        }
                    }
                    catch
                    {
                        DisplayAndLog("Appointment item processing failed or item is NULL. Continuing...");
                    }

                    iCheckedItems++;
                    if (i % 500 == 0)
                    {
                        // Give progress update every 500 items
                        Console.SetCursorPosition(0, Console.CursorTop);
                        Console.Write("");
                        Console.WriteLine("Completed " + iCheckedItems.ToString() + " items and continuing...");
                    }
                }

                bMore = findResults.MoreAvailable;
                if (bMore)
                {
                    cView.Offset += iPageSize;
                }

                // clear out progress marker now that we are done
                Console.SetCursorPosition(0, Console.CursorTop);
                Console.Write(" ");
            }

            return(true);
        }
示例#5
0
 private void FillFidMapping(GetSyncStateResult results, MailboxSession session)
 {
     foreach (DeviceData deviceData in results.Devices)
     {
         foreach (SyncStateFolderData syncStateFolderData in deviceData.SyncFolders)
         {
             if (syncStateFolderData != null && !string.IsNullOrEmpty(syncStateFolderData.SyncStateBlob))
             {
                 syncStateFolderData.FolderMapping = new List <FolderMappingData>();
                 using (PooledMemoryStream pooledMemoryStream = new PooledMemoryStream(102400))
                 {
                     byte[] array = Convert.FromBase64String(syncStateFolderData.SyncStateBlob);
                     pooledMemoryStream.Write(array, 0, array.Length);
                     pooledMemoryStream.Flush();
                     pooledMemoryStream.Position = 0L;
                     int  num;
                     int  num2;
                     long num3;
                     long num4;
                     Dictionary <string, bool> dictionary;
                     GenericDictionaryData <ConstStringData, string, DerivedData <ICustomSerializableBuilder> > genericDictionaryData = SyncState.InternalDeserializeData(pooledMemoryStream, out num, out num2, out num3, out num4, out dictionary);
                     FolderIdMapping       folderIdMapping    = genericDictionaryData.Data["IdMapping"].Data as FolderIdMapping;
                     IDictionaryEnumerator syncIdIdEnumerator = folderIdMapping.SyncIdIdEnumerator;
                     while (syncIdIdEnumerator.MoveNext())
                     {
                         string        shortId       = syncIdIdEnumerator.Key as string;
                         ISyncItemId   syncItemId    = syncIdIdEnumerator.Value as ISyncItemId;
                         StoreObjectId storeObjectId = syncItemId.NativeId as StoreObjectId;
                         try
                         {
                             using (Folder folder = Folder.Bind(session, storeObjectId, new PropertyDefinition[]
                             {
                                 FolderSchema.DisplayName
                             }))
                             {
                                 DefaultFolderType defaultFolderType = session.IsDefaultFolderType(folder.Id);
                                 syncStateFolderData.FolderMapping.Add(new FolderMappingData
                                 {
                                     ShortId           = shortId,
                                     LongId            = storeObjectId.ToString(),
                                     Name              = folder.DisplayName,
                                     DefaultFolderType = defaultFolderType.ToString(),
                                     Exception         = null
                                 });
                             }
                         }
                         catch (Exception ex)
                         {
                             syncStateFolderData.FolderMapping.Add(new FolderMappingData
                             {
                                 ShortId           = shortId,
                                 LongId            = "[Error]",
                                 Name              = "[Error]",
                                 DefaultFolderType = "[Error]",
                                 Exception         = ex.ToString()
                             });
                         }
                     }
                 }
             }
         }
     }
 }
示例#6
0
        internal static void Start(string[] args)
        {
            try
            {
                var applicationSettings = new Properties.Settings();

                ServicePointManager.ServerCertificateValidationCallback = CallbackMethods.CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

                // Get the information of the account.
                var user = new Office365User();
                service.Credentials = new WebCredentials(user.Account, user.Pwd);

                // Set the url of server.
                if (!AutodiscoverUrl(service, user))
                {
                    return;
                }

                var mailboxMonitorAddress = applicationSettings.Mailbox_Monitor;


                var moveMailFolderId    = GetFolderId(service, "Processed");
                var invalidMailFolderId = GetFolderId(service, "Invalid");

                var folderView = new FolderView(2);
                folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                folderView.Traversal   = FolderTraversal.Deep;

                //var inboxFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Test");
                //var inboxResults = service.FindFolders(WellKnownFolderName.Root, inboxFilter, folderView);
                //                var inboxResults = service.FindFolders(WellKnownFolderName.Inbox, folderView);

                //              if (inboxResults.TotalCount > 0)
                //            {
                Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                //            var inboxId = inboxResults.Folders[0].Id;
                Folder inboxFolder = Folder.Bind(service, inbox.Id);
                if (inboxFolder.UnreadCount > 0)
                {
                    ItemView unreadView = new ItemView(inboxFolder.UnreadCount);
                    unreadView.PropertySet = PropertySet.IdOnly;
                    FindItemsResults <Item> results = service.FindItems(inbox.Id, unreadView);
                    foreach (Item item in results.Items)
                    {
                        EmailMessage email = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId.ToString()));
                        if (!email.IsRead)
                        {
                            PropertySet ps = new PropertySet(ItemSchema.MimeContent, ItemSchema.Body, EmailMessageSchema.Sender, EmailMessageSchema.IsRead, ItemSchema.DateTimeReceived, ItemSchema.Attachments);
                            email.Load(ps);

                            var savedMySQLMessageId = MsSqlManager.SaveRAWMessage(email);

                            var processedPlainTextBody = ProcessEmailBodyText(email, mailboxMonitorAddress, moveMailFolderId, savedMySQLMessageId);
                            if (!processedPlainTextBody)
                            {
                                var processedAttachment = ProcessEmailAttachments(email, mailboxMonitorAddress, moveMailFolderId, savedMySQLMessageId);
                                if (!processedAttachment)
                                {
                                    ProcessEmailAsInvalid(email, mailboxMonitorAddress, invalidMailFolderId);
                                }
                            }
                        }
                    }
                }
                //          }
            }
            catch (Exception exc)
            {
                MsSqlManager.SaveLogging(new Atum.DAL.Logging.LoggingInfo(DateTime.Now.ToString(), "Start", "Exception", exc.StackTrace));
                MsSqlManager.SaveLogging(new Atum.DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Exchange Online", "Exception", exc.StackTrace));
            }
        }
        internal static PublicFolderMailboxDumpsterInfo LoadInfo(PublicFolderSession session, Action <LocalizedString, LocalizedString, int> writeProgress)
        {
            string value = null;
            int    num   = 0;
            bool   flag  = false;
            int    num2  = 0;
            int    num3  = 0;
            int    num4  = 0;
            int    num5  = 0;
            int    num6  = 0;

            using (Folder folder = Folder.Bind(session, session.GetDumpsterRootFolderId(), PublicFolderMailboxDumpsterInfo.DumpsterPropertiesToLoad))
            {
                byte[] valueOrDefault = folder.GetValueOrDefault <byte[]>(FolderSchema.PublicFolderDumpsterHolderEntryId, null);
                if (valueOrDefault != null)
                {
                    value = session.IdConverter.CreateFolderId(session.IdConverter.GetIdFromLongTermId(valueOrDefault)).ToHexEntryId();
                }
                using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.DeepTraversal, null, null, PublicFolderMailboxDumpsterInfo.DumpsterSubfoldersProperties))
                {
                    int  estimatedRowCount = queryResult.EstimatedRowCount;
                    bool flag2             = false;
                    int  num7 = 0;
                    for (;;)
                    {
                        object[][] rows = queryResult.GetRows(10000);
                        if (rows == null || rows.Length == 0)
                        {
                            break;
                        }
                        if (num == 0 && estimatedRowCount > rows.Length && writeProgress != null)
                        {
                            flag2 = true;
                        }
                        foreach (object[] array2 in rows)
                        {
                            num++;
                            if (flag2)
                            {
                                if (num > estimatedRowCount)
                                {
                                    estimatedRowCount = queryResult.EstimatedRowCount;
                                }
                                int num8 = num * 100 / estimatedRowCount;
                                if (num8 != num7 && num8 <= 100)
                                {
                                    writeProgress(ClientStrings.PublicFolderMailboxDumpsterInfo, ClientStrings.PublicFolderMailboxInfoFolderEnumeration(num, estimatedRowCount), num8);
                                    num7 = num8;
                                }
                            }
                            string text = array2[1] as string;
                            if (!string.IsNullOrEmpty(text))
                            {
                                bool flag3 = StringComparer.OrdinalIgnoreCase.Equals("\\NON_IPM_SUBTREE\\DUMPSTER_ROOT\\DUMPSTER_EXTEND", text);
                                if (flag3)
                                {
                                    flag = true;
                                }
                                else if (!text.StartsWith("\\NON_IPM_SUBTREE\\DUMPSTER_ROOT\\DUMPSTER_EXTEND\\", StringComparison.OrdinalIgnoreCase))
                                {
                                    num2++;
                                }
                                else
                                {
                                    object obj = array2[0];
                                    if (obj is int)
                                    {
                                        int num9 = (int)obj;
                                        if (num9 == 2)
                                        {
                                            num3++;
                                        }
                                        else if (num9 == 3)
                                        {
                                            num4++;
                                        }
                                        else if (num9 == 4)
                                        {
                                            num5++;
                                        }
                                        else if (num9 > 4)
                                        {
                                            num6++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            PublicFolderMailboxDumpsterInfo publicFolderMailboxDumpsterInfo = new PublicFolderMailboxDumpsterInfo();

            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.DumpsterHolderEntryId] = value;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.CountTotalFolders]     = num;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.HasDumpsterExtended]   = flag;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.CountLegacyDumpsters]  = num2;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.CountContainerLevel1]  = num3;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.CountContainerLevel2]  = num4;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.CountDumpsters]        = num5;
            publicFolderMailboxDumpsterInfo[PublicFolderDumpsterInfoSchema.CountDeletedFolders]   = num6;
            publicFolderMailboxDumpsterInfo.propertyBag.ResetChangeTracking();
            return(publicFolderMailboxDumpsterInfo);
        }
        // Token: 0x060007B4 RID: 1972 RVA: 0x000371A0 File Offset: 0x000353A0
        private List <VersionedId> QueryMatchingItems(MailboxSession itemStore, MeetingMessage item, byte[] itemGlobalObjId, string sentRepresenting, int itemSequenceNumber, ref OldMessageDeletion.LatestItemInfo latestInfo)
        {
            ExDateTime         utcNow = ExDateTime.UtcNow;
            List <VersionedId> list   = new List <VersionedId>();
            bool flag  = true;
            bool flag2 = (bool)Utils.SafeGetProperty(item, MessageItemSchema.MapiHasAttachment, false);
            bool flag3 = item.Body != null && item.Body.Size > 0L;
            bool flag4 = item is MeetingRequest;
            bool flag5 = item is MeetingResponse;
            bool flag6 = item is MeetingCancellation;

            SortBy[] sortColumns = new SortBy[]
            {
                new SortBy(CalendarItemBaseSchema.GlobalObjectId, SortOrder.Ascending),
                new SortBy(StoreObjectSchema.ItemClass, SortOrder.Descending)
            };
            ComparisonFilter seekFilter = new ComparisonFilter(ComparisonOperator.Equal, CalendarItemBaseSchema.GlobalObjectId, itemGlobalObjId);

            using (Folder folder = Folder.Bind(itemStore, item.ParentId))
            {
                using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, sortColumns, OldMessageDeletion.OMDColumnsToQuery))
                {
                    queryResult.SeekToCondition(SeekReference.OriginBeginning, seekFilter);
                    while (flag)
                    {
                        object[][] rows = queryResult.GetRows(25);
                        if (rows.Length < 1)
                        {
                            break;
                        }
                        ExDateTime itemOwnerChangeTime = (ExDateTime)Utils.SafeGetProperty(item, CalendarItemBaseSchema.OwnerCriticalChangeTime, utcNow);
                        foreach (object[] array in rows)
                        {
                            string text = array[0] as string;
                            if (!string.IsNullOrEmpty(text))
                            {
                                if (!itemStore.IsGroupMailbox())
                                {
                                    if ((flag4 || flag6) && !ObjectClass.IsMeetingRequest(text) && !ObjectClass.IsMeetingCancellation(text))
                                    {
                                        flag = false;
                                        break;
                                    }
                                    if (flag5 && !ObjectClass.IsMeetingResponse(text))
                                    {
                                        goto IL_186;
                                    }
                                }
                                byte[] rowGlobalObjectId = (array[2] is byte[]) ? (array[2] as byte[]) : null;
                                if (!OldMessageDeletion.GlobalObjectIdMatches(itemGlobalObjId, rowGlobalObjectId))
                                {
                                    flag = false;
                                    break;
                                }
                                this.DetermineIfWeDelete(list, item, array, itemOwnerChangeTime, sentRepresenting, itemSequenceNumber, ref latestInfo, ref flag2, ref flag3);
                            }
                            IL_186 :;
                        }
                    }
                }
            }
            return(list);
        }
        // Token: 0x060015B9 RID: 5561 RVA: 0x0004D7B0 File Offset: 0x0004B9B0
        protected override GetFlowConversationResponse InternalExecute()
        {
            QueryFilter  flowConversationFilter = GetFlowConversation.GetFlowConversationFilter(this.folderId, base.MailboxIdentityMailboxSession);
            IdAndSession folderIdAndSession     = GetFlowConversation.GetFolderIdAndSession(this.folderId, base.MailboxIdentityMailboxSession, base.IdConverter);
            List <FlowConversationItem> list    = new List <FlowConversationItem>();

            new ConversationFactory(base.MailboxIdentityMailboxSession);
            using (Folder folder = Folder.Bind((MailboxSession)folderIdAndSession.Session, folderIdAndSession.Id))
            {
                using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, flowConversationFilter, GetFlowConversation.SortByArray, GetFlowConversation.ItemQueryRequiredProperties))
                {
                    IStorePropertyBag[] propertyBags = queryResult.GetPropertyBags(10000);
                    foreach (IStorePropertyBag storePropertyBag in propertyBags)
                    {
                        if ((long)list.Count == this.requestedConversationCount)
                        {
                            break;
                        }
                        ParticipantSet participantSet;
                        string         text = this.GenerateParticipantsHash(storePropertyBag, out participantSet);
                        if (!this.allItemsData.ContainsKey(text))
                        {
                            FlowConversationItem flowConversationItem = new FlowConversationItem();
                            ExDateTime           valueOrDefault       = storePropertyBag.GetValueOrDefault <ExDateTime>(ItemSchema.ReceivedTime, ExDateTime.Now);
                            string       valueOrDefault2 = storePropertyBag.GetValueOrDefault <string>(ItemSchema.Preview, null);
                            string       valueOrDefault3 = storePropertyBag.GetValueOrDefault <string>(ItemSchema.Subject, null);
                            bool         valueOrDefault4 = storePropertyBag.GetValueOrDefault <bool>(MessageItemSchema.IsRead, true);
                            IParticipant valueOrDefault5 = storePropertyBag.GetValueOrDefault <IParticipant>(ItemSchema.From, null);
                            VersionedId  valueOrDefault6 = storePropertyBag.GetValueOrDefault <VersionedId>(ItemSchema.Id, null);
                            storePropertyBag.GetValueOrDefault <ConversationId>(ItemSchema.ConversationId, null);
                            List <IParticipant> list2 = new List <IParticipant>(participantSet.Count + 1);
                            participantSet.ExceptWith(new IParticipant[]
                            {
                                valueOrDefault5
                            });
                            list2.Add(valueOrDefault5);
                            list2.AddRange(participantSet);
                            flowConversationItem.FlowConversationId      = text;
                            flowConversationItem.LastItemId              = IdConverter.ConvertStoreItemIdToItemId(valueOrDefault6, folderIdAndSession.Session);
                            flowConversationItem.Participants            = ReplyToProperty.Render(list2).ToArray();
                            flowConversationItem.SenderPhotoEmailAddress = valueOrDefault5.SmtpEmailAddress;
                            flowConversationItem.Preview         = valueOrDefault2;
                            flowConversationItem.Subject         = valueOrDefault3;
                            flowConversationItem.TotalCount      = 1;
                            flowConversationItem.UnReadCount     = (valueOrDefault4 ? 0 : 1);
                            flowConversationItem.ReceivedTimeUtc = ExDateTimeConverter.ToSoapHeaderTimeZoneRelatedXsdDateTime(valueOrDefault);
                            this.allItemsData.Add(text, flowConversationItem);
                            list.Add(flowConversationItem);
                        }
                        else
                        {
                            if (!storePropertyBag.GetValueOrDefault <bool>(MessageItemSchema.IsRead, true))
                            {
                                this.allItemsData[text].UnReadCount++;
                            }
                            this.allItemsData[text].TotalCount++;
                        }
                    }
                }
            }
            return(new GetFlowConversationResponse
            {
                Conversations = list.ToArray()
            });
        }
        /// <summary>
        /// Create meetings either one at a time or batch request the creation of meetings. Meetings
        /// are appointments with attendees.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void CreateMeeting(ExchangeService service)
        {
            bool demoBatchCreateMeeting = true;

            Mailbox principle         = new Mailbox("*****@*****.**");
            Folder  principleCalendar = Folder.Bind(service, new FolderId(WellKnownFolderName.Calendar, principle));

            Appointment meeting1 = new Appointment(service);

            meeting1.Subject  = "Status Meeting";
            meeting1.Body     = "The purpose of this meeting is to discuss status.";
            meeting1.Start    = new DateTime(2013, 6, 1, 9, 0, 0);
            meeting1.End      = meeting1.Start.AddHours(2);
            meeting1.Location = "Conf Room";
            meeting1.RequiredAttendees.Add("*****@*****.**");
            meeting1.RequiredAttendees.Add("*****@*****.**");
            meeting1.OptionalAttendees.Add("*****@*****.**");

            Appointment meeting2 = new Appointment(service);

            meeting2.Subject  = "Lunch";
            meeting2.Body     = "The purpose of this meeting is to eat and be merry.";
            meeting2.Start    = new DateTime(2013, 6, 1, 12, 0, 0);
            meeting2.End      = meeting2.Start.AddHours(2);
            meeting2.Location = "Contoso cafe";
            meeting2.RequiredAttendees.Add("*****@*****.**");
            meeting2.RequiredAttendees.Add("*****@*****.**");
            meeting2.OptionalAttendees.Add("*****@*****.**");

            try
            {
                if (demoBatchCreateMeeting) // Show batch
                {
                    Collection <Appointment> meetings = new Collection <Appointment>();
                    meetings.Add(meeting1);
                    meetings.Add(meeting2);

                    // Create the batch of meetings. This results in a call to EWS by using the CreateItem operation.
                    ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(meetings,
                                                                                                principleCalendar.Id,
                                                                                                MessageDisposition.SendOnly,
                                                                                                SendInvitationsMode.SendToAllAndSaveCopy);

                    if (responses.OverallResult == ServiceResult.Success)
                    {
                        Console.WriteLine("You've successfully created a couple of meetings in a single call.");
                    }
                    else if (responses.OverallResult == ServiceResult.Warning)
                    {
                        Console.WriteLine("There are some issues with your batch request.");

                        foreach (ServiceResponse response in responses)
                        {
                            if (response.Result == ServiceResult.Error)
                            {
                                Console.WriteLine("Error code: " + response.ErrorCode.ToString());
                                Console.WriteLine("Error message: " + response.ErrorMessage);
                            }
                        }
                    }
                    else // responses.OverallResult == ServiceResult.Error
                    {
                        Console.WriteLine("There are errors with your batch request.");

                        foreach (ServiceResponse response in responses)
                        {
                            if (response.Result == ServiceResult.Error)
                            {
                                Console.WriteLine("Error code: " + response.ErrorCode.ToString());
                                Console.WriteLine("Error message: " + response.ErrorMessage);
                            }
                        }
                    }
                }
                else // Show creation of a single meeting.
                {
                    // Create a single meeting. This results in a call to EWS by using the CreateItem operation.
                    meeting1.Save(principleCalendar.Id, SendInvitationsMode.SendToAllAndSaveCopy);
                    Console.WriteLine("You've successfully created a single meeting.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception info: " + ex.Message);
            }
        }
示例#11
0
        public IEnumerable <T> FindPaged <T>(QueryFilter filter, ObjectId rootId, bool deepSearch, SortBy sortBy, int pageSize) where T : IConfigurable, new()
        {
            base.CheckDisposed();
            if (!typeof(PublicFolderStatistics).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()))
            {
                throw new NotSupportedException("FindPaged: " + typeof(T).FullName);
            }
            IEnumerable <PublicFolder> publicFolders = this.publicFolderDataProvider.FindPaged <PublicFolder>(filter, rootId, deepSearch, sortBy, pageSize);

            foreach (PublicFolder publicFolder in publicFolders)
            {
                PublicFolderSession contentSession = null;
                if (this.mailboxGuid == Guid.Empty)
                {
                    contentSession = this.PublicFolderDataProvider.PublicFolderSessionCache.GetPublicFolderSession(publicFolder.InternalFolderIdentity.ObjectId);
                }
                else
                {
                    contentSession = this.PublicFolderDataProvider.PublicFolderSessionCache.GetPublicFolderSession(this.mailboxGuid);
                }
                using (Folder contentFolder = Folder.Bind(contentSession, publicFolder.InternalFolderIdentity, PublicFolderStatisticsDataProvider.contentFolderProperties))
                {
                    PublicFolderStatistics publicFolderStatistics = new PublicFolderStatistics();
                    publicFolderStatistics.LoadDataFromXso(contentSession.MailboxPrincipal.ObjectId, contentFolder);
                    uint          ownerCount          = 0U;
                    uint          contactCount        = 0U;
                    PermissionSet folderPermissionSet = contentFolder.GetPermissionSet();
                    foreach (Permission permission in folderPermissionSet)
                    {
                        if (permission.IsFolderContact)
                        {
                            contactCount += 1U;
                        }
                        if (permission.IsFolderOwner)
                        {
                            ownerCount += 1U;
                        }
                    }
                    publicFolderStatistics.OwnerCount   = ownerCount;
                    publicFolderStatistics.ContactCount = contactCount;
                    StoreObjectId dumpsterId = PublicFolderCOWSession.GetRecoverableItemsDeletionsFolderId((CoreFolder)contentFolder.CoreObject);
                    checked
                    {
                        if (dumpsterId != null)
                        {
                            try
                            {
                                using (CoreFolder coreFolder = CoreFolder.Bind(contentSession, dumpsterId, PublicFolderStatisticsDataProvider.dumpsterProperties))
                                {
                                    publicFolderStatistics.DeletedItemCount     = (uint)((int)coreFolder.PropertyBag[FolderSchema.ItemCount]);
                                    publicFolderStatistics.TotalDeletedItemSize = ByteQuantifiedSize.FromBytes((ulong)((long)coreFolder.PropertyBag[FolderSchema.ExtendedSize]));
                                }
                            }
                            catch (ObjectNotFoundException)
                            {
                            }
                        }
                        yield return((T)((object)publicFolderStatistics));
                    }
                }
            }
            yield break;
        }
示例#12
0
        internal static Folder GetDefaultFolder(MailboxSession itemStore, ELCFolder elcFolder)
        {
            Folder result;

            if (elcFolder.FolderType == ElcFolderType.Inbox)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Inbox);
            }
            else if (elcFolder.FolderType == ElcFolderType.SentItems)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.SentItems);
            }
            else if (elcFolder.FolderType == ElcFolderType.DeletedItems)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.DeletedItems);
            }
            else if (elcFolder.FolderType == ElcFolderType.Calendar)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Calendar);
            }
            else if (elcFolder.FolderType == ElcFolderType.Contacts)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Contacts);
            }
            else if (elcFolder.FolderType == ElcFolderType.Drafts)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Drafts);
            }
            else if (elcFolder.FolderType == ElcFolderType.Outbox)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Outbox);
            }
            else if (elcFolder.FolderType == ElcFolderType.JunkEmail)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.JunkEmail);
            }
            else if (elcFolder.FolderType == ElcFolderType.Tasks)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Tasks);
            }
            else if (elcFolder.FolderType == ElcFolderType.Journal)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Journal);
            }
            else if (elcFolder.FolderType == ElcFolderType.Notes)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Notes);
            }
            else if (elcFolder.FolderType == ElcFolderType.All)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.Root);
            }
            else if (elcFolder.FolderType == ElcFolderType.SyncIssues)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.SyncIssues);
            }
            else if (elcFolder.FolderType == ElcFolderType.RssSubscriptions)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.RssSubscription);
            }
            else if (elcFolder.FolderType == ElcFolderType.ConversationHistory)
            {
                result = Folder.Bind(itemStore, DefaultFolderType.CommunicatorHistory);
            }
            else
            {
                if (elcFolder.FolderType != ElcFolderType.LegacyArchiveJournals)
                {
                    throw new ELCUnknownDefaultFolderException(elcFolder.FolderName, itemStore.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString());
                }
                result = Folder.Bind(itemStore, DefaultFolderType.LegacyArchiveJournals);
            }
            return(result);
        }
示例#13
0
        static void Main(string[] args)
        {
            string strAcct                 = "";
            string strTenant               = "";
            string strEmailAddr            = "";
            bool   bMailbox                = false;
            NameResolutionCollection ncCol = null;
            Folder fldCal = null;

            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].ToUpper() == "-M" || args[i].ToUpper() == "/M") // mailbox mode - use impersonation to get to another mailbox
                    {
                        if (args[i + 1].Length > 0)
                        {
                            strEmailAddr = args[i + 1];
                            bMailbox     = true;
                        }
                        else
                        {
                            Console.WriteLine("Please enter a valid SMTP address for the mailbox.");
                            ShowHelp();
                            return;
                        }
                    }
                    if (args[i].ToUpper() == "-R" || args[i].ToUpper() == "/R")
                    {
                        if (args[i + 1].Contains("@")) // checking ot see if the next param is an email address
                        {
                            Console.WriteLine("You must use the -M switch with an smtp address to connect to that mailbox.");
                            ShowHelp();
                            return;
                        }
                        else
                        {
                            bRestore = true;
                        }
                    }
                    if (args[i].ToUpper() == "-?" || args[i].ToUpper() == "/?") // display command switch help
                    {
                        ShowInfo();
                        ShowHelp();
                        return;
                    }
                }
            }

            ShowInfo();

            exService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            exService.UseDefaultCredentials = false;

            Console.Write("Press <ENTER> to enter credentials.");
            Console.ReadLine();
            Console.WriteLine();

            AuthenticationResult authResult = GetToken();

            if (authResult != null)
            {
                exService.Credentials = new OAuthCredentials(authResult.AccessToken);
                strAcct = authResult.UserInfo.DisplayableId;
            }
            else
            {
                return;
            }
            strTenant     = strAcct.Split('@')[1];
            exService.Url = new Uri(strSrvURI + "/ews/exchange.asmx");

            if (bMailbox)
            {
                ncCol = DoResolveName(strEmailAddr);
                exService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, strEmailAddr);
            }
            else
            {
                ncCol = DoResolveName(strAcct);
            }

            if (ncCol == null)
            {
                // Didn't get a NameResCollection, so error out.
                Console.WriteLine("");
                Console.WriteLine("Exiting the program.");
                return;
            }

            if (ncCol[0].Contact != null)
            {
                strDisplayName = ncCol[0].Contact.DisplayName;
                strEmailAddr   = ncCol[0].Mailbox.Address;
                if (!bRestore)
                {
                    Console.WriteLine("Backing up Calendar for " + strDisplayName);
                }
                else
                {
                    Console.WriteLine("Restoring Calendar for " + strDisplayName);
                }
            }
            else
            {
                if (!bRestore)
                {
                    Console.WriteLine("Backing up Calendar for " + strAcct);
                }
                else
                {
                    Console.WriteLine("Restoring Calendar for " + strAcct);
                }
            }

            // Get or create the backup folder...
            GetBackupFld();

            // Get or create the Restore folder
            if (bRestore)
            {
                GetRestoreFld();
            }
            else
            {
                // Get the Calendar folder
                try
                {
                    Console.WriteLine("Connecting to the Calendar.");
                    fldCal = Folder.Bind(exService, WellKnownFolderName.Calendar, new PropertySet(PropertySet.IdOnly));
                }
                catch (ServiceResponseException ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("");
                    Console.WriteLine("Could not connect to this user's mailbox or calendar.");
                    Console.WriteLine(ex.Message);
                    Console.ResetColor();
                    return;
                }
            }

            if (!bRestore)
            {
                // now go get the items and copy them to the backup folder.
                Console.WriteLine("Copying all items from Calendar to the CalBackup folder.");
                CopyItems(fldCal, fldCalBackup);

                Console.WriteLine("\r\n");
                Console.WriteLine("===============================================================");
                Console.WriteLine("Copied " + cItems.ToString() + " items to the CalBackup folder.");
                Console.WriteLine("===============================================================");
            }
            else
            {
                Console.WriteLine("Restoring items to the CalRestore folder.");
                CopyItems(fldCalBackup, fldCalRestore);

                Console.WriteLine("\r\n");
                Console.WriteLine("==================================================================");
                Console.WriteLine("Restored " + cItems.ToString() + " items to the CalRestore folder.");
                Console.WriteLine("==================================================================");
            }

            //Console.Write("Press a key to exit");
            //Console.Read();
            return;
        }
示例#14
0
 protected virtual IFolder InternalBindToCommonViewsFolder()
 {
     return(Folder.Bind((MailboxSession)this.mailboxSession, DefaultFolderType.CommonViews));
 }
        // Token: 0x060015BF RID: 5567 RVA: 0x0004DD44 File Offset: 0x0004BF44
        protected override FindFlowConversationItemResponse InternalExecute()
        {
            QueryFilter         flowConversationFilter = GetFlowConversation.GetFlowConversationFilter(this.folderId, base.MailboxIdentityMailboxSession);
            IdAndSession        folderIdAndSession     = GetFlowConversation.GetFolderIdAndSession(this.folderId, base.MailboxIdentityMailboxSession, base.IdConverter);
            SortBy              sortBy = new SortBy(ItemSchema.ReceivedTime, SortOrder.Descending);
            List <FlowItem>     list   = new List <FlowItem>();
            ConversationFactory conversationFactory = new ConversationFactory(base.MailboxIdentityMailboxSession);

            using (Folder folder = Folder.Bind((MailboxSession)folderIdAndSession.Session, folderIdAndSession.Id))
            {
                using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, flowConversationFilter, new SortBy[]
                {
                    sortBy
                }, FindFlowConversationItem.requiredProperties))
                {
                    IStorePropertyBag[] propertyBags = queryResult.GetPropertyBags(10000);
                    foreach (IStorePropertyBag storePropertyBag in propertyBags)
                    {
                        if ((long)list.Count == this.requestedItemCount)
                        {
                            break;
                        }
                        string text = this.GenerateParticipantsHash(storePropertyBag);
                        if (text.Equals(this.flowConversationId))
                        {
                            FlowItem       flowItem        = new FlowItem();
                            ExDateTime     valueOrDefault  = storePropertyBag.GetValueOrDefault <ExDateTime>(ItemSchema.ReceivedTime, ExDateTime.Now);
                            bool           valueOrDefault2 = storePropertyBag.GetValueOrDefault <bool>(MessageItemSchema.IsRead, true);
                            IParticipant   valueOrDefault3 = storePropertyBag.GetValueOrDefault <IParticipant>(ItemSchema.From, null);
                            VersionedId    valueOrDefault4 = storePropertyBag.GetValueOrDefault <VersionedId>(ItemSchema.Id, null);
                            ConversationId valueOrDefault5 = storePropertyBag.GetValueOrDefault <ConversationId>(ItemSchema.ConversationId, null);
                            flowItem.ItemId          = IdConverter.ConvertStoreItemIdToItemId(valueOrDefault4, base.MailboxIdentityMailboxSession);
                            flowItem.Sender          = FindFlowConversationItem.ConvertParticipantToEmailAddressWrapper(valueOrDefault3);
                            flowItem.IsRead          = valueOrDefault2;
                            flowItem.ReceivedTimeUtc = ExDateTimeConverter.ToSoapHeaderTimeZoneRelatedXsdDateTime(valueOrDefault);
                            Conversation key = conversationFactory.CreateConversation(valueOrDefault5, FindFlowConversationItem.ConversationCreatorRelevantProperties);
                            if (!this.conversationMap.ContainsKey(key))
                            {
                                this.conversationMap[key] = new List <StoreObjectId>();
                            }
                            this.conversationMap[key].Add(valueOrDefault4.ObjectId);
                            this.flowItemsMap[valueOrDefault4.ObjectId] = flowItem;
                            list.Add(flowItem);
                        }
                    }
                }
            }
            foreach (KeyValuePair <Conversation, List <StoreObjectId> > keyValuePair in this.conversationMap)
            {
                Conversation         key2  = keyValuePair.Key;
                List <StoreObjectId> value = keyValuePair.Value;
                key2.LoadItemParts(value);
                foreach (StoreObjectId storeObjectId in value)
                {
                    ItemPart itemPart = key2.GetItemPart(storeObjectId);
                    this.flowItemsMap[storeObjectId].ItemBody = itemPart.BodyPart;
                }
            }
            return(new FindFlowConversationItemResponse
            {
                Items = list.ToArray()
            });
        }
示例#16
0
        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);
        }
示例#17
0
        static int Main(string[] args)
        {
            // Test if input arguments were supplied:
            if (args.Length != 2)
            {
                Console.WriteLine("Please enter a config file");
                return(1);
            }
            string fileCfg = args[0];
            string fileLog = args[1];

            Logger(fileLog, "File cfg: " + fileCfg);
            Logger(fileLog, "File log: " + fileLog);

            try
            {
                StreamReader  file     = new StreamReader(@fileCfg);
                XmlSerializer reader   = new XmlSerializer(typeof(EWS_1C));
                EWS_1C        overview = (EWS_1C)reader.Deserialize(file);
                file.Close();

                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.UseDefaultCredentials = false;
                service.Credentials           = new WebCredentials(overview.Login, overview.Password, overview.Domain);
                service.Url = new Uri(overview.url);

                //service.EnableSs
                Logger(fileLog, service.Url.ToString());

                service.TraceEnabled = false;
                service.TraceFlags   = TraceFlags.All;

                // emails
                Logger(fileLog, "Писем для отправки: " + overview.emails.Length);
                for (int i = 0; i < overview.emails.Length; i++)
                {
                    EmailOut eml = overview.emails[i];
                    //System.Console.WriteLine("- Subject: " + eml.Subject);

                    EmailMessage message = new EmailMessage(service);
                    message.Subject = eml.Subject;
                    message.Body    = eml.Body;
                    for (int j = 0; j < eml.Recipient.Length; j++)
                    {
                        message.ToRecipients.Add(eml.Recipient[j]);
                    }
                    for (int j = 0; j < eml.File.Length; j++)
                    {
                        if (!String.IsNullOrEmpty(eml.File[j]))
                        {
                            message.Attachments.AddFileAttachment(eml.File[j]);
                        }
                    }

                    message.SendAndSaveCopy();
                    Logger(fileLog, "Email № " + (i + 1) + " send recipient = " + eml.Recipient.ToString());
                }

                // Bind the Inbox folder to the service object.
                Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                // The search filter to get unread email.
                //SearchFilter sf = new SearchFilter.SearchFilterCollection(
                //    LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                SearchFilter sf =
                    new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-5));

                ItemView view = new ItemView(30); //Больше 30 писем не получать

                // Fire the query for the unread items.
                // This method call results in a FindItem call to EWS.
                FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

                //var emailProps = new PropertySet(ItemSchema.MimeContent, ItemSchema.Body,
                //    ItemSchema.InternetMessageHeaders);

                var dirOut = Path.GetDirectoryName(fileCfg);
                Logger(fileLog, "dirOut = " + dirOut);

                List <EmailIn> list = new List <EmailIn>();

                Logger(fileLog, "Писем получено: " + findResults.TotalCount.ToString());
                foreach (EmailMessage i in findResults)
                {
                    //var email_ews = EmailMessage.Bind(service, i.Id, emailProps);
                    i.Load();
                    if (!i.IsRead)
                    {
                        i.IsRead = true;
                        i.Update(ConflictResolutionMode.AutoResolve);
                    }

                    var eml = new EmailIn();
                    eml.IdObj   = Guid.NewGuid().ToString();
                    eml.Subject = i.Subject;
                    eml.Body    = i.Body;
                    List <String> listRecipients = new List <String>();
                    foreach (EmailAddress ToRecipient in i.ToRecipients)
                    {
                        listRecipients.Add(ToRecipient.Name + " <" + ToRecipient.Address + ">");
                    }
                    eml.Recipient = listRecipients.ToArray();
                    eml.From      = i.From.Name + " <" + i.From.Address + ">";
                    eml.Id        = i.InternetMessageId;
                    eml.DateSend  = i.DateTimeSent;
                    Logger(fileLog, "id email: " + eml.Id);
                    Logger(fileLog, "id: " + eml.IdObj);


                    if (i.HasAttachments)
                    {
                        string dirEmail = Path.Combine(dirOut, "files", eml.IdObj);
                        if (!Directory.Exists(dirEmail))
                        {
                            Directory.CreateDirectory(dirEmail);
                        }
                        List <String> listFiles = new List <String>();
                        foreach (Attachment attachment in i.Attachments)
                        {
                            if (attachment is FileAttachment)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                string         fileEmail      = Path.Combine(dirEmail, fileAttachment.Name);
                                fileAttachment.Load(fileEmail);
                                listFiles.Add(fileEmail);
                            }
                            else
                            {
                                //Вложенные письма нам не нужны
                                //ItemAttachment itemAttachment = attachment as ItemAttachment;
                                //itemAttachment.Load();
                            }
                        }

                        eml.File = listFiles.ToArray();
                    }

                    list.Add(eml);
                }

                var outData = new Messages();
                outData.emails = list.ToArray();

                var writer = new System.Xml.Serialization.XmlSerializer(typeof(Messages));
                var wfile  = new System.IO.StreamWriter(@dirOut + "\\messages.xml");
                writer.Serialize(wfile, outData);
                wfile.Close();


                Logger(fileLog, "Done!");
            }
            catch (Exception e)
            {
                Logger(fileLog, e.Message);
            }

            return(0);
        }
示例#18
0
        public bool Upgrade(StoreObjectId storeId, Dictionary <string, CommonNode> items, Dictionary <string, string> mapping, List <TagNode> tags, StoreObjectType type, string synckeyIn, string shortParentId, int nextShortId, uint version)
        {
            if (storeId == null)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.TiUpgradeTracer, this, "Input to TiSyncUpgrade.Upgrade is null: field storeId");
                throw new ArgumentNullException("storeId");
            }
            if (items == null)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.TiUpgradeTracer, this, "Input to TiSyncUpgrade.Upgrade is null: field items");
                throw new ArgumentNullException("items");
            }
            if (mapping == null)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.TiUpgradeTracer, this, "Input to TiSyncUpgrade.Upgrade is null: field mapping");
                throw new ArgumentNullException("mapping");
            }
            if (tags == null)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.TiUpgradeTracer, this, "Input to TiSyncUpgrade.Upgrade is null: field tags");
                throw new ArgumentNullException("tags");
            }
            if (synckeyIn == null)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.TiUpgradeTracer, this, "Input to TiSyncUpgrade.Upgrade is null: field synckeyIn");
                throw new ArgumentNullException("synckeyIn");
            }
            if (shortParentId == null && mapping.Count > 0)
            {
                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.TiUpgradeTracer, this, "Input to TiSyncUpgrade.Upgrade is null: field shortParentId, and mapping.Count > 0");
                throw new ArgumentNullException("shortParentId");
            }
            Dictionary <StoreObjectId, string> dictionary = new Dictionary <StoreObjectId, string>();

            this.storeId = storeId;
            try
            {
                this.LoadE12SyncState(storeId, shortParentId, nextShortId);
                Folder sourceFolder = null;
                try
                {
                    sourceFolder = Folder.Bind(this.mailboxSession, storeId, null);
                }
                catch (ObjectNotFoundException)
                {
                    return(false);
                }
                if (!TiSyncUpgrade.ParseSupportedTags((int)version, tags, type))
                {
                    return(false);
                }
                Dictionary <string, CommonNode> items2 = new Dictionary <string, CommonNode>(items);
                ItemSyncUpgrade itemSyncUpgrade        = new ItemSyncUpgrade();
                dictionary = itemSyncUpgrade.Upgrade(this.syncState, items, sourceFolder, this.mailboxSession);
                if (dictionary == null)
                {
                    return(false);
                }
                DateTimeCustomSyncFilter dateTimeFilter = new DateTimeCustomSyncFilter(this.syncState);
                this.UpdateFilter(dictionary, dateTimeFilter, items2);
                this.UpdateMapping(dictionary, mapping);
                this.syncState[CustomStateDatumType.AirSyncProtocolVersion] = new Int32Data((int)version);
                ((ItemIdMapping)this.syncState[CustomStateDatumType.IdMapping]).CommitChanges();
                string text = synckeyIn;
                int    num  = text.LastIndexOf("}");
                if (num >= 0)
                {
                    text = text.Substring(num + 1, text.Length - num - 1);
                }
                uint data = (uint)int.Parse(text, CultureInfo.InvariantCulture);
                this.syncState[CustomStateDatumType.SyncKey] = new UInt32Data(data);
                this.syncState.Commit();
            }
            finally
            {
                if (this.syncState != null)
                {
                    this.syncState.Dispose();
                }
            }
            return(true);
        }
示例#19
0
        // Token: 0x06000220 RID: 544 RVA: 0x00007D80 File Offset: 0x00005F80
        public static bool RemoveFolder(AnchorContext context, MailboxSession mailboxSession, string folderName)
        {
            StoreObjectId defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Root);
            StoreObjectId folderId        = AnchorFolder.GetFolderId(context, mailboxSession, defaultFolderId, folderName);

            if (folderId == null)
            {
                context.Logger.Log(MigrationEventType.Verbose, "couldn't find folder with name {0} treating as success", new object[]
                {
                    folderName
                });
                return(true);
            }
            using (Folder folder = Folder.Bind(mailboxSession, folderId, AnchorFolder.FolderIdPropertyDefinition))
            {
                context.Logger.Log(MigrationEventType.Information, "About to remove all messages & subfolders from {0} with id {1}", new object[]
                {
                    folderName,
                    folderId
                });
                GroupOperationResult groupOperationResult = folder.DeleteAllObjects(DeleteItemFlags.HardDelete, true);
                if (groupOperationResult.OperationResult != OperationResult.Succeeded)
                {
                    context.Logger.Log(MigrationEventType.Warning, "unsuccessfully removed messages & subfolders from {0} with id {1} with result {2}", new object[]
                    {
                        folderName,
                        folderId,
                        groupOperationResult
                    });
                    return(false);
                }
            }
            bool result;

            using (Folder folder2 = Folder.Bind(mailboxSession, defaultFolderId))
            {
                context.Logger.Log(MigrationEventType.Information, "About to remove folder {0} with id {1}", new object[]
                {
                    folderName,
                    folderId
                });
                AggregateOperationResult aggregateOperationResult = folder2.DeleteObjects(DeleteItemFlags.HardDelete, new StoreId[]
                {
                    folderId
                });
                if (aggregateOperationResult.OperationResult != OperationResult.Succeeded)
                {
                    context.Logger.Log(MigrationEventType.Warning, "unsuccessfully removed folder {0} with id {1} with result {2}", new object[]
                    {
                        folderName,
                        folderId,
                        aggregateOperationResult
                    });
                    result = false;
                }
                else
                {
                    result = true;
                }
            }
            return(result);
        }
        // Token: 0x0600022B RID: 555 RVA: 0x0001416C File Offset: 0x0001236C
        public static ItemOperations.Result GetNextViewItem(UserContext userContext, ItemOperations.Action action, StoreObjectId itemId, StoreObjectId folderId)
        {
            Folder folder = null;

            ItemOperations.Result result;
            try
            {
                MessageModuleSearchViewState messageModuleSearchViewState = userContext.LastClientViewState as MessageModuleSearchViewState;
                SortBy[] sortOrder;
                if (messageModuleSearchViewState != null)
                {
                    using (Folder folder2 = Folder.Bind(userContext.MailboxSession, messageModuleSearchViewState.FolderId))
                    {
                        sortOrder = ItemOperations.GetSortOrder(userContext, folder2);
                        FolderSearch folderSearch = new FolderSearch();
                        folder = folderSearch.Execute(userContext, folder2, messageModuleSearchViewState.SearchScope, messageModuleSearchViewState.SearchString, userContext.ForceNewSearch, false);
                        userContext.ForceNewSearch = false;
                        goto IL_77;
                    }
                }
                folder    = Folder.Bind(userContext.MailboxSession, folderId);
                sortOrder = ItemOperations.GetSortOrder(userContext, folder);
IL_77:
                using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, null, sortOrder, new PropertyDefinition[]
                {
                    ItemSchema.Id
                }))
                {
                    queryResult.SeekToCondition(SeekReference.OriginBeginning, new ComparisonFilter(ComparisonOperator.Equal, ItemSchema.Id, itemId));
                    int num  = queryResult.CurrentRow;
                    int num2 = queryResult.EstimatedRowCount;
                    int num3 = 0;
                    if (num == num2 || num2 == 1)
                    {
                        result = null;
                    }
                    else
                    {
                        switch (action)
                        {
                        case ItemOperations.Action.Next:
                            if (num + 1 == num2)
                            {
                                return(null);
                            }
                            num3 = queryResult.SeekToOffset(SeekReference.OriginCurrent, 1);
                            break;

                        case ItemOperations.Action.Prev:
                            if (num == 0)
                            {
                                return(null);
                            }
                            num3 = queryResult.SeekToOffset(SeekReference.OriginCurrent, -1);
                            break;

                        case ItemOperations.Action.Delete:
                            if (userContext.UserOptions.NextSelection == NextSelectionDirection.Previous)
                            {
                                if (num == 0)
                                {
                                    num3 = queryResult.SeekToOffset(SeekReference.OriginCurrent, 1);
                                    num3 = 0;
                                }
                                else
                                {
                                    num3 = queryResult.SeekToOffset(SeekReference.OriginCurrent, -1);
                                }
                            }
                            else if (userContext.UserOptions.NextSelection == NextSelectionDirection.Next)
                            {
                                if (num2 - (num + 1) == 0)
                                {
                                    num3 = queryResult.SeekToOffset(SeekReference.OriginCurrent, -1);
                                }
                                else
                                {
                                    num3 = queryResult.SeekToOffset(SeekReference.OriginCurrent, 1);
                                    num3 = 0;
                                }
                            }
                            else if (userContext.UserOptions.NextSelection == NextSelectionDirection.ReturnToView)
                            {
                                return(null);
                            }
                            num2--;
                            break;
                        }
                        num += num3;
                        if (messageModuleSearchViewState != null)
                        {
                            messageModuleSearchViewState.PageNumber = num / userContext.UserOptions.BasicViewRowCount + 1;
                        }
                        else
                        {
                            ListViewViewState listViewViewState = userContext.LastClientViewState as ListViewViewState;
                            if (listViewViewState != null && folderId.Equals(listViewViewState.FolderId))
                            {
                                listViewViewState.PageNumber = num / userContext.UserOptions.BasicViewRowCount + 1;
                            }
                        }
                        object[][] rows = queryResult.GetRows(1);
                        result = new ItemOperations.Result(((VersionedId)rows[0][0]).ObjectId, folderId);
                    }
                }
            }
            catch (ObjectNotFoundException)
            {
                result = null;
            }
            finally
            {
                if (folder != null)
                {
                    folder.Dispose();
                }
            }
            return(result);
        }
示例#21
0
        // Token: 0x06001A60 RID: 6752 RVA: 0x000613C0 File Offset: 0x0005F5C0
        private void GetAttachmentsFromEwsFolder(BaseFolderId baseFolderId, ModernAttachmentGroup outGroup)
        {
            if (baseFolderId == null || outGroup == null)
            {
                return;
            }
            string folderIdDisplayName = GetModernAttachmentsCommand.Utilities.GetFolderIdDisplayName(baseFolderId);

            try
            {
                IdAndSession idAndSession = base.IdConverter.ConvertFolderIdToIdAndSessionReadOnly(baseFolderId);
                ExDateTime   now          = ExDateTime.Now;
                using (Folder folder = Folder.Bind(idAndSession.Session, idAndSession.Id))
                {
                    List <ModernAttachment> list = new List <ModernAttachment>(0);
                    SortBy[]    sortColumns      = this.BuildSortBy();
                    QueryFilter queryFilter      = this.BuildQueryFilter();
                    using (QueryResult queryResult = folder.ItemQuery(ItemQueryType.None, queryFilter, sortColumns, GetModernAttachmentsCommand.findItemsQueryPropDefs))
                    {
                        int        itemsOffset = this.request.ItemsOffset;
                        int        num         = this.request.ItemsToProcessMax;
                        int        num2        = itemsOffset + num + 1;
                        object[][] rows        = queryResult.GetRows(num2 - 1);
                        this.perfFindItemsDuration = ExDateTime.Now - now;
                        now = ExDateTime.Now;
                        outGroup.ItemsTotal = rows.Length;
                        if (itemsOffset >= rows.Length)
                        {
                            return;
                        }
                        if (num2 > rows.Length)
                        {
                            num2 = rows.Length;
                        }
                        outGroup.ItemsOffsetNext   = num2;
                        outGroup.RetrievedLastItem = (num2 == rows.Length);
                        if (rows != null && rows.Length > 0)
                        {
                            this.perfItemsFoundCount += rows.Length;
                            for (int i = itemsOffset; i < num2; i++)
                            {
                                object[] array   = rows[i];
                                StoreId  storeId = (StoreId)array[0];
                                this.GetAttachmentsFromItemByStoreId(idAndSession.Session, storeId, list);
                                outGroup.ItemsProcessed++;
                            }
                        }
                        outGroup.AttachmentsReturned = this.perfAttachmentCount;
                        this.perfBindItemsDuration   = ExDateTime.Now - now;
                        outGroup.AttachmentGroup     = list.ToArray();
                    }
                    outGroup.Path = new string[]
                    {
                        GetModernAttachmentsCommand.Utilities.FormatParam("folderId.DisplayName", folderIdDisplayName),
                        GetModernAttachmentsCommand.Utilities.FormatParam("folder.ClassName", folder.ClassName),
                        GetModernAttachmentsCommand.Utilities.FormatParam("folder.DisplayName", folder.DisplayName),
                        GetModernAttachmentsCommand.Utilities.FormatParam("perfItemsFoundCount", this.perfItemsFoundCount),
                        GetModernAttachmentsCommand.Utilities.FormatParam("perfItemsBoundCount", this.perfItemsBoundCount),
                        GetModernAttachmentsCommand.Utilities.FormatParam("perfAttachmentsEnumeratedCount", this.perfAttachmentsEnumeratedCount),
                        GetModernAttachmentsCommand.Utilities.FormatParam("perfAttachmentCount", this.perfAttachmentCount),
                        GetModernAttachmentsCommand.Utilities.FormatParam("perfFindItemsDuration", this.perfFindItemsDuration),
                        GetModernAttachmentsCommand.Utilities.FormatParam("perfBindItemsDuration", this.perfBindItemsDuration)
                    };
                }
            }
            catch (Exception exception)
            {
                StructuredErrors structuredErrors = this.ConvertToNestedErrors(exception);
                structuredErrors.Path = new string[]
                {
                    "GetAttachmentsFromEwsFolder",
                    GetModernAttachmentsCommand.Utilities.FormatParam("folderId.DisplayName", folderIdDisplayName),
                    GetModernAttachmentsCommand.Utilities.FormatParam("folderId.DisplayName", folderIdDisplayName),
                    GetModernAttachmentsCommand.Utilities.FormatParam("perfItemsFoundCount", this.perfItemsFoundCount),
                    GetModernAttachmentsCommand.Utilities.FormatParam("perfItemsBoundCount", this.perfItemsBoundCount),
                    GetModernAttachmentsCommand.Utilities.FormatParam("perfAttachmentsEnumeratedCount", this.perfAttachmentsEnumeratedCount),
                    GetModernAttachmentsCommand.Utilities.FormatParam("perfAttachmentCount", this.perfAttachmentCount),
                    GetModernAttachmentsCommand.Utilities.FormatParam("perfFindItemsDuration", this.perfFindItemsDuration),
                    GetModernAttachmentsCommand.Utilities.FormatParam("perfBindItemsDuration", this.perfBindItemsDuration)
                };
                this.response.AddError(structuredErrors);
            }
        }
        // Token: 0x06000C83 RID: 3203 RVA: 0x00042C38 File Offset: 0x00040E38
        public void Execute()
        {
            Folder folder = null;

            try
            {
                folder = Folder.Bind(this.mailboxSession, this.mailboxSession.GetDefaultFolderId(DefaultFolderType.SearchFolders));
                string text = "EAS Search Device:" + this.context.Request.DeviceIdentity.DeviceId;
                bool   flag = !this.forceResetSearchCriteria;
                AirSyncDiagnostics.TraceDebug <bool>(ExTraceGlobals.AlgorithmTracer, this, "reuseExistingSearchFolderCriteria = !this.forceResetSearchCriteria, therefore reuseExistingSearchFolderCriteria = {0}", flag);
                if (this.queryFilter != null)
                {
                    StoreObjectId storeObjectId = null;
                    using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.None, null, MailboxSearchProvider.displayNameSortBy, new PropertyDefinition[]
                    {
                        FolderSchema.Id,
                        StoreObjectSchema.DisplayName
                    }))
                    {
                        QueryFilter seekFilter = new ComparisonFilter(ComparisonOperator.Equal, StoreObjectSchema.DisplayName, text);
                        if (queryResult.SeekToCondition(SeekReference.OriginBeginning, seekFilter))
                        {
                            object[][] rows = queryResult.GetRows(1);
                            storeObjectId = ((VersionedId)rows[0][0]).ObjectId;
                        }
                    }
                    SearchFolderCriteria searchFolderCriteria = null;
                    if (storeObjectId != null)
                    {
                        this.searchFolder = SearchFolder.Bind(this.mailboxSession, storeObjectId, new PropertyDefinition[]
                        {
                            MailboxSearchProvider.SearchFolderTextDescription,
                            FolderSchema.ItemCount,
                            FolderSchema.UnreadCount,
                            FolderSchema.SearchFolderItemCount
                        });
                        try
                        {
                            searchFolderCriteria = this.searchFolder.GetSearchCriteria();
                            AirSyncDiagnostics.TraceDebug <SearchFolderCriteria>(ExTraceGlobals.AlgorithmTracer, this, "Existing search folder has search criteria {0}", searchFolderCriteria);
                        }
                        catch (StoragePermanentException)
                        {
                            flag = false;
                            AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "GetSearchCriteria() threw StoragePermanentException due to a pre-existing restriction on the search folder.  This condition is expected and handled.");
                        }
                        catch (ArgumentException)
                        {
                            flag = false;
                            AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "GetSearchCriteria() threw ArgumentException due to a pre-existing restriction on the search folder.  This condition is expected and handled.");
                        }
                        catch (ObjectNotInitializedException)
                        {
                            flag = false;
                            AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "Search folder has null search criteria, reuseExistingSearchFolderCriteria = false;");
                        }
                        if (flag)
                        {
                            if (searchFolderCriteria.FolderScope == null || searchFolderCriteria.FolderScope.Length != this.folderScope.Length)
                            {
                                if (searchFolderCriteria.FolderScope == null)
                                {
                                    AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "searchCriteria.FolderScope is null.");
                                }
                                else
                                {
                                    AirSyncDiagnostics.TraceDebug <int>(ExTraceGlobals.AlgorithmTracer, this, "searchCriteria.FolderScope is not null and searchCriteria.FolderScope.Length is {0}", searchFolderCriteria.FolderScope.Length);
                                }
                                flag = false;
                                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "therefore reuseExistingSearchFolderCriteria = false");
                            }
                            else
                            {
                                for (int i = 0; i < this.folderScope.Length; i++)
                                {
                                    bool flag2 = false;
                                    for (int j = 0; j < searchFolderCriteria.FolderScope.Length; j++)
                                    {
                                        if (searchFolderCriteria.FolderScope[j].Equals(this.folderScope[i]))
                                        {
                                            flag2 = true;
                                            break;
                                        }
                                    }
                                    if (!flag2)
                                    {
                                        flag = false;
                                        AirSyncDiagnostics.TraceDebug <StoreId>(ExTraceGlobals.AlgorithmTracer, this, "foundIt == false for this.folderScope[idx1] == {0}, therefore reuseExistingSearchFolderCriteria = false", this.folderScope[i]);
                                        break;
                                    }
                                    AirSyncDiagnostics.TraceDebug <StoreId, bool>(ExTraceGlobals.AlgorithmTracer, this, "foundIt == true for this.folderScope[idx1] == {0}, therefore reuseExistingSearchFolderCriteria stays at value: {1}", this.folderScope[i], flag);
                                }
                            }
                        }
                        if (flag)
                        {
                            string text2 = this.searchFolder.TryGetProperty(MailboxSearchProvider.SearchFolderTextDescription) as string;
                            if (searchFolderCriteria.SearchQuery == null)
                            {
                                AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "searchCriteria.SearchQuery == null, therefore reuseExistingSearchFolderCriteria = false");
                                flag = false;
                            }
                            else if (text2 != this.queryFilter.ToString())
                            {
                                AirSyncDiagnostics.TraceDebug <string, QueryFilter>(ExTraceGlobals.AlgorithmTracer, this, "oldSearchFilter == {0}, and this.queryFilter.ToString() == {1}, therefore reuseExistingSearchFolderCriteria = false", text2, this.queryFilter);
                                flag = false;
                            }
                            else if (searchFolderCriteria.DeepTraversal != this.deepTraversal)
                            {
                                AirSyncDiagnostics.TraceDebug <bool, bool>(ExTraceGlobals.AlgorithmTracer, this, "searchCriteria.DeepTraversal == {0}, and this.deepTraversal == {1}, therefore reuseExistingSearchFolderCriteria = false", searchFolderCriteria.DeepTraversal, this.deepTraversal);
                                flag = false;
                            }
                        }
                    }
                    else
                    {
                        this.searchFolder = SearchFolder.Create(this.mailboxSession, folder.Id.ObjectId, text, CreateMode.OpenIfExists);
                        AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.AlgorithmTracer, this, "Created a new search folder with display name: {0}", text);
                        this.searchFolder.Save();
                        this.searchFolder.Load(new PropertyDefinition[]
                        {
                            FolderSchema.ItemCount,
                            FolderSchema.UnreadCount,
                            FolderSchema.SearchFolderItemCount
                        });
                        flag = false;
                        AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "Search folder was just recreated, therefore reuseExistingSearchFolderCriteria = false");
                    }
                    if (!flag)
                    {
                        searchFolderCriteria = new SearchFolderCriteria(this.queryFilter, this.folderScope);
                        searchFolderCriteria.DeepTraversal       = this.deepTraversal;
                        searchFolderCriteria.MaximumResultsCount = new int?(GlobalSettings.MaxMailboxSearchResults);
                        AirSyncDiagnostics.TraceDebug <QueryFilter, int, bool>(ExTraceGlobals.AlgorithmTracer, this, "Created search criteria on search folder with queryFilter=={0}, folderScope.Length=={1}, deepTraversal=={2}", this.queryFilter, this.folderScope.Length, this.deepTraversal);
                        Stopwatch    stopwatch           = Stopwatch.StartNew();
                        IAsyncResult asyncResult         = this.searchFolder.BeginApplyOneTimeSearch(searchFolderCriteria, null, null);
                        int          millisecondsTimeout = this.mailboxSession.Mailbox.IsContentIndexingEnabled ? this.maximumSearchTime : this.maximumSearchTimeNoContentIndexing;
                        bool         flag3 = asyncResult.AsyncWaitHandle.WaitOne(millisecondsTimeout, false);
                        stopwatch.Stop();
                        Command.CurrentCommand.Context.ProtocolLogger.SetValue(ProtocolLoggerData.SearchQueryTime, (int)stopwatch.ElapsedMilliseconds);
                        if (!flag3)
                        {
                            AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "MailboxSearchProvider.Execute. Search timed out.");
                            throw new SearchTimeOutException();
                        }
                        this.searchFolder[MailboxSearchProvider.SearchFolderTextDescription] = ((this.queryFilter == null) ? "null" : this.queryFilter.ToString());
                        this.searchFolder.EndApplyOneTimeSearch(asyncResult);
                        this.searchFolder.Save();
                        this.searchFolder.Load(new PropertyDefinition[]
                        {
                            FolderSchema.ItemCount,
                            FolderSchema.UnreadCount,
                            FolderSchema.SearchFolderItemCount
                        });
                    }
                }
            }
            catch (SearchTimeOutException)
            {
                throw;
            }
            catch (Exception innerException)
            {
                throw new AirSyncPermanentException(StatusCode.Sync_InvalidSyncKey, innerException, false)
                      {
                          ErrorStringForProtocolLogger = "GeneralMbxSearchError"
                      };
            }
            finally
            {
                if (this.folderIdMappingSyncState != null)
                {
                    this.folderIdMappingSyncState.Dispose();
                }
                this.folderIdMappingSyncState = null;
                if (folder != null)
                {
                    folder.Dispose();
                }
                folder = null;
            }
        }
示例#23
0
        protected override IEnumerable <KeyValuePair <string, string> > InternalGetEventDetails()
        {
            foreach (KeyValuePair <string, string> detail in base.InternalGetEventDetails())
            {
                yield return(detail);
            }
            if (base.COWSettings.CurrentFolderId != null)
            {
                yield return(new KeyValuePair <string, string>("FolderId", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    base.COWSettings.CurrentFolderId
                })));

                FolderAuditInfo currentFolder;
                if (this.parentFolders.TryGetValue(base.COWSettings.CurrentFolderId, out currentFolder))
                {
                    yield return(new KeyValuePair <string, string>("FolderPathName", currentFolder.PathName));
                }
                else
                {
                    string folderPathName = base.GetCurrentFolderPathName();
                    if (folderPathName != null)
                    {
                        yield return(new KeyValuePair <string, string>("FolderPathName", folderPathName));
                    }
                }
            }
            bool crossMailbox = this.destinationSession != null && base.MailboxSession != this.destinationSession;

            yield return(new KeyValuePair <string, string>("CrossMailboxOperation", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
            {
                crossMailbox
            })));

            MailboxSession destinationMailboxSession = base.MailboxSession;

            if (crossMailbox && this.destinationSession is MailboxSession)
            {
                destinationMailboxSession = (this.destinationSession as MailboxSession);
                yield return(new KeyValuePair <string, string>("DestMailboxGuid", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    destinationMailboxSession.MailboxOwner.MailboxInfo.MailboxGuid
                })));

                yield return(new KeyValuePair <string, string>("DestMailboxOwnerUPN", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    destinationMailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress
                })));

                if (destinationMailboxSession.MailboxOwner.Sid != null)
                {
                    yield return(new KeyValuePair <string, string>("DestMailboxOwnerSid", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                    {
                        destinationMailboxSession.MailboxOwner.Sid
                    })));

                    if (destinationMailboxSession.MailboxOwner.MasterAccountSid != null)
                    {
                        yield return(new KeyValuePair <string, string>("DestMailboxOwnerMasterAccountSid", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                        {
                            destinationMailboxSession.MailboxOwner.MasterAccountSid
                        })));
                    }
                }
            }
            if (this.destinationFolderId != null)
            {
                yield return(new KeyValuePair <string, string>("DestFolderId", string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    this.destinationFolderId
                })));

                string    folderPathName2 = null;
                Exception exception       = null;
                try
                {
                    using (Folder folder2 = Folder.Bind(destinationMailboxSession, this.destinationFolderId, new PropertyDefinition[]
                    {
                        FolderSchema.FolderPathName
                    }))
                    {
                        if (folder2 != null)
                        {
                            folderPathName2 = (folder2.TryGetProperty(FolderSchema.FolderPathName) as string);
                            if (folderPathName2 != null)
                            {
                                folderPathName2 = folderPathName2.Replace(COWSettings.StoreIdSeparator, '\\');
                            }
                        }
                    }
                }
                catch (StorageTransientException ex)
                {
                    exception = ex;
                }
                catch (StoragePermanentException ex2)
                {
                    exception = ex2;
                }
                if (exception != null)
                {
                    ExTraceGlobals.SessionTracer.TraceError <StoreObjectId, Exception>((long)base.MailboxSession.GetHashCode(), "[GroupOperationAuditEvent::ToString] failed to get FolderPathName property of destination folder {0}. Exception: {1}", this.destinationFolderId, exception);
                }
                if (folderPathName2 != null)
                {
                    yield return(new KeyValuePair <string, string>("DestFolderPathName", folderPathName2));
                }
            }
            int folderCount = 0;

            foreach (KeyValuePair <StoreObjectId, FolderAuditInfo> folder in this.folderAuditInfo)
            {
                KeyValuePair <StoreObjectId, FolderAuditInfo> keyValuePair = folder;
                StoreObjectId folderId = keyValuePair.Key;
                KeyValuePair <StoreObjectId, FolderAuditInfo> keyValuePair2 = folder;
                FolderAuditInfo folderInfo = keyValuePair2.Value;
                if (base.COWSettings.CurrentFolderId == null || !folderId.Equals(base.COWSettings.CurrentFolderId))
                {
                    yield return(new KeyValuePair <string, string>(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[]
                    {
                        folderCount,
                        ".SourceFolderId"
                    }), string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                    {
                        folderId
                    })));

                    if (folderInfo.PathName != null)
                    {
                        yield return(new KeyValuePair <string, string>(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[]
                        {
                            folderCount,
                            ".SourceFolderPathName"
                        }), folderInfo.PathName));
                    }
                    folderCount++;
                }
            }
            int itemCount = 0;

            foreach (KeyValuePair <StoreObjectId, ItemAuditInfo> item in this.itemAuditInfo)
            {
                KeyValuePair <StoreObjectId, ItemAuditInfo> keyValuePair3 = item;
                StoreObjectId itemId = keyValuePair3.Key;
                KeyValuePair <StoreObjectId, ItemAuditInfo> keyValuePair4 = item;
                ItemAuditInfo itemInfo = keyValuePair4.Value;
                yield return(new KeyValuePair <string, string>(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[]
                {
                    itemCount,
                    ".SourceItemId"
                }), string.Format(CultureInfo.InvariantCulture, "{0}", new object[]
                {
                    itemId
                })));

                if (itemInfo.Subject != null)
                {
                    yield return(new KeyValuePair <string, string>(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[]
                    {
                        itemCount,
                        ".SourceItemSubject"
                    }), itemInfo.Subject));
                }
                FolderAuditInfo folderInfo2;
                if (itemInfo.ParentFolderId != null && this.parentFolders.TryGetValue(itemInfo.ParentFolderId, out folderInfo2))
                {
                    yield return(new KeyValuePair <string, string>(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", new object[]
                    {
                        itemCount,
                        ".SourceItemFolderPathName"
                    }), folderInfo2.PathName));
                }
                itemCount++;
            }
            yield break;
        }
        // Token: 0x06000C86 RID: 3206 RVA: 0x00043324 File Offset: 0x00041524
        public void ParseQueryNode(XmlElement queryNode)
        {
            this.searchCriteriaBuilder = new MailboxSearchCriteriaBuilder(this.context.Request.Culture);
            if (!this.mailboxSession.Mailbox.IsContentIndexingEnabled)
            {
                AirSyncDiagnostics.LogPeriodicEvent(AirSyncEventLogConstants.Tuple_ContentIndexingNotEnabled, "ContentIndexingNotEnabled", new string[]
                {
                    this.mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn
                });
            }
            this.queryFilter = this.searchCriteriaBuilder.ParseTopLevelClassAndFolders(queryNode, this.mailboxSession.Mailbox.IsContentIndexingEnabled, this.versionFactory, this.context);
            this.schemaCache = this.searchCriteriaBuilder.SchemaCache;
            if (this.FolderIdMappingSyncState == null || !this.FolderIdMappingSyncState.Contains(CustomStateDatumType.FullFolderTree))
            {
                AirSyncDiagnostics.TraceDebug <string>(ExTraceGlobals.AlgorithmTracer, this, "FolderIdMappingSyncState error: {0}", (this.FolderIdMappingSyncState != null) ? "no FullFolderTree" : "FolderIdMappingSyncState is null");
                throw new SearchNeedToFolderSyncException();
            }
            List <string>   list            = this.searchCriteriaBuilder.FolderScope;
            FolderIdMapping folderIdMapping = (FolderIdMapping)this.FolderIdMappingSyncState[CustomStateDatumType.IdMapping];
            FolderTree      folderTree      = (FolderTree)this.FolderIdMappingSyncState[CustomStateDatumType.FullFolderTree];

            if (list.Count == 0)
            {
                this.folderScope = new StoreId[]
                {
                    this.mailboxSession.GetDefaultFolderId(DefaultFolderType.Root)
                };
            }
            else
            {
                int num = 0;
                this.folderScope = new StoreId[list.Count];
                foreach (string text in list)
                {
                    StoreObjectId storeObjectId = null;
                    if (text == "0")
                    {
                        storeObjectId = this.mailboxSession.GetDefaultFolderId(DefaultFolderType.Root);
                    }
                    else
                    {
                        SyncCollection.CollectionTypes collectionType = AirSyncUtility.GetCollectionType(text);
                        if (collectionType != SyncCollection.CollectionTypes.Mailbox && collectionType != SyncCollection.CollectionTypes.Unknown)
                        {
                            throw new AirSyncPermanentException(StatusCode.InvalidCombinationOfIDs, false)
                                  {
                                      ErrorStringForProtocolLogger = "BadIdComboInMbxSearch"
                                  };
                        }
                        MailboxSyncItemId mailboxSyncItemId = folderIdMapping[text] as MailboxSyncItemId;
                        if (mailboxSyncItemId != null)
                        {
                            if (folderTree.IsSharedFolder(mailboxSyncItemId))
                            {
                                throw new AirSyncPermanentException(StatusCode.Sync_InvalidParameters, false)
                                      {
                                          ErrorStringForProtocolLogger = "AccessDeniedInMbxSearch"
                                      };
                            }
                            storeObjectId = (StoreObjectId)mailboxSyncItemId.NativeId;
                        }
                    }
                    if (storeObjectId == null)
                    {
                        throw new SearchNeedToFolderSyncException();
                    }
                    try
                    {
                        using (Folder.Bind(this.mailboxSession, storeObjectId))
                        {
                        }
                    }
                    catch (ObjectNotFoundException)
                    {
                        throw new SearchNeedToFolderSyncException();
                    }
                    this.folderScope[num++] = storeObjectId;
                }
            }
            foreach (object obj in folderTree)
            {
                ISyncItemId       syncItemId         = (ISyncItemId)obj;
                MailboxSyncItemId mailboxSyncItemId2 = syncItemId as MailboxSyncItemId;
                if (mailboxSyncItemId2 != null && (folderTree.IsHidden(syncItemId) || folderTree.IsSharedFolder(syncItemId)))
                {
                    this.searchCriteriaBuilder.ExcludedFolders.Add((StoreObjectId)mailboxSyncItemId2.NativeId);
                }
            }
            if (this.mailboxSchemaOptions.HasBodyPartPreferences)
            {
                if (this.searchCriteriaBuilder.Conversation == null)
                {
                    AirSyncDiagnostics.TraceDebug(ExTraceGlobals.AlgorithmTracer, this, "<BodyPartPreference> is only supported when search for ConversationId");
                    throw new AirSyncPermanentException(StatusCode.Sync_ObjectNotFound, false)
                          {
                              ErrorStringForProtocolLogger = "BodyPartNotSupported"
                          };
                }
                this.searchCriteriaBuilder.Conversation.LoadBodySummaries();
            }
        }
示例#25
0
        public static int Unread()
        {
            ServicePointManager.ServerCertificateValidationCallback =
                delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                // Replace this line with code to validate server certificate.
                return(true);
            };

            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);

            if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange))
            {
                service.AutodiscoverUrl(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, (string redirectionUrl) => { return(true); });
            }
            else
            {
                service.Url = new Uri("https://" + HAP.Web.Configuration.hapConfig.Current.SMTP.Exchange + "/ews/exchange.asmx");
            }
            HAP.AD.User u = ((HAP.AD.User)Membership.GetUser());
            if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Forms && string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser))
            {
                HttpCookie token = HttpContext.Current.Request.Cookies["token"];
                if (token == null)
                {
                    throw new AccessViolationException("Token Cookie Missing, user not logged in correctly");
                }
                service.Credentials = new NetworkCredential((hapConfig.Current.SMTP.EWSUseEmailoverAN ? u.Email : u.UserName), TokenGenerator.ConvertToPlain(token.Value), HAP.Web.Configuration.hapConfig.Current.AD.UPN);
            }
            else
            {
                if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser))
                {
                    u.ImpersonateContained();
                    service.UseDefaultCredentials = true;
                    //service.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    if (string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain))
                    {
                        service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword);
                    }
                    else
                    {
                        service.Credentials = new WebCredentials(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationPassword, HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationDomain);
                    }

                    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, u.Email);
                }
            }

            Folder                  inbox       = Folder.Bind(service, WellKnownFolderName.Inbox);
            SearchFilter            sf          = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            ItemView                view        = new ItemView(10);
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

            if (HAP.Web.Configuration.hapConfig.Current.AD.AuthenticationMode == Configuration.AuthMode.Windows || !string.IsNullOrEmpty(HAP.Web.Configuration.hapConfig.Current.SMTP.ImpersonationUser))
            {
                u.EndContainedImpersonate();
            }
            return(findResults.TotalCount);
        }
        public override void PerformBatchOperation(object[][] batchedItemBuffer, int fetchedItemCount, StoreId currentFolderId, MailboxSession sourceMailbox, MailboxSession targetMailbox, Dictionary <StoreId, FolderNode> folderNodeMap, SearchResultProcessor processor)
        {
            processor.CheckTargetMailboxAvailableSpace();
            StoreId[] array = new StoreId[fetchedItemCount];
            for (int i = 0; i < fetchedItemCount; i++)
            {
                array[i] = (StoreId)batchedItemBuffer[i][0];
            }
            FolderNode folderNode = folderNodeMap[currentFolderId];

            using (Folder folder = Folder.Bind(sourceMailbox, currentFolderId))
            {
                processor.BackOffFromSourceStore();
                processor.BackOffFromTargetStore();
                try
                {
                    GroupOperationResult groupOperationResult = null;
                    lock (targetMailbox)
                    {
                        if (processor.IsAborted())
                        {
                            return;
                        }
                        if (folderNode.TargetFolderId == null)
                        {
                            this.CreateTargetFolder(targetMailbox, folderNode);
                        }
                        groupOperationResult = folder.CopyItems(targetMailbox, folderNode.TargetFolderId, false, array);
                    }
                    if (groupOperationResult.OperationResult != OperationResult.Succeeded)
                    {
                        SearchMailboxAction.Tracer.TraceError <OperationResult, LocalizedException>((long)this.GetHashCode(), "DeleteItems operation failed with operation result: {0} and exception: {1}", groupOperationResult.OperationResult, groupOperationResult.Exception);
                        if (groupOperationResult.Exception.GetType() == typeof(MapiExceptionPartialCompletion) || groupOperationResult.Exception.GetType() == typeof(PartialCompletionException))
                        {
                            StoragePermanentException e = new StoragePermanentException(Strings.CopyItemsFailed, groupOperationResult.Exception);
                            processor.ReportActionException(e);
                        }
                        else
                        {
                            SearchMailboxException e2 = new SearchMailboxException(Strings.CopyItemsFailed, groupOperationResult.Exception);
                            processor.ReportActionException(e2);
                        }
                    }
                    else
                    {
                        SearchMailboxAction.Tracer.TraceDebug <int, string>((long)this.GetHashCode(), "SearchMailboxWoker progressed with {0} message deletes on mailbox {1}", array.Length, processor.GetSourceUserName());
                    }
                }
                catch (ArgumentException ex)
                {
                    SearchMailboxAction.Tracer.TraceError <ArgumentException>((long)this.GetHashCode(), "CopyItems operation failed due to item validation failed, exception: {0}", ex);
                    SearchMailboxException e3 = new SearchMailboxException(Strings.CopyItemsFailed, ex);
                    processor.ReportActionException(e3);
                }
                catch (MapiExceptionPartialCompletion mapiExceptionPartialCompletion)
                {
                    SearchMailboxAction.Tracer.TraceError <MapiExceptionPartialCompletion>((long)this.GetHashCode(), "CopyItems operation failed due to insufficient space in target mailbox, exception: {0}", mapiExceptionPartialCompletion);
                    StoragePermanentException e4 = new StoragePermanentException(Strings.CopyItemsFailed, mapiExceptionPartialCompletion);
                    processor.ReportActionException(e4);
                }
                catch (PartialCompletionException ex2)
                {
                    SearchMailboxAction.Tracer.TraceError <PartialCompletionException>((long)this.GetHashCode(), "CopyItems operation failed due to insufficient space in target mailbox, exception: {0}", ex2);
                    StoragePermanentException e5 = new StoragePermanentException(Strings.CopyItemsFailed, ex2);
                    processor.ReportActionException(e5);
                }
            }
        }
示例#27
0
        private static void ProcessRogueMessages(EWSConnection ewsConnection)
        {
            Logger.InfoFormat("Processing rogue messages...");
            var folderName         = "Rogue Messages";
            var folders            = ewsConnection.Service.FindFolders(WellKnownFolderName.Inbox, new FolderView(100));
            var rogueMessageFolder = folders.SingleOrDefault(f => f.DisplayName == folderName);

            if (rogueMessageFolder == null)
            {
                Logger.InfoFormat("Could not find folder '{0}' on server. Using 'Deleted Items' instead.", folderName);
                rogueMessageFolder = Folder.Bind(ewsConnection.Service, WellKnownFolderName.DeletedItems);
            }

            var rogueMessages = ewsConnection.Router.RogueMessages;

            if (rogueMessages.Count == 0)
            {
                Logger.InfoFormat("No rogue messages found.");
                return;
            }

            Logger.InfoFormat("Replying to {0} rogue messages without configuration and moving to '{1}' folder...",
                              rogueMessages.Count, rogueMessageFolder.DisplayName);

            string[] previouslyProcessedRogueMessages;
            try
            {
                previouslyProcessedRogueMessages = ewsConnection.Service.FindItems(rogueMessageFolder.Id, new ItemView(1000)).
                                                   Select(i => new EWSIncomingMessage((EmailMessage)i).ConversationTopic).ToArray();
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("Failed to connect to mailbox server. Will retry on next iteration. {0}", e);
                return;
            }

            foreach (var message in rogueMessages)
            {
                var ewsMessage = message as EWSIncomingMessage;
                if (ewsMessage == null)
                {
                    continue;
                }

                if (previouslyProcessedRogueMessages.Contains(ewsMessage.ConversationTopic))
                {
                    Logger.InfoFormat("Already replied to conversation topic.");
                    MoveMessageToFolder(ewsMessage, rogueMessageFolder);
                    continue;
                }

                var sender    = ewsMessage.SenderAlias;
                var recipient = "*****@*****.**";

                try
                {
                    Logger.InfoFormat("Replying to '{0}', subject '{1}'.", sender, ewsMessage.Subject);
                    var replyMessage = string.Format(ReplyMessage, sender, recipient);
                    ewsMessage.Reply(replyMessage, true);
                }
                catch (Exception e)
                {
                    Logger.ErrorFormat(
                        "Failed to send reply. Possible cause: original mail item moved by the Exchange Server rules. {0}",
                        e);
                }

                MoveMessageToFolder(ewsMessage, rogueMessageFolder);
            }

            Logger.InfoFormat("Completed replying to rogue messages.");
            rogueMessages.Clear();
        }
示例#28
0
        private void FindSarachfolders(ExchangeService oService)
        {
            int  offset         = 0;
            bool MoreItems      = true;
            int  iPageSize      = 250;
            int  folderViewSize = 250;

            ListViewItem oListItem = null;
            Object       oPath     = null;
            string       sPath     = string.Empty;
            bool         bIsHidden = false;

            Folder oRootFolder = Folder.Bind(_ExchangeService, WellKnownFolderName.Root);
            //Folder oMsgFolderRoot = Folder.Bind(_ExchangeService, WellKnownFolderName.MsgFolderRoot);
            Folder oSearchFolders = Folder.Bind(_ExchangeService, WellKnownFolderName.SearchFolders);


            ExtendedPropertyDefinition PR_Folder_Path = new ExtendedPropertyDefinition(26293, MapiPropertyType.String);
            ExtendedPropertyDefinition isHiddenProp   = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean);
            StringBuilder oSB = new StringBuilder();

            PrepareFolderLV();
            bool bProcess = false;

            int iCountPages      = 0;
            int iCountTotalItems = 0;

            while (MoreItems)
            {
                iCountPages++;

                FolderView oFolderView = new FolderView(folderViewSize, offset, OffsetBasePoint.Beginning);
                //ItemView oItemView = new ItemView(iPageSize, offset, OffsetBasePoint.Beginning);
                oFolderView.PropertySet = new PropertySet(
                    BasePropertySet.IdOnly,
                    FolderSchema.ParentFolderId,
                    FolderSchema.DisplayName,
                    FolderSchema.FolderClass,
                    FolderSchema.TotalCount,
                    isHiddenProp,
                    FolderSchema.Id,
                    PR_Folder_Path
                    );

                List <SearchFilter> searchFilterCollection = new List <SearchFilter>();
                oFolderView.Traversal = FolderTraversal.Deep;

                oService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.

                FindFoldersResults oFindFoldersResults = oService.FindFolders(WellKnownFolderName.Root, oFolderView);
                MoreItems = oFindFoldersResults.MoreAvailable;

                foreach (Folder oFolder in oFindFoldersResults.Folders)
                {
                    iCountTotalItems++;
                    bProcess = false;

                    if (oFolder is SearchFolder)
                    {
                        if (chkShowFoldersUnderRootFolder.Checked == true)
                        {
                            if (oFolder.ParentFolderId.UniqueId == oRootFolder.Id.UniqueId)
                            {
                                bProcess = true;
                            }
                        }
                        else
                        {
                            if (chkShowFolderUnderSharedFolders.Checked == true)
                            {
                                if (oFolder.ParentFolderId.UniqueId == oSearchFolders.Id.UniqueId)
                                {
                                    bProcess = true;
                                }
                            }
                            else
                            {
                                if (chkShowSearchFoldersNotUnderSharedFoldersAndNotUnderRoot.Checked == true)
                                {
                                    if (oFolder.ParentFolderId.UniqueId != oRootFolder.Id.UniqueId && oFolder.ParentFolderId.UniqueId != oSearchFolders.Id.UniqueId)
                                    {
                                        bProcess = true;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        bProcess = false;
                    }

                    if (bProcess == true)
                    {
                        oFolder.TryGetProperty(PR_Folder_Path, out oPath);
                        // https://social.technet.microsoft.com/Forums/exchange/en-US/e5d07492-f8a3-4db5-b137-46e920ab3dde/exchange-ews-managed-getting-full-path-for-a-folder?forum=exchangesvrdevelopment
                        sPath = Encoding.Unicode.GetString(HexStringToByteArray(BitConverter.ToString(UnicodeEncoding.Unicode.GetBytes((String)oPath)).Replace("FE-FF", "5C-00").Replace("-", "")));

                        oFolder.TryGetProperty(isHiddenProp, out bIsHidden);

                        oListItem = new ListViewItem(oFolder.FolderClass, 0);
                        oListItem.SubItems.Add(oFolder.DisplayName);
                        oListItem.SubItems.Add(sPath);

                        oListItem.SubItems.Add(bIsHidden.ToString());
                        oListItem.SubItems.Add(oFolder.TotalCount.ToString());

                        oListItem.SubItems.Add(oFolder.Id.UniqueId);

                        oListItem.Tag = new FolderTag(oFolder.Id, oFolder.FolderClass);
                        lvFolders.Items.AddRange(new ListViewItem[] { oListItem });;



                        oListItem = null;
                    }
                }

                // Set the flag to discontinue paging.
                if (!oFindFoldersResults.MoreAvailable)
                {
                    MoreItems = false;
                }

                // Update the offset if there are more items to page.
                if (MoreItems)
                {
                    offset += iPageSize;
                }
                //MoreItems = false;
            }
        }
示例#29
0
        public override void Execute()
        {
            if (!this.ShouldExecuteOnThisStage)
            {
                return;
            }
            if (base.Context.DeliveryFolder != null && this.TargetFolderId.Equals(base.Context.DeliveryFolder.Id))
            {
                base.Context.TraceDebug("Copy action: Ignoring copy to same folder.");
                return;
            }
            bool           flag           = false;
            MailboxSession mailboxSession = base.Context.StoreSession as MailboxSession;

            if (mailboxSession != null && CopyWorkItem.IsRententionPolicyEnabled(base.Context.RecipientCache, base.Context.Recipient))
            {
                base.Context.TraceDebug("Copy action: Retention policy is enabled.");
                flag = true;
            }
            if (ExecutionStage.OnPromotedMessage == base.Context.ExecutionStage)
            {
                base.Context.TraceDebug("Copy action: Creating message.");
                using (MessageItem messageItem = MessageItem.Create(base.Context.StoreSession, this.TargetFolderId))
                {
                    base.Context.TraceDebug("Copy action: Copying content from original message.");
                    Item.CopyItemContent(base.Context.Message, messageItem);
                    if (base.Context.PropertiesForAllMessageCopies != null)
                    {
                        foreach (KeyValuePair <PropertyDefinition, object> keyValuePair in base.Context.PropertiesForAllMessageCopies)
                        {
                            if (keyValuePair.Value != null)
                            {
                                base.Context.TraceDebug <string, object>("Copy action: Setting property {0} to {1}", keyValuePair.Key.Name, keyValuePair.Value);
                            }
                            else
                            {
                                base.Context.TraceDebug <string>("Copy action: Removing property {0}", keyValuePair.Key.Name);
                            }
                            messageItem.SetOrDeleteProperty(keyValuePair.Key, keyValuePair.Value);
                        }
                    }
                    MessageFlags messageFlags = messageItem.GetValueOrDefault <MessageFlags>(MessageItemSchema.Flags);
                    messageFlags |= MessageFlags.IsUnmodified;
                    messageFlags &= ~(MessageFlags.IsRead | MessageFlags.IsDraft);
                    messageItem[MessageItemSchema.Flags] = messageFlags;
                    if (flag)
                    {
                        this.TagItem(mailboxSession, messageItem);
                    }
                    else
                    {
                        base.Context.TraceDebug("Copy action: Retention policy is not enabled. Skip tagging.");
                    }
                    base.Context.TraceDebug("Copy action: Saving message.");
                    messageItem.Save(SaveMode.ResolveConflicts);
                    base.Context.TraceDebug("Copy action: Message saved.");
                    return;
                }
            }
            if (ExecutionStage.OnDeliveredMessage == base.Context.ExecutionStage)
            {
                base.Context.TraceDebug("Copy action: Loading original message.");
                base.Context.DeliveredMessage.Load(new PropertyDefinition[]
                {
                    ItemSchema.Id
                });
                if (base.Context.DeliveredMessage.Id == null)
                {
                    base.Context.TraceError("Copy action: Cannot copy message since the message is not deliverred to store.");
                    return;
                }
                if (!flag)
                {
                    if (!base.Context.FinalDeliveryFolderId.Equals(base.Context.DeliveryFolder.Id))
                    {
                        base.Context.TraceDebug("Copy action: Binding to final delivery folder.");
                        using (Folder folder = Folder.Bind(base.Context.StoreSession, base.Context.FinalDeliveryFolderId))
                        {
                            base.Context.TraceDebug("Copy action: Copying from final delivery folder.");
                            folder.CopyItems(this.TargetFolderId, new StoreId[]
                            {
                                base.Context.DeliveredMessage.Id
                            });
                            return;
                        }
                    }
                    base.Context.TraceDebug("Copy action: Copying from initial delivery folder.");
                    base.Context.DeliveryFolder.CopyItems(this.TargetFolderId, new StoreId[]
                    {
                        base.Context.DeliveredMessage.Id
                    });
                    return;
                }
                base.Context.TraceDebug("Copy action: Copying from delivery folder and fixing RetentionPolicies on Item.");
                AggregateOperationResult aggregateOperationResult = mailboxSession.Copy(mailboxSession, this.TargetFolderId, true, new StoreId[]
                {
                    base.Context.DeliveredMessage.Id
                });
                if (aggregateOperationResult.OperationResult == OperationResult.Succeeded && aggregateOperationResult.GroupOperationResults.Length == 1 && aggregateOperationResult.GroupOperationResults[0].ResultObjectIds.Count == 1)
                {
                    PropertyDefinition[] array = new PropertyDefinition[]
                    {
                        ItemSchema.Id,
                        StoreObjectSchema.PolicyTag,
                        StoreObjectSchema.RetentionFlags,
                        StoreObjectSchema.RetentionPeriod,
                        StoreObjectSchema.ArchiveTag,
                        StoreObjectSchema.ArchivePeriod,
                        FolderSchema.RetentionTagEntryId
                    };
                    using (MessageItem messageItem2 = MessageItem.Bind(base.Context.StoreSession, aggregateOperationResult.GroupOperationResults[0].ResultObjectIds[0], (ICollection <PropertyDefinition>)array))
                    {
                        messageItem2.OpenAsReadWrite();
                        this.TagItem(mailboxSession, messageItem2);
                        base.Context.TraceDebug("Copy action: Saving message.");
                        messageItem2.Save(SaveMode.ResolveConflicts);
                        base.Context.TraceDebug("Copy action: Message saved.");
                    }
                }
            }
        }
示例#30
0
        private void Load()
        {
            this.folders = new List <object[]>(50);
            Folder folder = null;

            object[][] array = null;
            try
            {
                if (this.parentFolderList == null)
                {
                    if (this.userContext.IsWebPartRequest && this.userContext.IsExplicitLogon)
                    {
                        folder = Utilities.SafeFolderBind(this.mailboxSession, this.rootFolderId, this.queryProperties);
                        if (folder == null)
                        {
                            return;
                        }
                    }
                    else
                    {
                        folder = Folder.Bind(this.mailboxSession, this.rootFolderId, this.queryProperties);
                    }
                    this.deletedFolderIds = new List <StoreObjectId>(10);
                    if (this.isListRootFolder)
                    {
                        this.folders.Add(folder.GetProperties(this.queryProperties));
                    }
                    using (QueryResult queryResult = folder.FolderQuery(this.isDeepTraversal ? FolderQueryFlags.DeepTraversal : FolderQueryFlags.None, (this.queryFilter == null) ? FolderList.NonHiddenFilter : new AndFilter(new QueryFilter[]
                    {
                        FolderList.NonHiddenFilter,
                        this.queryFilter
                    }), null, this.queryProperties))
                    {
                        array = Utilities.FetchRowsFromQueryResult(queryResult, 10000);
                        goto IL_104;
                    }
                }
                array = this.FetchRowsFromParentFolderList();
IL_104:
                bool flag = false;
                int num = -1;
                int i   = 0;
                while (i < array.Length)
                {
                    bool          flag2         = false;
                    StoreObjectId storeObjectId = null;
                    object[]      array2        = array[i];
                    if (!flag)
                    {
                        storeObjectId = ((VersionedId)array2[this.propertyIndexes[FolderSchema.Id]]).ObjectId;
                        if (Utilities.IsDefaultFolderId(this.mailboxSession, storeObjectId, DefaultFolderType.DeletedItems))
                        {
                            num = (int)array2[this.propertyIndexes[FolderSchema.FolderHierarchyDepth]];
                        }
                        else if (num != -1)
                        {
                            int num2 = (int)array2[this.propertyIndexes[FolderSchema.FolderHierarchyDepth]];
                            if (num2 == num)
                            {
                                flag  = true;
                                flag2 = false;
                            }
                            else
                            {
                                flag2 = true;
                            }
                        }
                    }
                    if (flag2)
                    {
                        if (this.isListDeletedFolders)
                        {
                            goto IL_1E1;
                        }
                    }
                    else
                    {
                        if (this.folderTypes == null)
                        {
                            goto IL_1E1;
                        }
                        object obj = array2[this.propertyIndexes[StoreObjectSchema.ContainerClass]];
                        if (!(obj is PropertyError))
                        {
                            string folderType = (string)obj;
                            if (this.IsQueriedType(folderType))
                            {
                                goto IL_1E1;
                            }
                        }
                    }
IL_212:
                    i++;
                    continue;
IL_1E1:
                    if (this.folders.Count >= this.maxFolders)
                    {
                        break;
                    }
                    this.folders.Add(array2);
                    if (flag2)
                    {
                        this.deletedFolderIds.Add(storeObjectId);
                        goto IL_212;
                    }
                    goto IL_212;
                }
                if (this.sortProperty != null)
                {
                    this.folders.Sort(this);
                }
            }
            finally
            {
                if (folder != null)
                {
                    folder.Dispose();
                }
            }
        }