protected override IConfigurable ResolveDataObject()
        {
            ADRecipient adrecipient = (ADRecipient)base.ResolveDataObject();

            if (MailboxTaskHelper.ExcludeArbitrationMailbox(adrecipient, base.Arbitration) || MailboxTaskHelper.ExcludePublicFolderMailbox(adrecipient, base.PublicFolder) || MailboxTaskHelper.ExcludeGroupMailbox(adrecipient, false) || MailboxTaskHelper.ExcludeMailboxPlan(adrecipient, false) || MailboxTaskHelper.ExcludeAuditLogMailbox(adrecipient, base.AuditLog))
            {
                base.WriteError(new ManagementObjectNotFoundException(base.GetErrorMessageObjectNotFound(this.Identity.ToString(), typeof(ADUser).ToString(), (base.DataSession != null) ? base.DataSession.Source : null)), ExchangeErrorCategory.Client, this.Identity);
            }
            if (adrecipient != null && adrecipient.RecipientTypeDetails == RecipientTypeDetails.TeamMailbox)
            {
                TeamMailbox teamMailbox = TeamMailbox.FromDataObject((ADUser)adrecipient);
                teamMailbox.ClosedTime = new DateTime?(DateTime.UtcNow);
                this.removeTeamMailboxFromResolverCache = true;
                if (teamMailbox.SharePointUrl != null && base.ExchangeRunspaceConfig != null)
                {
                    TeamMailboxHelper teamMailboxHelper = new TeamMailboxHelper(teamMailbox, base.ExchangeRunspaceConfig.ExecutingUser, base.ExchangeRunspaceConfig.ExecutingUserOrganizationId, (IRecipientSession)base.DataSession, new TeamMailboxGetDataObject <ADUser>(base.GetDataObject <ADUser>));
                    try
                    {
                        teamMailboxHelper.LinkSharePointSite(null, false, false);
                    }
                    catch (RecipientTaskException ex)
                    {
                        this.WriteWarning(Strings.ErrorTeamMailFailedUnlinkSharePointSite(this.Identity.ToString(), teamMailbox.SharePointUrl.ToString(), ex.Message));
                    }
                }
            }
            return(adrecipient);
        }
Exemple #2
0
        protected override IConfigurable ConvertDataObjectToPresentationObject(IConfigurable dataObject)
        {
            if (dataObject == null)
            {
                return(null);
            }
            TeamMailbox teamMailbox = TeamMailbox.FromDataObject((ADUser)dataObject);

            teamMailbox.SetMyRole(this.executingUserId);
            if (this.executingUserId == null)
            {
                teamMailbox.ShowInMyClient = false;
            }
            else if (base.ExecutingUserOrganizationId == base.CurrentOrganizationId)
            {
                if (teamMailbox.Active)
                {
                    ADUser aduser = (ADUser)base.GetDataObject <ADUser>(new MailboxIdParameter(this.executingUserId), base.DataSession, null, new LocalizedString?(Strings.ErrorMailboxNotFound(this.executingUserId.ToString())), new LocalizedString?(Strings.ErrorMailboxNotUnique(this.executingUserId.ToString())));
                    teamMailbox.ShowInMyClient = aduser.TeamMailboxShowInClientList.Contains(teamMailbox.Id);
                }
                else
                {
                    teamMailbox.ShowInMyClient = false;
                }
            }
            return(teamMailbox);
        }
Exemple #3
0
        protected override bool ShouldSkipObject(IConfigurable dataObject)
        {
            ADUser aduser = dataObject as ADUser;

            if (aduser == null)
            {
                return(true);
            }
            if (this.DeletedSiteMailbox)
            {
                return(!TeamMailbox.IsPendingDeleteSiteMailbox(aduser));
            }
            if (TeamMailbox.IsPendingDeleteSiteMailbox(aduser))
            {
                return(true);
            }
            if (!TeamMailbox.IsLocalTeamMailbox(aduser) && !TeamMailbox.IsRemoteTeamMailbox(aduser))
            {
                return(true);
            }
            if (base.ParameterSetName == "TeamMailboxIW")
            {
                TeamMailbox teamMailbox = TeamMailbox.FromDataObject((ADUser)dataObject);
                return(!teamMailbox.OwnersAndMembers.Contains(this.executingUserId));
            }
            return(false);
        }
 internal TeamMailboxHelper(TeamMailbox teamMailbox, ADRawEntry actAsUser, OrganizationId actAsUserOrgId, IRecipientSession adSession, TeamMailboxGetDataObject <ADUser> getAdUser)
 {
     if (teamMailbox == null)
     {
         throw new ArgumentNullException("teamMailbox");
     }
     if (actAsUser == null)
     {
         throw new ArgumentNullException("actAsUser");
     }
     if (actAsUserOrgId == null)
     {
         throw new ArgumentNullException("actAsUserOrgId");
     }
     if (adSession == null)
     {
         throw new ArgumentNullException("adSession");
     }
     if (getAdUser == null)
     {
         throw new ArgumentNullException("getAdUser");
     }
     this.teamMailbox    = teamMailbox;
     this.actAsUser      = actAsUser;
     this.actAsUserOrgId = actAsUserOrgId;
     this.adSession      = adSession;
     this.getAdUser      = getAdUser;
 }
Exemple #5
0
        public bool ClearClosedAndDeletedTeamMailboxesInShowInMyClientList(ADUser userMailbox)
        {
            if (userMailbox == null)
            {
                throw new ArgumentNullException("userMailbox");
            }
            bool result            = false;
            List <ADObjectId> list = new List <ADObjectId>();

            foreach (ADObjectId item in userMailbox.TeamMailboxShowInClientList)
            {
                list.Add(item);
            }
            foreach (ADObjectId adobjectId in list)
            {
                Exception ex;
                ADUser    aduser = TeamMailboxADUserResolver.Resolve(this.DataSession, adobjectId, out ex);
                if (ex == null && (aduser == null || !TeamMailbox.FromDataObject(aduser).Active))
                {
                    userMailbox.TeamMailboxShowInClientList.Remove(adobjectId);
                    result = true;
                }
            }
            return(result);
        }
		private static TeamMailbox GetTeamMailbox(MailboxSession session, out IRecipientSession recipientSession)
		{
			TeamMailbox result;
			try
			{
				ADUser aduser = DirectoryHelper.ReadADRecipient(session.MailboxOwner.MailboxInfo.MailboxGuid, session.MailboxOwner.MailboxInfo.IsArchive, session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid)) as ADUser;
				if (aduser == null)
				{
					throw new StorageTransientException(new LocalizedString("Failed to find the Site Mailbox"));
				}
				recipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, null, CultureInfo.InvariantCulture.LCID, true, ConsistencyMode.IgnoreInvalid, null, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(session.MailboxOwner.MailboxInfo.OrganizationId), 382, "GetTeamMailbox", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\LinkedFolder\\TeamMailboxNotificationHelper.cs");
				result = TeamMailbox.FromDataObject(aduser);
			}
			catch (ADTransientException innerException)
			{
				throw new StorageTransientException(new LocalizedString("Failed to get the Site Mailbox because of AD error"), innerException);
			}
			catch (ADExternalException innerException2)
			{
				throw new StorageTransientException(new LocalizedString("Failed to get the Site Mailbox because of AD error"), innerException2);
			}
			catch (ADOperationException innerException3)
			{
				throw new StorageTransientException(new LocalizedString("Failed to get the Site Mailbox because of AD error"), innerException3);
			}
			catch (DataValidationException innerException4)
			{
				throw new StorageTransientException(new LocalizedString("Failed to get the Site Mailbox because of AD error"), innerException4);
			}
			return result;
		}
        protected override void WriteResult(ADObject result)
        {
            ADUser      dataObject  = (ADUser)result;
            TeamMailbox teamMailbox = TeamMailbox.FromDataObject(dataObject);

            teamMailbox.SetMyRole(this.executingUserId);
            teamMailbox.ShowInMyClient = true;
            base.WriteResult(teamMailbox);
        }
        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);
        }
Exemple #9
0
 public TeamMailboxMembershipHelper(TeamMailbox tm, IRecipientSession dataSession)
 {
     if (tm == null)
     {
         throw new ArgumentNullException("tm");
     }
     if (dataSession == null)
     {
         throw new ArgumentNullException("dataSession");
     }
     this.TeamMailbox = tm;
     this.DataSession = dataSession;
 }
		public TeamMailboxNotificationHelper(TeamMailbox tm, IRecipientSession dataSession)
		{
			if (tm == null)
			{
				throw new ArgumentNullException("tm");
			}
			if (dataSession == null)
			{
				throw new ArgumentNullException("dataSession");
			}
			this.tm = tm;
			this.dataSession = dataSession;
			this.tmSmtpAddress = this.tm.PrimarySmtpAddress.ToString();
		}
Exemple #11
0
 protected override void InternalProcessRecord()
 {
     foreach (KeyValuePair <ADUser, ExchangePrincipal> entry in base.TMPrincipals)
     {
         TeamMailboxDiagnosticsInfo teamMailboxDiagnosticsInfo = null;
         try
         {
             teamMailboxDiagnosticsInfo = this.GetOneTeamMailboxDiagnosticsInfo(entry);
         }
         catch (StorageTransientException ex)
         {
             base.WriteError(new RecipientTaskException(Strings.ErrorGetSiteMailboxDiagnostics(entry.Value.MailboxInfo.DisplayName, ex.Message), ex), ExchangeErrorCategory.ServerTransient, null);
         }
         catch (StoragePermanentException ex2)
         {
             base.WriteError(new RecipientTaskException(Strings.ErrorGetSiteMailboxDiagnostics(entry.Value.MailboxInfo.DisplayName, ex2.Message), ex2), ExchangeErrorCategory.ServerOperation, null);
         }
         base.WriteObject(teamMailboxDiagnosticsInfo);
         if (base.Fields.IsModified("SendMeEmail"))
         {
             ADObjectId item;
             if (!base.TryGetExecutingUserId(out item))
             {
                 base.WriteError(new RecipientTaskException(Strings.ErrorTeamMailboxCannotIdentifyTheUser), ExchangeErrorCategory.Client, null);
             }
             TeamMailbox teamMailbox = TeamMailbox.FromDataObject(entry.Key);
             TeamMailboxNotificationHelper teamMailboxNotificationHelper = new TeamMailboxNotificationHelper(teamMailbox, (IRecipientSession)base.DataSession);
             try
             {
                 teamMailboxNotificationHelper.SendNotification(new List <ADObjectId>
                 {
                     item
                 }, Strings.SiteMailboxDiagnosticsEmailSubject(teamMailbox.DisplayName), teamMailboxDiagnosticsInfo.ToString(), RemotingOptions.AllowCrossSite);
             }
             catch (StorageTransientException ex3)
             {
                 base.WriteError(new RecipientTaskException(Strings.ErrorSendNotificationForSiteMailbox(teamMailbox.DisplayName, ex3.Message), ex3), ExchangeErrorCategory.ServerTransient, null);
             }
             catch (StoragePermanentException ex4)
             {
                 base.WriteError(new RecipientTaskException(Strings.ErrorSendNotificationForSiteMailbox(teamMailbox.DisplayName, ex4.Message), ex4), ExchangeErrorCategory.ServerOperation, null);
             }
         }
     }
 }
Exemple #12
0
 public bool UpdateTeamMailboxUserList(IList <ADObjectId> currentUserList, IList <ADObjectId> newUserList, out IList <ADObjectId> usersToAdd, out IList <ADObjectId> usersToRemove)
 {
     if (currentUserList == null)
     {
         throw new ArgumentNullException("currentList");
     }
     if (newUserList == null)
     {
         throw new ArgumentNullException("newUserList");
     }
     usersToRemove = TeamMailbox.DiffUsers(currentUserList, newUserList);
     usersToAdd    = TeamMailbox.DiffUsers(newUserList, currentUserList);
     foreach (ADObjectId item in usersToRemove)
     {
         currentUserList.Remove(item);
     }
     foreach (ADObjectId item2 in usersToAdd)
     {
         currentUserList.Add(item2);
     }
     return(usersToRemove.Count > 0 || usersToAdd.Count > 0);
 }
        private LinkSharePointSiteResult InternalLinkSharePointSite(Uri sharePointUrl, out string sharePointTeamMailboxKey, bool siteChecked, bool forceToUnlink)
        {
            LinkSharePointSiteResult linkSharePointSiteResult = LinkSharePointSiteResult.Success;

            sharePointTeamMailboxKey = "N/A";
            bool      flag = sharePointUrl == null;
            Uri       uri  = sharePointUrl ?? this.teamMailbox.SharePointUrl;
            Exception ex   = null;

            if (flag)
            {
                if (this.teamMailbox.SharePointUrl == null)
                {
                    return(LinkSharePointSiteResult.CurrentlyNotLinked);
                }
                sharePointUrl = this.teamMailbox.SharePointUrl;
            }
            try
            {
                using (ClientContext clientContext = new ClientContext(sharePointUrl.AbsoluteUri))
                {
                    clientContext.RequestTimeout = 60000;
                    bool flag2;
                    TeamMailboxHelper.GetCredentialAndConfigureClientContext(this.actAsUser, this.actAsUserOrgId, clientContext, true, out flag2);
                    Web web = clientContext.Web;
                    clientContext.Load <Web>(web, new Expression <Func <Web, object> >[]
                    {
                        (Web x) => x.AllProperties,
                        (Web x) => (object)x.Id
                    });
                    Site site = clientContext.Site;
                    clientContext.Load <Site>(site, new Expression <Func <Site, object> >[]
                    {
                        (Site x) => x.Url
                    });
                    clientContext.ExecuteQuery();
                    if (!siteChecked && clientContext.ServerVersion.Major < 15)
                    {
                        return(LinkSharePointSiteResult.SPServerVersionNotCompatible);
                    }
                    string text = this.teamMailbox.PrimarySmtpAddress.ToString();
                    if (web.AllProperties.FieldValues.ContainsKey("ExchangeTeamMailboxEmailAddress"))
                    {
                        sharePointTeamMailboxKey = (string)web.AllProperties["ExchangeTeamMailboxEmailAddress"];
                        if (!string.Equals(text, sharePointTeamMailboxKey, StringComparison.OrdinalIgnoreCase))
                        {
                            linkSharePointSiteResult = LinkSharePointSiteResult.LinkedByOthers;
                        }
                        else if (flag)
                        {
                            web.AllProperties["ExchangeTeamMailboxEmailAddress"] = null;
                            web.Update();
                            clientContext.ExecuteQuery();
                            this.teamMailbox.SharePointUrl = null;
                            this.teamMailbox.SetSharePointSiteInfo(null, Guid.Empty);
                            this.teamMailbox.SharePointLinkedBy = null;
                        }
                        else
                        {
                            if (this.actAsUser.Id.Equals(this.teamMailbox.SharePointLinkedBy))
                            {
                                linkSharePointSiteResult = LinkSharePointSiteResult.AlreadyLinkedBySelf;
                            }
                            else
                            {
                                this.teamMailbox.SharePointLinkedBy = this.actAsUser.Id;
                            }
                            this.teamMailbox.SharePointUrl = sharePointUrl;
                        }
                    }
                    else if (flag)
                    {
                        this.teamMailbox.SharePointUrl = null;
                        this.teamMailbox.SetSharePointSiteInfo(null, Guid.Empty);
                        this.teamMailbox.SharePointLinkedBy = null;
                    }
                    else
                    {
                        Uri url = TeamMailbox.GetUrl(site.Url);
                        if (url == null)
                        {
                            throw new RecipientTaskException(Strings.ErrorSharePointSiteHasNoValidWebCollectionUrl(site.Url));
                        }
                        web.AllProperties["ExchangeTeamMailboxEmailAddress"]      = text;
                        web.AllProperties["ExchangeTeamMailboxSharePointUrl"]     = sharePointUrl.AbsoluteUri;
                        web.AllProperties["ExchangeTeamMailboxSiteID"]            = web.Id.ToString();
                        web.AllProperties["ExchangeTeamMailboxSiteCollectionUrl"] = site.Url;
                        web.Update();
                        clientContext.ExecuteQuery();
                        this.teamMailbox.SharePointUrl = sharePointUrl;
                        this.teamMailbox.SetSharePointSiteInfo(url, web.Id);
                        this.teamMailbox.SharePointLinkedBy = this.actAsUser.Id;
                    }
                }
            }
            catch (ClientRequestException ex2)
            {
                ex = new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(uri.AbsoluteUri, ex2.Message));
            }
            catch (ServerException ex3)
            {
                ex = new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSiteWithCorrelationId(uri.AbsoluteUri, ex3.Message, ex3.ServerErrorTraceCorrelationId));
            }
            catch (TimeoutException ex4)
            {
                ex = new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(uri.AbsoluteUri, ex4.Message));
            }
            catch (IOException ex5)
            {
                ex = new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(uri.AbsoluteUri, ex5.Message));
            }
            catch (WebException e)
            {
                SharePointException ex6 = new SharePointException(uri.AbsoluteUri, e, false);
                ex = new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(uri.AbsoluteUri, ex6.DiagnosticInfo));
            }
            catch (FormatException ex7)
            {
                ex = new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(uri.AbsoluteUri, ex7.Message));
            }
            if (flag && forceToUnlink)
            {
                if (ex != null || linkSharePointSiteResult == LinkSharePointSiteResult.LinkedByOthers)
                {
                    this.teamMailbox.SharePointUrl = null;
                    this.teamMailbox.SetSharePointSiteInfo(null, Guid.Empty);
                    this.teamMailbox.SharePointLinkedBy = null;
                    linkSharePointSiteResult            = LinkSharePointSiteResult.Success;
                }
            }
            else if (ex != null)
            {
                throw ex;
            }
            return(linkSharePointSiteResult);
        }
		public static void SendWelcomeMessageIfNeeded(MailboxSession originalSession)
		{
			if (!string.IsNullOrEmpty(originalSession.ClientInfoString) && (originalSession.ClientInfoString.Equals("Client=TeamMailbox;Action=SendWelcomeMessageToSiteMailbox;Interactive=False", StringComparison.OrdinalIgnoreCase) || originalSession.ClientInfoString.Equals("Client=TeamMailbox;Action=GetDiagnostics;Interactive=False", StringComparison.OrdinalIgnoreCase) || originalSession.ClientInfoString.Equals("Client=TeamMailbox;Action=Send_Notification", StringComparison.OrdinalIgnoreCase)))
			{
				return;
			}
			originalSession.Mailbox.Load(new PropertyDefinition[]
			{
				MailboxSchema.SiteMailboxInternalState
			});
			int? siteMailboxInternalState = originalSession.Mailbox.TryGetProperty(InternalSchema.SiteMailboxInternalState) as int?;
			if (siteMailboxInternalState != null)
			{
				if ((siteMailboxInternalState.Value & 1) == 1)
				{
					return;
				}
			}
			try
			{
				using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(originalSession.MailboxOwner, originalSession.InternalCulture, "Client=TeamMailbox;Action=SendWelcomeMessageToSiteMailbox;Interactive=False"))
				{
					string internetMessageId = "ed590c4ca1674effa0067475ab2b93b2_" + mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress;
					using (MessageItem messageItem = MessageItem.CreateForDelivery(mailboxSession, mailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox), internetMessageId, new ExDateTime?(ExDateTime.MinValue)))
					{
						messageItem.Recipients.Add(new Participant(mailboxSession.MailboxOwner.MailboxInfo.DisplayName, mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString(), "SMTP"));
						messageItem.From = new Participant(mailboxSession.MailboxOwner);
						IRecipientSession recipientSession = null;
						TeamMailbox teamMailbox = TeamMailboxNotificationHelper.GetTeamMailbox(mailboxSession, out recipientSession);
						TeamMailboxNotificationHelper teamMailboxNotificationHelper = new TeamMailboxNotificationHelper(teamMailbox, recipientSession);
						messageItem.Subject = teamMailboxNotificationHelper.GetSubject(TeamMailboxNotificationType.Welcome);
						using (Stream stream = messageItem.Body.OpenWriteStream(new BodyWriteConfiguration(BodyFormat.TextHtml, Charset.Unicode)))
						{
							using (StreamWriter streamWriter = new StreamWriter(stream, Encoding.Unicode))
							{
								streamWriter.WriteLine(teamMailboxNotificationHelper.GetBody(TeamMailboxNotificationType.Welcome));
							}
						}
						messageItem.AutoResponseSuppress = AutoResponseSuppress.All;
						messageItem.InternetMessageId = internetMessageId;
						messageItem.PropertyBag[InternalSchema.SentTime] = ExDateTime.UtcNow;
						mailboxSession.Deliver(messageItem, ProxyAddress.Parse(ProxyAddressPrefix.Smtp.PrimaryPrefix, mailboxSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString()), RecipientItemType.To);
					}
					TeamMailboxNotificationHelper.UpdateWelcomeMessageSentState(siteMailboxInternalState, mailboxSession);
				}
			}
			catch (StoragePermanentException ex)
			{
				if (ex.InnerException != null && ex.InnerException is MapiExceptionDuplicateDelivery)
				{
					using (MailboxSession mailboxSession2 = MailboxSession.OpenAsAdmin(originalSession.MailboxOwner, originalSession.Culture, "Client=TeamMailbox;Action=SendWelcomeMessageToSiteMailbox;Interactive=False"))
					{
						TeamMailboxNotificationHelper.UpdateWelcomeMessageSentState(siteMailboxInternalState, mailboxSession2);
						goto IL_27D;
					}
					goto IL_27B;
					IL_27D:
					return;
				}
				IL_27B:
				throw;
			}
		}
        internal static MultiValuedProperty <CultureInfo> CheckSharePointSite(SmtpAddress teamMailboxEmailAddress, ref Uri sharePointUrl, ADRawEntry actAsUser, OrganizationId actAsUserOrgId, ADUser executingUser, out SharePointMemberShip executingUserMembership, out Uri webCollectionUrl, out Guid webId)
        {
            MultiValuedProperty <CultureInfo> multiValuedProperty = new MultiValuedProperty <CultureInfo>();

            executingUserMembership = SharePointMemberShip.Others;
            try
            {
                using (ClientContext clientContext = new ClientContext(sharePointUrl.AbsoluteUri))
                {
                    clientContext.RequestTimeout = 60000;
                    bool flag;
                    TeamMailboxHelper.GetCredentialAndConfigureClientContext(actAsUser, actAsUserOrgId, clientContext, true, out flag);
                    Web web = clientContext.Web;
                    clientContext.Load <Web>(web, new Expression <Func <Web, object> >[]
                    {
                        (Web x) => x.AllProperties,
                        (Web x) => x.Url,
                        (Web x) => (object)x.Language,
                        (Web x) => x.Features,
                        (Web x) => (object)x.Id
                    });
                    Feature byId = web.Features.GetById(new Guid("{502A2D54-6102-4757-AAA0-A90586106368}"));
                    clientContext.Load <Feature>(byId, new Expression <Func <Feature, object> > [0]);
                    Group associatedOwnerGroup  = clientContext.Web.AssociatedOwnerGroup;
                    Group associatedMemberGroup = clientContext.Web.AssociatedMemberGroup;
                    clientContext.Load <UserCollection>(associatedOwnerGroup.Users, new Expression <Func <UserCollection, object> > [0]);
                    clientContext.Load <UserCollection>(associatedMemberGroup.Users, new Expression <Func <UserCollection, object> > [0]);
                    Site site = clientContext.Site;
                    clientContext.Load <Site>(site, new Expression <Func <Site, object> >[]
                    {
                        (Site x) => x.Url
                    });
                    bool flag2 = false;
                    try
                    {
                        clientContext.ExecuteQuery();
                        if (byId.ServerObjectIsNull != null)
                        {
                            flag2 = !byId.ServerObjectIsNull.Value;
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                    }
                    if (!flag2)
                    {
                        throw new RecipientTaskException(Strings.ErrorTeamMailboxFeatureNotInstalled(web.Url));
                    }
                    if (clientContext.ServerVersion.Major < 15)
                    {
                        throw new RecipientTaskException(Strings.ErrorTeamMailboxSharePointServerVersionInCompatible);
                    }
                    if (web.AllProperties.FieldValues.ContainsKey("ExchangeTeamMailboxEmailAddress") && (teamMailboxEmailAddress == SmtpAddress.Empty || !string.Equals(teamMailboxEmailAddress.ToString(), (string)web.AllProperties["ExchangeTeamMailboxEmailAddress"], StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new RecipientTaskException(Strings.ErrorTeamMailboxSharePointSiteAlreadyLinkedWithOtherTM(sharePointUrl.ToString(), (string)web.AllProperties["ExchangeTeamMailboxEmailAddress"]));
                    }
                    webCollectionUrl = TeamMailbox.GetUrl(site.Url);
                    webId            = web.Id;
                    if (webCollectionUrl == null)
                    {
                        throw new RecipientTaskException(Strings.ErrorSharePointSiteHasNoValidWebCollectionUrl(site.Url));
                    }
                    multiValuedProperty.Add(new CultureInfo((int)web.Language));
                    try
                    {
                        foreach (User spUser in associatedOwnerGroup.Users)
                        {
                            if (TeamMailboxHelper.ExchangeSharePointUserMatch(executingUser, spUser))
                            {
                                executingUserMembership = SharePointMemberShip.Owner;
                                break;
                            }
                        }
                        if (executingUserMembership == SharePointMemberShip.Others)
                        {
                            foreach (User spUser2 in associatedMemberGroup.Users)
                            {
                                if (TeamMailboxHelper.ExchangeSharePointUserMatch(executingUser, spUser2))
                                {
                                    executingUserMembership = SharePointMemberShip.Member;
                                    break;
                                }
                            }
                        }
                    }
                    catch (CollectionNotInitializedException)
                    {
                        executingUserMembership = SharePointMemberShip.Others;
                    }
                    string uriString = null;
                    if (!MaintenanceSynchronizer.TryEscapeAndGetWellFormedUrl(web.Url, out uriString))
                    {
                        throw new RecipientTaskException(Strings.ErrorSharePointSiteHasNoValidUrl(web.Url));
                    }
                    Uri uri = new Uri(uriString);
                    if (uri != sharePointUrl)
                    {
                        sharePointUrl = uri;
                    }
                }
            }
            catch (ClientRequestException ex)
            {
                throw new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(sharePointUrl.AbsoluteUri, ex.Message));
            }
            catch (ServerException ex2)
            {
                throw new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSiteWithCorrelationId(sharePointUrl.AbsoluteUri, ex2.Message, ex2.ServerErrorTraceCorrelationId));
            }
            catch (TimeoutException ex3)
            {
                throw new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(sharePointUrl.AbsoluteUri, ex3.Message));
            }
            catch (IOException ex4)
            {
                throw new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(sharePointUrl.AbsoluteUri, ex4.Message));
            }
            catch (WebException e)
            {
                SharePointException ex5 = new SharePointException(sharePointUrl.AbsoluteUri, e, false);
                throw new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(sharePointUrl.AbsoluteUri, ex5.DiagnosticInfo));
            }
            catch (FormatException ex6)
            {
                throw new RecipientTaskException(Strings.ErrorTeamMailboxContactSharePointSite(sharePointUrl.AbsoluteUri, ex6.Message));
            }
            return(multiValuedProperty);
        }
        protected override void InternalProcessRecord()
        {
            ADUser      dataObject  = this.DataObject;
            TeamMailbox teamMailbox = TeamMailbox.FromDataObject(dataObject);

            this.teamMailboxHelper = new TeamMailboxHelper(teamMailbox, base.ExchangeRunspaceConfig.ExecutingUser, base.ExchangeRunspaceConfig.ExecutingUserOrganizationId, (IRecipientSession)base.DataSession, new TeamMailboxGetDataObject <ADUser>(base.GetDataObject <ADUser>));
            TeamMailboxMembershipHelper teamMailboxMembershipHelper = new TeamMailboxMembershipHelper(teamMailbox, (IRecipientSession)base.DataSession);
            Exception ex     = null;
            ADUser    aduser = TeamMailboxADUserResolver.Resolve((IRecipientSession)base.DataSession, this.executingUserId, out ex);

            if (aduser == null)
            {
                base.WriteError(new RecipientTaskException(Strings.ErrorExecutingUserIsNull), ExchangeErrorCategory.Client, null);
            }
            if (base.Fields.IsModified("DisplayName"))
            {
                teamMailbox.DisplayName = this.DisplayName;
            }
            teamMailbox.SetPolicy(this.provisioningPolicy);
            base.WriteVerbose(Strings.SiteMailboxPolicySet(this.provisioningPolicy.ToString()));
            teamMailbox.SetMyRole(this.executingUserId);
            Uri sharePointUrl = this.SharePointUrl;
            SharePointMemberShip sharePointMemberShip = SharePointMemberShip.Others;
            Uri  webCollectionUrl = null;
            Guid empty            = Guid.Empty;

            if (base.Fields.IsModified("SharePointUrl") && !base.Fields.IsModified("Force"))
            {
                try
                {
                    TeamMailboxHelper.CheckSharePointSite(SmtpAddress.Empty, ref sharePointUrl, base.ExchangeRunspaceConfig.ExecutingUser, base.ExchangeRunspaceConfig.ExecutingUserOrganizationId, aduser, out sharePointMemberShip, out webCollectionUrl, out empty);
                }
                catch (RecipientTaskException exception)
                {
                    base.WriteError(exception, ExchangeErrorCategory.Client, null);
                }
            }
            teamMailbox.SharePointUrl = sharePointUrl;
            teamMailbox.SetSharePointSiteInfo(webCollectionUrl, empty);
            teamMailbox.SharePointLinkedBy = this.executingUserId;
            List <ADObjectId>  list          = new List <ADObjectId>();
            List <ADObjectId>  list2         = new List <ADObjectId>();
            IList <ADObjectId> list3         = null;
            IList <ADObjectId> usersToRemove = null;

            if (TeamMailboxMembershipHelper.IsUserQualifiedType(aduser))
            {
                if (sharePointMemberShip == SharePointMemberShip.Owner)
                {
                    list.Add(this.executingUserId);
                    teamMailboxMembershipHelper.UpdateTeamMailboxUserList(teamMailbox.Owners, list, out list3, out usersToRemove);
                    teamMailboxMembershipHelper.UpdateTeamMailboxUserList(teamMailbox.OwnersAndMembers, list, out list3, out usersToRemove);
                }
                else if (sharePointMemberShip == SharePointMemberShip.Member)
                {
                    list2.Add(this.executingUserId);
                    teamMailboxMembershipHelper.UpdateTeamMailboxUserList(teamMailbox.OwnersAndMembers, list2, out list3, out usersToRemove);
                }
            }
            Exception ex2 = null;

            try
            {
                teamMailboxMembershipHelper.SetTeamMailboxUserPermissions(list3, usersToRemove, new SecurityIdentifier[]
                {
                    WellKnownSids.SiteMailboxGrantedAccessMembers
                }, false);
                if (list3 != null)
                {
                    base.WriteVerbose(Strings.SiteMailboxCreatorSet(list3[0].ToString()));
                }
            }
            catch (OverflowException ex3)
            {
                ex2 = ex3;
            }
            catch (COMException ex4)
            {
                ex2 = ex4;
            }
            catch (UnauthorizedAccessException ex5)
            {
                ex2 = ex5;
            }
            catch (TransientException ex6)
            {
                ex2 = ex6;
            }
            catch (DataSourceOperationException ex7)
            {
                ex2 = ex7;
            }
            if (ex2 != null)
            {
                base.WriteError(new RecipientTaskException(Strings.ErrorSetTeamMailboxUserPermissions(teamMailbox.DisplayName, ex2.Message)), ExchangeErrorCategory.Client, null);
            }
            base.InternalProcessRecord();
            if (base.Fields.IsModified("SharePointUrl") && !base.Fields.IsModified("Force"))
            {
                try
                {
                    this.teamMailboxHelper.LinkSharePointSite(sharePointUrl, true, false);
                    base.WriteVerbose(Strings.SiteMailboxLinkedToSharePointSite(sharePointUrl.AbsoluteUri));
                }
                catch (RecipientTaskException exception2)
                {
                    base.DataSession.Delete(this.DataObject);
                    base.WriteError(exception2, ExchangeErrorCategory.Client, null);
                }
            }
            IList <Exception> list4;

            teamMailboxMembershipHelper.SetShowInMyClient(list3, usersToRemove, out list4);
            foreach (Exception ex8 in list4)
            {
                this.WriteWarning(Strings.ErrorTeamMailboxResolveUser(ex8.Message));
            }
            EnqueueResult enqueueResult = EnqueueResult.Success;

            if (this.databaseLocationInfo != null)
            {
                int num = 0;
                for (;;)
                {
                    base.WriteVerbose(new LocalizedString(string.Format("Trying to send membership sync request to server {0} for MailboxGuid {1} using domain controller {2}", this.databaseLocationInfo.ServerFqdn, dataObject.ExchangeGuid, this.lastUsedDc)));
                    enqueueResult = RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.databaseLocationInfo.ServerFqdn, dataObject.ExchangeGuid, QueueType.TeamMailboxMembershipSync, base.CurrentOrganizationId, "NewTMCMD_" + base.ExecutingUserIdentityName, this.lastUsedDc, SyncOption.Default);
                    base.WriteVerbose(new LocalizedString(string.Format("The membership sync result is {0}", enqueueResult.Result)));
                    if (enqueueResult.Result == EnqueueResultType.Successful)
                    {
                        goto IL_409;
                    }
                    if (num > 12)
                    {
                        break;
                    }
                    Thread.Sleep(5000);
                    num++;
                }
                this.WriteWarning(Strings.ErrorTeamMailboxEnqueueMembershipSyncEvent(enqueueResult.ResultDetail));
                goto IL_414;
IL_409:
                base.WriteVerbose(Strings.SiteMailboxMembershipSyncEventEnqueued);
IL_414:
                enqueueResult = RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.databaseLocationInfo.ServerFqdn, dataObject.ExchangeGuid, QueueType.TeamMailboxDocumentSync, base.CurrentOrganizationId, "NewTMCMD_" + base.ExecutingUserIdentityName, this.lastUsedDc, SyncOption.Default);
                base.WriteVerbose(new LocalizedString(string.Format("Document sync request to server {0} for MailboxGuid {1} using domain controller {2}. The result is: {3}", new object[]
                {
                    this.databaseLocationInfo.ServerFqdn,
                    dataObject.ExchangeGuid,
                    this.lastUsedDc,
                    enqueueResult.ResultDetail
                })));
                return;
            }
            this.WriteWarning(Strings.ErrorTeamMailboxEnqueueMembershipSyncEvent("No database location information available"));
        }
Exemple #17
0
        protected virtual Exception ProcessNewOwnersAndMembers(Guid mailboxGuid, List <ADObjectId> newOwners, List <ADObjectId> newMembers)
        {
            Exception ex = null;

            try
            {
                this.mailbox = (this.recipientSession.FindByExchangeGuid(mailboxGuid) as ADUser);
                if (this.mailbox == null)
                {
                    throw new ObjectNotFoundException(new LocalizedString("Cannot find the team mailbox by mailbox guid " + mailboxGuid));
                }
                this.tm = TeamMailbox.FromDataObject(this.mailbox);
            }
            catch (ADTransientException ex2)
            {
                ex = ex2;
            }
            catch (ADExternalException ex3)
            {
                ex = ex3;
            }
            catch (ADOperationException ex4)
            {
                ex = ex4;
            }
            catch (DataValidationException ex5)
            {
                ex = ex5;
            }
            catch (ObjectNotFoundException ex6)
            {
                ex = ex6;
            }
            if (ex != null)
            {
                ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: Failed to find team mailbox {0}", (this.mailbox == null) ? mailboxGuid.ToString() : this.mailbox.PrimarySmtpAddress.ToString()), ex);
                return(ex);
            }
            this.membershipHelper = new TeamMailboxMembershipHelper(this.tm, this.recipientSession);
            TeamMailboxNotificationHelper teamMailboxNotificationHelper = null;

            if (this.isFirstSync)
            {
                teamMailboxNotificationHelper = new TeamMailboxNotificationHelper(this.tm, this.recipientSession);
                ADObjectId adobjectId = (this.tm.OwnersAndMembers.Count > 0) ? this.tm.OwnersAndMembers[0] : null;
                try
                {
                    if (adobjectId != null)
                    {
                        List <ADObjectId> list = MembershipSynchronizer.ListForSingleId(adobjectId);
                        ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: the following users have been added to team mailbox {0}: {1}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list)));
                        int count = this.tm.Owners.Count;
                        teamMailboxNotificationHelper.SendNotification(list, TeamMailboxNotificationType.MemberInvitation);
                    }
                }
                catch (StorageTransientException ex7)
                {
                    ex = ex7;
                }
                catch (StoragePermanentException ex8)
                {
                    ex = ex8;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed sending notifications for team mailbox {0}", this.mailbox.PrimarySmtpAddress), ex);
                }
            }
            new List <ADObjectId>();
            IList <ADObjectId> newUserList = TeamMailbox.MergeUsers(newOwners, newMembers);
            IList <ADObjectId> userList;
            IList <ADObjectId> list2;
            bool flag = this.membershipHelper.UpdateTeamMailboxUserList(this.tm.Owners, newOwners, out userList, out list2);
            IList <ADObjectId> list3;
            IList <ADObjectId> list4;
            bool flag2 = this.membershipHelper.UpdateTeamMailboxUserList(this.tm.OwnersAndMembers, newUserList, out list3, out list4);

            if (flag || flag2)
            {
                TeamMailbox.DiffUsers(list3, userList);
                try
                {
                    this.membershipHelper.SetTeamMailboxUserPermissions(list3, list4, null, true);
                }
                catch (OverflowException ex9)
                {
                    ex = ex9;
                }
                catch (COMException ex10)
                {
                    ex = ex10;
                }
                catch (UnauthorizedAccessException ex11)
                {
                    ex = ex11;
                }
                catch (TransientException ex12)
                {
                    ex = ex12;
                }
                catch (DataSourceOperationException ex13)
                {
                    ex = ex13;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed setting AD permissions for team mailbox {0}", this.mailbox.PrimarySmtpAddress), ex);
                    return(ex);
                }
                ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: the following users have been added to team mailbox {0}: {1}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list3)));
                ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: the following users have been removed from team mailbox {0}: {1}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list4)));
                try
                {
                    this.teamMailboxSecurityRefresher.Refresh(this.mailbox, this.recipientSession);
                }
                catch (DatabaseNotFoundException ex14)
                {
                    ex = ex14;
                }
                catch (ObjectNotFoundException ex15)
                {
                    ex = ex15;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed setting team mailbox {0} store permissions for userToAdd {1} and usersToRemove {2}", this.mailbox.PrimarySmtpAddress, MembershipSynchronizer.GetUsersString(list3), MembershipSynchronizer.GetUsersString(list4)), ex);
                }
                if (teamMailboxNotificationHelper == null)
                {
                    teamMailboxNotificationHelper = new TeamMailboxNotificationHelper(this.tm, this.recipientSession);
                }
                try
                {
                    teamMailboxNotificationHelper.SendNotification(list3, TeamMailboxNotificationType.MemberInvitation);
                }
                catch (StorageTransientException ex16)
                {
                    ex = ex16;
                }
                catch (StoragePermanentException ex17)
                {
                    ex = ex17;
                }
                if (ex != null)
                {
                    ProtocolLog.LogError(this.loggingComponent, this.loggingContext, string.Format("MembershipSynchronizer.ProcessNewOwnersAndMembers: failed sending member invitation for team mailbox {0}", this.mailbox.PrimarySmtpAddress), ex);
                }
                this.usersToUpdateShowInMyClient = new MembershipSynchronizer.UsersToUpdateShowInMyClient(list3, list4, this);
                while (this.usersToUpdateShowInMyClient.UpdateNextBatch())
                {
                    TimeSpan timeSpan;
                    this.IsThrottleDelayNeeded(out timeSpan);
                }
            }
            return(ex);
        }