private static BodyReadStream InternalTryCreateBodyStream(ICoreItem coreItem, BodyReadConfiguration configuration, bool createEmtpyStreamIfNotFound, long?length) { BodyReadStream result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { Stream stream = BodyReadStream.OpenBodyStream(coreItem); disposeGuard.Add <Stream>(stream); Stream stream2 = stream; if (stream2 == null) { if (!createEmtpyStreamIfNotFound) { return(null); } stream2 = Body.GetEmptyStream(); } ConversionCallbackBase conversionCallbackBase; Stream disposable = BodyReadDelegates.CreateStream(coreItem, configuration, stream2, out conversionCallbackBase); disposeGuard.Add <Stream>(disposable); BodyReadStream bodyReadStream = new BodyReadStream(stream, disposable, conversionCallbackBase, length); disposeGuard.Add <BodyReadStream>(bodyReadStream); disposeGuard.Success(); result = bodyReadStream; } return(result); }
public override IAttachment Read(string attachmentId) { IList <AttachmentId> attachmentIds = IdConverter.GetAttachmentIds(attachmentId); IAttachment result; using (IItem item = this.BindToParentItem()) { using (DisposeGuard disposeGuard = default(DisposeGuard)) { IItem item2 = item; Attachment attachment = null; for (int i = 0; i < attachmentIds.Count; i++) { attachment = IrmUtils.GetAttachmentCollection(item2).Open(attachmentIds[i]); disposeGuard.Add <Attachment>(attachment); if (i < attachmentIds.Count - 1) { if (!(attachment is ItemAttachment)) { throw new CorruptDataException(Strings.ErrorAllButLastNestedAttachmentMustBeItemAttachment); } ItemAttachment itemAttachment = attachment as ItemAttachment; item2 = itemAttachment.GetItem(); disposeGuard.Add <IItem>(item2); } } StorageTranslator <IAttachment, IAttachment> attachmentTranslator = this.GetAttachmentTranslator(attachment.AttachmentType, false); IAttachment attachment2 = attachmentTranslator.ConvertToEntity(attachment); attachment2.Id = attachmentId; result = attachment2; } } return(result); }
internal static ActivityScope AddActivityScope(ActivityContextState activityContextState) { Guid guid = Guid.NewGuid(); ActivityScope result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { try { ActivityScopeImpl.scopeCacheLock.EnterWriteLock(); ActivityScopeImpl activityScopeImpl = new ActivityScopeImpl(guid); disposeGuard.Add <ActivityScopeImpl>(activityScopeImpl); ActivityScopeImpl.scopeCache.Add(guid, activityScopeImpl); ActivityScope activityScope = new ActivityScope(activityScopeImpl); disposeGuard.Add <ActivityScope>(activityScope); activityScopeImpl.UpdateFromState(activityContextState); SingleContext.Singleton.LocalId = new Guid?(guid); SingleContext.Singleton.SetId(); disposeGuard.Success(); result = activityScope; } finally { try { ActivityScopeImpl.scopeCacheLock.ExitWriteLock(); } catch (SynchronizationLockException) { } } } return(result); }
// Token: 0x06000310 RID: 784 RVA: 0x000132E8 File Offset: 0x000114E8 private static RfriContext CreateRfriContext(ClientBinding clientBinding) { RfriContext rfriContext = null; using (DisposeGuard disposeGuard = default(DisposeGuard)) { ClientSecurityContext clientSecurityContext = null; bool isAnonymous = false; string text = null; string userDomain = null; RpcHttpConnectionProperties rpcHttpConnectionProperties = null; if (!RpcDispatch.TryGetAuthContextInfo(clientBinding, out clientSecurityContext, out isAnonymous, out text, out userDomain, out rpcHttpConnectionProperties)) { ExTraceGlobals.ReferralTracer.TraceError <Guid>(0L, "Could not resolve anonymous user for session id: {0}", clientBinding.AssociationGuid); throw new RfriException(RfriStatus.LogonFailed, "Could not resolve anonymous user."); } disposeGuard.Add <ClientSecurityContext>(clientSecurityContext); Guid empty = Guid.Empty; if (rpcHttpConnectionProperties != null && rpcHttpConnectionProperties.RequestIds.Length > 0) { Guid.TryParse(rpcHttpConnectionProperties.RequestIds[rpcHttpConnectionProperties.RequestIds.Length - 1], out empty); } rfriContext = new RfriContext(clientSecurityContext, userDomain, clientBinding.ClientAddress, clientBinding.ServerAddress, clientBinding.ProtocolSequence, clientBinding.AuthenticationType.ToString(), clientBinding.IsEncrypted, isAnonymous, empty); disposeGuard.Add <RfriContext>(rfriContext); if (!rfriContext.TryAcquireBudget()) { ExTraceGlobals.ReferralTracer.TraceError((long)rfriContext.ContextHandle, "Could not acquire budget"); throw new RfriException(RfriStatus.GeneralFailure, "Failed to acquire budget."); } disposeGuard.Success(); } return(rfriContext); }
private void VerifyLegacyPublicFolderDatabaseLocked() { PublicFolderEndpoint publicFolderEndpoint = (PublicFolderEndpoint)this.DataObject.SourceEndpoint; using (DisposeGuard disposeGuard = default(DisposeGuard)) { IMailbox mailbox; if (publicFolderEndpoint != null) { mailbox = disposeGuard.Add <IMailbox>(publicFolderEndpoint.ConnectToSourceDatabase()); } else { DatabaseIdParameter id = DatabaseIdParameter.Parse(this.DataObject.SourcePublicFolderDatabase); PublicFolderDatabase publicFolderDatabase = (PublicFolderDatabase)base.GetDataObject <PublicFolderDatabase>(id, this.ConfigurationSession, null, new LocalizedString?(Strings.ErrorDatabaseNotFound(this.DataObject.SourcePublicFolderDatabase)), new LocalizedString?(Strings.ErrorDatabaseNotUnique(this.DataObject.SourcePublicFolderDatabase))); mailbox = disposeGuard.Add <IMailbox>(PublicFolderEndpoint.ConnectToLocalSourceDatabase(publicFolderDatabase.ExchangeObjectId)); } try { bool flag; mailbox.SetInTransitStatus(InTransitStatus.MoveSource, out flag); mailbox.SetInTransitStatus(InTransitStatus.NotInTransit, out flag); } catch (SourceMailboxAlreadyBeingMovedTransientException) { base.WriteError(new MigrationBatchCannotBeCompletedException(Strings.CompletePublicFolderMigrationBatchRequiresSourceLockDown)); } } }
public PersistablePropertyBag CreateAttachment(ICollection <PropertyDefinition> propertiesToLoad, CoreAttachment attachmentToClone, IItem itemToAttach, out int attachmentNumber) { this.CheckDisposed(null); InMemoryPersistablePropertyBag inMemoryPersistablePropertyBag = new InMemoryPersistablePropertyBag(propertiesToLoad); inMemoryPersistablePropertyBag.ExTimeZone = this.ExTimeZone; if (attachmentToClone != null) { throw new NotSupportedException("CreateAttachment for copied attachments is not supported"); } attachmentNumber = this.attachmentCounter++; inMemoryPersistablePropertyBag[InternalSchema.AttachNum] = attachmentNumber; this.newAttachmentList.Add(attachmentNumber, inMemoryPersistablePropertyBag); if (itemToAttach != null) { string text = itemToAttach.TryGetProperty(InternalSchema.ItemClass) as string; Schema schema = (text != null) ? ObjectClass.GetSchema(text) : ItemSchema.Instance; propertiesToLoad = InternalSchema.Combine <PropertyDefinition>(schema.AutoloadProperties, propertiesToLoad); using (DisposeGuard disposeGuard = default(DisposeGuard)) { PersistablePropertyBag persistablePropertyBag = new InMemoryPersistablePropertyBag(propertiesToLoad); disposeGuard.Add <PersistablePropertyBag>(persistablePropertyBag); persistablePropertyBag.ExTimeZone = this.ExTimeZone; CoreItem coreItem = new CoreItem(null, persistablePropertyBag, null, null, Origin.New, ItemLevel.Attached, propertiesToLoad, ItemBindOption.LoadRequiredPropertiesOnly); disposeGuard.Add <CoreItem>(coreItem); CoreItem.CopyItemContent(itemToAttach.CoreItem, coreItem); this.attachedItems.Add(attachmentNumber, coreItem); disposeGuard.Success(); } } return(inMemoryPersistablePropertyBag); }
private static Folder GetFolder(AnchorContext context, MailboxSession mailboxSession, StoreObjectId rootFolderId, string folderName) { AnchorUtil.ThrowOnNullArgument(mailboxSession, "mailboxSession"); AnchorUtil.ThrowOnNullArgument(rootFolderId, "rootFolderId"); AnchorUtil.ThrowOnNullArgument(folderName, "folderName"); Folder result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { Folder folder = null; StoreObjectId storeObjectId = AnchorFolder.GetFolderId(context, mailboxSession, rootFolderId, folderName); if (storeObjectId == null) { folder = Folder.Create(mailboxSession, rootFolderId, StoreObjectType.Folder, folderName, CreateMode.OpenIfExists); disposeGuard.Add <Folder>(folder); folder.Save(); folder.Load(AnchorFolder.FolderIdPropertyDefinition); storeObjectId = folder.Id.ObjectId; } if (folder == null) { folder = Folder.Bind(mailboxSession, storeObjectId, AnchorFolder.FolderIdPropertyDefinition); disposeGuard.Add <Folder>(folder); } disposeGuard.Success(); result = folder; } return(result); }
// Token: 0x06000313 RID: 787 RVA: 0x0001366C File Offset: 0x0001186C private ICancelableAsyncResult BeginWrapper(string methodName, CancelableAsyncCallback asyncCallback, object asyncState, ClientBinding clientBinding, string legacyDn, Func <RfriContext, RfriDispatchTask> beginDelegate) { ICancelableAsyncResult asyncResult = null; RfriAsyncDispatch.ConditionalExceptionWrapper(ExTraceGlobals.ReferralTracer.IsTraceEnabled(TraceType.DebugTrace), delegate { if (ExTraceGlobals.ReferralTracer.IsTraceEnabled(TraceType.DebugTrace)) { using (ClientSecurityContext clientSecurityContext = clientBinding.GetClientSecurityContext()) { ExTraceGlobals.ReferralTracer.TraceDebug(0, 0L, "{0} started. LegacyDn={1}. ClientAddress={2}. ServerAddress={3}. ProtocolSequence={4}. EndPoint={5}. IsEncrypted={6}. ClientSecurityContext={7}.", new object[] { methodName, legacyDn, clientBinding.ClientAddress, clientBinding.ServerAddress, clientBinding.ProtocolSequence, clientBinding.ClientEndpoint, clientBinding.IsEncrypted, clientSecurityContext }); } } FailureAsyncResult <RfriStatus> failureAsyncResult = null; this.CheckShuttingDown(); try { using (DisposeGuard disposeGuard = default(DisposeGuard)) { RfriContext rfriContext = RfriAsyncDispatch.CreateRfriContext(clientBinding); disposeGuard.Add <RfriContext>(rfriContext); RfriDispatchTask rfriDispatchTask = beginDelegate(rfriContext); disposeGuard.Add <RfriDispatchTask>(rfriDispatchTask); asyncResult = rfriDispatchTask.AsyncResult; this.SubmitTask(rfriDispatchTask); disposeGuard.Success(); } } catch (FailRpcException ex) { failureAsyncResult = new FailureAsyncResult <RfriStatus>((RfriStatus)ex.ErrorCode, IntPtr.Zero, ex, asyncCallback, asyncState); asyncResult = failureAsyncResult; } catch (RfriException ex2) { failureAsyncResult = new FailureAsyncResult <RfriStatus>(ex2.Status, IntPtr.Zero, ex2, asyncCallback, asyncState); asyncResult = failureAsyncResult; } if (failureAsyncResult != null && !ThreadPool.QueueUserWorkItem(RfriAsyncDispatch.FailureWaitCallback, failureAsyncResult)) { failureAsyncResult.InvokeCallback(); } ExTraceGlobals.ReferralTracer.TraceDebug <string>(0, 0L, "{0} succeeded.", methodName); }, delegate(Exception exception) { ExTraceGlobals.ReferralTracer.TraceDebug <string, Exception>(0, 0L, "{0} failed. Exception={1}.", methodName, exception); }); return(asyncResult); }
protected override TeamMailboxSyncInfo CreateOnCacheMiss(TeamMailboxSyncId key, ref bool shouldAdd) { IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(key.DomainController, true, ConsistencyMode.PartiallyConsistent, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(key.OrgId), 105, "CreateOnCacheMiss", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\LinkedFolder\\TeamMailboxSyncInfoCache.cs"); ADRecipient adrecipient = tenantOrRootOrgRecipientSession.FindByExchangeGuid(key.MailboxGuid); ADUser aduser = adrecipient as ADUser; if (aduser == null) { return(null); } TeamMailboxLifecycleState teamMailboxLifecycleState = TeamMailboxLifecycleState.Active; if (TeamMailbox.IsPendingDeleteSiteMailbox(aduser)) { teamMailboxLifecycleState = TeamMailboxLifecycleState.PendingDelete; } else if (aduser.SharePointUrl == null) { teamMailboxLifecycleState = TeamMailboxLifecycleState.Unlinked; } ExchangePrincipal exchangePrincipal = null; try { exchangePrincipal = ExchangePrincipal.FromMailboxGuid(ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(key.OrgId), key.MailboxGuid, key.DomainController); } catch (ObjectNotFoundException) { return(null); } TeamMailboxSyncInfo result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { MailboxSession mailboxSession = null; UserConfiguration userConfiguration = null; if (teamMailboxLifecycleState == TeamMailboxLifecycleState.Active) { mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=TeamMailbox;Action=CommitChanges;Interactive=False"); disposeGuard.Add <MailboxSession>(mailboxSession); if (!string.Equals(mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn, TeamMailboxSyncInfoCache.LocalServerFqdn, StringComparison.OrdinalIgnoreCase)) { throw new WrongServerException(new LocalizedString(string.Format("Non-local XSO MailboxSession not allowed for TeamMailboxSync. TeamMailbox Name: {0}, MailboxGuid {1}, ServerFqdn {2}", mailboxSession.MailboxOwner.MailboxInfo.DisplayName, mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, mailboxSession.MailboxOwner.MailboxInfo.Location.ServerFqdn))); } userConfiguration = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, this.syncLogConfigurationName, UserConfigurationTypes.Stream, true); disposeGuard.Add <UserConfiguration>(userConfiguration); } TeamMailbox teamMailbox = TeamMailbox.FromDataObject(aduser); TeamMailboxSyncInfo teamMailboxSyncInfo = new TeamMailboxSyncInfo(key.MailboxGuid, teamMailboxLifecycleState, mailboxSession, exchangePrincipal, teamMailbox.DisplayName, teamMailbox.WebCollectionUrl, teamMailbox.WebId, (aduser.SharePointUrl != null) ? aduser.SharePointUrl.AbsoluteUri : null, (teamMailboxLifecycleState == TeamMailboxLifecycleState.Active) ? this.resourceMonitorFactory.Create(exchangePrincipal.MailboxInfo.MailboxDatabase.ObjectGuid) : null, userConfiguration); disposeGuard.Success(); result = teamMailboxSyncInfo; } return(result); }
private Folder GetSearchRequestFolder() { StoreObjectId defaultFolderId = base.MailboxSession.GetDefaultFolderId(DefaultFolderType.Root); string folderName = this.setting.FolderName; Folder folder = null; using (DisposeGuard disposeGuard = default(DisposeGuard)) { int num = 0; while (folder == null && num <= 1) { StoreObjectId storeObjectId; lock (this.setting.LockObj) { if (!this.setting.CachedFolderIds.TryGetValue(base.MailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, out storeObjectId)) { storeObjectId = this.GetFolderId(base.MailboxSession, defaultFolderId, folderName); if (storeObjectId == null) { folder = Folder.Create(base.MailboxSession, defaultFolderId, StoreObjectType.Folder, folderName, CreateMode.OpenIfExists); disposeGuard.Add <Folder>(folder); folder.Save(); folder.Load(AuditLogSearchDataProviderBase.FolderProperties); storeObjectId = folder.Id.ObjectId; } this.setting.CachedFolderIds[base.MailboxSession.MailboxOwner.MailboxInfo.MailboxGuid] = storeObjectId; } } if (folder == null) { try { folder = Folder.Bind(base.MailboxSession, storeObjectId); disposeGuard.Add <Folder>(folder); } catch (ObjectNotFoundException) { lock (this.setting.LockObj) { this.setting.CachedFolderIds.Remove(base.MailboxSession.MailboxOwner.MailboxInfo.MailboxGuid); } bool flag3 = num >= 1; if (flag3) { throw; } } } num++; } disposeGuard.Success(); } return(folder); }
protected override GetItemJsonResponse InternalExecute(PublishedCalendar publishedFolder) { base.TraceDebug("GetItemAnonymous:InternalExecute", new object[0]); if (publishedFolder.DetailLevel == DetailLevelEnumType.AvailabilityOnly) { return(this.CreateErrorResponse(new InvalidOperationException("Item details are not allowed"), ResponseCodeType.ErrorInvalidRequest)); } StoreObjectId itemId = null; bool flag; try { this.GetStoreObjectId(out itemId, out flag); } catch (StoragePermanentException exception) { return(this.CreateErrorResponse(exception, ResponseCodeType.ErrorInvalidRequest)); } GetItemJsonResponse result; try { base.TraceDebug("Get item from published folder", new object[0]); using (DisposeGuard disposeGuard = default(DisposeGuard)) { CalendarItemBase item = publishedFolder.GetItem(itemId, GetItemAnonymous.propertiesToFetch); disposeGuard.Add <CalendarItemBase>(item); if (flag) { base.TraceDebug("Request was for a Recurring Master", new object[0]); if (!(item is CalendarItemOccurrence)) { return(this.CreateErrorResponse(new Exception("Invalid RecurrenceMasterId"), ResponseCodeType.ErrorInvalidRequest)); } itemId = ((CalendarItemOccurrence)item).MasterId.ObjectId; item = publishedFolder.GetItem(itemId, GetItemAnonymous.propertiesToFetch); disposeGuard.Add <CalendarItemBase>(item); } EwsCalendarItemType serviceObject = this.CreateServiceObject(item); if (item.Sensitivity == Sensitivity.Private) { base.TraceDebug("Clear sensitive information", new object[0]); this.ClearSensitiveInformation(serviceObject); } result = this.CreateSuccessResponse(serviceObject); } } catch (ObjectNotFoundException exception2) { result = this.CreateErrorResponse(exception2, ResponseCodeType.ErrorInvalidRequest); } return(result); }
internal static NspiContext CreateContext(ClientBinding clientBinding) { NspiContext result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { ClientSecurityContext clientSecurityContext = null; bool isAnonymous = false; string text = null; string userDomain = null; RpcHttpConnectionProperties rpcHttpConnectionProperties = null; if (!RpcDispatch.TryGetAuthContextInfo(clientBinding, out clientSecurityContext, out isAnonymous, out text, out userDomain, out rpcHttpConnectionProperties)) { ExTraceGlobals.NspiTracer.TraceError <Guid>(0L, "Could not resolve anonymous user for session id: {0}", clientBinding.AssociationGuid); throw new NspiException(NspiStatus.LogonFailed, "Could not resolve anonymous user."); } disposeGuard.Add <ClientSecurityContext>(clientSecurityContext); Guid empty = Guid.Empty; if (rpcHttpConnectionProperties != null && rpcHttpConnectionProperties.RequestIds.Length > 0) { Guid.TryParse(rpcHttpConnectionProperties.RequestIds[rpcHttpConnectionProperties.RequestIds.Length - 1], out empty); } NspiContext nspiContext = new NspiContext(clientSecurityContext, userDomain, clientBinding.ClientAddress, clientBinding.ServerAddress, clientBinding.ProtocolSequence, empty); disposeGuard.Add <NspiContext>(nspiContext); nspiContext.IsAnonymous = isAnonymous; if (!nspiContext.TryAcquireBudget()) { ExTraceGlobals.NspiTracer.TraceError((long)nspiContext.ContextHandle, "Could not acquire budget"); throw new NspiException(NspiStatus.GeneralFailure, "Failed to acquire budget."); } bool flag = false; lock (ClientContextCache.clientContextDictionaryLock) { flag = ClientContextCache.clientContextDictionary.ContainsKey(nspiContext.ContextHandle); if (!flag) { ClientContextCache.clientContextDictionary.Add(nspiContext.ContextHandle, nspiContext); AddressBookPerformanceCountersWrapper.AddressBookPerformanceCounters.NspiConnectionsCurrent.RawValue = (long)ClientContextCache.clientContextDictionary.Count; AddressBookPerformanceCountersWrapper.AddressBookPerformanceCounters.NspiConnectionsTotal.Increment(); AddressBookPerformanceCountersWrapper.AddressBookPerformanceCounters.NspiConnectionsRate.Increment(); } } if (flag) { ExTraceGlobals.NspiTracer.TraceError((long)nspiContext.ContextHandle, "Duplicate contextHandle found in context dictionary"); throw new NspiException(NspiStatus.GeneralFailure, "Duplicate contextHandle found in context dictionary."); } disposeGuard.Success(); result = nspiContext; } return(result); }
// Token: 0x06001894 RID: 6292 RVA: 0x00064FAC File Offset: 0x000631AC public static TcpServerChannel AuthenticateAsServer(TcpListener listener, Socket connection) { TcpServerChannel tcpServerChannel = null; int iotimeoutInMSec = listener.ListenerConfig.IOTimeoutInMSec; NegotiateStream negotiateStream = null; using (DisposeGuard disposeGuard = default(DisposeGuard)) { NetworkStream networkStream = new NetworkStream(connection, false); disposeGuard.Add <NetworkStream>(networkStream); negotiateStream = new NegotiateStream(networkStream, false); disposeGuard.Add <NegotiateStream>(negotiateStream); negotiateStream.WriteTimeout = iotimeoutInMSec; negotiateStream.ReadTimeout = iotimeoutInMSec; negotiateStream.AuthenticateAsServer(CredentialCache.DefaultNetworkCredentials, ProtectionLevel.None, TokenImpersonationLevel.Identification); if (!negotiateStream.IsAuthenticated) { string text = "Authentication failed"; ExTraceGlobals.TcpServerTracer.TraceError((long)connection.GetHashCode(), text); ReplayCrimsonEvents.ServerSideConnectionFailure.LogPeriodic <string, string, string>(Environment.MachineName, DiagCore.DefaultEventSuppressionInterval, connection.RemoteEndPoint.ToString(), connection.LocalEndPoint.ToString(), text); } if (!negotiateStream.IsMutuallyAuthenticated) { ExTraceGlobals.TcpServerTracer.TraceError((long)connection.GetHashCode(), "Mutual Authentication failed"); } WindowsIdentity wid = negotiateStream.RemoteIdentity as WindowsIdentity; string text2 = null; try { text2 = negotiateStream.RemoteIdentity.Name; } catch (SystemException ex) { string text3 = string.Format("RemoteIdentity.Name failed: {0}", ex.ToString()); ExTraceGlobals.TcpServerTracer.TraceError((long)connection.GetHashCode(), text3); ReplayCrimsonEvents.ServerSideConnectionFailure.LogPeriodic <string, string, string>(Environment.MachineName, DiagCore.DefaultEventSuppressionInterval, connection.RemoteEndPoint.ToString(), connection.LocalEndPoint.ToString(), text3); } if (!RemoteDataProvider.AuthorizeRequest(wid)) { ExTraceGlobals.TcpServerTracer.TraceError <string, string>((long)connection.GetHashCode(), "Authorization failed. ClientMachine={0}, User={1}", connection.RemoteEndPoint.ToString(), text2); ReplayCrimsonEvents.ServerSideConnectionFailure.LogPeriodic <string, string, string>(Environment.MachineName, DiagCore.DefaultEventSuppressionInterval, connection.RemoteEndPoint.ToString(), connection.LocalEndPoint.ToString(), string.Format("AuthorizeRequest failed. User={0}", text2)); return(null); } tcpServerChannel = new TcpServerChannel(connection, negotiateStream, listener.ListenerConfig.IOTimeoutInMSec, listener.ListenerConfig.IdleLimit); ExTraceGlobals.TcpServerTracer.TraceDebug <string, bool, bool>((long)tcpServerChannel.GetHashCode(), "Connection authenticated as {0}. Encrypted={1} Signed={2}", text2, negotiateStream.IsEncrypted, negotiateStream.IsSigned); if (tcpServerChannel != null) { disposeGuard.Success(); } } return(tcpServerChannel); }
public static SecureArray <char> TransformToSecureCharArray(this SecureString securePassword, CharTransformDelegate transform) { if (securePassword == null) { throw new ArgumentNullException("securePassword"); } if (transform == null) { throw new ArgumentNullException("transform"); } SecureArray <char> secureArray = null; using (DisposeGuard disposeGuard = default(DisposeGuard)) { secureArray = securePassword.ConvertToSecureCharArray(); disposeGuard.Add <SecureArray <char> >(secureArray); int num = 0; bool flag = false; foreach (char c in secureArray.ArrayValue) { char[] array = transform(c); num += ((array == null) ? 1 : array.Length); flag |= (array != null); } if (flag) { using (SecureArray <char> secureArray2 = secureArray) { secureArray = new SecureArray <char>(num); disposeGuard.Add <SecureArray <char> >(secureArray); int num2 = 0; foreach (char c2 in secureArray2.ArrayValue) { char[] array2 = transform(c2); if (array2 == null) { secureArray.ArrayValue[num2] = c2; num2++; } else { array2.CopyTo(secureArray.ArrayValue, num2); num2 += array2.Length; } } } } disposeGuard.Success(); } return(secureArray); }
// Token: 0x06000314 RID: 788 RVA: 0x000137EC File Offset: 0x000119EC private RfriStatus EndWrapper(string methodName, ICancelableAsyncResult asyncResult, Func <RfriDispatchTask, RfriStatus> endDelegate) { RfriStatus rfriStatus = RfriStatus.Success; RfriAsyncDispatch.ConditionalExceptionWrapper(ExTraceGlobals.ReferralTracer.IsTraceEnabled(TraceType.DebugTrace), delegate { DispatchTaskAsyncResult dispatchTaskAsyncResult = asyncResult as DispatchTaskAsyncResult; if (dispatchTaskAsyncResult != null) { RfriDispatchTask rfriDispatchTask = (RfriDispatchTask)dispatchTaskAsyncResult.DispatchTask; using (DisposeGuard disposeGuard = default(DisposeGuard)) { disposeGuard.Add <RfriDispatchTask>(rfriDispatchTask); rfriStatus = endDelegate(rfriDispatchTask); } ExTraceGlobals.ReferralTracer.TraceDebug <string, RfriStatus>(0, 0L, "{0} succeeded. RfriStatus={1}.", methodName, rfriStatus); return; } FailureAsyncResult <RfriStatus> failureAsyncResult = asyncResult as FailureAsyncResult <RfriStatus>; if (failureAsyncResult != null) { rfriStatus = failureAsyncResult.ErrorCode; ExTraceGlobals.ReferralTracer.TraceDebug <string, RfriStatus, Exception>(0, 0L, "{0} failed. RfriStatus={1}. Exception={2}.", methodName, rfriStatus, failureAsyncResult.Exception); return; } throw new InvalidOperationException(string.Format("Invalid IAsyncResult encountered; {0}", asyncResult)); }, delegate(Exception exception) { ExTraceGlobals.ReferralTracer.TraceDebug <string, Exception>(0, 0L, "{0} failed. Exception={1}.", methodName, exception); }); return(rfriStatus); }
public Stream GetReadOnlyApplefileStream() { base.CheckDisposed("GetReadOnlyApplefileStream"); if (this.IsFlaggedAsMacAttachment) { object obj = base.TryGetProperty(InternalSchema.AttachmentMacInfo); if (obj is byte[]) { return(new MemoryStream(obj as byte[], false)); } if (PropertyError.IsPropertyValueTooBig(obj)) { return(this.OpenPropertyStream(InternalSchema.AttachmentMacInfo, PropertyOpenMode.ReadOnly)); } using (Stream rawContentStream = this.GetRawContentStream(PropertyOpenMode.ReadOnly)) { if (this.IsMacAttachmentInternal(rawContentStream)) { using (DisposeGuard disposeGuard = default(DisposeGuard)) { Stream stream = disposeGuard.Add <MemoryStream>(new MemoryStream()); string text = null; byte[] array = null; MimeAppleTranscoder.MacBinToApplefile(rawContentStream, stream, out text, out array); disposeGuard.Success(); return(stream); } } throw new CorruptDataException(ServerStrings.ConversionFailedInvalidMacBin); } } throw new InvalidOperationException(); }
protected virtual IInjectorService CreateInjectorClient(DirectoryServer server, IDirectoryProvider directory) { IInjectorService result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { InjectorClient injectorClient = InjectorClient.Create(server.Fqdn, directory, this.logger); disposeGuard.Add <InjectorClient>(injectorClient); bool flag = true; IInjectorService injectorService = injectorClient; if (!injectorClient.ServerVersion[1]) { flag = false; injectorService = this.CreateCompatibilityInjectorClient(server); } if (!injectorClient.ServerVersion[2]) { injectorService = new ConsumerMetricsInjectorCapabilityDecorator(injectorService); } if (flag) { disposeGuard.Success(); } result = injectorService; } return(result); }
protected virtual ILoadBalanceService CreateLoadBalancerClient(DirectoryServer server, IDirectoryProvider directory) { ILoadBalanceService result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { LoadBalancerClient loadBalancerClient = LoadBalancerClient.Create(server.Fqdn, directory, this.logger); disposeGuard.Add <LoadBalancerClient>(loadBalancerClient); bool flag = true; ILoadBalanceService loadBalanceService = loadBalancerClient; if (!loadBalancerClient.ServerVersion[1]) { flag = false; loadBalanceService = this.CreateCompatibilityLoadBalanceClient(server); } else if (!loadBalancerClient.ServerVersion[2]) { loadBalanceService = new SoftDeletedRemovalCapabilityDecorator(loadBalanceService, server); } if (!loadBalancerClient.ServerVersion[3]) { loadBalanceService = new ConsumerMetricsLoadBalanceCapabilityDecorator(loadBalanceService, server); } if (!loadBalancerClient.ServerVersion[5]) { loadBalanceService = new CapacitySummaryCapabilityDecorator(loadBalanceService, server, this.serviceContext); } if (flag) { disposeGuard.Success(); } result = loadBalanceService; } return(result); }
private ISourceMailbox GetSourceMailbox() { ISourceMailbox result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { ExchangePrincipal exchangePrincipal; if (!PublicFolderSession.TryGetPublicFolderMailboxPrincipal(this.OrganizationId, PublicFolderSession.HierarchyMailboxGuidAlias, true, out exchangePrincipal)) { throw new StoragePermanentException(PublicFolderSession.GetNoPublicFoldersProvisionedError(this.OrganizationId)); } ISourceMailbox sourceMailbox = new RemoteSourceMailbox(exchangePrincipal.MailboxInfo.Location.ServerFqdn, null, null, this.isSingleFolderSync ? ProxyControlFlags.SkipWLMThrottling : ProxyControlFlags.None, PublicFolderSynchronizerContext.RequiredCapabilities, false, LocalMailboxFlags.None); disposeGuard.Add <ISourceMailbox>(sourceMailbox); TenantPartitionHint partitionHint = CommonUtils.GetPartitionHint(this.OrganizationId); if (this.Logger != null) { this.Logger.LogEvent(LogEventType.Verbose, string.Format("Connecting to Primary Hierarchy. [Mailbox:{0}; Server:{1}; Database:{2}; PartitionHint:{3}]", new object[] { exchangePrincipal.MailboxInfo.MailboxGuid, exchangePrincipal.MailboxInfo.Location.ServerFqdn, exchangePrincipal.MailboxInfo.GetDatabaseGuid(), partitionHint })); } sourceMailbox.Config(null, exchangePrincipal.MailboxInfo.MailboxGuid, exchangePrincipal.MailboxInfo.MailboxGuid, partitionHint, exchangePrincipal.MailboxInfo.GetDatabaseGuid(), MailboxType.SourceMailbox, null); sourceMailbox.Connect(MailboxConnectFlags.PublicFolderHierarchyReplication); disposeGuard.Success(); result = sourceMailbox; } return(result); }
public static MessageItem CreateDelegateForward(MessageItem originalItem, CultureInfo culture, string imceaDomain, string xLoop, IRuleEvaluationContext context) { Util.ThrowOnNullArgument(originalItem, "originalItem"); ExTraceGlobals.StorageTracer.Information(0L, "RuleMessageUtils::CreateDelegateForward."); MessageItem result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { MessageItem messageItem = RuleMessageUtils.CreateRedirect(originalItem, culture, imceaDomain, xLoop, context); disposeGuard.Add <MessageItem>(messageItem); for (int i = 0; i < RuleMessageUtils.rcvdRepresentingProps.Length; i++) { if (originalItem.GetValueOrDefault <object>(RuleMessageUtils.rcvdRepresentingProps[i]) == null) { object valueOrDefault = originalItem.GetValueOrDefault <object>(RuleMessageUtils.rcvdByProps[i]); if (valueOrDefault != null) { messageItem[RuleMessageUtils.rcvdRepresentingProps[i]] = valueOrDefault; } } messageItem.Delete(RuleMessageUtils.rcvdByProps[i]); } object valueOrDefault2 = originalItem.GetValueOrDefault <object>(InternalSchema.SentRepresentingEntryId); if (valueOrDefault2 != null) { messageItem[InternalSchema.ReadReceiptEntryId] = valueOrDefault2; messageItem[InternalSchema.ReportEntryId] = valueOrDefault2; } disposeGuard.Success(); result = messageItem; } return(result); }
public override Stream OpenPropertyStream(PropertyDefinition propertyDefinition, PropertyOpenMode openMode) { base.CheckDisposed("OpenPropertyStream"); EnumValidator.AssertValid <PropertyOpenMode>(openMode); NativeStorePropertyDefinition nativeStorePropertyDefinition = propertyDefinition as NativeStorePropertyDefinition; if (nativeStorePropertyDefinition == null) { throw new InvalidOperationException(ServerStrings.ExPropertyNotStreamable(propertyDefinition.ToString())); } Stream result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { StoreObjectStream storeObjectStream = new StoreObjectStream(this, nativeStorePropertyDefinition, openMode); disposeGuard.Add <StoreObjectStream>(storeObjectStream); this.listOfStreams.Add(storeObjectStream); disposeGuard.Success(); if (openMode == PropertyOpenMode.Create || openMode == PropertyOpenMode.Modify) { this.TrackProperty(nativeStorePropertyDefinition, true); } result = storeObjectStream; } return(result); }
private static CalendarGroup CreateMyCalendarsGroup(MailboxSession session) { CalendarGroup calendarGroup = null; using (DisposeGuard disposeGuard = default(DisposeGuard)) { calendarGroup = CalendarGroup.InternalCreateGroup(session, CalendarGroupType.MyCalendars); disposeGuard.Add <CalendarGroup>(calendarGroup); using (CalendarGroupEntry calendarGroupEntry = CalendarGroupEntry.Create(session, session.GetDefaultFolderId(DefaultFolderType.Calendar), FolderTreeData.MyFoldersClassId, calendarGroup.GroupName)) { calendarGroupEntry.CalendarName = ClientStrings.Calendar.ToString(session.InternalCulture); ConflictResolutionResult conflictResolutionResult = calendarGroupEntry.Save(SaveMode.NoConflictResolution); if (conflictResolutionResult.SaveStatus != SaveResult.Success) { ExTraceGlobals.StorageTracer.TraceWarning <SmtpAddress>(0L, "Unable to associate default calendar with the MyCalendars group for user: {0}. Attempting to delete default calendars group.", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress); AggregateOperationResult aggregateOperationResult = session.Delete(DeleteItemFlags.HardDelete, new StoreId[] { calendarGroup.Id }); if (aggregateOperationResult.OperationResult != OperationResult.Succeeded) { ExTraceGlobals.StorageTracer.TraceWarning <SmtpAddress>(0L, "Unable to delete default calendar group after failing to add the default calendar to it. User: {0}", session.MailboxOwner.MailboxInfo.PrimarySmtpAddress); } throw new DefaultCalendarNodeCreationException(); } } disposeGuard.Success(); } return(calendarGroup); }
protected override void ConfigureProviders(bool continueAfterConfiguringProviders) { using (DisposeGuard disposeGuard = default(DisposeGuard)) { ISourceMailbox sourceMailbox = this.ConfigureSourceMailbox(); disposeGuard.Add <ISourceMailbox>(sourceMailbox); IDestinationMailbox destinationMailbox = this.ConfigureDestinationMailbox(); disposeGuard.Add <IDestinationMailbox>(destinationMailbox); this.PrimaryHierarchyMbxWrapper = this.ConfigureHierarchyMailbox(sourceMailbox, destinationMailbox); string orgID = (base.CachedRequestJob.OrganizationId != null && base.CachedRequestJob.OrganizationId.OrganizationalUnit != null) ? (base.CachedRequestJob.OrganizationId.OrganizationalUnit.Name + "\\") : string.Empty; this.SourceMbxWrapper = new SourceMailboxWrapper(sourceMailbox, MailboxWrapperFlags.Source, MrsStrings.AuxFolderMoveTracingId(orgID, base.CachedRequestJob.SourceExchangeGuid)); this.folderMover.SetMailboxWrappers(this.SourceMbxWrapper, destinationMailbox); disposeGuard.Success(); } base.ConfigureProviders(continueAfterConfiguringProviders); }
public static RightsManagedMessageItem ReBind(MessageItem item, OutboundConversionOptions options, bool acquireLicense) { Util.ThrowOnNullArgument(item, "item"); Util.ThrowOnNullArgument(options, "options"); StoreSession storeSession = item.Session ?? ((item.CoreItem.TopLevelItem != null) ? item.CoreItem.TopLevelItem.Session : null); if (storeSession == null) { throw new ArgumentException("Cannot use ReBind() for in-memory message.", "item"); } RightsManagedMessageItem.CheckSession(storeSession); if (!item.IsRestricted) { throw new ArgumentException("Only protected messages can be used for ReBind()"); } RightsManagedMessageItem result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { RightsManagedMessageItem rightsManagedMessageItem = new RightsManagedMessageItem(new CoreItemWrapper(item.CoreItem)); disposeGuard.Add <RightsManagedMessageItem>(rightsManagedMessageItem); rightsManagedMessageItem.Decode(options, acquireLicense); disposeGuard.Success(); rightsManagedMessageItem.originalItem = item; result = rightsManagedMessageItem; } return(result); }
internal static bool IsSmimeMessage(ICoreItem coreItem, out bool isMultipartSigned, out bool isOpaqueSigned, out StreamAttachment attachment) { isMultipartSigned = false; isOpaqueSigned = false; attachment = null; string valueOrDefault = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.ItemClass, string.Empty); if (!ObjectClass.IsSmime(valueOrDefault)) { return(false); } IList <AttachmentHandle> allHandles = coreItem.AttachmentCollection.GetAllHandles(); if (allHandles.Count != 1) { return(false); } using (DisposeGuard disposeGuard = default(DisposeGuard)) { CoreAttachment coreAttachment = coreItem.AttachmentCollection.Open(allHandles[0]); disposeGuard.Add <CoreAttachment>(coreAttachment); StreamAttachment streamAttachment = (StreamAttachment)AttachmentCollection.CreateTypedAttachment(coreAttachment, new AttachmentType?(AttachmentType.Stream)); if (streamAttachment == null) { return(false); } disposeGuard.Add <StreamAttachment>(streamAttachment); if (ObjectClass.IsSmimeClearSigned(valueOrDefault)) { isMultipartSigned = ConvertUtils.IsMessageMultipartSigned(coreItem, streamAttachment); if (isMultipartSigned) { attachment = streamAttachment; disposeGuard.Success(); return(true); } } isOpaqueSigned = ConvertUtils.IsMessageOpaqueSigned(coreItem, streamAttachment); if (isOpaqueSigned) { attachment = streamAttachment; disposeGuard.Success(); return(true); } } return(false); }
protected override IFxProxyPool GetFxProxyPoolTransmissionPipeline(EntryIdMap <byte[]> sourceMap) { IFxProxyPool result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { IFxProxyPool fxProxyPool = base.DestMailbox.GetFxProxyPool(sourceMap.Keys); disposeGuard.Add <IFxProxyPool>(fxProxyPool); IFxProxyPool fxProxyPool2 = new MailboxMerger.SimpleTranslatingProxyPool(fxProxyPool, sourceMap); disposeGuard.Success(); disposeGuard.Add <IFxProxyPool>(fxProxyPool2); IFxProxyPool fxProxyPool3 = base.CreateFxProxyPoolTransmissionPipeline(fxProxyPool2); disposeGuard.Success(); result = fxProxyPool3; } return(result); }
public static PFRuleEvaluationContext Create(StoreObjectId folderId, ProxyAddress recipientProxyAddress, ICoreItem message, long mimeSize, PublicFolderSession session) { PFRuleEvaluationContext result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { Folder folder = Folder.Bind(session, folderId, RuleEvaluationContextBase.AdditionalFolderProperties); disposeGuard.Add <Folder>(folder); PFMessageContext pfmessageContext = new PFMessageContext(folder, message, session, recipientProxyAddress ?? ProxyAddress.Parse(ProxyAddressPrefix.Smtp.PrimaryPrefix, session.MailboxPrincipal.MailboxInfo.PrimarySmtpAddress.ToString()), new ADRecipientCache <ADRawEntry>(PFRuleEvaluationContext.RecipientProperties, 0, session.MailboxPrincipal.MailboxInfo.OrganizationId), mimeSize); disposeGuard.Add <PFMessageContext>(pfmessageContext); pfmessageContext.traceFormatter = new TraceFormatter(false); session.ProhibitFolderRuleEvaluation = true; disposeGuard.Success(); result = pfmessageContext; } return(result); }
// Token: 0x060001EA RID: 490 RVA: 0x00007478 File Offset: 0x00005678 private static AnchorDataProvider CreateProviderForMailboxSession(AnchorContext context, AnchorADProvider activeDirectoryProvider, string folderName, Func <ExchangePrincipal, MailboxSession> mailboxSessionCreator) { AnchorUtil.ThrowOnNullArgument(mailboxSessionCreator, "mailboxSessionCreator"); AnchorDataProvider result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { ExchangePrincipal mailboxOwner = activeDirectoryProvider.GetMailboxOwner(AnchorDataProvider.GetMailboxFilter(context.AnchorCapability)); MailboxSession disposable = mailboxSessionCreator(mailboxOwner); disposeGuard.Add <MailboxSession>(disposable); AnchorFolder disposable2 = AnchorFolder.GetFolder(context, disposable, folderName); disposeGuard.Add <AnchorFolder>(disposable2); AnchorDataProvider anchorDataProvider = new AnchorDataProvider(context, activeDirectoryProvider, disposable, disposable2, true); disposeGuard.Success(); result = anchorDataProvider; } return(result); }
public StreamAttachment ConvertToImageAttachment(CoreAttachmentCollection collection, ImageFormat format) { base.CheckDisposed("ConvertToImageAttachment"); Util.ThrowOnNullArgument(collection, "collection"); EnumValidator.ThrowIfInvalid <ImageFormat>(format); StreamAttachment result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { CoreAttachment coreAttachment = collection.InternalCreateCopy(new AttachmentType?(AttachmentType.Stream), base.CoreAttachment); disposeGuard.Add <CoreAttachment>(coreAttachment); StreamAttachment streamAttachment = (StreamAttachment)AttachmentCollection.CreateTypedAttachment(coreAttachment, new AttachmentType?(AttachmentType.Stream)); disposeGuard.Add <StreamAttachment>(streamAttachment); string text = streamAttachment.FileName; if (string.IsNullOrEmpty(text)) { text = Attachment.GenerateFilename(); } string str = null; switch (format) { case ImageFormat.Jpeg: str = ".jpg"; break; case ImageFormat.Png: str = ".png"; break; } streamAttachment.FileName = text + str; streamAttachment.ContentType = "image/jpeg"; streamAttachment.IsInline = true; using (Stream contentStream = streamAttachment.GetContentStream(PropertyOpenMode.Create)) { if (!this.TryConvertToImage(contentStream, ImageFormat.Jpeg)) { ConvertUtils.SaveDefaultImage(contentStream); } } disposeGuard.Success(); result = streamAttachment; } return(result); }
public IAsyncResult BeginAuditLogQuery(QueryFilter queryFilter, int maximumResultsCount) { if (this.pendingAsyncResult != null) { throw new InvalidOperationException("Asynchronous query is already pending."); } StoreId storeId = null; IAsyncResult result; using (DisposeGuard disposeGuard = default(DisposeGuard)) { Folder disposable; if (queryFilter != null) { SearchFolder searchFolder = SearchFolder.Create(this.auditLog.Session, this.auditLog.Session.GetDefaultFolderId(DefaultFolderType.SearchFolders), "SearchAuditMailboxFolder" + Guid.NewGuid().ToString(), CreateMode.OpenIfExists); disposeGuard.Add <SearchFolder>(searchFolder); searchFolder.Save(); searchFolder.Load(); storeId = searchFolder.Id; result = searchFolder.BeginApplyOneTimeSearch(new SearchFolderCriteria(queryFilter, new StoreId[] { this.auditLog.LogFolderId }) { DeepTraversal = false, UseCiForComplexQueries = true, FailNonContentIndexedSearch = true, MaximumResultsCount = new int?(maximumResultsCount) }, null, null); disposable = searchFolder; } else { disposable = Folder.Bind(this.auditLog.Session, this.auditLog.LogFolderId); disposeGuard.Add <Folder>(disposable); result = new CompletedAsyncResult(); } disposeGuard.Success(); this.pendingAsyncResult = result; this.folder = disposable; this.folderIdToDelete = storeId; } return(result); }