Example #1
0
        public ADRecipient GetOnPremUser(SmtpAddress emailAddress)
        {
            IRecipientSession recipientSession = DirectorySessionFactory.Default.CreateRootOrgRecipientSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 49, "GetOnPremUser", "f:\\15.00.1497\\sources\\dev\\autodisc\\src\\AutoDiscoverV2\\TenantRepository.cs");

            this.logger.AppendGenericInfo("GetOnPremUser", "Start Ad lookup");
            return(recipientSession.FindByProxyAddress(new SmtpProxyAddress(emailAddress.Address, false)));
        }
Example #2
0
        // Token: 0x06000B96 RID: 2966 RVA: 0x00050E70 File Offset: 0x0004F070
        private static bool IsUsersEmailOrDomain(string email, bool isDomain, UserContext userContext)
        {
            IRecipientSession recipientSession = Utilities.CreateADRecipientSession(Culture.GetUserCulture().LCID, true, ConsistencyMode.IgnoreInvalid, true, userContext);
            ADRecipient       adrecipient      = null;

            try
            {
                SmtpProxyAddress proxyAddress = new SmtpProxyAddress(userContext.ExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), true);
                adrecipient = recipientSession.FindByProxyAddress(proxyAddress);
            }
            catch (NonUniqueRecipientException ex)
            {
                ExTraceGlobals.CoreTracer.TraceDebug <string>(0L, "IsUsersEmailOrDomain: NonUniqueRecipientException was thrown by FindByProxyAddress: {0}", ex.Message);
            }
            if (adrecipient == null)
            {
                return(false);
            }
            foreach (ProxyAddress proxyAddress2 in adrecipient.EmailAddresses)
            {
                if (proxyAddress2 != null && SmtpAddress.IsValidSmtpAddress(proxyAddress2.AddressString) && proxyAddress2.Prefix == ProxyAddressPrefix.Smtp)
                {
                    string smtpAddress = ((SmtpProxyAddress)proxyAddress2).SmtpAddress;
                    int    num         = smtpAddress.IndexOf('@');
                    int    length      = smtpAddress.Length;
                    if (string.Equals((!isDomain || num == -1) ? smtpAddress : smtpAddress.Substring(num, length - num), email, StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
        // Token: 0x0600206D RID: 8301 RVA: 0x00078A6C File Offset: 0x00076C6C
        internal static bool AddOtherMailboxConfig(CallContext callContext, string displayName, string primarySMTPAddress)
        {
            if (string.IsNullOrWhiteSpace(primarySMTPAddress))
            {
                return(false);
            }
            UserContext userContext = UserContextManager.GetUserContext(callContext.HttpContext, callContext.EffectiveCaller, true);

            if (userContext.IsExplicitLogon)
            {
                throw new OwaInvalidRequestException("Cannot open other's folder in explict logon mode");
            }
            SmtpAddress       smtpAddress        = SmtpAddress.Parse(primarySMTPAddress);
            IRecipientSession adrecipientSession = CallContext.Current.ADRecipientSessionContext.GetADRecipientSession();
            ADRecipient       adrecipient        = adrecipientSession.FindByProxyAddress(ProxyAddress.Parse(smtpAddress.ToString()));

            if (string.Equals(userContext.ExchangePrincipal.LegacyDn, adrecipient.LegacyExchangeDN, StringComparison.OrdinalIgnoreCase))
            {
                throw new OwaInvalidOperationException("Cannot open own folder");
            }
            SimpleConfiguration <OtherMailboxConfigEntry> otherMailboxConfig = OwaOtherMailboxConfiguration.GetOtherMailboxConfig(CallContext.Current);

            if (OwaOtherMailboxConfiguration.FindOtherMailboxConfigEntry(otherMailboxConfig, primarySMTPAddress) == null)
            {
                OtherMailboxConfigEntry otherMailboxConfigEntry = new OtherMailboxConfigEntry();
                otherMailboxConfigEntry.DisplayName          = displayName;
                otherMailboxConfigEntry.PrincipalSMTPAddress = primarySMTPAddress;
                otherMailboxConfig.Entries.Add(otherMailboxConfigEntry);
                otherMailboxConfig.Save(CallContext.Current);
            }
            return(true);
        }
        protected override ValidRecipient InternalCheckOneRecipient(ADRecipient mailboxOwner, string recipient, IRecipientSession recipientSession)
        {
            ADRecipient adrecipient = recipientSession.FindByProxyAddress(new SmtpProxyAddress(recipient, false));
            bool        flag;

            if (adrecipient == null)
            {
                ExTraceGlobals.SharingTracer.TraceDebug <ADRecipient, string>((long)this.GetHashCode(), "{0}: {1} is not found from AD in {0}'s organization.", mailboxOwner, recipient);
                flag = false;
            }
            else
            {
                ExTraceGlobals.SharingTracer.TraceDebug((long)this.GetHashCode(), "{0}: {1} is found from AD in {0}'s organization: RecipientType = {2}; RecipientDisplayType = {3}; IsValidSecurityPrincipal = {4}.", new object[]
                {
                    mailboxOwner,
                    recipient,
                    adrecipient.RecipientType,
                    adrecipient.RecipientDisplayType,
                    adrecipient.IsValidSecurityPrincipal
                });
                flag = adrecipient.IsValidSecurityPrincipal;
            }
            if (!flag)
            {
                return(null);
            }
            return(new ValidRecipient(recipient, adrecipient));
        }
Example #5
0
        public static TrackedUser Create(string smtpAddress, IRecipientSession galSession)
        {
            ProxyAddress proxyAddress = ProxyAddress.Parse(smtpAddress);
            ADRecipient  adrecipient  = null;

            try
            {
                adrecipient = galSession.FindByProxyAddress(proxyAddress);
            }
            catch (NonUniqueRecipientException arg)
            {
                TraceWrapper.SearchLibraryTracer.TraceError <ProxyAddress, NonUniqueRecipientException>(0, "Create from SmtpAddress: Caught NonUniqueRecipientException when attempting to look up user for address {0}, exception: {1}", proxyAddress, arg);
                return(null);
            }
            if (adrecipient != null)
            {
                try
                {
                    return(new TrackedUser(adrecipient));
                }
                catch (TrackedUserCreationException arg2)
                {
                    TraceWrapper.SearchLibraryTracer.TraceError <string, TrackedUserCreationException>(0, "Create from SmtpAddress: TrackedUserCreationException initializing from ADRecipient: {0}, {1}", smtpAddress, arg2);
                    return(null);
                }
            }
            return(new TrackedUser(smtpAddress));
        }
        public static ADRawEntry GetSender(IRecipientSession session, ProxyAddress sendingAs, ADPropertyDefinition[] properties)
        {
            ADRawEntry        sender            = null;
            ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
            {
                sender = session.FindByProxyAddress(sendingAs, properties);
            });

            if (!adoperationResult.Succeeded)
            {
                if (adoperationResult.Exception is NonUniqueRecipientException)
                {
                    string message = Strings.descMailTipsSenderNotUnique(sendingAs.ToString());
                    throw new SenderNotUniqueException(message);
                }
                throw adoperationResult.Exception;
            }
            else
            {
                if (sender == null)
                {
                    string message2 = Strings.descMailTipsSenderNotFound(sendingAs.ToString());
                    throw new SenderNotFoundException(message2);
                }
                return(sender);
            }
        }
        private PermissionSecurityPrincipal CreatePermissionSecurityPrincipal(ValidRecipient recipient, IExchangePrincipal mailboxPrincipal)
        {
            ADRecipient adrecipient = recipient.ADRecipient;

            if (adrecipient == null)
            {
                IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.FullyConsistent, null, mailboxPrincipal.MailboxInfo.OrganizationId.ToADSessionSettings(), 248, "CreatePermissionSecurityPrincipal", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Sharing\\SharingProviderHandlerInternal.cs");
                adrecipient = tenantOrRootOrgRecipientSession.FindByProxyAddress(new SmtpProxyAddress(recipient.SmtpAddress, false));
            }
            return(new PermissionSecurityPrincipal(adrecipient));
        }
        protected override ValidRecipient InternalCheckOneRecipient(ADRecipient mailboxOwner, string recipient, IRecipientSession recipientSession)
        {
            ADRecipient adrecipient = recipientSession.FindByProxyAddress(new SmtpProxyAddress(recipient, false));

            if (adrecipient != null)
            {
                ExTraceGlobals.SharingTracer.TraceDebug <ADRecipient, string>((long)this.GetHashCode(), "{0}: {1} is found from AD in {0}'s organization.", mailboxOwner, recipient);
                return(null);
            }
            return(new ValidRecipient(recipient, adrecipient));
        }
        public IGenericADUser FindByProxyAddress(IRecipientSession recipientSession, ProxyAddress proxyAddress)
        {
            ArgumentValidator.ThrowIfNull("recipientSession", recipientSession);
            IGenericADUser adUser = null;

            this.DoAdCallAndTranslateExceptions(delegate
            {
                adUser = this.TranslateADRecipient(recipientSession.FindByProxyAddress(proxyAddress), false);
            }, "DirectoryAccessor::FindByProxyAddress");
            return(adUser);
        }
Example #10
0
        private static ADRawEntry FindByProxyAddress(ProxyAddress proxyAddress, IRecipientSession recipientSession, IRoutingDiagnostics diagnostics)
        {
            DateTime   utcNow = DateTime.UtcNow;
            ADRawEntry result;

            try
            {
                result = recipientSession.FindByProxyAddress(proxyAddress, ActiveDirectoryUserProvider.AdRawEntryProperties);
            }
            finally
            {
                diagnostics.AddAccountForestLatency(DateTime.UtcNow - utcNow);
            }
            return(result);
        }
Example #11
0
        // Token: 0x0600016E RID: 366 RVA: 0x000078D4 File Offset: 0x00005AD4
        protected override ADRawEntry LoadADRawEntry()
        {
            IRecipientSession session = DirectoryHelper.GetRecipientSessionFromSmtpOrLiveId(this.Smtp, base.RequestContext.Logger, base.RequestContext.LatencyTracker, !this.FailOnDomainNotFound);
            ADRawEntry        ret     = null;

            if (session != null)
            {
                ret = DirectoryHelper.InvokeAccountForest <ADRawEntry>(base.RequestContext.LatencyTracker, delegate()
                {
                    if (FaultInjection.TraceTest <bool>(FaultInjection.LIDs.ShouldFailSmtpAnchorMailboxADLookup))
                    {
                        return(null);
                    }
                    return(session.FindByProxyAddress(new SmtpProxyAddress(this.Smtp, true), this.PropertySet, "d:\\dbs\\sh\\e16df\\0212_214120_0\\cmd\\1g\\sources\\Dev\\Cafe\\src\\HttpProxy\\AnchorMailbox\\SmtpAnchorMailbox.cs", 107, "LoadADRawEntry"));
                }, base.RequestContext.Logger, session);
            }
            return(base.CheckForNullAndThrowIfApplicable <ADRawEntry>(ret));
        }
Example #12
0
 protected override bool TryGetGroupInfo(IRecipientSession session, RoutingAddress group, out Guid objectGuid, out Microsoft.Exchange.Data.Directory.Recipient.RecipientType recipientType, out int ldapQueries)
 {
     ldapQueries = 0;
     if (group.IsValid)
     {
         ADRawEntry adrawEntry = session.FindByProxyAddress(new SmtpProxyAddress((string)group, false), IsMemberOfResolverADAdapter <RoutingAddress> .properties);
         ldapQueries = 1;
         if (adrawEntry != null)
         {
             objectGuid    = adrawEntry.Id.ObjectGuid;
             recipientType = (Microsoft.Exchange.Data.Directory.Recipient.RecipientType)adrawEntry[ADRecipientSchema.RecipientType];
             return(true);
         }
     }
     objectGuid    = Guid.Empty;
     recipientType = Microsoft.Exchange.Data.Directory.Recipient.RecipientType.Invalid;
     return(false);
 }
Example #13
0
 public static string[] GetAllEmailAddresses(string emailAddress, OrganizationId organizationId)
 {
     if (string.IsNullOrEmpty(emailAddress))
     {
         throw new ArgumentNullException("emailAddress");
     }
     if (organizationId == null)
     {
         throw new ArgumentNullException("organizationId");
     }
     if (emailAddress.IndexOf('@') > 0)
     {
         if (!SmtpAddress.IsValidSmtpAddress(emailAddress))
         {
             throw new ArgumentException(string.Format("emailAddress:{0} is not a valid ProxyAddress", emailAddress));
         }
         ProxyAddress      proxyAddress     = new SmtpProxyAddress(emailAddress, false);
         IRecipientSession recipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(organizationId), 345, "GetAllEmailAddresses", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\PolicyTips\\ADUtils.cs");
         ADRawEntry        lookupResult     = null;
         ADNotificationAdapter.RunADOperation(delegate()
         {
             lookupResult = recipientSession.FindByProxyAddress(proxyAddress, ADUtils.PropertiesToGet);
         });
         if (lookupResult != null)
         {
             ProxyAddressCollection proxyAddressCollection = (ProxyAddressCollection)lookupResult[ADRecipientSchema.EmailAddresses];
             if (proxyAddressCollection != null && proxyAddressCollection.Count > 0)
             {
                 string[] array = new string[proxyAddressCollection.Count];
                 int      num   = 0;
                 foreach (ProxyAddress proxyAddress2 in proxyAddressCollection)
                 {
                     array[num++] = proxyAddress2.AddressString;
                 }
                 return(array);
             }
         }
     }
     return(new string[]
     {
         emailAddress
     });
 }
Example #14
0
        private void SendNotifications(RoutingAddress from, RoutingAddress recipient, MbxTransportMailItem rmi, string threadIndex, string threadTopic, string existingDecisionMakerAddress, ApprovalStatus?existingApprovalStatus, ExDateTime?existingDecisionTime)
        {
            HeaderList headers = rmi.RootPart.Headers;
            Header     acceptLanguageHeader     = headers.FindFirst("Accept-Language");
            Header     contentLanguageHeader    = headers.FindFirst(HeaderId.ContentLanguage);
            string     decisionMakerDisplayName = existingDecisionMakerAddress;
            bool?      flag = null;

            if (existingApprovalStatus != null)
            {
                if ((existingApprovalStatus.Value & ApprovalStatus.Approved) == ApprovalStatus.Approved)
                {
                    flag = new bool?(true);
                }
                else if ((existingApprovalStatus.Value & ApprovalStatus.Rejected) == ApprovalStatus.Rejected)
                {
                    flag = new bool?(false);
                }
            }
            if (!string.IsNullOrEmpty(existingDecisionMakerAddress))
            {
                ADNotificationAdapter.TryRunADOperation(delegate()
                {
                    IRecipientSession recipientSession = ApprovalProcessor.CreateRecipientSessionFromSmtpAddress(existingDecisionMakerAddress);
                    ADRawEntry adrawEntry = recipientSession.FindByProxyAddress(new SmtpProxyAddress(existingDecisionMakerAddress, true), ApprovalProcessingAgent.DisplayNameProperty);
                    if (adrawEntry != null)
                    {
                        string text = (string)adrawEntry[ADRecipientSchema.DisplayName];
                        if (!string.IsNullOrEmpty(text))
                        {
                            decisionMakerDisplayName = text;
                        }
                    }
                }, 1);
            }
            ApprovalProcessingAgent.diag.TraceDebug <bool?, string>(0L, "Generating conflict notification. Decision='{0}', DecisionMaker='{1}'", flag, decisionMakerDisplayName);
            EmailMessage emailMessage = NotificationGenerator.GenerateDecisionNotTakenNotification(from, recipient, rmi.Subject, threadIndex, threadTopic, decisionMakerDisplayName, flag, existingDecisionTime, acceptLanguageHeader, contentLanguageHeader, rmi.TransportSettings.InternalDsnDefaultLanguage);

            if (emailMessage != null)
            {
                this.server.SubmitMessage(rmi, emailMessage, rmi.OrganizationId, rmi.ExternalOrganizationId, false);
            }
        }
Example #15
0
        protected override ADRawEntry LoadADRawEntry()
        {
            IRecipientSession session = DirectoryHelper.GetRecipientSessionFromSmtpOrLiveId(base.RequestContext.LatencyTracker, this.Smtp, !this.FailOnDomainNotFound);
            ADRawEntry        ret     = null;

            if (session != null)
            {
                ret = DirectoryHelper.InvokeAccountForest(base.RequestContext.LatencyTracker, delegate
                {
                    bool flag = FaultInjection.TraceTest <bool>(FaultInjection.LIDs.ShouldFailSmtpAnchorMailboxADLookup);
                    if (flag)
                    {
                        return(null);
                    }
                    return(session.FindByProxyAddress(new SmtpProxyAddress(this.Smtp, true), this.PropertySet));
                });
            }
            return(base.CheckForNullAndThrowIfApplicable <ADRawEntry>(ret));
        }
        public static OAuthCredentials Create(InternalClientContext clientContext, RequestLogger requestLogger)
        {
            ArgumentValidator.ThrowIfNull("clientContext", clientContext);
            OrganizationId organizationId = clientContext.OrganizationId;
            ADUser         aduser         = clientContext.ADUser;
            string         text           = FaultInjection.TraceTest <string>((FaultInjection.LIDs) 2743479613U);

            if (!string.IsNullOrEmpty(text))
            {
                SmtpAddress       smtpAddress      = SmtpAddress.Parse(text);
                IRecipientSession recipientSession = DirectorySessionFactory.Default.CreateTenantRecipientSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromTenantAcceptedDomain(smtpAddress.Domain), 68, "Create", "f:\\15.00.1497\\sources\\dev\\infoworker\\src\\common\\RequestDispatch\\OAuthCredentialsFactory.cs");
                aduser         = (recipientSession.FindByProxyAddress(ProxyAddress.Parse(text)) as ADUser);
                organizationId = aduser.OrganizationId;
            }
            OAuthCredentials oauthCredentialsForAppActAsToken = OAuthCredentials.GetOAuthCredentialsForAppActAsToken(organizationId, aduser, null);

            OAuthCredentialsFactory.SetCredentialsProperties(oauthCredentialsForAppActAsToken, clientContext, requestLogger);
            return(oauthCredentialsForAppActAsToken);
        }
Example #17
0
        internal static ADUser GetADUser(MailboxSession session, bool readOnly, out IRecipientSession recipSession)
        {
            recipSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(readOnly, ConsistencyMode.FullyConsistent, session.MailboxOwner.MailboxInfo.OrganizationId.ToADSessionSettings(), 43, "GetADUser", "f:\\15.00.1497\\sources\\dev\\infoworker\\src\\common\\ELC\\AdReader.cs");
            ADRecipient adrecipient = null;
            string      text        = session.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString();

            try
            {
                if (session.MailboxOwner.MailboxInfo.MailboxGuid != Guid.Empty)
                {
                    adrecipient = recipSession.FindByExchangeGuidIncludingArchive(session.MailboxOwner.MailboxInfo.MailboxGuid);
                }
                else if (SmtpAddress.IsValidSmtpAddress(text))
                {
                    SmtpProxyAddress proxyAddress = new SmtpProxyAddress(text, true);
                    adrecipient = recipSession.FindByProxyAddress(proxyAddress);
                }
                else
                {
                    AdReader.Tracer.TraceDebug <string>(0L, "Mailbox '{0}' does not have a valid smtp address.", text);
                }
            }
            catch (DataValidationException)
            {
                AdReader.Tracer.TraceError <string>(0L, "AD object for '{0}' has a data validation issue.", text);
                return(null);
            }
            if (adrecipient == null)
            {
                AdReader.Tracer.TraceDebug <string>(0L, "Mailbox '{0}' does not have a user associated with it.", text);
                return(null);
            }
            ADUser aduser = adrecipient as ADUser;

            if (aduser == null)
            {
                AdReader.Tracer.TraceDebug <string>(0L, "'{0}': Is not an ADUser.", text);
                return(null);
            }
            return(aduser);
        }
Example #18
0
        internal static string EnsureGroupIsInDirectoryCache(string perfTrackerPrefix, IRecipientSession readWriteSession, ADUser groupAdUser)
        {
            string result;

            using (new StopwatchPerformanceTracker(perfTrackerPrefix + ".EnsureGroupIsInDirectoryCache", GenericCmdletInfoDataLogger.Instance))
            {
                IRecipientSession tenantOrRootRecipientReadOnlySession = DirectorySessionFactory.Default.GetTenantOrRootRecipientReadOnlySession(readWriteSession, groupAdUser.OriginatingServer, 204, "EnsureGroupIsInDirectoryCache", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\RecipientTasks\\GroupMailbox\\GroupMailboxContext.cs");
                ProxyAddress      proxyAddress     = new SmtpProxyAddress(groupAdUser.PrimarySmtpAddress.ToString(), true);
                ADUser            aduser           = tenantOrRootRecipientReadOnlySession.FindByProxyAddress(proxyAddress) as ADUser;
                OWAMiniRecipient  owaminiRecipient = tenantOrRootRecipientReadOnlySession.FindMiniRecipientByProxyAddress <OWAMiniRecipient>(proxyAddress, OWAMiniRecipientSchema.AdditionalProperties);
                string            text             = string.Format("Querying AD for group. ProxyAddress={0}, DomainController={1}, FoundADUser={2}, FoundOwaMiniRecipient={3}", new object[]
                {
                    proxyAddress,
                    groupAdUser.OriginatingServer,
                    aduser != null,
                    owaminiRecipient != null
                });
                GroupMailboxContext.Tracer.TraceDebug <string>(0L, "{0}", text);
                result = text;
            }
            return(result);
        }
Example #19
0
        internal static string GetSipUri(string emailAddress, IUserContext userContext)
        {
            IRecipientSession recipientSession = InstantMessageUtilities.CreateADRecipientSession(Culture.GetUserCulture().LCID, true, ConsistencyMode.IgnoreInvalid, true, userContext.ExchangePrincipal, false, userContext.MailboxIdentity.GetOWAMiniRecipient().QueryBaseDN);

            try
            {
                SmtpProxyAddress proxyAddress = new SmtpProxyAddress(emailAddress, true);
                ADRecipient      adrecipient  = recipientSession.FindByProxyAddress(proxyAddress);
                if (adrecipient != null)
                {
                    string sipUri = ADPersonToContactConverter.GetSipUri(adrecipient);
                    Microsoft.Exchange.Diagnostics.Components.Clients.ExTraceGlobals.InstantMessagingTracer.TraceDebug <string, string>(0L, "SIPUri for {0}: {1}", emailAddress, sipUri);
                    return(sipUri);
                }
            }
            catch (NonUniqueRecipientException ex)
            {
                Microsoft.Exchange.Diagnostics.Components.Clients.ExTraceGlobals.InstantMessagingTracer.TraceError <string>(0L, "Failed to get unique recipient: Error: {0}", ex.Message);
            }
            Microsoft.Exchange.Diagnostics.Components.Clients.ExTraceGlobals.InstantMessagingTracer.TraceError <string>(0L, "Failed to get SIP Address for: {0}", emailAddress);
            return(null);
        }
Example #20
0
        private static void GetNamesByAnrFromAD(UserContext userContext, AnrManager.NameParsingResult parsingResult, AnrManager.Options options, List <RecipientAddress> addresses)
        {
            IRecipientSession recipientSession = Utilities.CreateADRecipientSession(Culture.GetUserCulture().LCID, true, ConsistencyMode.IgnoreInvalid, true, userContext);

            ADRawEntry[] array = null;
            bool         flag  = parsingResult.ParsedSuccessfully && !Utilities.IsMobileRoutingType(parsingResult.RoutingType);
            string       text  = flag ? string.Format("{0}:{1}", parsingResult.RoutingType, parsingResult.RoutingAddress) : parsingResult.Name;

            if (flag)
            {
                ADRawEntry adrawEntry = recipientSession.FindByProxyAddress(ProxyAddress.Parse(text), AnrManager.AnrProperties.Get(AnrManager.AnrProperties.PropertiesType.AD, options));
                if (adrawEntry != null)
                {
                    if ((bool)adrawEntry[ADRecipientSchema.HiddenFromAddressListsEnabled])
                    {
                        array = new ADRawEntry[0];
                        ExTraceGlobals.CoreTracer.TraceDebug <ADObjectId>(0L, "AnrManager.GetNamesByAnrFromAD: Recipient ignored because it is hiddem from address lists: {0}", adrawEntry.Id);
                    }
                    else
                    {
                        array = new ADRawEntry[]
                        {
                            adrawEntry
                        };
                    }
                }
            }
            if (array == null)
            {
                QueryFilter filter = new AndFilter(new QueryFilter[]
                {
                    new AmbiguousNameResolutionFilter(text),
                    AnrManager.addressListMembershipExists
                });
                array = recipientSession.Find(null, QueryScope.SubTree, filter, null, AnrManager.nameLimit, AnrManager.AnrProperties.Get(AnrManager.AnrProperties.PropertiesType.AD, options));
            }
            AnrManager.AddADRecipients(array, options, addresses);
        }
Example #21
0
        internal static OAuthCredentials GetOAuthCredential(string sipUri)
        {
            ProxyAddress proxyAddress = ProxyAddress.Parse(sipUri);
            string       sipDomain    = OnlineMeetingHelper.GetSipDomain(sipUri);

            if (string.IsNullOrEmpty(sipDomain))
            {
                ExTraceGlobals.OnlineMeetingTracer.TraceError <string>(0L, "[UcwaConfigurationUtilities.GetOAuthCredential] Unable to determine domain from sip uri: {0}", sipUri);
                throw new OwaException(string.Format("Unable to determine domain from sip uri: {0}", sipUri));
            }
            MiniRecipient     miniRecipient    = null;
            IRecipientSession recipientSession = null;

            try
            {
                recipientSession = UserContextUtilities.CreateScopedRecipientSession(true, ConsistencyMode.FullyConsistent, sipDomain, null);
            }
            catch (OwaADObjectNotFoundException innerException)
            {
                throw new OwaException(string.Format("Couldn't create a scoped recipient session for {0}", sipDomain), innerException);
            }
            try
            {
                miniRecipient = recipientSession.FindByProxyAddress <MiniRecipient>(proxyAddress);
                if (miniRecipient == null)
                {
                    ExTraceGlobals.OnlineMeetingTracer.TraceError <string>(0L, "[UcwaConfigurationUtilities.GetOAuthCredential] IRecipientSession.FindByProxyAddress() unable to find to recipient with address: {0}", sipUri);
                    throw new OwaException(string.Format("Couldn't find a match for {0}", proxyAddress.ToString()));
                }
            }
            catch (NonUniqueRecipientException innerException2)
            {
                ExTraceGlobals.OnlineMeetingTracer.TraceError <string>(0L, "[UcwaConfigurationUtilities.GetOAuthCredential] Couldn't find a unique match for: {0}", sipUri);
                throw new OwaException(string.Format("Couldn't find a unique match for {0}", proxyAddress.ToString()), innerException2);
            }
            return(OAuthCredentials.GetOAuthCredentialsForAppActAsToken(miniRecipient.OrganizationId, miniRecipient, sipDomain));
        }
Example #22
0
        // Token: 0x06000B1E RID: 2846 RVA: 0x0004EC1C File Offset: 0x0004CE1C
        internal static string GetUserPrincipalName(string emailAddress, UserContext userContext)
        {
            string text = string.Empty;

            try
            {
                IRecipientSession recipientSession = Utilities.CreateADRecipientSession(ConsistencyMode.IgnoreInvalid, userContext);
                ProxyAddress      proxyAddress     = ProxyAddress.Parse(emailAddress);
                ADRecipient       adrecipient      = recipientSession.FindByProxyAddress(proxyAddress);
                if (adrecipient != null)
                {
                    text = adrecipient[ADUserSchema.UserPrincipalName].ToString();
                }
            }
            catch (Exception ex)
            {
                ExTraceGlobals.CoreTracer.TraceDebug <string>(0L, "IntantMessageUtilities.GetUserPrincipalName: Exception was thrown by User: {0}", ex.Message);
            }
            if (string.IsNullOrEmpty(text))
            {
                text = emailAddress;
            }
            return(text);
        }
Example #23
0
        internal override bool OnApprove(MessageItem message)
        {
            AutoGroupApplication.diag.TraceFunction((long)this.GetHashCode(), "AutoGroupApplication.OnApprove");
            message.Load(new PropertyDefinition[]
            {
                MessageItemSchema.ReceivedBy,
                MessageItemSchema.ApprovalDecisionMaker,
                MessageItemSchema.ApprovalRequestor,
                MessageItemSchema.ApprovalAllowedDecisionMakers,
                MessageItemSchema.ApprovalApplicationData
            });
            CultureInfo cultureInfo    = null;
            CultureInfo messageCulture = null;
            string      arg;
            SmtpAddress smtpAddress;
            SmtpAddress smtpAddress2;

            SmtpAddress[] array;
            if (!AutoGroupApplication.GetItemRecipients(message, out arg, out smtpAddress, out smtpAddress2, out array))
            {
                AutoGroupApplication.diag.TraceError <string, SmtpAddress, SmtpAddress>((long)this.GetHashCode(), "'{0}' message has invalid approver '{1}', requester '{2}', or empty moderators list.", arg, smtpAddress, smtpAddress2);
                return(false);
            }
            SmtpAddress emailAddressFromMailboxItem = AutoGroupApplication.GetEmailAddressFromMailboxItem(message);

            if (emailAddressFromMailboxItem == SmtpAddress.Empty)
            {
                AutoGroupApplication.diag.TraceError <string>((long)this.GetHashCode(), "'{0}' cannot get arbitration mailbox SMTP address from message.", arg);
                return(false);
            }
            string     valueOrDefault = message.GetValueOrDefault <string>(MessageItemSchema.ApprovalApplicationData);
            string     text;
            ADObjectId adobjectId;

            if (string.IsNullOrEmpty(valueOrDefault) || !AutoGroupApplication.ParseApprovalData(valueOrDefault, out text, out adobjectId))
            {
                AutoGroupApplication.diag.TraceError <string, string>((long)this.GetHashCode(), "'{0}' applicationData '{1}' cannot be parsed", arg, valueOrDefault);
                return(false);
            }
            IRecipientSession recipientSession = ApprovalProcessor.CreateRecipientSessionFromSmtpAddress(smtpAddress);
            ADRawEntry        adrawEntry       = null;
            bool flag = true;

            try
            {
                adrawEntry = recipientSession.FindByProxyAddress(new SmtpProxyAddress(smtpAddress.ToString(), true), new PropertyDefinition[]
                {
                    ADObjectSchema.Id,
                    ADUserSchema.Languages
                });
            }
            catch (NonUniqueRecipientException)
            {
                flag = false;
            }
            ADRawEntry adrawEntry2 = null;
            bool       flag2       = true;

            try
            {
                adrawEntry2 = recipientSession.FindByProxyAddress(new SmtpProxyAddress(smtpAddress2.ToString(), true), new PropertyDefinition[]
                {
                    ADObjectSchema.Id,
                    ADRecipientSchema.PrimarySmtpAddress,
                    ADUserSchema.Languages
                });
            }
            catch (NonUniqueRecipientException)
            {
                flag2 = false;
            }
            MiniRecipient miniRecipient = recipientSession.ReadMiniRecipient(adobjectId, null);

            if (miniRecipient == null)
            {
                AutoGroupApplication.diag.TraceError <string, ADObjectId>((long)this.GetHashCode(), "'{0}' group '{1}' not found in AD.", arg, adobjectId);
                return(false);
            }
            string group;

            if (string.IsNullOrEmpty(miniRecipient.DisplayName))
            {
                group = miniRecipient.Name;
            }
            else
            {
                group = miniRecipient.DisplayName;
            }
            if (adrawEntry == null)
            {
                if (flag)
                {
                    AutoGroupApplication.diag.TraceError <string, SmtpAddress>((long)this.GetHashCode(), "'{0}' approver '{1}' not found in AD.", arg, smtpAddress);
                }
                else
                {
                    AutoGroupApplication.diag.TraceError <string, SmtpAddress>((long)this.GetHashCode(), "'{0}' approver '{1}' not unique in AD.", arg, smtpAddress);
                }
                ApprovalProcessor.SendNotification(emailAddressFromMailboxItem, message.Id.ObjectId, new SmtpAddress[]
                {
                    smtpAddress
                }, Strings.AutoGroupRequestFailedSubject(group), Strings.AutoGroupRequestFailedHeader(group), Strings.AutoGroupRequestFailedBodyBadApprover(group, ApprovalProcessor.GetDisplayNameFromSmtpAddress(smtpAddress2.ToString()), ApprovalProcessor.GetDisplayNameFromSmtpAddress(smtpAddress.ToString())), LocalizedString.Empty, null);
                return(false);
            }
            MultiValuedProperty <CultureInfo> multiValuedProperty = (MultiValuedProperty <CultureInfo>)adrawEntry[ADUserSchema.Languages];

            if (multiValuedProperty.Count > 0)
            {
                cultureInfo = multiValuedProperty[0];
            }
            if (adrawEntry2 == null)
            {
                if (flag2)
                {
                    AutoGroupApplication.diag.TraceError <string, SmtpAddress>((long)this.GetHashCode(), "'{0}' requester '{1}' not found in AD.", arg, smtpAddress2);
                }
                else
                {
                    AutoGroupApplication.diag.TraceError <string, SmtpAddress>((long)this.GetHashCode(), "'{0}' requester '{1}' not unique in AD.", arg, smtpAddress2);
                }
                ApprovalProcessor.SendNotification(emailAddressFromMailboxItem, message.Id.ObjectId, new SmtpAddress[]
                {
                    smtpAddress
                }, Strings.AutoGroupRequestFailedSubject(group), Strings.AutoGroupRequestFailedHeader(group), Strings.AutoGroupRequestFailedBodyBadRequester(group, ApprovalProcessor.GetDisplayNameFromSmtpAddress(smtpAddress2.ToString())), LocalizedString.Empty, cultureInfo);
                return(false);
            }
            MultiValuedProperty <CultureInfo> multiValuedProperty2 = (MultiValuedProperty <CultureInfo>)adrawEntry2[ADUserSchema.Languages];

            if (multiValuedProperty2.Count > 0)
            {
                messageCulture = multiValuedProperty2[0];
            }
            bool   flag3 = false;
            string a;

            if ((a = text) != null)
            {
                if (!(a == "Add-DistributionGroupMember"))
                {
                    if (!(a == "Remove-DistributionGroupMember"))
                    {
                        goto IL_393;
                    }
                    flag3 = true;
                }
                PSCommand pscommand = new PSCommand().AddCommand(text);
                pscommand.AddParameter("Identity", adobjectId);
                pscommand.AddParameter("Member", adrawEntry2.Id);
                if (flag3)
                {
                    pscommand.AddParameter("Confirm", new SwitchParameter(false));
                }
                AutoGroupApplication.diag.Information <string, string>((long)this.GetHashCode(), "'{0}' executing command '{1}'.", arg, pscommand.ToString());
                string text2;
                string text3;
                ApprovalApplication.ExecuteCommandsInRunspace(smtpAddress, pscommand, cultureInfo, out text2, out text3);
                if (!text2.Equals(string.Empty))
                {
                    AutoGroupApplication.diag.TraceError <string, string, string>((long)this.GetHashCode(), "'{0}' command '{1}' failed with error {2}.", arg, pscommand.ToString(), text2);
                    ApprovalProcessor.SendNotification(emailAddressFromMailboxItem, message.Id.ObjectId, new SmtpAddress[]
                    {
                        smtpAddress
                    }, Strings.AutoGroupRequestFailedSubject(group), Strings.AutoGroupRequestFailedHeader(group), Strings.AutoGroupRequestFailedBodyTaskError(text2), LocalizedString.Empty, cultureInfo);
                    return(false);
                }
                AutoGroupApplication.diag.Information <string, string>((long)this.GetHashCode(), "'{0}' command '{1}' completed successfully.", arg, pscommand.ToString());
                ApprovalProcessor.SendApproveNotification(emailAddressFromMailboxItem, message.Id.ObjectId, new SmtpAddress[]
                {
                    (SmtpAddress)adrawEntry2[ADRecipientSchema.PrimarySmtpAddress]
                }, Strings.AutoGroupRequestApprovedSubject(group), Strings.AutoGroupRequestApprovedHeader(ApprovalProcessor.GetDisplayNameFromSmtpAddress(smtpAddress.ToString()), group), Strings.AutoGroupRequestApprovedBody, LocalizedString.Empty, messageCulture);
                return(true);
            }
IL_393:
            AutoGroupApplication.diag.TraceError <string, string>((long)this.GetHashCode(), "'{0}' command '{1}' not recognized.", arg, text);
            return(false);
        }
        private void Discover(ExchangePrincipal principal, ADUser executingUser, out string ewsEndpoint, out DelegationTokenRequest ewsTokenRequest)
        {
            SmtpAddress              value           = principal.MailboxInfo.RemoteIdentity.Value;
            ADSessionSettings        sessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(OrganizationId.ForestWideOrgId);
            IRecipientSession        tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.FullyConsistent, null, sessionSettings, ConfigScopes.TenantSubTree, 168, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs");
            ADUser                   aduser = null;
            TransportConfigContainer transportConfigContainer = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, sessionSettings, 171, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs").FindSingletonConfigurationObject <TransportConfigContainer>();

            if (transportConfigContainer != null && transportConfigContainer.OrganizationFederatedMailbox != SmtpAddress.NullReversePath)
            {
                SmtpAddress  organizationFederatedMailbox = transportConfigContainer.OrganizationFederatedMailbox;
                ProxyAddress proxyAddress = null;
                try
                {
                    proxyAddress = ProxyAddress.Parse(organizationFederatedMailbox.ToString());
                }
                catch (ArgumentException ex)
                {
                    ExTraceGlobals.SessionTracer.TraceError <string>((long)this.GetHashCode(), "Proxy address of organization federated mailbox is invalid: {0}", ex.ToString());
                }
                if (proxyAddress != null && !(proxyAddress is InvalidProxyAddress))
                {
                    aduser = (tenantOrRootOrgRecipientSession.FindByProxyAddress(proxyAddress) as ADUser);
                }
            }
            OrganizationIdCacheValue organizationIdCacheValue = OrganizationIdCache.Singleton.Get(OrganizationId.ForestWideOrgId);
            OrganizationRelationship organizationRelationship = organizationIdCacheValue.GetOrganizationRelationship(value.Domain);

            if (aduser == null || organizationRelationship == null)
            {
                throw new OrganizationNotFederatedException();
            }
            DelegationTokenRequest request = new DelegationTokenRequest
            {
                FederatedIdentity = aduser.GetFederatedIdentity(),
                EmailAddress      = aduser.GetFederatedSmtpAddress().ToString(),
                Target            = organizationRelationship.GetTokenTarget(),
                Offer             = Offer.Autodiscover
            };
            FedOrgCredentials credentials = new FedOrgCredentials(request, this.GetSecurityTokenService(aduser.OrganizationId));
            Uri uri = null;

            using (AutoDiscoverUserSettingsClient autoDiscoverUserSettingsClient = AutoDiscoverUserSettingsClient.CreateInstance(DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, sessionSettings, 215, "Discover", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxSearchEwsClient.cs"), credentials, value, organizationRelationship.TargetAutodiscoverEpr, MailboxSearchEwsClient.AutoDiscoverRequestedSettings))
            {
                UserSettings  userSettings  = autoDiscoverUserSettingsClient.Discover();
                StringSetting stringSetting = userSettings.GetSetting("ExternalEwsUrl") as StringSetting;
                if (stringSetting == null || !Uri.TryCreate(stringSetting.Value, UriKind.Absolute, out uri))
                {
                    throw new AutoDAccessException(ServerStrings.AutoDRequestFailed);
                }
            }
            ewsEndpoint = EwsWsSecurityUrl.Fix(uri.ToString());
            string text = null;

            if (executingUser.EmailAddresses != null && executingUser.EmailAddresses.Count > 0)
            {
                List <string> federatedEmailAddresses = executingUser.GetFederatedEmailAddresses();
                if (federatedEmailAddresses != null && federatedEmailAddresses.Count > 0)
                {
                    text = federatedEmailAddresses[0];
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                ewsTokenRequest = new DelegationTokenRequest
                {
                    FederatedIdentity = aduser.GetFederatedIdentity(),
                    EmailAddress      = aduser.GetFederatedSmtpAddress().ToString(),
                    Target            = organizationRelationship.GetTokenTarget(),
                    Offer             = Offer.MailboxSearch
                };
                return;
            }
            ewsTokenRequest = new DelegationTokenRequest
            {
                FederatedIdentity = executingUser.GetFederatedIdentity(),
                EmailAddress      = text.ToString(),
                Target            = organizationRelationship.GetTokenTarget(),
                Offer             = Offer.MailboxSearch
            };
        }
Example #25
0
        protected override ADRawEntry LoadADRawEntry()
        {
            IRecipientSession session    = DirectoryHelper.GetRecipientSessionFromSmtpOrLiveId(base.RequestContext.LatencyTracker, base.Smtp, false);
            ADRawEntry        adrawEntry = DirectoryHelper.InvokeAccountForest(base.RequestContext.LatencyTracker, () => session.FindByProxyAddress(new SmtpProxyAddress(this.Smtp, true), this.PropertySet));

            if (adrawEntry == null)
            {
                PerfCounters.HttpProxyCountersInstance.RedirectByTenantMailboxCount.Increment();
                adrawEntry = DirectoryHelper.InvokeAccountForest(base.RequestContext.LatencyTracker, () => HttpProxyBackEndHelper.GetDefaultOrganizationMailbox(session, this.ToCookieKey()));
            }
            else
            {
                PerfCounters.HttpProxyCountersInstance.RedirectBySenderMailboxCount.Increment();
            }
            return(base.CheckForNullAndThrowIfApplicable <ADRawEntry>(adrawEntry));
        }
        // Token: 0x06002F23 RID: 12067 RVA: 0x0010FD4C File Offset: 0x0010DF4C
        private RecipientWellEventHandler.ADRecipientProperties GetADRecipientProperties(ADObjectId adObjectId, string routingAddress, string routingType)
        {
            if (string.IsNullOrEmpty(routingAddress))
            {
                throw new ArgumentNullException("routingAddress");
            }
            if (string.IsNullOrEmpty(routingType))
            {
                throw new ArgumentNullException("routingType");
            }
            IRecipientSession recipientSession = Utilities.CreateADRecipientSession(Culture.GetUserCulture().LCID, true, ConsistencyMode.IgnoreInvalid, true, base.UserContext);
            ADRecipient       adrecipient      = null;

            RecipientWellEventHandler.ADRecipientProperties result = default(RecipientWellEventHandler.ADRecipientProperties);
            if (string.Equals(routingType, "EX", StringComparison.Ordinal))
            {
                try
                {
                    CustomProxyAddress proxyAddress = new CustomProxyAddress((CustomProxyAddressPrefix)ProxyAddressPrefix.LegacyDN, routingAddress, true);
                    adrecipient = recipientSession.FindByProxyAddress(proxyAddress);
                    goto IL_FB;
                }
                catch (NonUniqueRecipientException ex)
                {
                    ExTraceGlobals.CoreTracer.TraceDebug <string>((long)this.GetHashCode(), "GetADRecipientProperties: NonUniqueRecipientException was thrown by FindByProxyAddress: {0}", ex.Message);
                    throw new OwaEventHandlerException("Unable to retrieve properties.", LocalizedStrings.GetNonEncoded(-1953304495));
                }
            }
            if (string.Equals(routingType, "SMTP", StringComparison.Ordinal))
            {
                try
                {
                    SmtpProxyAddress proxyAddress2 = new SmtpProxyAddress(routingAddress, true);
                    adrecipient = recipientSession.FindByProxyAddress(proxyAddress2);
                }
                catch (NonUniqueRecipientException ex2)
                {
                    ExTraceGlobals.CoreTracer.TraceDebug <string>(0L, "GetADRecipientProperties: NonUniqueRecipientException was thrown by FindByProxyAddress: {0}", ex2.Message);
                    throw new OwaEventHandlerException("Unable to retrieve properties.", LocalizedStrings.GetNonEncoded(-1953304495));
                }
            }
IL_FB:
            if (adrecipient == null && adObjectId != null)
            {
                adrecipient = recipientSession.Read(adObjectId);
            }
            if (adrecipient == null)
            {
                throw new OwaEventHandlerException("Unable to retrieve properties.", LocalizedStrings.GetNonEncoded(-1953304495));
            }
            IADOrgPerson iadorgPerson = adrecipient as IADOrgPerson;

            if (iadorgPerson != null)
            {
                result.Office = iadorgPerson.Office;
                result.Phone  = iadorgPerson.Phone;
                if (adrecipient.Id == null)
                {
                    throw new OwaEventHandlerException("Unable to retrieve id for AD Recipient.", LocalizedStrings.GetNonEncoded(-1953304495));
                }
                result.Id = DirectoryAssistance.ToHtmlString(adrecipient.Id);
            }
            return(result);
        }
Example #27
0
        protected void ResolveRequestedADRecipient()
        {
            string resolveMethod = "Unknown";

            try
            {
                if (this.Caller != null)
                {
                    if (!string.IsNullOrEmpty(this.RequestData.LegacyDN) && string.Equals(this.Caller.LegacyExchangeDN, this.RequestData.LegacyDN, StringComparison.OrdinalIgnoreCase))
                    {
                        this.RequestedRecipient = this.Caller;
                        resolveMethod           = "CallerByLegacyDN";
                        return;
                    }
                    if (!string.IsNullOrEmpty(this.RequestData.LegacyDN) && this.Caller.EmailAddresses != null)
                    {
                        string       x500 = "x500:" + this.RequestData.LegacyDN;
                        ProxyAddress a    = this.Caller.EmailAddresses.Find((ProxyAddress x) => string.Equals(x.ToString(), x500, StringComparison.OrdinalIgnoreCase));
                        if (a != null)
                        {
                            this.RequestedRecipient = this.Caller;
                            resolveMethod           = "CallerByX500";
                            return;
                        }
                    }
                    if (!string.IsNullOrEmpty(this.RequestData.EMailAddress) && SmtpAddress.IsValidSmtpAddress(this.RequestData.EMailAddress))
                    {
                        SmtpProxyAddress smtpProxy = new SmtpProxyAddress(this.RequestData.EMailAddress, true);
                        ProxyAddress     a2        = this.Caller.EmailAddresses.Find((ProxyAddress x) => x.Equals(smtpProxy));
                        if (a2 != null)
                        {
                            this.RequestedRecipient = this.Caller;
                            resolveMethod           = "CallerByProxy";
                            return;
                        }
                    }
                    if (AutodiscoverCommonUserSettings.HasLocalArchive(this.Caller) && AutodiscoverCommonUserSettings.IsEmailAddressTargetingArchive(this.Caller as ADUser, this.RequestData.EMailAddress))
                    {
                        this.RequestedRecipient = this.Caller;
                        resolveMethod           = "CallerByArchive";
                        return;
                    }
                }
                if (this.Caller == null)
                {
                    if (VariantConfiguration.InvariantNoFlightingSnapshot.Autodiscover.NoADLookupForUser.Enabled)
                    {
                        goto IL_285;
                    }
                }
                try
                {
                    RequestDetailsLoggerBase <RequestDetailsLogger> .Current.TrackLatency(ServiceLatencyMetadata.RequestedUserADLatency, delegate()
                    {
                        IRecipientSession callerScopedRecipientSession = this.GetCallerScopedRecipientSession();
                        if (!string.IsNullOrEmpty(this.RequestData.LegacyDN))
                        {
                            this.RequestedRecipient = callerScopedRecipientSession.FindByLegacyExchangeDN(this.RequestData.LegacyDN);
                            if (this.RequestedRecipient != null)
                            {
                                resolveMethod = "FoundByLegacyDN";
                            }
                        }
                        if (this.RequestedRecipient == null && this.RequestData.EMailAddress != null && SmtpAddress.IsValidSmtpAddress(this.RequestData.EMailAddress))
                        {
                            Guid guid;
                            if (AutodiscoverCommonUserSettings.TryGetExchangeGuidFromEmailAddress(this.RequestData.EMailAddress, out guid))
                            {
                                this.RequestedRecipient = callerScopedRecipientSession.FindByExchangeGuidIncludingArchive(guid);
                                ADUser aduser           = this.RequestedRecipient as ADUser;
                                if (aduser != null && aduser.ArchiveGuid.Equals(guid) && RemoteMailbox.IsRemoteMailbox(aduser.RecipientTypeDetails) && aduser.ArchiveDatabase == null)
                                {
                                    this.RequestedRecipient = null;
                                }
                                if (this.RequestedRecipient != null)
                                {
                                    resolveMethod = "FoundByGUID";
                                }
                            }
                            if (this.RequestedRecipient == null)
                            {
                                SmtpProxyAddress proxyAddress = new SmtpProxyAddress(this.RequestData.EMailAddress, true);
                                this.RequestedRecipient       = callerScopedRecipientSession.FindByProxyAddress(proxyAddress);
                                if (this.RequestedRecipient != null)
                                {
                                    resolveMethod = "FoundBySMTP";
                                }
                            }
                        }
                    });
                }
                catch (LocalizedException ex)
                {
                    ExTraceGlobals.FrameworkTracer.TraceError <string, string>(0L, "[UpdateCacheCallback()] 'LocalizedException' Message=\"{0}\";StackTrace=\"{1}\"", ex.Message, ex.StackTrace);
                    Common.EventLog.LogEvent(AutodiscoverEventLogConstants.Tuple_ErrWebException, Common.PeriodicKey, new object[]
                    {
                        ex.Message,
                        ex.StackTrace
                    });
                    resolveMethod = "Exception";
                }
                IL_285 :;
            }
            finally
            {
                RequestDetailsLoggerBase <RequestDetailsLogger> .Current.AppendGenericInfo("ResolveMethod", resolveMethod);
            }
        }
Example #28
0
        internal static List <string> ValidateAddresses(IRecipientSession recipientSession, ADObjectId executingUserId, MultiValuedProperty <string> notificationEmailAddresses, out IList <LocalizedString> localizedWarnings)
        {
            if (recipientSession == null)
            {
                throw new ArgumentNullException("recipientSession");
            }
            List <string> list = new List <string>(((notificationEmailAddresses != null) ? notificationEmailAddresses.Count : 0) + 1);

            localizedWarnings = new List <LocalizedString>(list.Count);
            if (executingUserId != null)
            {
                ADRecipient adrecipient = recipientSession.Read(executingUserId);
                if (adrecipient == null || !MobileDeviceTaskHelper.IsUserMailboxEnabled(adrecipient))
                {
                    localizedWarnings.Add(Strings.LogonUserIsNotAValidADRecipient(executingUserId.ToString()));
                }
                else
                {
                    list.Add(adrecipient.PrimarySmtpAddress.ToString());
                }
            }
            if (notificationEmailAddresses != null)
            {
                foreach (string text in notificationEmailAddresses)
                {
                    if (!SmtpAddress.IsValidSmtpAddress(text))
                    {
                        ADRecipient[] array = recipientSession.FindByANR(text, 2, null);
                        if (array == null || array.Length != 1 || !MobileDeviceTaskHelper.IsUserMailboxEnabled(array[0]))
                        {
                            localizedWarnings.Add(Strings.InvalidSmtpAddressOrAlias(text));
                        }
                        else
                        {
                            list.Add(array[0].PrimarySmtpAddress.ToString());
                        }
                    }
                    else
                    {
                        IRecipientSession recipientSession2 = recipientSession;
                        if (GlobalSettings.IsMultiTenancyEnabled)
                        {
                            try
                            {
                                ADSessionSettings sessionSettings = ADSessionSettings.FromTenantAcceptedDomain(SmtpAddress.Parse(text).Domain);
                                recipientSession2 = DirectorySessionFactory.Default.CreateTenantRecipientSession(true, ConsistencyMode.IgnoreInvalid, sessionSettings, 240, "ValidateAddresses", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\AirSync\\MobileDeviceTaskHelper.cs");
                            }
                            catch (CannotResolveTenantNameException)
                            {
                                localizedWarnings.Add(Strings.InvalidSmtpAddressOrAlias(text));
                                recipientSession2 = null;
                            }
                        }
                        if (recipientSession2 != null)
                        {
                            ADRecipient adrecipient2 = recipientSession2.FindByProxyAddress(ProxyAddress.Parse(text));
                            if (adrecipient2 == null)
                            {
                                localizedWarnings.Add(Strings.InvalidSmtpAddressOrAlias(text));
                            }
                            else
                            {
                                list.Add(adrecipient2.PrimarySmtpAddress.ToString());
                            }
                        }
                    }
                }
            }
            return(list);
        }
Example #29
0
        internal override bool OnExpire(MessageItem message, out bool sendUpdate)
        {
            AutoGroupApplication.diag.TraceFunction((long)this.GetHashCode(), "AutoGroupApplication.OnExpire");
            sendUpdate = true;
            message.Load(new PropertyDefinition[]
            {
                MessageItemSchema.ReceivedBy,
                MessageItemSchema.ApprovalDecisionMaker,
                MessageItemSchema.ApprovalRequestor,
                MessageItemSchema.ApprovalAllowedDecisionMakers,
                MessageItemSchema.ApprovalApplicationData
            });
            CultureInfo messageCulture = null;
            string      arg;
            SmtpAddress arg2;
            SmtpAddress smtpAddress;

            SmtpAddress[] array;
            if (!AutoGroupApplication.GetItemRecipients(message, out arg, out arg2, out smtpAddress, out array))
            {
                AutoGroupApplication.diag.TraceError <string, SmtpAddress, SmtpAddress>((long)this.GetHashCode(), "'{0}' message has invalid approver '{1}', requester '{2}', or empty moderators list.", arg, arg2, smtpAddress);
                return(false);
            }
            SmtpAddress emailAddressFromMailboxItem = AutoGroupApplication.GetEmailAddressFromMailboxItem(message);

            if (emailAddressFromMailboxItem == SmtpAddress.Empty)
            {
                AutoGroupApplication.diag.TraceError <string>((long)this.GetHashCode(), "'{0}' cannot get arbitration mailbox SMTP address from message.", arg);
                return(false);
            }
            string     valueOrDefault = message.GetValueOrDefault <string>(MessageItemSchema.ApprovalApplicationData);
            string     text;
            ADObjectId adobjectId;

            if (string.IsNullOrEmpty(valueOrDefault) || !AutoGroupApplication.ParseApprovalData(valueOrDefault, out text, out adobjectId))
            {
                AutoGroupApplication.diag.TraceError <string, string>((long)this.GetHashCode(), "'{0}' applicationData '{1}' cannot be parsed", arg, valueOrDefault);
                return(false);
            }
            IRecipientSession recipientSession = ApprovalProcessor.CreateRecipientSessionFromSmtpAddress(smtpAddress);
            MiniRecipient     miniRecipient    = recipientSession.ReadMiniRecipient(adobjectId, null);

            if (miniRecipient == null)
            {
                AutoGroupApplication.diag.TraceError <string, ADObjectId>((long)this.GetHashCode(), "'{0}' group '{1}' not found in AD.", arg, adobjectId);
                return(false);
            }
            string group;

            if (string.IsNullOrEmpty(miniRecipient.DisplayName))
            {
                group = miniRecipient.Name;
            }
            else
            {
                group = miniRecipient.DisplayName;
            }
            ADRawEntry adrawEntry = recipientSession.FindByProxyAddress(new SmtpProxyAddress(smtpAddress.ToString(), true), new PropertyDefinition[]
            {
                ADObjectSchema.Id,
                ADUserSchema.Languages
            });

            if (adrawEntry != null)
            {
                MultiValuedProperty <CultureInfo> multiValuedProperty = (MultiValuedProperty <CultureInfo>)adrawEntry[ADUserSchema.Languages];
                if (multiValuedProperty.Count > 0)
                {
                    messageCulture = multiValuedProperty[0];
                }
            }
            ApprovalProcessor.SendNotification(emailAddressFromMailboxItem, message.Id.ObjectId, new SmtpAddress[]
            {
                smtpAddress
            }, Strings.AutoGroupRequestExpiredSubject(group), Strings.AutoGroupRequestExpiredBody(group), LocalizedString.Empty, LocalizedString.Empty, messageCulture);
            return(true);
        }
        // Token: 0x06000018 RID: 24 RVA: 0x0000252C File Offset: 0x0000072C
        internal static Collection <PSObject> ExecuteCommandsInRunspace(SmtpAddress user, PSCommand command, CultureInfo executingCulture, out string errorMessage, out string warningMessage)
        {
            Collection <PSObject> result         = null;
            StringBuilder         stringBuilder  = new StringBuilder();
            StringBuilder         stringBuilder2 = new StringBuilder();

            errorMessage   = string.Empty;
            warningMessage = string.Empty;
            IRecipientSession recipientSession = ApprovalProcessor.CreateRecipientSessionFromSmtpAddress(user);
            ADUser            aduser           = recipientSession.FindByProxyAddress(ProxyAddress.Parse((string)user)) as ADUser;

            if (aduser == null)
            {
                errorMessage = Strings.ErrorUserNotFound((string)user);
                return(null);
            }
            GenericIdentity     identity            = new GenericIdentity(aduser.Sid.ToString());
            InitialSessionState initialSessionState = null;

            try
            {
                initialSessionState = new ExchangeRunspaceConfiguration(identity).CreateInitialSessionState();
                initialSessionState.LanguageMode = PSLanguageMode.FullLanguage;
            }
            catch (CmdletAccessDeniedException)
            {
                errorMessage = Strings.ErrorNoRBACRoleAssignment((string)user);
                return(null);
            }
            CultureInfo currentCulture   = Thread.CurrentThread.CurrentCulture;
            CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;

            try
            {
                if (executingCulture != null)
                {
                    Thread.CurrentThread.CurrentCulture   = executingCulture;
                    Thread.CurrentThread.CurrentUICulture = executingCulture;
                }
                using (RunspaceProxy runspaceProxy = new RunspaceProxy(new RunspaceMediator(new ForestScopeRunspaceFactory(new BasicInitialSessionStateFactory(initialSessionState), new BasicPSHostFactory(typeof(RunspaceHost), true)), new EmptyRunspaceCache())))
                {
                    try
                    {
                        PowerShellProxy powerShellProxy = new PowerShellProxy(runspaceProxy, command);
                        result = powerShellProxy.Invoke <PSObject>();
                        if (powerShellProxy.Errors != null)
                        {
                            foreach (ErrorRecord errorRecord in powerShellProxy.Errors)
                            {
                                stringBuilder.Append(errorRecord.ToString());
                            }
                        }
                        if (powerShellProxy.Warnings != null)
                        {
                            foreach (WarningRecord warningRecord in powerShellProxy.Warnings)
                            {
                                stringBuilder2.Append(warningRecord.ToString());
                            }
                        }
                    }
                    catch (CmdletInvocationException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    catch (ParameterBindingException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    catch (CommandNotFoundException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    catch (RuntimeException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    finally
                    {
                        errorMessage   = stringBuilder.ToString();
                        warningMessage = stringBuilder2.ToString();
                    }
                }
            }
            finally
            {
                if (executingCulture != null)
                {
                    Thread.CurrentThread.CurrentCulture   = currentCulture;
                    Thread.CurrentThread.CurrentUICulture = currentUICulture;
                }
            }
            return(result);
        }