private void InitializeFolderAndNotifyApps()
		{
			using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(this.mailboxPrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=NewConnectSubscription"))
			{
				this.providerImpl.InitializeFolderAndNotifyApps(mailboxSession, this.DataObject);
			}
		}
Example #2
0
        private void GetProtocolLogs(ADUser user)
        {
            ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(user, RemotingOptions.AllowCrossSite);

            if (exchangePrincipal == null)
            {
                base.WriteVerbose(Strings.ExchangePrincipalNotFoundException(user.ToString()));
                return;
            }
            try
            {
                using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Get-CasMailbox"))
                {
                    if (this.GetPopProtocolLog)
                    {
                        this.GetProtocolLogs(mailboxSession, "POP3");
                    }
                    if (this.GetImapProtocolLog)
                    {
                        this.GetProtocolLogs(mailboxSession, "IMAP4");
                    }
                }
            }
            catch (LocalizedException ex)
            {
                this.WriteWarning(Strings.FailedToGetLogs(user.ToString(), ex.LocalizedString));
            }
        }
Example #3
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     try
     {
         ExchangePrincipal mailboxOwner = ExchangePrincipal.FromADUser(this.DataObject, null);
         using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, "Client=Management;Action=Set-MailboxAssociationReplicationState"))
         {
             if (this.Instance.NextReplicationTime != null)
             {
                 LocalAssociationStore.SaveMailboxSyncStatus(mailboxSession, this.Instance.NextReplicationTime, null);
             }
         }
     }
     catch (StorageTransientException exception)
     {
         base.WriteError(exception, ErrorCategory.ReadError, this.Identity);
     }
     catch (StoragePermanentException exception2)
     {
         base.WriteError(exception2, ErrorCategory.ReadError, this.Identity);
     }
     finally
     {
         TaskLogger.LogExit();
     }
 }
 public void Save(TenantInfo tenantInfo)
 {
     try
     {
         using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(this.SyncMailboxPrincipal, CultureInfo.InvariantCulture, "Client=UnifiedPolicy;Action=CommitChanges;Interactive=False"))
         {
             using (UserConfiguration mailboxConfiguration = UserConfigurationHelper.GetMailboxConfiguration(mailboxSession, "TenantInfoConfigurations", UserConfigurationTypes.Stream, true))
             {
                 using (Stream stream = mailboxConfiguration.GetStream())
                 {
                     BinaryFormatter binaryFormatter = ExchangeBinaryFormatterFactory.CreateBinaryFormatter(null);
                     binaryFormatter.Serialize(stream, tenantInfo);
                 }
                 mailboxConfiguration.Save();
             }
         }
     }
     catch (StoragePermanentException innerException)
     {
         throw new SyncAgentPermanentException("TenantInfoProvider.Save failed with StoragePermanentException", innerException);
     }
     catch (StorageTransientException innerException2)
     {
         throw new SyncAgentTransientException("TenantInfoProvider.Save failed with StorageTransientException", innerException2);
     }
     catch (IOException innerException3)
     {
         throw new SyncAgentTransientException("TenantInfoProvider.Save failed with IOException", innerException3);
     }
 }
Example #5
0
 private void OpenMailboxSession()
 {
     if (this.mailboxSession == null)
     {
         this.mailboxSession = MailboxSession.OpenAsAdmin(this.principal, CultureInfo.InvariantCulture, "Client=Management;Action=Remove-ActiveSyncDevice");
     }
 }
Example #6
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     CmdletProxy.ThrowExceptionIfProxyIsNeeded(base.CurrentTaskContext, base.DataObject, false, this.ConfirmationMessage, null);
     try
     {
         ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(base.DataObject, null);
         using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Remove-UserPhoto"))
         {
             new PhotoRemovalPipeline(RemoveUserPhoto.PhotosConfiguration, mailboxSession, (IRecipientSession)base.DataSession, this.tracer).Upload(this.CreateRemovePhotoRequest(exchangePrincipal), Stream.Null);
         }
     }
     catch (WrongServerException ex)
     {
         this.LogFailedToRemovePhotoEvent(ex);
         this.WriteError(new CannotModifyPhotoBecauseMailboxIsInTransitException(ex), ExchangeErrorCategory.ServerTransient, base.DataObject, true);
     }
     catch (Exception e)
     {
         this.LogFailedToRemovePhotoEvent(e);
         throw;
     }
     finally
     {
         this.tracer.Dump(new PhotoRequestLogWriter(RemoveUserPhoto.RequestLog, RemoveUserPhoto.GenerateRequestId()));
     }
     TaskLogger.LogExit();
 }
Example #7
0
        internal static MailboxSession OpenMailboxSession(ADUser adUser, string clientString, Task.TaskErrorLoggingDelegate writeError)
        {
            LocalizedString?localizedString = null;

            try
            {
                ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(adUser.OrganizationId.ToADSessionSettings(), adUser);
                if (exchangePrincipal == null)
                {
                    return(null);
                }
                return(MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, clientString));
            }
            catch (StorageTransientException ex)
            {
                localizedString = new LocalizedString?(Strings.ExceptionStorageOther(ex.ErrorCode, ex.Message));
            }
            catch (StoragePermanentException ex2)
            {
                if (ex2 is AccessDeniedException)
                {
                    localizedString = new LocalizedString?(Strings.ExceptionStorageAccessDenied(ex2.ErrorCode, ex2.Message));
                }
                else
                {
                    localizedString = new LocalizedString?(Strings.ExceptionStorageOther(ex2.ErrorCode, ex2.Message));
                }
            }
            if (localizedString != null)
            {
                writeError(new TaskException(localizedString.Value), ErrorCategory.ReadError, null);
            }
            return(null);
        }
Example #8
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     try
     {
         ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(this.DataObject, null);
         using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Set-UserPhoto"))
         {
             PhotoRequest        request             = this.CreateRequest(exchangePrincipal);
             PhotoUploadPipeline photoUploadPipeline = new PhotoUploadPipeline(SetUserPhoto.PhotosConfiguration, mailboxSession, (IRecipientSession)base.DataSession, this.tracer);
             photoUploadPipeline.Upload(request, Stream.Null);
             if (!this.Save && !this.Cancel && !this.Preview)
             {
                 photoUploadPipeline.Upload(this.CreateSavePreviewRequest(exchangePrincipal), Stream.Null);
             }
         }
     }
     catch (WrongServerException ex)
     {
         this.LogFailedToUploadPhotoEvent(ex);
         this.WriteError(new CannotModifyPhotoBecauseMailboxIsInTransitException(ex), ExchangeErrorCategory.ServerTransient, this.DataObject, true);
     }
     catch (Exception e)
     {
         this.LogFailedToUploadPhotoEvent(e);
         throw;
     }
     finally
     {
         this.tracer.Dump(new PhotoRequestLogWriter(SetUserPhoto.RequestLog, SetUserPhoto.GenerateRequestId()));
     }
     TaskLogger.LogExit();
 }
        public static MailboxSession CreateMailboxSessionForConfiguration(ExchangePrincipal groupPrincipal, string domainController)
        {
            MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(groupPrincipal, CultureInfo.InvariantCulture, "Client=WebServices;Action=ConfigureGroupMailbox");

            mailboxSession.SetADRecipientSessionFactory((bool isReadonly, ConsistencyMode consistencyMode) => DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(domainController, isReadonly, consistencyMode, null, groupPrincipal.MailboxInfo.OrganizationId.ToADSessionSettings(), 127, "CreateMailboxSessionForConfiguration", "f:\\15.00.1497\\sources\\dev\\UnifiedGroups\\src\\UnifiedGroups\\GroupMailboxAccessLayer\\Commands\\ConfigureGroupMailbox.cs"));
            return(mailboxSession);
        }
 public void SetProperties(DefaultFolderContext context, Folder folder)
 {
     MatchAdminFolderFlags.< > c__DisplayClass2 CS$ < > 8__locals1 = new MatchAdminFolderFlags.< > c__DisplayClass2();
     CS$ < > 8__locals1.folder      = folder;
     CS$ < > 8__locals1.< > 4__this = this;
     ExTraceGlobals.DefaultFoldersTracer.TraceDebug <ELCFolderFlags, Folder>((long)this.GetHashCode(), "MatchAdminFolderFlags::SetPropertiesInternal. Setting AdminFolderFlags to {0} for folder {1} on the admin session.", this.adminFolderFlags, CS$ < > 8__locals1.folder);
     if (context.Session.LogonType == LogonType.Admin || (context.Session != null && context.Session.IsMoveUser))
     {
         CS$ < > 8__locals1.folder[InternalSchema.AdminFolderFlags] = this.adminFolderFlags;
         return;
     }
     using (MailboxSession adminSession = MailboxSession.OpenAsAdmin(context.Session.MailboxOwner, CultureInfo.InvariantCulture, context.Session.ClientInfoString + ";COW=DumpsterFolderFlag"))
     {
         adminSession.BypassAuditing(delegate
         {
             adminSession.BypassAuditsFolderAccessChecking(delegate
             {
                 using (Folder folder2 = Folder.Bind(adminSession, CS$ < > 8__locals1.folder.Id, new PropertyDefinition[]
                 {
                     FolderSchema.AdminFolderFlags
                 }))
                 {
                     folder2[InternalSchema.AdminFolderFlags] = CS$ < > 8__locals1.< > 4__this.adminFolderFlags;
                     folder2.Save();
                 }
             });
Example #11
0
        private bool IsGroupMemberInMailboxAssociation()
        {
            IExtensibleLogger logger = MailboxAssociationDiagnosticsFrameFactory.Default.CreateLogger(this.groupMailboxToLogon.MailboxInfo.MailboxGuid, this.organizationId);
            IMailboxAssociationPerformanceTracker performanceTracker = MailboxAssociationDiagnosticsFrameFactory.Default.CreatePerformanceTracker(null);
            bool result;

            using (MailboxAssociationDiagnosticsFrameFactory.Default.CreateDiagnosticsFrame("XSO", "CheckMembership", logger, performanceTracker))
            {
                try
                {
                    using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(this.groupMailboxToLogon, CultureInfo.InvariantCulture, this.clientInfoString))
                    {
                        using (IAssociationStore associationStore = this.GetAssociationStore(mailboxSession, performanceTracker))
                        {
                            using (IMailboxAssociationUser memberAssociationInformation = this.GetMemberAssociationInformation(associationStore))
                            {
                                result = (memberAssociationInformation != null && (bool)memberAssociationInformation[MailboxAssociationBaseSchema.IsMember]);
                            }
                        }
                    }
                }
                catch (AssociationNotFoundException)
                {
                    GroupMailboxAuthorizationHandler.Tracer.TraceDebug <string, string>((long)this.GetHashCode(), "MemberRetrieval: Unable to make IsMember() check for the user {0} on the mailbox {1}", this.accessingUserInfo.Identity, this.groupMailboxToLogon.MailboxInfo.DisplayName);
                    result = false;
                }
                catch (LocalizedException)
                {
                    GroupMailboxAuthorizationHandler.Tracer.TraceDebug <string, string>((long)this.GetHashCode(), "MemberRetrieval: Unable to make IsMember() check for the user {0} on the mailbox {1}", this.accessingUserInfo.Identity, this.groupMailboxToLogon.MailboxInfo.DisplayName);
                    result = false;
                }
            }
            return(result);
        }
        internal MailboxSession ConnectToEDiscoveryMailbox(string clientString)
        {
            ADUser            dataObject   = this.DataObject;
            ExchangePrincipal mailboxOwner = ExchangePrincipal.FromADUser(dataObject, RemotingOptions.AllowCrossSite);

            return(MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, clientString));
        }
Example #13
0
 internal static MailboxSession OpenMailboxSessionForSubmission(ADUser adUser, bool catchStorageException)
 {
     try
     {
         ExchangePrincipal mailboxOwner = ExchangePrincipal.FromADUser(adUser.OrganizationId.ToADSessionSettings(), adUser, RemotingOptions.AllowCrossSite);
         return(MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, "Client=EDiscoverySearch;Action=Search;Interactive=False", null, true));
     }
     catch (StoragePermanentException arg)
     {
         SearchUtils.Tracer.TraceError <StoragePermanentException>(0L, "SearchUtils.OpenMailboxSession error {0}", arg);
         if (!catchStorageException)
         {
             throw;
         }
     }
     catch (StorageTransientException arg2)
     {
         SearchUtils.Tracer.TraceError <StorageTransientException>(0L, "SearchUtils.OpenMailboxSession error {0}", arg2);
         if (!catchStorageException)
         {
             throw;
         }
     }
     return(null);
 }
 // Token: 0x06000503 RID: 1283 RVA: 0x00025B70 File Offset: 0x00023D70
 private void InitializeArchiveMailboxSession()
 {
     if (this.primaryMailboxSession != null)
     {
         IMailboxInfo archiveMailbox = this.primaryMailboxSession.MailboxOwner.GetArchiveMailbox();
         if (archiveMailbox != null)
         {
             try
             {
                 ExchangePrincipal mailboxOwner = ExchangePrincipal.FromMailboxGuid(this.primaryMailboxSession.GetADSessionSettings(), archiveMailbox.MailboxGuid, RemotingOptions.AllowCrossSite | RemotingOptions.AllowCrossPremise, null);
                 this.archiveMailboxSession = MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.CurrentCulture, "Client=TBA;Action=MoveToArchive;Interactive=False", null, true);
             }
             catch (ObjectNotFoundException arg)
             {
                 LocalArchiveProcessor.Tracer.TraceDebug <IExchangePrincipal, ObjectNotFoundException>((long)this.primaryMailboxSession.GetHashCode(), "{0}: Problems opening the archive.{1}", this.primaryMailboxSession.MailboxOwner, arg);
             }
             catch (StorageTransientException arg2)
             {
                 LocalArchiveProcessor.Tracer.TraceWarning <IExchangePrincipal, MailboxSession, StorageTransientException>((long)this.primaryMailboxSession.GetHashCode(), "{0}: Failed to connect to the the archive mailbox : {1}.\nError:\n{2}", this.primaryMailboxSession.MailboxOwner, this.primaryMailboxSession, arg2);
             }
             catch (StoragePermanentException arg3)
             {
                 LocalArchiveProcessor.Tracer.TraceError <IExchangePrincipal, MailboxSession, StoragePermanentException>((long)this.primaryMailboxSession.GetHashCode(), "{0}: Failed to connect to the the archive mailbox : {1}.\nError:\n{2}", this.primaryMailboxSession.MailboxOwner, this.primaryMailboxSession, arg3);
             }
         }
     }
 }
Example #15
0
        public override MRSRequestMailboxEntry Read(RequestIndexEntryProvider requestIndexEntryProvider, RequestIndexEntryObjectId identity)
        {
            this.ValidateRequestIndexId(identity.IndexId);
            ADUser aduser = requestIndexEntryProvider.ReadADUser(identity.IndexId.Mailbox, Guid.Empty);

            if (aduser == null)
            {
                return(null);
            }
            ExchangePrincipal      mailboxOwner = ExchangePrincipal.FromADUser(aduser, RemotingOptions.AllowCrossSite);
            MRSRequestMailboxEntry result;

            using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, "Client=MSExchangeMigration"))
            {
                MailboxStoreTypeProvider session = new MailboxStoreTypeProvider(aduser)
                {
                    MailboxSession = mailboxSession
                };
                MRSRequestMailboxEntry mrsrequestMailboxEntry = MRSRequest.Read <MRSRequestMailboxEntry>(session, identity.RequestGuid);
                mrsrequestMailboxEntry.RequestIndexId = identity.IndexId;
                mrsrequestMailboxEntry.OrganizationId = identity.OrganizationId;
                result = mrsrequestMailboxEntry;
            }
            return(result);
        }
Example #16
0
        public void Save(IConfigurable instance)
        {
            this.mailMessage = (MailMessage)instance;
            CultureInfo currentCulture = CultureInfo.CurrentCulture;

            using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(ExchangePrincipal.FromDirectoryObjectId(this.adSession, this.mailbox.Id, RemotingOptions.LocalConnectionsOnly), currentCulture, "Client=Management;Action=New-MailMessage"))
            {
                StoreObjectId defaultFolderId = mailboxSession.GetDefaultFolderId(DefaultFolderType.Drafts);
                using (MessageItem messageItem = MessageItem.Create(mailboxSession, defaultFolderId))
                {
                    if (!string.IsNullOrEmpty(this.mailMessage.Subject))
                    {
                        messageItem.Subject = this.mailMessage.Subject;
                    }
                    if (!string.IsNullOrEmpty(this.mailMessage.Body))
                    {
                        using (TextWriter textWriter = messageItem.Body.OpenTextWriter((BodyFormat)this.mailMessage.BodyFormat))
                        {
                            textWriter.WriteLine(this.mailMessage.Body);
                        }
                    }
                    messageItem.Save(SaveMode.NoConflictResolution);
                    messageItem.Load();
                    this.mailMessage.SetIdentity(messageItem.Id.ObjectId);
                }
            }
        }
 private void NotifyApps()
 {
     using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(this.mailboxPrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=SetConnectSubscription"))
     {
         this.providerImpl.NotifyApps(mailboxSession);
     }
 }
 protected override void WriteResult(IConfigurable dataObject)
 {
     TaskLogger.LogEnter();
     try
     {
         if (dataObject != null)
         {
             ADUser            user         = (ADUser)dataObject;
             ExchangePrincipal mailboxOwner = ExchangePrincipal.FromADUser(user, null);
             using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, "Client=Management;Action=Get-MailboxActivityLog"))
             {
                 IActivityLog activityLog = ActivityLogFactory.Current.Bind(mailboxSession);
                 foreach (Activity activity in activityLog.Query())
                 {
                     base.WriteResult(new ActivityLogEntryPresentationObject(activity));
                 }
             }
         }
     }
     catch (StorageTransientException exception)
     {
         base.WriteError(exception, ErrorCategory.ReadError, null);
     }
     catch (StoragePermanentException exception2)
     {
         base.WriteError(exception2, ErrorCategory.ReadError, null);
     }
     finally
     {
         TaskLogger.LogExit();
     }
 }
        public static void InitExtendedRuleSizeLimitIfNeeded(MailboxSession originalSession)
        {
            if (originalSession.LogonType != LogonType.BestAccess && originalSession.LogonType != LogonType.Delegated && originalSession.LogonType != LogonType.Owner)
            {
                return;
            }
            int?num = originalSession.Mailbox.TryGetProperty(MailboxSchema.ExtendedRuleSizeLimit) as int?;

            if (num == null || num > 522240)
            {
                using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(originalSession.MailboxOwner, originalSession.InternalCulture, "Client=Management;Action=InitExtendedRuleSizeLimit"))
                {
                    mailboxSession.Mailbox.SetProperties(new PropertyDefinition[]
                    {
                        MailboxSchema.ExtendedRuleSizeLimit
                    }, new object[]
                    {
                        522240
                    });
                    CoreObject.GetPersistablePropertyBag((CoreMailboxObject)mailboxSession.Mailbox.CoreObject).FlushChanges();
                }
                originalSession.Mailbox.ForceReload(new PropertyDefinition[]
                {
                    MailboxSchema.ExtendedRuleSizeLimit
                });
            }
        }
Example #20
0
        internal static MailboxSession OpenMailboxSession(ExchangePrincipal principal, string taskName, bool allowAdminLocalization)
        {
            TaskLogger.LogEnter();
            MailboxSession result = MailboxSession.OpenAsAdmin(principal, CultureInfo.InvariantCulture, string.Format("Client=Management;Action={0};Privilege:ActAsAdmin", taskName), false, false, null, allowAdminLocalization);

            TaskLogger.LogExit();
            return(result);
        }
Example #21
0
 internal static MailboxSession OpenMailboxSession(ExchangePrincipal principal, GenericIdentity actualExecutingIdentity)
 {
     if (actualExecutingIdentity == null)
     {
         throw new ArgumentNullException("actualExecutingIdentity");
     }
     return(MailboxSession.OpenAsAdmin(principal, CultureInfo.InvariantCulture, "Client=EDiscoverySearch;Action=Search;Interactive=False", actualExecutingIdentity, true));
 }
Example #22
0
        private static MailboxSession OpenMailboxSession(ADUser adUser)
        {
            if (adUser == null)
            {
                throw new ArgumentNullException("adUser");
            }
            ExchangePrincipal mailboxOwner = ExchangePrincipal.FromADUser(adUser.OrganizationId.ToADSessionSettings(), adUser, RemotingOptions.AllowCrossSite);

            return(MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, "Client=ELC;Action=Manage-SearchObject;Interactive=false", null, true));
        }
Example #23
0
 public XsoMailboxDataProviderBase(ExchangePrincipal mailboxOwner, string action)
 {
     using (DisposeGuard disposeGuard = this.Guard())
     {
         Util.ThrowOnNullArgument(mailboxOwner, "mailboxOwner");
         Util.ThrowOnNullOrEmptyArgument(action, "action");
         this.MailboxSession = MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, string.Format("Client=Management;Action={0};Privilege:ActAsAdmin", action));
         disposeGuard.Success();
     }
 }
Example #24
0
        private static SessionManager.SessionData OpenSession(ExchangePrincipal principal, ExTimeZone timeZone, string clientInfoString)
        {
            MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(principal, CultureInfo.InvariantCulture, clientInfoString);

            if (timeZone != null)
            {
                mailboxSession.ExTimeZone = timeZone;
            }
            return(new SessionManager.SessionData(mailboxSession));
        }
Example #25
0
        protected override IConfigurable ConvertDataObjectToPresentationObject(IConfigurable dataObject)
        {
            if (dataObject == null)
            {
                return(null);
            }
            ADUser aduser = (ADUser)dataObject;
            UserPhotoConfiguration userPhotoConfiguration = new UserPhotoConfiguration(dataObject.Identity, Stream.Null, null);

            if (CmdletProxy.TryToProxyOutputObject(userPhotoConfiguration, base.CurrentTaskContext, aduser, this.Identity == null, this.ConfirmationMessage, CmdletProxy.AppendIdentityToProxyCmdlet(aduser)))
            {
                return(userPhotoConfiguration);
            }
            IConfigurable result;

            try
            {
                ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(aduser, null);
                using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Get-UserPhoto"))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        PhotoManagementRetrievalPipeline photoManagementRetrievalPipeline = new PhotoManagementRetrievalPipeline(GetUserPhoto.PhotosConfiguration, mailboxSession, (IRecipientSession)base.DataSession, this.tracer);
                        PhotoResponse  photoResponse = photoManagementRetrievalPipeline.Retrieve(this.CreateRetrievePhotoRequest(exchangePrincipal), memoryStream);
                        HttpStatusCode status        = photoResponse.Status;
                        if (status != HttpStatusCode.OK && status == HttpStatusCode.NotFound)
                        {
                            this.WriteError(new UserPhotoNotFoundException(this.Preview), ExchangeErrorCategory.Client, this.Identity, true);
                            throw new InvalidOperationException();
                        }
                        memoryStream.Seek(0L, SeekOrigin.Begin);
                        result = new UserPhotoConfiguration(dataObject.Identity, memoryStream, photoResponse.Thumbprint);
                    }
                }
            }
            catch (UserPhotoNotFoundException)
            {
                throw;
            }
            catch (Exception ex)
            {
                ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FailedToRetrievePhoto, new string[]
                {
                    dataObject.ToString(),
                    ((ADUser)dataObject).UserPrincipalName,
                    ex.ToString()
                });
                throw;
            }
            finally
            {
                this.tracer.Dump(new PhotoRequestLogWriter(GetUserPhoto.RequestLog, GetUserPhoto.GenerateRequestId()));
            }
            return(result);
        }
Example #26
0
        private static IEnumerable <MRSRequestMailboxEntry> GetRequestIndexEntries(ADUser user, RequestIndexEntryQueryFilter requestIndexEntryQueryFilter)
        {
            ExchangePrincipal mailboxOwner = ExchangePrincipal.FromADUser(user, RemotingOptions.AllowCrossSite);
            IEnumerable <MRSRequestMailboxEntry> result;

            using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(mailboxOwner, CultureInfo.InvariantCulture, "Client=MSExchangeMigration"))
            {
                result = MRSRequestMailboxEntry.Read(mailboxSession, requestIndexEntryQueryFilter);
            }
            return(result);
        }
        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);
        }
		public List<Exception> SendNotification(IList<ADObjectId> recipients, string subject, string body, RemotingOptions remotingOptons = RemotingOptions.LocalConnectionsOnly)
		{
			if (recipients == null)
			{
				throw new ArgumentNullException("recipients");
			}
			if (subject == null)
			{
				throw new ArgumentNullException("subject");
			}
			if (body == null)
			{
				throw new ArgumentNullException("body");
			}
			List<Exception> list = new List<Exception>();
			if (recipients.Count > 0)
			{
				using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(ExchangePrincipal.FromADUser((ADUser)this.tm.DataObject, remotingOptons), CultureInfo.InvariantCulture, "Client=TeamMailbox;Action=Send_Notification"))
				{
					using (MessageItem messageItem = MessageItem.Create(mailboxSession, mailboxSession.GetDefaultFolderId(DefaultFolderType.Drafts)))
					{
						foreach (ADObjectId adobjectId in recipients)
						{
							Exception ex = null;
							ADUser aduser = TeamMailboxADUserResolver.Resolve(this.dataSession, adobjectId, out ex);
							if (ex != null)
							{
								list.Add(new Exception(string.Format("When resolving recipient {0}, got an excetion: {1}", adobjectId, ex)));
							}
							else if (aduser == null)
							{
								list.Add(new Exception("Cannot find recipient: " + adobjectId));
							}
							else
							{
								messageItem.Recipients.Add(new Participant(aduser.DisplayName, aduser.PrimarySmtpAddress.ToString(), "SMTP"));
							}
						}
						messageItem.Subject = subject;
						using (Stream stream = messageItem.Body.OpenWriteStream(new BodyWriteConfiguration(BodyFormat.TextHtml, Charset.Unicode)))
						{
							using (StreamWriter streamWriter = new StreamWriter(stream, Encoding.Unicode))
							{
								streamWriter.WriteLine(body);
							}
						}
						messageItem.AutoResponseSuppress = AutoResponseSuppress.All;
						messageItem.SendWithoutSavingMessage();
					}
				}
			}
			return list;
		}
Example #29
0
 internal static StoreSession OpenSession(ExchangePrincipal principal, GenericIdentity actualExecutingIdentity, bool publicFolderSession = false)
 {
     if (actualExecutingIdentity == null)
     {
         throw new ArgumentNullException("actualExecutingIdentity");
     }
     if (!publicFolderSession)
     {
         return(MailboxSession.OpenAsAdmin(principal, CultureInfo.InvariantCulture, "Client=EDiscoverySearch;Action=Search;Interactive=False", actualExecutingIdentity, true));
     }
     return(PublicFolderSession.OpenAsAdmin(principal.MailboxInfo.OrganizationId, null, principal.MailboxInfo.MailboxGuid, null, CultureInfo.InvariantCulture, "Client=EDiscoverySearch;Action=Search;Interactive=False", null));
 }
 public override void Save(RequestIndexEntryProvider requestIndexEntryProvider, T instance)
 {
     ArgumentValidator.ThrowIfNull("instance", instance);
     ArgumentValidator.ThrowIfNull("instance.TargetUser", instance.TargetUser);
     ArgumentValidator.ThrowIfNull("instance.TargetExchangeGuid", instance.TargetExchangeGuid);
     instance.SetExchangePrincipal();
     using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(instance.GetExchangePrincipal(), CultureInfo.InvariantCulture, "Client=MSExchangeMigration"))
     {
         instance.Save(new MailboxStoreTypeProvider(instance.TargetUser)
         {
             MailboxSession = mailboxSession
         });
     }
 }