private bool TryOpenHistoryFolder() { bool result; try { MapiStore mapiStore = this.context.StoreSession.Mailbox.MapiStore; using (MapiFolder nonIpmSubtreeFolder = mapiStore.GetNonIpmSubtreeFolder()) { this.oofHistoryFolder = nonIpmSubtreeFolder.OpenSubFolderByName("Freebusy Data"); } this.Trace("OOF history folder opened."); result = true; } catch (MapiExceptionNotFound mapiExceptionNotFound) { this.context.TraceError <string>("Unable to open the OOF history folder {0}, OOF history operation skipped.", "Freebusy Data"); this.context.LogEvent(this.context.OofHistoryFolderMissing, mapiExceptionNotFound.GetType().ToString(), new object[] { ((MailboxSession)this.context.StoreSession).MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString() }); result = false; } return(result); }
private void WaitAndProcessProbeResponses(MapiFolder folder, string fromAddress, Dictionary <string, string> subjectTargets, ExDateTime probeSentTime) { List <byte[]> list = new List <byte[]>(); List <string> list2 = new List <string>(); for (int i = 0; i < base.Task.ExecutionTimeout; i++) { foreach (KeyValuePair <string, string> keyValuePair in subjectTargets) { if (!string.IsNullOrEmpty(keyValuePair.Value)) { using (MapiMessage deliveryReceipt = TestMailFlowHelper.GetDeliveryReceipt(folder, keyValuePair.Key, false)) { if (deliveryReceipt != null) { PropValue prop = deliveryReceipt.GetProp(PropTag.MessageDeliveryTime); PropValue prop2 = deliveryReceipt.GetProp(PropTag.EntryId); PropValue prop3 = deliveryReceipt.GetProp(PropTag.Subject); if (!prop.IsError() && prop.Value != null && prop3.Value != null) { string text = prop3.Value.ToString(); if (text.StartsWith("RSP: CrossPremiseMailFlowMonitoring-", StringComparison.OrdinalIgnoreCase)) { EnhancedTimeSpan latency = ((ExDateTime)prop.GetDateTime() > probeSentTime) ? ((ExDateTime)prop.GetDateTime() - probeSentTime) : EnhancedTimeSpan.Zero; base.OutputResult(Strings.TestMailflowSucceeded(fromAddress, keyValuePair.Value), latency, base.IsRemoteTest); } else if (text.StartsWith("Undeliverable: CrossPremiseMailFlowMonitoring-", StringComparison.OrdinalIgnoreCase)) { EnhancedTimeSpan latency2 = EnhancedTimeSpan.FromSeconds(0.0); string info = (string)deliveryReceipt.GetProp(PropTag.Body).Value; base.OutputResult(Strings.CrossPremiseProbeNdred(fromAddress, keyValuePair.Value, info), latency2, base.IsRemoteTest); } list2.Add(keyValuePair.Key); list.Add(prop2.GetBytes()); } } } } } foreach (string key in list2) { subjectTargets.Remove(key); } list2.Clear(); if (subjectTargets.Count == 0) { break; } Thread.Sleep(1000); } foreach (KeyValuePair <string, string> keyValuePair2 in subjectTargets) { if (!string.IsNullOrEmpty(keyValuePair2.Value)) { EnhancedTimeSpan latency3 = EnhancedTimeSpan.FromSeconds(0.0); base.OutputResult(Strings.MapiTransactionResultFailure, latency3, base.IsRemoteTest); } } folder.DeleteMessages(DeleteMessagesFlags.ForceHardDelete, list.ToArray()); }
internal override void Read(bool keepUnmanagedResources) { if (base.ObjectState != ObjectState.New) { throw new MapiInvalidOperationException(Strings.ExceptionObjectStateInvalid(base.ObjectState.ToString())); } Folder.CheckRequirementsToContinue(this.Identity, base.MapiSession); bool flag = false; ExTraceGlobals.FolderTracer.TraceDebug <FolderId, string>((long)this.GetHashCode(), "To Read Folder '{0}' from server '{1}'.", this.Identity, base.MapiSession.ServerName); base.EnableDisposeTracking(); using (MapiStore messageStore = this.GetMessageStore()) { using (MapiFolder mapiFolder = this.GetMapiFolder(messageStore)) { try { base.Instantiate(mapiFolder.GetProps(base.GetPropertyTagsToRead())); this.UpdateIdentity(this.UpdateIdentityFlagsForReading); flag = true; } finally { if (!keepUnmanagedResources || !flag) { base.Dispose(); } } } } base.ResetChangeTrackingAndObjectState(); }
private void WriteFolder(Folder folder) { this.writer.WriteStartElement("Folder"); if (folder != null) { Rule[] rules = null; Exception exception; if (RuleUtil.TryRunStoreCode(delegate { MapiFolder mapiFolder = folder.MapiFolder; rules = mapiFolder.GetRules(new PropTag[0]); }, out exception)) { this.writer.WriteAttributeString("FolderName", folder.DisplayName); this.writer.WriteAttributeString("Rules", rules.Length.ToString()); for (int i = 0; i < rules.Length; i++) { Rule rule = rules[i]; this.WriteRule(rule, i); } } else { this.WriteExceptionElement("Getting rules from folder: " + folder.DisplayName, exception); } } this.writer.WriteEndElement(); }
private static MapiStream OpenAndLockStream(MapiFolder oofHistoryFolder, byte[] initialBytes, long hashCode, out bool isNew) { MapiStream mapiStream = null; isNew = false; OpenPropertyFlags openPropertyFlags = OpenPropertyFlags.Modify | OpenPropertyFlags.DeferredErrors; try { mapiStream = oofHistoryFolder.OpenStream(PropTag.OofHistory, openPropertyFlags); OofHistory.LockStreamWithRetry(mapiStream, hashCode); } catch (MapiExceptionNotFound) { if (mapiStream != null) { mapiStream.Dispose(); mapiStream = null; } OofHistory.Tracer.TraceDebug(hashCode, "OOF history property does not exist, trying to open with create flag."); openPropertyFlags |= OpenPropertyFlags.Create; mapiStream = oofHistoryFolder.OpenStream(PropTag.OofHistory, openPropertyFlags); OofHistory.LockStreamWithRetry(mapiStream, hashCode); OofHistory.ResetOofHistoryProperty(mapiStream, initialBytes, hashCode); isNew = true; } return(mapiStream); }
protected static void CreateAndSubmitMessage(MapiFolder folder, string sourceMailboxName, string targetMailAddress, string subject, bool deleteAfterSubmit) { using (MapiMessage mapiMessage = folder.CreateMessage()) { PropValue[] props = new PropValue[] { new PropValue(PropTag.DeleteAfterSubmit, deleteAfterSubmit), new PropValue(PropTag.Subject, subject), new PropValue(PropTag.ReceivedByEmailAddress, targetMailAddress), new PropValue(PropTag.Body, "This is a Test-Mailflow probe message.") }; mapiMessage.SetProps(props); mapiMessage.ModifyRecipients(ModifyRecipientsFlags.AddRecipients, new AdrEntry[] { new AdrEntry(new PropValue[] { new PropValue(PropTag.EmailAddress, targetMailAddress), new PropValue(PropTag.OriginatorDeliveryReportRequested, deleteAfterSubmit), new PropValue(PropTag.AddrType, "SMTP"), new PropValue(PropTag.RecipientType, RecipientType.To), new PropValue(PropTag.DisplayName, sourceMailboxName) }) }); mapiMessage.SaveChanges(); mapiMessage.SubmitMessage(SubmitMessageFlags.ForceSubmit); } }
internal static MapiFolder GetFolderByPath(MapiStore mapiStore, MapiFolder parentFolder, MapiFolderPath folderPath) { if (null == folderPath) { throw new ArgumentNullException("folderPath"); } if (folderPath.IsSubtreeRoot) { if (mapiStore == null) { throw new ArgumentNullException("mapiStore"); } if (!folderPath.IsIpmPath) { return(mapiStore.GetNonIpmSubtreeFolder()); } return(mapiStore.GetIpmSubtreeFolder()); } else { if (parentFolder == null) { throw new ArgumentNullException("parentFolder"); } return(parentFolder.OpenSubFolderByName(folderPath[folderPath.Depth - 1])); } }
private void ParseRules(bool includeHidden) { MapiFolder mapiFolder = this.Folder.MapiFolder; Rules.RunMapiCode(ServerStrings.ErrorLoadingRules, delegate { this.serverRules = mapiFolder.GetRules(new PropTag[0]); }); int num = 10; foreach (Rule rule in this.serverRules) { if (Rules.IsInboxRule(rule) || includeHidden) { Rule rule2 = Rule.Create(this.Folder, rule); this.data.Add(rule2); rule2.Id = new RuleId(this.data.IndexOf(rule2), rule.ID); rule2.ClearDirty(); if (rule2.Sequence != num) { rule2.Sequence = num; } num++; } } }
private void WaitAndProcessDeliveryReceipt(MapiFolder folder, string subject, string fromAddress, string toAddress, string perfInstance) { using (MapiMessage mapiMessage = this.WaitForDeliveryReceipt(folder, subject, base.Task.ErrorLatency, base.Task.ExecutionTimeout, fromAddress, toAddress)) { if (mapiMessage != null) { PropValue prop = mapiMessage.GetProp(PropTag.MessageDeliveryTime); PropValue prop2 = mapiMessage.GetProp(PropTag.OriginalSubmitTime); EnhancedTimeSpan enhancedTimeSpan = prop.GetDateTime() - prop2.GetDateTime(); if (enhancedTimeSpan < EnhancedTimeSpan.Zero) { enhancedTimeSpan = EnhancedTimeSpan.Zero; } base.OutputResult(Strings.MapiTransactionResultSuccess, enhancedTimeSpan, base.IsRemoteTest); base.AddSuccessMonitoringEvent(1000, Strings.TestMailflowSucceeded(fromAddress, toAddress)); base.AddPerfCounter("Mailflow Latency", perfInstance, enhancedTimeSpan.TotalSeconds); } else { EnhancedTimeSpan latency = EnhancedTimeSpan.FromSeconds(0.0); base.OutputResult(Strings.MapiTransactionResultFailure, latency, base.IsRemoteTest); base.AddErrorMonitoringEvent(1001, Strings.TestMailflowFailed(fromAddress, toAddress, base.Task.ExecutionTimeout)); base.AddPerfCounter("Mailflow Latency", perfInstance, -1.0); } } }
internal override void InternalProcessRecord() { base.InternalProcessRecord(); if (!this.sourceServerHasMdb) { base.AddSuccessMonitoringEvent(1000, Strings.TestMailflowSucceededNoDatabaseOnSourceServer(base.SourceMailboxServer.Name)); base.Task.WriteWarning(Strings.TestMailflowServerWithoutMdbs(base.SourceMailboxServer.Name)); return; } if (!this.targetServerHasMdb) { base.AddSuccessMonitoringEvent(1000, Strings.TestMailflowSucceededNoDatabaseOnTargetServer(base.Task.TargetMailboxServer.ToString())); base.Task.WriteWarning(Strings.TestMailflowServerWithoutMdbs(base.Task.TargetMailboxServer.ToString())); return; } using (MapiStore mapiStore = MapiStore.OpenMailbox(base.SourceMailboxServer.Fqdn, base.SourceSystemMailbox.LegacyExchangeDN, base.SourceSystemMailbox.ExchangeGuid, base.SourceSystemMailbox.Database.ObjectGuid, base.SourceSystemMailbox.Name, null, null, ConnectFlag.UseAdminPrivilege | ConnectFlag.UseSeparateConnection, OpenStoreFlag.UseAdminPrivilege | OpenStoreFlag.TakeOwnership | OpenStoreFlag.MailboxGuid, CultureInfo.InvariantCulture, null, "Client=Management;Action=LegacyTestMailFlow", null)) { using (MapiFolder outboxFolder = mapiStore.GetOutboxFolder()) { using (MapiFolder inboxFolder = mapiStore.GetInboxFolder()) { LegacyTestMailFlowHelper.CleanUpInbox(inboxFolder); string subject = string.Format("Test-Mailflow {0} {1}", Guid.NewGuid(), "66c7004a-6860-44b2-983a-327aa3c9cfec"); TestMailFlowHelper.CreateAndSubmitMessage(outboxFolder, base.SourceSystemMailbox.Name, this.targetMailboxAddress, subject, true); this.WaitAndProcessDeliveryReceipt(inboxFolder, subject, this.friendlySourceAddress, this.friendlyTargetAddress, this.GetPerfInstanceName()); } } } }
private static void ModifyRule(params object[] arguments) { MapiFolder mapiFolder = (MapiFolder)arguments[1]; mapiFolder.ModifyRules(new Rule[] { (Rule)arguments[0] }); }
internal static void DisableRule(Rule rule, MapiFolder mapiFolder) { rule.StateFlags &= ~RuleStateFlags.Enabled; RuleUtil.RunMapiCode(ServerStrings.ModifyRuleInStore, new ActionParams(RuleUtil.ModifyRule), new object[] { rule, mapiFolder }); }
internal static void MarkRuleInError(Rule rule, MapiFolder mapiFolder) { rule.StateFlags |= RuleStateFlags.Error; RuleUtil.RunMapiCode(ServerStrings.ModifyRuleInStore, new ActionParams(RuleUtil.ModifyRule), new object[] { rule, mapiFolder }); }
internal override void InternalProcessRecord() { base.InternalProcessRecord(); if (base.Task.MonitoringContext && !this.IsFirstActiveMdbLocallyMounted()) { base.AddInformationMonitoringEvent(2004, Strings.CrossPremiseServerNotSelected(base.SourceMailboxServer.Name)); return; } List <SmtpAddress> siteEgressTargets = this.GetSiteEgressTargets(); if (siteEgressTargets.Count <SmtpAddress>() == 0) { base.AddWarningMonitoringEvent(2003, Strings.CrossPremiseNoEgressTargets(base.SourceMailboxServer.Name)); base.Task.WriteWarning(Strings.CrossPremiseNoEgressTargets(base.SourceMailboxServer.Name)); return; } ADSystemMailbox adsystemMailbox = this.localSystemMailbox as ADSystemMailbox; using (MapiStore mapiStore = MapiStore.OpenMailbox(base.SourceMailboxServer.Fqdn, this.localSystemMailbox.LegacyExchangeDN, adsystemMailbox.ExchangeGuid, adsystemMailbox.Database.ObjectGuid, this.localSystemMailbox.Name, null, null, ConnectFlag.UseAdminPrivilege | ConnectFlag.UseSeparateConnection, OpenStoreFlag.UseAdminPrivilege | OpenStoreFlag.TakeOwnership | OpenStoreFlag.MailboxGuid, CultureInfo.InvariantCulture, null, "Client=Management;Action=CrossPremiseTestMailFlow", null)) { using (MapiFolder rootFolder = mapiStore.GetRootFolder()) { using (MapiFolder inboxFolder = mapiStore.GetInboxFolder()) { using (MapiFolder mapiFolder = rootFolder.CreateFolder("Cross Premise", "The folder for cross premise mailflow monitoring.", true)) { if (base.Task.MonitoringContext) { this.MatchCrossPremiseMessages(inboxFolder, mapiFolder, this.localSystemMailbox.WindowsEmailAddress, siteEgressTargets); using (List <SmtpAddress> .Enumerator enumerator = siteEgressTargets.GetEnumerator()) { while (enumerator.MoveNext()) { SmtpAddress smtpAddress = enumerator.Current; string subject = string.Format("{0}{{{1}}}", "CrossPremiseMailFlowMonitoring-", Guid.NewGuid()); TestMailFlowHelper.CreateAndSubmitMessage(mapiFolder, this.localSystemMailbox.Name, smtpAddress.ToString(), subject, false); } goto IL_238; } } Dictionary <string, string> dictionary = new Dictionary <string, string>(); ExDateTime utcNow = ExDateTime.UtcNow; foreach (SmtpAddress smtpAddress2 in siteEgressTargets) { string text = string.Format("{0}{{{1}}}", "CrossPremiseMailFlowMonitoring-", Guid.NewGuid()); TestMailFlowHelper.CreateAndSubmitMessage(mapiFolder, this.localSystemMailbox.Name, smtpAddress2.ToString(), text, true); dictionary[text] = smtpAddress2.ToString(); } this.WaitAndProcessProbeResponses(inboxFolder, this.localSystemMailbox.Name, dictionary, utcNow); IL_238 :; } } } } }
public int TraverseFolder(MapiFolder folder) { int size = 0; foreach (MapiFolder subFolder in folder) { size += TraverseFolder(subFolder); } foreach (MAPI.Message message in folder.Messages) { size += (int)message.Size; } return(size); }
internal override void Delete() { if (ObjectState.Deleted == base.ObjectState) { throw new MapiInvalidOperationException(Strings.ExceptionObjectStateInvalid(base.ObjectState.ToString())); } if (base.ObjectState == ObjectState.New) { base.MarkAsDeleted(); return; } Folder.CheckRequirementsToContinue(this.Identity, base.MapiSession); ExTraceGlobals.FolderTracer.TraceDebug <FolderId, string>((long)this.GetHashCode(), "To Delete Folder '{0}' on server '{1}'.", this.Identity, base.MapiSession.ServerName); base.EnableDisposeTracking(); using (MapiStore messageStore = this.GetMessageStore()) { using (MapiFolder mapiFolder = this.GetMapiFolder(messageStore)) { try { this.DetectDisallowedModification(messageStore); bool flag = false; this.TryTestHasSubFolders(mapiFolder, out flag); try { using (MapiFolder parentFolder = this.GetParentFolder(messageStore)) { parentFolder.DeleteFolder((byte[])this.Identity.MapiEntryId); } } catch (MapiExceptionPartialCompletion innerException) { if (flag) { throw new MapiPartialCompletionException(Strings.ErrorRemovalPartialCompleted(this.Identity.ToString()), innerException); } throw; } } finally { base.Dispose(); } } } base.ResetChangeTracking(); base.MarkAsDeleted(); }
private static void CleanUpInbox(MapiFolder folder) { DateTime t = DateTime.UtcNow.AddMinutes(-20.0); MapiTable contentsTable; MapiTable mapiTable = contentsTable = folder.GetContentsTable(); try { mapiTable.SetColumns(new PropTag[] { PropTag.EntryId, PropTag.MessageDeliveryTime, PropTag.NormalizedSubject, PropTag.OriginalSubject }); Restriction restriction = Restriction.Or(new Restriction[] { Restriction.Content(PropTag.NormalizedSubject, "66c7004a-6860-44b2-983a-327aa3c9cfec", ContentFlags.SubString | ContentFlags.IgnoreCase), Restriction.Content(PropTag.OriginalSubject, "66c7004a-6860-44b2-983a-327aa3c9cfec", ContentFlags.SubString | ContentFlags.IgnoreCase) }); mapiTable.Restrict(restriction); mapiTable.SortTable(new SortOrder(PropTag.MessageDeliveryTime, SortFlags.Ascend), SortTableFlags.None); PropValue[][] array = mapiTable.QueryRows(100, QueryRowsFlags.None); List <byte[]> list = new List <byte[]>(100); for (int i = 0; i <= array.GetUpperBound(0); i++) { if (TestMailFlowHelper.IsValidPropData(array, i, 2)) { if (array[i][1].GetDateTime() > t) { break; } list.Add(array[i][0].GetBytes()); } } if (list.Count > 0) { folder.DeleteMessages(DeleteMessagesFlags.ForceHardDelete, list.ToArray()); } } finally { if (contentsTable != null) { ((IDisposable)contentsTable).Dispose(); } } }
public static FolderHierarchyChangeDetector.MailboxChangesManifest RunICSManifestSync(bool catchup, FolderHierarchyChangeDetector.SyncHierarchyManifestState hierState, MailboxSession mailboxSession, ISyncLogger syncLogger = null) { if (syncLogger == null) { syncLogger = TracingLogger.Singleton; } syncLogger.TraceDebug <SmtpAddress, bool>(ExTraceGlobals.SyncProcessTracer, 0L, "[FolderHierarchyChangeDetector.RunICSManifestSync] Checking for folder hierarhcy changes for Mailbox: {0}. Catchup? {1}", mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress, catchup); MapiStore _ContainedMapiStore = mailboxSession.__ContainedMapiStore; FolderHierarchyChangeDetector.MailboxChangesManifest mailboxChangesManifest = new FolderHierarchyChangeDetector.MailboxChangesManifest(); FolderHierarchyChangeDetector.ManifestHierarchyCallback iMapiManifestCallback = new FolderHierarchyChangeDetector.ManifestHierarchyCallback(catchup, mailboxChangesManifest); try { using (MapiFolder ipmSubtreeFolder = _ContainedMapiStore.GetIpmSubtreeFolder()) { SyncConfigFlags syncConfigFlags = SyncConfigFlags.ManifestHierReturnDeletedEntryIds; int serverVersion = mailboxSession.MailboxOwner.MailboxInfo.Location.ServerVersion; if ((serverVersion >= Server.E14MinVersion && serverVersion < Server.E15MinVersion) || (long)serverVersion >= FolderHierarchyChangeDetector.E15MinVersionSupportsOnlySpecifiedPropsForHierarchy) { syncConfigFlags |= SyncConfigFlags.OnlySpecifiedProps; } using (MapiHierarchyManifestEx mapiHierarchyManifestEx = ipmSubtreeFolder.CreateExportHierarchyManifestEx(syncConfigFlags, hierState.IdsetGiven, hierState.CnsetSeen, iMapiManifestCallback, FolderHierarchyChangeDetector.PropsToFetch, null)) { while (mapiHierarchyManifestEx.Synchronize() != ManifestStatus.Done) { } byte[] idSetGiven; byte[] cnetSeen; mapiHierarchyManifestEx.GetState(out idSetGiven, out cnetSeen); syncLogger.TraceDebug <SmtpAddress, int, int>(ExTraceGlobals.SyncProcessTracer, 0L, "[FolderHierarchyChangeDetector.RunICSManifestSync] Updating ICS state for mailbox: '{0}'. Change Count: {1}, Delete Count: {2}", mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress, mailboxChangesManifest.ChangedFolders.Count, mailboxChangesManifest.DeletedFolders.Count); hierState.Update(idSetGiven, cnetSeen); } } } catch (MapiPermanentException arg) { syncLogger.TraceDebug <SmtpAddress, MapiPermanentException>(ExTraceGlobals.SyncProcessTracer, 0L, "[FolderHierarchyChangeDetector.RunICSManifestSync] Caught MapiPermanentException when determining folder ICS changes for mailbox: {0}. Exception: {1}", mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress, arg); return(null); } catch (MapiRetryableException arg2) { syncLogger.TraceDebug <SmtpAddress, MapiRetryableException>(ExTraceGlobals.SyncProcessTracer, 0L, "[FolderHierarchyChangeDetector.RunICSManifestSync] Caught MapiRetryableException when determining folder ICS changes for mailbox: {0}. Exception: {1}", mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress, arg2); return(null); } return(mailboxChangesManifest); }
private bool EnsureMapiManifest(MailboxSyncWatermark minWatermark, int numOperations, Dictionary <ISyncItemId, ServerManifestEntry> newServerManifest) { MemoryStream memoryStream = null; MapiFolder mapiFolder = this.folder.MapiFolder; if (this.manifest != null) { if (MailboxSyncProvider.IcsStateEquals(this.icsState, minWatermark.IcsState)) { if (this.extraServerManifestEntry != null) { if (numOperations == 0) { return(true); } newServerManifest.Add(this.extraServerManifestEntry.Id, this.extraServerManifestEntry); if (this.extraServerManifestEntry.Watermark != null) { minWatermark.ChangeNumber = ((MailboxSyncWatermark)this.extraServerManifestEntry.Watermark).ChangeNumber; } this.SyncLogger.Information <ISyncItemId>(ExTraceGlobals.SyncProcessTracer, (long)this.GetHashCode(), "MailboxSyncProvider::EnsureMapiManifest Adding cached change, id = {0}", this.extraServerManifestEntry.Id); this.extraServerManifestEntry = null; } this.icsCallback.Bind(minWatermark, numOperations, newServerManifest); this.SyncLogger.Information <int, int>(ExTraceGlobals.SyncProcessTracer, (long)this.GetHashCode(), "MailboxSyncProvider::EnsureMapiManifest Reusing ICS manifest, numOperations = {0}, newServerManifest.Count = {1}", numOperations, newServerManifest.Count); return(false); } this.manifest.Dispose(); this.manifest = null; this.SyncLogger.Information <int, int>(ExTraceGlobals.SyncProcessTracer, (long)this.GetHashCode(), "MailboxSyncProvider::EnsureMapiManifest Tossed old ICS manifest, numOperations = {0}, newServerManifest.Count = {1}", numOperations, newServerManifest.Count); } try { memoryStream = ((minWatermark.IcsState == null) ? new MemoryStream() : new MemoryStream(minWatermark.IcsState)); this.manifest = mapiFolder.CreateExportManifest(); this.icsCallback = new IcsCallback(this, newServerManifest, numOperations, minWatermark); Restriction restriction = (this.icsPropertyGroupFilter == null) ? null : FilterRestrictionConverter.CreateRestriction(this.folder.Session, this.folder.Session.ExTimeZone, this.folder.MapiFolder, this.icsPropertyGroupFilter); this.manifest.Configure(this.GetConfigFlags(), restriction, memoryStream, this.icsCallback, IcsCallback.PropTags); this.SyncLogger.Information <int, int>(ExTraceGlobals.SyncProcessTracer, (long)this.GetHashCode(), "MailboxSyncProvider::EnsureMapiManifest Created new ICS manifest, numOperations = {0}, newServerManifest.Count = {1}", numOperations, newServerManifest.Count); } finally { Util.DisposeIfPresent(memoryStream); } return(false); }
internal static MapiFolder GetFolderByPath(MapiStore mapiStore, MapiFolderPath folderPath) { MapiFolder mapiFolder = null; MapiFolder folderByPath; try { folderByPath = Folder.GetFolderByPath(mapiStore, folderPath, out mapiFolder); } finally { if (mapiFolder != null) { mapiFolder.Dispose(); } } return(folderByPath); }
internal static MapiFolder RetrieveMapiFolder(MapiStore store, FolderId identity) { MapiFolder mapiFolder = null; MapiFolder result; try { FolderId folderId = null; result = Folder.RetrieveMapiFolder(store, identity, ref mapiFolder, null, out folderId); } finally { if (mapiFolder != null) { mapiFolder.Dispose(); } } return(result); }
protected virtual List <Rule> LoadRulesFromStore() { Folder currentFolder = this.context.CurrentFolder; MapiFolder mapiFolder = currentFolder.MapiFolder; RulesRetrievalInfo rulesRetrievalInfo; Rule[] rulesForTransport = mapiFolder.GetRulesForTransport(out rulesRetrievalInfo, new PropTag[0]); switch (rulesRetrievalInfo) { case RulesRetrievalInfo.CacheMiss: this.UpdateExtraTrackingData("RuleCacheMisses", currentFolder); break; case RulesRetrievalInfo.CacheCorruption: this.UpdateExtraTrackingData("RuleCacheCorruptions", currentFolder); break; } return(new List <Rule>(rulesForTransport)); }
private MapiMessage WaitForDeliveryReceipt(MapiFolder folder, string subject, int errorLatency, int timeoutSeconds, string sourceAddress, string targetAddress) { bool flag = false; MapiMessage mapiMessage = null; for (int i = 0; i < timeoutSeconds; i++) { mapiMessage = TestMailFlowHelper.GetDeliveryReceipt(folder, subject, true); if (mapiMessage != null) { break; } Thread.Sleep(1000); if (!flag && i >= errorLatency) { flag = true; base.AddErrorMonitoringEvent(1002, Strings.TestMailflowError(sourceAddress, targetAddress, errorLatency)); } } return(mapiMessage); }
private static bool TryOpenFolder(MailboxSession itemStore, out MapiFolder nonIpmSubtreeFolder, out MapiFolder oofHistoryFolder) { MapiStore _ContainedMapiStore = itemStore.__ContainedMapiStore; nonIpmSubtreeFolder = _ContainedMapiStore.GetNonIpmSubtreeFolder(); oofHistoryFolder = null; if (nonIpmSubtreeFolder == null) { OofHistory.Tracer.TraceError((long)itemStore.GetHashCode(), "Unable to open the non ipm subtree folder, OOF history operation is not executed."); return(false); } try { oofHistoryFolder = nonIpmSubtreeFolder.OpenSubFolderByName("Freebusy Data"); } catch (MapiExceptionNotFound) { OofHistory.Tracer.TraceError <string>((long)itemStore.GetHashCode(), "Unable to open the OOF history folder {0}, OOF history operation is not executed.", "Freebusy Data"); return(false); } return(true); }
protected static MapiMessage GetDeliveryReceipt(MapiFolder folder, string subject, bool dsnOnly) { string value = DsnHumanReadableWriter.GetLocalizedSubjectPrefix(DsnFlags.Relay).ToString(); MapiTable contentsTable; MapiTable mapiTable = contentsTable = folder.GetContentsTable(); try { mapiTable.SetColumns(new PropTag[] { PropTag.EntryId, PropTag.Subject, PropTag.MessageClass }); PropValue[][] array = mapiTable.QueryRows(1000, QueryRowsFlags.None); for (int i = 0; i <= array.GetUpperBound(0); i++) { if (!dsnOnly || ObjectClass.IsDsnPositive(array[i][2].Value.ToString())) { string text = array[i][1].Value.ToString(); if ((!text.StartsWith(value, StringComparison.OrdinalIgnoreCase) || subject.StartsWith(value, StringComparison.OrdinalIgnoreCase)) && text.EndsWith(subject, StringComparison.OrdinalIgnoreCase)) { byte[] bytes = array[i][0].GetBytes(); return((MapiMessage)folder.OpenEntry(bytes)); } } } } finally { if (contentsTable != null) { ((IDisposable)contentsTable).Dispose(); } } return(null); }
internal static void ClearOofHistory(MailboxSession itemStore, bool oofEnabled) { MapiFolder mapiFolder = null; MapiFolder mapiFolder2 = null; MapiStream mapiStream = null; bool flag = false; byte[] initialBytes = oofEnabled ? OofHistory.InitialBytesOofStateOn : OofHistory.InitialBytesOofStateOff; try { if (OofHistory.TryOpenFolder(itemStore, out mapiFolder, out mapiFolder2)) { long num = (long)itemStore.GetHashCode(); bool flag2; mapiStream = OofHistory.OpenAndLockStream(mapiFolder2, initialBytes, num, out flag2); flag = true; if (!flag2) { byte[] array = new byte[2]; if (2 != mapiStream.Read(array, 0, 2)) { OofHistory.ResetOofHistoryProperty(mapiStream, initialBytes, num); } else { bool flag3 = 0 != array[1]; if (flag3 == oofEnabled) { OofHistory.Tracer.TraceDebug <bool>(num, "Current OOF state {0} matches in OOF history and mailbox properties, clear is not executed.", oofEnabled); } else { OofHistory.ResetOofHistoryProperty(mapiStream, initialBytes, num); } } } } } finally { if (mapiStream != null) { try { if (flag) { mapiStream.UnlockRegion(0L, 1L, 1); } } finally { mapiStream.Dispose(); } } if (mapiFolder != null) { mapiFolder.Dispose(); mapiFolder = null; } if (mapiFolder2 != null) { mapiFolder2.Dispose(); mapiFolder2 = null; } } }
public override void Execute() { if (!this.ShouldExecuteOnThisStage) { return; } if (base.Context.DetectLoop()) { string[] valueOrDefault = base.Context.Message.GetValueOrDefault <string[]>(MessageItemSchema.XLoop, null); if (valueOrDefault == null || valueOrDefault.Length != 1) { return; } base.Context.TraceDebug("Sending OOF even though loop was detected due to 1 XLoop header in the message."); } if (string.IsNullOrEmpty(base.Context.SenderAddress)) { base.Context.TraceDebug("Sender address was empty, this OOF reply work item is not executed."); return; } MapiFolder nonIpmSubtreeFolder = null; MapiFolder oofHistoryFolder = null; OofHistory oofHistory = null; try { MailboxSession mailboxSession = base.Context.StoreSession as MailboxSession; bool shouldSendOofReply = true; bool shouldKeepOofHistory = true; if ((base.Rule.StateFlags & RuleStateFlags.KeepOOFHistory) == (RuleStateFlags)0) { base.Context.TraceError("Rule does not have 'keep OOF history' flag set, OOF history operation skipped."); shouldKeepOofHistory = false; } if (shouldKeepOofHistory && mailboxSession == null) { base.Context.TraceError("This is a public folder delivery, OOF history operation skipped."); shouldKeepOofHistory = false; } if (shouldKeepOofHistory && mailboxSession.MailboxOwner.MailboxInfo.Location.ServerVersion < 1937801494) { base.Context.TraceError("Recipient's mailbox doesn't support OOF history."); shouldKeepOofHistory = false; } if (string.IsNullOrEmpty(base.Context.SenderAddress)) { base.Context.TraceError("Sender address was empty, OOF history operation skipped."); shouldKeepOofHistory = false; } if (shouldKeepOofHistory) { RuleUtil.RunMapiCode(ServerStrings.UpdateOOFHistoryOperation, delegate(object[] param0) { MapiStore mapiStore = this.Context.StoreSession.Mailbox.MapiStore; byte[] globalRuleId = mapiStore.GlobalIdFromId(this.Rule.ID); byte[] bytes = Encoding.ASCII.GetBytes(this.Context.SenderAddress); oofHistory = new OofHistory(bytes, globalRuleId, this.Context); if (!oofHistory.TryInitialize()) { shouldKeepOofHistory = false; return; } if (mailboxSession.IsMailboxOof()) { shouldSendOofReply = oofHistory.ShouldSendOofReply(); this.Context.TraceDebug <bool>("Should send automatic reply: {0}.", shouldSendOofReply); return; } this.Context.TraceDebug("Mailbox is not OOF, not sending oof reply"); }, new object[0]); } if (!shouldSendOofReply) { if (!ObjectClass.IsOfClass(base.Context.Message.ClassName, "IPM.Note.Microsoft.Approval.Request")) { base.Context.TraceDebug("Automatic reply will not be sent."); return; } base.Context.TraceDebug("Sending automatic reply anyway - the incoming message is an approval request."); } if (!base.Context.LimitChecker.DoesExceedAutoReplyLimit()) { using (MessageItem messageItem = base.OpenMessage(this.messageTemplateEntryId)) { using (MessageItem messageItem2 = RuleMessageUtils.CreateOofReply(base.Context.Message, messageItem, base.Context.StoreSession.PreferedCulture, new InboundConversionOptions(base.Context.StoreSession.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid), base.Context.DefaultDomainName), base.Context.XLoopValue)) { messageItem2[ItemSchema.SpamConfidenceLevel] = -1; messageItem2.AutoResponseSuppress = AutoResponseSuppress.All; base.Context.SetMailboxOwnerAsSender(messageItem2); base.SetRecipientsResponsibility(messageItem2); base.SubmitMessage(messageItem2); } } if (shouldKeepOofHistory && oofHistory != null) { RuleUtil.RunMapiCode(ServerStrings.AppendOOFHistoryEntry, delegate(object[] param0) { oofHistory.AppendEntry(); }, new object[0]); } } } finally { if (oofHistory != null) { RuleUtil.RunMapiCode(ServerStrings.UnlockOOFHistory, delegate(object[] param0) { oofHistory.Dispose(); }, new object[0]); } if (oofHistoryFolder != null) { RuleUtil.RunMapiCode(ServerStrings.DisposeOOFHistoryFolder, delegate(object[] param0) { oofHistoryFolder.Dispose(); }, new object[0]); } if (nonIpmSubtreeFolder != null) { RuleUtil.RunMapiCode(ServerStrings.DisposeNonIPMFolder, delegate(object[] param0) { nonIpmSubtreeFolder.Dispose(); }, new object[0]); } } }
public void CommitChanges(MailboxSession itemStore, MapiFolder folder) { Exception ex = null; try { if (this.toRemove != null) { folder.DeleteRules(this.toRemove.ToArray()); List <byte[]> list = new List <byte[]>(); foreach (Rule rule in this.toRemove) { RuleManager.Tracer.TraceDebug <IExchangePrincipal, string>((long)this.GetHashCode(), "Mailbox:{0}: Deleted rule '{1}'", itemStore.MailboxOwner, rule.Name); RuleManager.TracerPfd.TracePfd <int, IExchangePrincipal, string>((long)this.GetHashCode(), "PFD IWO {0} Mailbox:{1}: Deleted rule '{2}'", 29591, itemStore.MailboxOwner, rule.Name); if (((RuleAction.OOFReply)rule.Actions[0]).ReplyTemplateMessageEntryID != null) { list.Add(((RuleAction.OOFReply)rule.Actions[0]).ReplyTemplateMessageEntryID); } } if (list.Count > 0) { folder.DeleteMessages(DeleteMessagesFlags.None, list.ToArray()); foreach (byte[] bytes in list) { RuleManager.Tracer.TraceDebug <IExchangePrincipal, ByteArray>((long)this.GetHashCode(), "Mailbox:{0}: Deleted reply template '{1}'", itemStore.MailboxOwner, new ByteArray(bytes)); RuleManager.TracerPfd.TracePfd <int, IExchangePrincipal, ByteArray>((long)this.GetHashCode(), "PFD IWO {0} Mailbox:{1}: Deleted reply template '{2}'", 19607, itemStore.MailboxOwner, new ByteArray(bytes)); } } this.toRemove = null; } if (this.toUpdate != null) { folder.ModifyRules(this.toUpdate.ToArray()); foreach (Rule rule2 in this.toUpdate) { RuleManager.Tracer.TraceDebug <IExchangePrincipal, string>((long)this.GetHashCode(), "Mailbox:{0}: Updated rule '{1}'", itemStore.MailboxOwner, rule2.Name); RuleManager.TracerPfd.TracePfd <int, IExchangePrincipal, string>((long)this.GetHashCode(), "PFD IWO {0} Mailbox:{1}: Updated rule '{2}'", 27799, itemStore.MailboxOwner, rule2.Name); } this.toUpdate = null; } if (this.toAdd != null) { folder.AddRules(this.toAdd.ToArray()); foreach (Rule rule3 in this.toAdd) { RuleManager.Tracer.TraceDebug <IExchangePrincipal, string>((long)this.GetHashCode(), "Mailbox:{0}: Created new rule '{1}'", itemStore.MailboxOwner, rule3.Name); RuleManager.TracerPfd.TracePfd <int, IExchangePrincipal, string>((long)this.GetHashCode(), "PFD IWO {0} Mailbox:{1}: Created new rule '{2}'", 23703, itemStore.MailboxOwner, rule3.Name); } this.toAdd = null; } } catch (MapiExceptionInvalidParameter mapiExceptionInvalidParameter) { ex = mapiExceptionInvalidParameter; } catch (MapiExceptionNotFound mapiExceptionNotFound) { ex = mapiExceptionNotFound; } catch (MapiExceptionQuotaExceeded mapiExceptionQuotaExceeded) { ex = mapiExceptionQuotaExceeded; } catch (MapiExceptionShutoffQuotaExceeded mapiExceptionShutoffQuotaExceeded) { ex = mapiExceptionShutoffQuotaExceeded; } catch (MapiExceptionNotEnoughMemory mapiExceptionNotEnoughMemory) { ex = mapiExceptionNotEnoughMemory; } if (ex is MapiExceptionQuotaExceeded || ex is MapiExceptionShutoffQuotaExceeded || ex is MapiExceptionNotEnoughMemory) { RuleManager.Tracer.TraceError <IExchangePrincipal, Exception>((long)this.GetHashCode(), "Mailbox:{0}: cannot commit rule changes because exceeded rule quota. Exception {1}", itemStore.MailboxOwner, ex); Globals.OOFLogger.LogEvent(InfoWorkerEventLogConstants.Tuple_OOFRulesQuotaExceeded, itemStore.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString(), new object[] { itemStore.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString() }); } if (ex != null) { RuleManager.Tracer.TraceError <IExchangePrincipal, Exception>((long)this.GetHashCode(), "Mailbox:{0}: An OOF rule could not be saved. Exception: {1}", itemStore.MailboxOwner, ex); throw new OofRulesSaveException(ex); } }
internal static Folder BindToSubfolderByName(StoreSession session, StoreObjectId containerId, string folderName, params PropertyDefinition[] propsToReturn) { Folder result; using (Folder folder = Folder.Bind(session, containerId)) { MapiFolder mapiFolder = null; Folder folder2 = null; bool flag = false; try { object thisObject = null; bool flag2 = false; try { if (session != null) { session.BeginMapiCall(); session.BeginServerHealthCall(); flag2 = true; } if (StorageGlobals.MapiTestHookBeforeCall != null) { StorageGlobals.MapiTestHookBeforeCall(MethodBase.GetCurrentMethod()); } mapiFolder = folder.MapiFolder.OpenSubFolderByName(folderName); } catch (MapiPermanentException ex) { throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenFolder, ex, session, thisObject, "{0}. MapiException = {1}.", new object[] { string.Format("DefaultFolderCreator::BindToSubfolderByName. Unable to open folder by name.", new object[0]), ex }); } catch (MapiRetryableException ex2) { throw StorageGlobals.TranslateMapiException(ServerStrings.MapiCannotOpenFolder, ex2, session, thisObject, "{0}. MapiException = {1}.", new object[] { string.Format("DefaultFolderCreator::BindToSubfolderByName. Unable to open folder by name.", new object[0]), ex2 }); } finally { try { if (session != null) { session.EndMapiCall(); if (flag2) { session.EndServerHealthCall(); } } } finally { if (StorageGlobals.MapiTestHookAfterCall != null) { StorageGlobals.MapiTestHookAfterCall(MethodBase.GetCurrentMethod()); } } } using (MapiPropertyBag mapiPropertyBag = new MapiPropertyBag(session, mapiFolder)) { byte[] entryId = (byte[])mapiPropertyBag.GetProperties(new NativeStorePropertyDefinition[] { InternalSchema.EntryId })[0]; StoreObjectId folderObjectId = StoreObjectId.FromProviderSpecificId(entryId); folder2 = Folder.InternalBind <Folder>(session, mapiFolder, folderObjectId, null, propsToReturn); mapiPropertyBag.DetachMapiProp(); } flag = true; result = folder2; } finally { if (!flag) { Util.DisposeIfPresent(folder2); Util.DisposeIfPresent(mapiFolder); } } } return(result); }
internal static void RemoveOofHistoryEntriesWithProperty(MailboxSession itemStore, bool oofEnabled, OofHistory.PropId propId, byte[] propValue) { MapiFolder mapiFolder = null; MapiFolder mapiFolder2 = null; MapiStream mapiStream = null; bool flag = false; byte[] initialBytes = oofEnabled ? OofHistory.InitialBytesOofStateOn : OofHistory.InitialBytesOofStateOff; try { if (OofHistory.TryOpenFolder(itemStore, out mapiFolder, out mapiFolder2)) { long hashCode = (long)itemStore.GetHashCode(); bool flag2; mapiStream = OofHistory.OpenAndLockStream(mapiFolder2, initialBytes, hashCode, out flag2); flag = true; if (!flag2) { int num; if (OofHistory.TryGetStreamLengthForEntryRemoval(hashCode, mapiStream, out num)) { byte[] buffer; if (OofHistory.TryReadAllFromStream(hashCode, mapiStream, num, out buffer)) { int num2 = OofHistory.RemoveEntriesWithProperty(num, buffer, propId, propValue, hashCode); if (num2 < num) { mapiStream.Seek(0L, SeekOrigin.Begin); mapiStream.Write(buffer, 0, num2); mapiStream.SetLength((long)num2); } } } } } } finally { if (mapiStream != null) { try { if (flag) { mapiStream.UnlockRegion(0L, 1L, 1); } } finally { mapiStream.Dispose(); } } if (mapiFolder != null) { mapiFolder.Dispose(); mapiFolder = null; } if (mapiFolder2 != null) { mapiFolder2.Dispose(); mapiFolder2 = null; } } }