Example #1
0
        // Token: 0x06001AC0 RID: 6848 RVA: 0x00064FF8 File Offset: 0x000631F8
        private ServiceResult <EwsRoomType[]> GetAllAvailableRooms()
        {
            UserContext       userContext  = UserContextManager.GetUserContext(base.CallContext.HttpContext, base.CallContext.EffectiveCaller, true);
            QueryFilter       filter       = null;
            AddressLists      addressLists = new AddressLists(base.CallContext.EffectiveCaller.ClientSecurityContext, base.MailboxIdentityMailboxSession.MailboxOwner, userContext);
            ADSessionSettings sessionSettings;

            if (addressLists.AllRoomsAddressList == null)
            {
                filter = new OrFilter(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientDisplayType, RecipientDisplayType.ConferenceRoomMailbox),
                    new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientDisplayType, RecipientDisplayType.SyncedConferenceRoomMailbox)
                });
                sessionSettings = ADSessionSettings.FromOrganizationIdWithAddressListScopeServiceOnly(addressLists.GlobalAddressList.OrganizationId, addressLists.GlobalAddressList.Id);
            }
            else
            {
                sessionSettings = ADSessionSettings.FromOrganizationIdWithAddressListScopeServiceOnly(addressLists.AllRoomsAddressList.OrganizationId, addressLists.AllRoomsAddressList.Id);
            }
            int         lcid        = 0;
            CultureInfo cultureInfo = base.CallContext.AccessingPrincipal.PreferredCultures.FirstOrDefault <CultureInfo>();

            if (cultureInfo != null)
            {
                lcid = cultureInfo.LCID;
            }
            IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, null, lcid, true, ConsistencyMode.IgnoreInvalid, null, sessionSettings, 123, "GetAllAvailableRooms", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\ServiceCommands\\GetRoomsInternal.cs");

            ADRecipient[] rooms = tenantOrRootOrgRecipientSession.Find(null, QueryScope.SubTree, filter, new SortBy(ADRecipientSchema.DisplayName, SortOrder.Ascending), 100);
            return(new ServiceResult <EwsRoomType[]>(GetRooms.GetRoomTypes(rooms, this.GetHashCode()).ToArray()));
        }
Example #2
0
        public IAutodMiniRecipient GetNextUserFromSortedList(SmtpAddress emailAddress)
        {
            IRecipientSession recipientSession = DirectorySessionFactory.Default.CreateRootOrgRecipientSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 66, "GetNextUserFromSortedList", "f:\\15.00.1497\\sources\\dev\\autodisc\\src\\AutoDiscoverV2\\TenantRepository.cs");

            this.logger.AppendGenericInfo("GetOnPremUser", "Start Ad lookup");
            QueryFilter filter = new AndFilter(new QueryFilter[]
            {
                new OrFilter(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientTypeDetails, RecipientTypeDetails.UserMailbox),
                    new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientTypeDetails, RecipientTypeDetails.MailUser)
                }),
                new ComparisonFilter(ComparisonOperator.GreaterThanOrEqual, ADUserSchema.UserPrincipalName, emailAddress.Address)
            });

            ADRawEntry[] array = recipientSession.Find(null, QueryScope.SubTree, filter, null, 1, new PropertyDefinition[]
            {
                ADUserSchema.UserPrincipalName,
                ADRecipientSchema.ExternalEmailAddress
            });
            if (array != null)
            {
                ADRawEntry adrawEntry = array.FirstOrDefault <ADRawEntry>();
                if (adrawEntry != null)
                {
                    return(new AutodMiniRecipient(adrawEntry));
                }
            }
            return(null);
        }
Example #3
0
        public static ADSystemMailbox GetADSystemMailbox(Guid mdbGuid, string dcName, NetworkCredential cred)
        {
            IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(dcName, true, ConsistencyMode.PartiallyConsistent, cred, ADSessionSettings.FromRootOrgScopeSet(), 1080, "GetADSystemMailbox", "f:\\15.00.1497\\sources\\dev\\mrs\\src\\Common\\MapiUtils.cs");

            tenantOrRootOrgRecipientSession.UseGlobalCatalog    = true;
            tenantOrRootOrgRecipientSession.EnforceDefaultScope = false;
            string text = string.Format(CultureInfo.InvariantCulture, "SystemMailbox{{{0}}}", new object[]
            {
                mdbGuid.ToString()
            });
            QueryFilter filter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Name, text);

            ADRecipient[] array = tenantOrRootOrgRecipientSession.Find(null, QueryScope.SubTree, filter, null, 2);
            if (array.Length != 1)
            {
                MrsTracer.Common.Error("Found {0} mailboxes named '{1}' in the AD", new object[]
                {
                    array.Length,
                    text
                });
                throw new SystemMailboxNotFoundPermanentException(mdbGuid.ToString());
            }
            ADSystemMailbox adsystemMailbox = array[0] as ADSystemMailbox;

            if (adsystemMailbox == null)
            {
                throw new SystemMailboxNotFoundPermanentException(text);
            }
            return(adsystemMailbox);
        }
Example #4
0
 private static IEnumerable <T> GetRecipients <T>(IRecipientSession session, QueryFilter filter, Func <string, LocalizedException> recipientNotFoundExceptionCallback, Func <string, LocalizedException> invalidRecipientTypeExceptionCallback, string debugContext) where T : class
 {
     Util.ThrowOnNullArgument(session, "session");
     Util.ThrowOnNullArgument(filter, "filter");
     ADRecipient[] recipients = null;
     MigrationHelperBase.DoAdCallAndTranslateExceptions(delegate
     {
         recipients = session.Find(null, QueryScope.SubTree, filter, null, 0);
     }, true, debugContext);
     if (recipients == null || recipients.Length < 1)
     {
         string arg = string.Format("Could not find {0} using filter {1} with scoped session for {2}", typeof(T), filter, debugContext);
         throw recipientNotFoundExceptionCallback(arg);
     }
     foreach (ADRecipient recip in recipients)
     {
         T recipient = recip as T;
         if (recipient == null)
         {
             string arg2 = string.Format("Found an AD recipient that's not a {0} using filter {1} with scoped session for {2}", typeof(T), filter, debugContext);
             throw invalidRecipientTypeExceptionCallback(arg2);
         }
         yield return(recipient);
     }
     yield break;
 }
        public static ADUser GetDiscoveryMailbox(IRecipientSession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            IRecipientSession recipientSession = session;

            if (recipientSession.ConfigScope != ConfigScopes.TenantLocal)
            {
                recipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(session.DomainController, true, ConsistencyMode.PartiallyConsistent, session.NetworkCredential, session.SessionSettings, 104, "GetDiscoveryMailbox", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Search\\MailboxSearch\\MailboxDataProvider.cs");
                recipientSession.UseGlobalCatalog    = true;
                recipientSession.EnforceDefaultScope = session.EnforceDefaultScope;
            }
            ADRecipient[] array = recipientSession.Find(null, QueryScope.SubTree, MailboxDataProvider.DiscoverySystemMailboxFilter, null, 2);
            switch (array.Length)
            {
            case 0:
                throw new ObjectNotFoundException(ServerStrings.DiscoveryMailboxNotFound);

            case 1:
                return(array[0] as ADUser);

            default:
                throw new NonUniqueRecipientException(array[0], new NonUniqueAddressError(ServerStrings.DiscoveryMailboxIsNotUnique(array[0].Id.ToString(), array[1].Id.ToString()), array[0].Id, "DiscoveryMailbox"));
            }
        }
Example #6
0
        private bool IsNameUnique()
        {
            IRecipientSession recipientSession = (IRecipientSession)((RecipientObjectResolver)RecipientObjectResolver.Instance).CreateAdSession();

            recipientSession.UseConfigNC         = false;
            recipientSession.UseGlobalCatalog    = true;
            recipientSession.EnforceDefaultScope = false;
            QueryFilter filter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Name, this.Name);

            ADRecipient[] array = recipientSession.Find(null, QueryScope.SubTree, filter, null, 1);
            return(array.Length <= 0);
        }
Example #7
0
        // Token: 0x0600015D RID: 349 RVA: 0x00006C38 File Offset: 0x00004E38
        private ADSystemMailbox FindSystemMailbox()
        {
            IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 526, "FindSystemMailbox", "f:\\15.00.1497\\sources\\dev\\assistants\\src\\Assistants\\DatabaseInfo.cs");

            ADRecipient[] array = tenantOrRootOrgRecipientSession.Find(null, QueryScope.SubTree, new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Name, this.systemMailboxName), null, 1);
            if (array.Length != 1 || !(array[0] is ADSystemMailbox))
            {
                ExTraceGlobals.DatabaseInfoTracer.TraceError <DatabaseInfo, int, string>((long)this.GetHashCode(), "{0}: Found {1} mailboxes named '{2}' in the AD", this, array.Length, this.systemMailboxName);
                throw new MissingSystemMailboxException(this.DisplayName, base.Logger);
            }
            return((ADSystemMailbox)array[0]);
        }
        private static void ClearThrottlingPolicyAssoicate(IRecipientSession session, ThrottlingPolicy policy)
        {
            QueryFilter filter = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.ThrottlingPolicy, policy.Id);

            ADRecipient[] array = session.Find <ADRecipient>(null, QueryScope.SubTree, filter, null, 100);
            if (array != null && array.Length > 0)
            {
                foreach (ADRecipient adrecipient in array)
                {
                    adrecipient.ThrottlingPolicy = null;
                    session.Save(adrecipient);
                }
            }
        }
        private static ADRawEntry[] Find(IRecipientSession recipientSession, QueryFilter filter, int maxResults, IEnumerable <PropertyDefinition> properties)
        {
            if (filter == null)
            {
                return(null);
            }
            QueryFilter filter2 = new AndFilter(new QueryFilter[]
            {
                DirectoryPersonSearcher.BaseFilter,
                filter
            });

            DirectoryPersonSearcher.Tracer.TraceDebug <QueryFilter>(0L, "Searching for matching recipient in AD with filter: {0}", filter);
            return(recipientSession.Find(null, QueryScope.SubTree, filter2, null, maxResults, properties));
        }
        internal static string FindUniqueSamAccountName(IRecipientSession session, ADObjectId dom, string samOrig)
        {
            string suffix = "";

            for (int i = 1; i < 100; i++)
            {
                string       text   = InitializeExchangeUniversalGroups.Concat(samOrig, suffix, 256);
                QueryFilter  filter = new ComparisonFilter(ComparisonOperator.Equal, IADSecurityPrincipalSchema.SamAccountName, text);
                ADRawEntry[] array  = session.Find(dom, QueryScope.SubTree, filter, null, 1);
                if (array.Length == 0)
                {
                    return(text);
                }
                suffix = i.ToString();
            }
            return(InitializeExchangeUniversalGroups.Concat(samOrig, Guid.NewGuid().ToString("N"), 256));
        }
 private static ADRecipient GetADRecipientBySmtpAddress(SmtpAddress smtpAddress)
 {
     try
     {
         IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.IgnoreInvalid, null, ADSessionSettings.FromTenantAcceptedDomain(smtpAddress.Domain), 802, "GetADRecipientBySmtpAddress", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\JournalRule\\JournalRuleObject.cs");
         QueryFilter       filter = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.PrimarySmtpAddress, smtpAddress.ToString());
         ADRecipient[]     array  = tenantOrRootOrgRecipientSession.Find <ADRecipient>(null, QueryScope.SubTree, filter, null, 1);
         if (array != null && array.Length > 0)
         {
             return(array[0]);
         }
     }
     catch (CannotResolveTenantNameException)
     {
     }
     return(null);
 }
Example #12
0
        internal static ADRecipient FindMailboxByLegacyDN(string legacyDN, IRecipientSession globalCatalogSession)
        {
            QueryFilter queryFilter  = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.LegacyExchangeDN, legacyDN);
            QueryFilter queryFilter2 = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientType, RecipientType.UserMailbox);
            AndFilter   filter       = new AndFilter(new QueryFilter[]
            {
                queryFilter2,
                queryFilter
            });

            ADRecipient[] array = globalCatalogSession.Find(null, QueryScope.SubTree, filter, null, 1);
            if (array != null && array.Length > 0)
            {
                return(array[0]);
            }
            return(null);
        }
 private void RefreshCache()
 {
     try
     {
         IRecipientSession recipientSession  = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(null, true, ConsistencyMode.IgnoreInvalid, null, this.adSettings, ConfigScopes.TenantSubTree, 208, "RefreshCache", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\Auditing\\AuditCaches.cs");
         QueryFilter       filter            = new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.AuditBypassEnabled, true);
         ADRawEntry[]      recipients        = null;
         ADOperationResult adoperationResult = ADNotificationAdapter.TryRunADOperation(delegate()
         {
             recipients = recipientSession.Find(null, QueryScope.SubTree, filter, null, 0, BypassAuditCache.OrganizationCache.queryProperties);
         });
         if (adoperationResult.Succeeded)
         {
             HashSet <SecurityIdentifier> hashSet = null;
             if (recipients != null && recipients.Length > 0)
             {
                 hashSet = new HashSet <SecurityIdentifier>();
                 foreach (ADRawEntry adrawEntry in recipients)
                 {
                     SecurityIdentifier securityIdentifier = adrawEntry[IADSecurityPrincipalSchema.Sid] as SecurityIdentifier;
                     if (null != securityIdentifier && !hashSet.Contains(securityIdentifier))
                     {
                         hashSet.Add(securityIdentifier);
                     }
                 }
             }
             Interlocked.Exchange <HashSet <SecurityIdentifier> >(ref this.bypassingUserSid, hashSet);
         }
         else
         {
             ProcessInfoEventLogger.Log(StorageEventLogConstants.Tuple_ErrorReadingBypassAudit, this.adSettings.CurrentOrganizationId.ToString(), new object[]
             {
                 this.adSettings.CurrentOrganizationId,
                 adoperationResult.Exception
             });
         }
     }
     finally
     {
         this.refreshTimer.Change(this.RefreshInterval, new TimeSpan(0, 0, 0, 0, -1));
     }
 }
Example #14
0
        private bool LegacyDNIsUnique(string legacyDN)
        {
            QueryFilter filter = new AndFilter(new QueryFilter[]
            {
                new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.LegacyExchangeDN, legacyDN),
                new ComparisonFilter(ComparisonOperator.NotEqual, ADObjectSchema.Id, this.DataObject.Id)
            });
            IRecipientSession recipientSession = RecipientTaskHelper.CreatePartitionOrRootOrgScopedGcSession(base.DomainController, this.DataObject.Id);

            base.WriteVerbose(TaskVerboseStringHelper.GetFindDataObjectsVerboseString(recipientSession, typeof(ADRecipient), filter, null, true));
            ADRecipient[] array = null;
            try
            {
                array = recipientSession.Find(null, QueryScope.SubTree, filter, null, 1);
            }
            finally
            {
                base.WriteVerbose(TaskVerboseStringHelper.GetSourceVerboseString(recipientSession));
            }
            return(0 == array.Length);
        }
Example #15
0
            public override LoadBalancingMiniRecipient FindRecipient(DirectoryIdentity identity)
            {
                if (identity == null)
                {
                    throw new ArgumentNullException("identity", "DirectoryIdentity should not be null");
                }
                ADSessionSettings sessionSettings;

                if (identity.OrganizationId == Guid.Empty)
                {
                    sessionSettings = ADSessionSettings.FromRootOrgScopeSet();
                }
                else
                {
                    sessionSettings = ADSessionSettings.FromExternalDirectoryOrganizationId(identity.OrganizationId);
                }
                IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(true, ConsistencyMode.IgnoreInvalid, sessionSettings, 129, "FindRecipient", "f:\\15.00.1497\\sources\\dev\\mrs\\src\\MailboxLoadBalance\\Directory\\ExchangeDirectory\\RecipientSessionAdapter.cs");
                QueryFilter       queryFilter  = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Id, identity.ADObjectId);
                QueryFilter       queryFilter2 = new ComparisonFilter(ComparisonOperator.Equal, MiniRecipientSchema.ArchiveGuid, identity.Guid);
                QueryFilter       queryFilter3 = new ComparisonFilter(ComparisonOperator.Equal, MiniRecipientSchema.ExchangeGuid, identity.Guid);
                QueryFilter       queryFilter4 = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.ExchangeObjectId, identity.Guid);
                QueryFilter       filter       = QueryFilter.OrTogether(new QueryFilter[]
                {
                    queryFilter,
                    queryFilter2,
                    queryFilter3,
                    queryFilter4
                });

                LoadBalancingMiniRecipient[] array = tenantOrRootOrgRecipientSession.Find <LoadBalancingMiniRecipient>(null, QueryScope.SubTree, filter, null, 2);
                if (array == null || array.Length == 0)
                {
                    throw new RecipientNotFoundException(identity.ToString());
                }
                if (array.Length > 1)
                {
                    throw new MultipleRecipientFoundException(identity.ToString());
                }
                return(array[0]);
            }
Example #16
0
        internal static void ValidateCertificateSubject(MultiValuedProperty <X509Identifier> certificateSubjects, PartitionId partitionId, ADObjectId excludeObjectId, Task.TaskErrorLoggingDelegate errorLogger)
        {
            if (errorLogger == null)
            {
                throw new ArgumentNullException("errorLogger");
            }
            ADSessionSettings sessionSettings;

            if (partitionId != null)
            {
                sessionSettings = ADSessionSettings.FromAllTenantsPartitionId(partitionId);
            }
            else
            {
                sessionSettings = ADSessionSettings.FromRootOrgScopeSet();
            }
            IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(ConsistencyMode.PartiallyConsistent, sessionSettings, 220, "ValidateCertificateSubject", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\RecipientTasks\\LinkedUser\\NewLinkedUser.cs");

            tenantOrRootOrgRecipientSession.UseGlobalCatalog = true;
            if (certificateSubjects != null && certificateSubjects.Count != 0)
            {
                foreach (X509Identifier x509Identifier in certificateSubjects)
                {
                    QueryFilter queryFilter = ADUser.GetCertificateMatchFilter(x509Identifier);
                    if (excludeObjectId != null)
                    {
                        queryFilter = new AndFilter(new QueryFilter[]
                        {
                            queryFilter,
                            new ComparisonFilter(ComparisonOperator.NotEqual, ADObjectSchema.Id, excludeObjectId)
                        });
                    }
                    ADRecipient[] array = tenantOrRootOrgRecipientSession.Find(null, QueryScope.SubTree, queryFilter, null, 1);
                    if (array != null && array.Length > 0)
                    {
                        errorLogger(new RecipientTaskException(Strings.ErrorDuplicateCertificateSubject(x509Identifier.ToString())), ErrorCategory.InvalidArgument, excludeObjectId);
                    }
                }
            }
        }
Example #17
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 #18
0
        internal int GetRecipientCount(int maxCount, bool userMailboxOnly, bool includeSoftDeletedObjects)
        {
            int result = 0;
            IRecipientSession recipientSession = this.recipientSession;
            QueryFilter       queryFilter      = new NotFilter(new OrFilter(new QueryFilter[]
            {
                new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientTypeDetails, RecipientTypeDetails.ArbitrationMailbox),
                new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientTypeDetails, RecipientTypeDetails.MailboxPlan),
                new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientTypeDetails, RecipientTypeDetails.DiscoveryMailbox),
                new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientTypeDetails, RecipientTypeDetails.AuditLogMailbox),
                new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.Alias, this.organizationFederatedMailboxAlias)
            }));

            if (userMailboxOnly)
            {
                queryFilter = new AndFilter(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADRecipientSchema.RecipientType, RecipientType.UserMailbox),
                    queryFilter
                });
            }
            if (includeSoftDeletedObjects)
            {
                ADSessionSettings sessionSettings = this.recipientSession.SessionSettings;
                sessionSettings.IncludeSoftDeletedObjects = true;
                recipientSession = DirectorySessionFactory.Default.CreateTenantRecipientSession(this.recipientSession.DomainController, this.recipientSession.SearchRoot, this.recipientSession.Lcid, this.recipientSession.ReadOnly, this.recipientSession.ConsistencyMode, this.recipientSession.NetworkCredential, sessionSettings, ConfigScopes.TenantSubTree, 555, "GetRecipientCount", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\Deployment\\RemoveOrganization.cs");
                recipientSession.EnforceDefaultScope  = this.recipientSession.EnforceDefaultScope;
                recipientSession.UseGlobalCatalog     = this.recipientSession.UseGlobalCatalog;
                recipientSession.LinkResolutionServer = this.recipientSession.LinkResolutionServer;
            }
            ADRecipient[] array = recipientSession.Find(null, QueryScope.SubTree, queryFilter, null, maxCount);
            if (array != null)
            {
                result = array.Length;
            }
            return(result);
        }
Example #19
0
        private static void InternalUpdateRecipients(IEnumerator <ADRecipient> pagedReaderGC, AddressBookBase abb, QueryFilter removeFilter, List <Guid> abbObjectGuidList, string domainControllerFqdn, IRecipientSession globalCatalogSession, Task.TaskWarningLoggingDelegate writeWarning, WriteProgress writeProgress, Cmdlet cmdlet, ref int currentPercent)
        {
            if (cmdlet != null && cmdlet.Stopping)
            {
                return;
            }
            string domainControllerDomainName = null;

            if (!string.IsNullOrEmpty(domainControllerFqdn))
            {
                int num = domainControllerFqdn.IndexOf(".");
                if (0 <= num)
                {
                    domainControllerDomainName = domainControllerFqdn.Substring(num + 1);
                }
            }
            IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(false, ConsistencyMode.PartiallyConsistent, globalCatalogSession.SessionSettings, 300, "InternalUpdateRecipients", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\AddressBook\\UpdateAddressBook.cs");

            tenantOrRootOrgRecipientSession.EnforceDefaultScope         = false;
            tenantOrRootOrgRecipientSession.EnforceContainerizedScoping = false;
            string text = null;

            while (pagedReaderGC.MoveNext())
            {
                ADRecipient adrecipient = pagedReaderGC.Current;
                if (cmdlet != null && cmdlet.Stopping)
                {
                    return;
                }
                ADRecipient adrecipient2 = adrecipient;
                try
                {
                    SystemConfigurationTasksHelper.PrepareDomainControllerRecipientSessionForUpdate(tenantOrRootOrgRecipientSession, adrecipient.Id, domainControllerFqdn, domainControllerDomainName);
                    tenantOrRootOrgRecipientSession.LinkResolutionServer = null;
                    IConfigurable configurable = null;
                    if (abb != null)
                    {
                        IEnumerator <ADRecipient> enumerator = abb.FindUpdatingRecipientsPaged(tenantOrRootOrgRecipientSession, adrecipient.Id).GetEnumerator();
                        if (enumerator.MoveNext())
                        {
                            configurable = enumerator.Current;
                        }
                    }
                    else
                    {
                        IConfigurable[] array = tenantOrRootOrgRecipientSession.Find(adrecipient.Id, QueryScope.Base, removeFilter, null, 1);
                        if (array.Length > 0)
                        {
                            configurable = array[0];
                        }
                    }
                    if (configurable != null)
                    {
                        adrecipient2 = (ADRecipient)configurable;
                        if (!adrecipient2.IsValid || adrecipient2.IsReadOnly)
                        {
                            writeWarning(Strings.ErrorCannotUpdateInvalidRecipient(adrecipient2.Id.ToString()));
                        }
                        else
                        {
                            if (cmdlet != null && cmdlet.Stopping)
                            {
                                break;
                            }
                            bool flag = false;
                            if (abb != null)
                            {
                                using (MultiValuedProperty <ADObjectId> .Enumerator enumerator2 = adrecipient2.AddressListMembership.GetEnumerator())
                                {
                                    while (enumerator2.MoveNext())
                                    {
                                        ADObjectId adobjectId = enumerator2.Current;
                                        if (ADObjectId.Equals(adobjectId, abb.Id))
                                        {
                                            flag = true;
                                            adrecipient2.AddressListMembership.Remove(adobjectId);
                                            break;
                                        }
                                    }
                                    goto IL_1E5;
                                }
                            }
                            int num2 = adrecipient2.AddressListMembership.Count - 1;
                            while (0 <= num2)
                            {
                                if (abbObjectGuidList.BinarySearch(adrecipient2.AddressListMembership[num2].ObjectGuid) >= 0)
                                {
                                    flag = true;
                                    adrecipient2.AddressListMembership.RemoveAt(num2);
                                }
                                num2--;
                            }
IL_1E5:
                            if (!flag && !adrecipient2.HiddenFromAddressListsEnabled)
                            {
                                if (string.IsNullOrEmpty(text))
                                {
                                    try
                                    {
                                        if (!string.IsNullOrEmpty(abb.OriginatingServer))
                                        {
                                            text = SystemConfigurationTasksHelper.GetConfigurationDomainControllerFqdn(abb.OriginatingServer);
                                        }
                                    }
                                    catch (SocketException ex)
                                    {
                                        writeWarning(Strings.ErrorResolveFqdnForDomainController(abb.OriginatingServer, ex.Message));
                                        continue;
                                    }
                                }
                                tenantOrRootOrgRecipientSession.LinkResolutionServer = text;
                                adrecipient2.AddressListMembership.Add(abb.Id);
                            }
                            currentPercent = currentPercent++ % 99 + 1;
                            writeProgress(Strings.ProgressActivityUpdateRecipient, Strings.ProgressStatusUpdateRecipient(adrecipient2.Id.ToString()), currentPercent);
                            tenantOrRootOrgRecipientSession.Save(adrecipient2);
                        }
                    }
                }
                catch (DataSourceTransientException ex2)
                {
                    writeWarning(Strings.ErrorUpdateRecipient(adrecipient2.Id.ToString(), ex2.Message));
                    TaskLogger.Trace("Exception is raised while updating recipient '{0}': {1}", new object[]
                    {
                        adrecipient2.Id.ToString(),
                        ex2.Message
                    });
                }
                catch (DataSourceOperationException ex3)
                {
                    writeWarning(Strings.ErrorUpdateRecipient(adrecipient2.Id.ToString(), ex3.Message));
                    TaskLogger.Trace("Exception is raised while updating recipient '{0}': {1}", new object[]
                    {
                        adrecipient2.Id.ToString(),
                        ex3.Message
                    });
                }
                catch (DataValidationException ex4)
                {
                    writeWarning(Strings.ErrorUpdateRecipient(adrecipient2.Id.ToString(), ex4.Message));
                    TaskLogger.Trace("Exception is raised while updating recipient '{0}': {1}", new object[]
                    {
                        adrecipient2.Id.ToString(),
                        ex4.Message
                    });
                }
            }
        }
        private static void CleanADOrphanAndInconsistencyForMoves(IRecipientSession recipientSession, RequestJobProvider rjProvider, Guid dbGuid)
        {
            ADObjectId  propertyValue = new ADObjectId(dbGuid);
            QueryFilter queryFilter   = new AndFilter(new QueryFilter[]
            {
                new ComparisonFilter(ComparisonOperator.NotEqual, ADUserSchema.MailboxMoveStatus, RequestStatus.None),
                new ExistsFilter(ADUserSchema.MailboxMoveStatus)
            });
            QueryFilter queryFilter2 = QueryFilter.OrTogether(new QueryFilter[]
            {
                QueryFilter.AndTogether(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADUserSchema.MailboxMoveSourceMDB, propertyValue),
                    new BitMaskAndFilter(ADUserSchema.MailboxMoveFlags, 4UL)
                }),
                QueryFilter.AndTogether(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADUserSchema.MailboxMoveTargetMDB, propertyValue),
                    new BitMaskAndFilter(ADUserSchema.MailboxMoveFlags, 8UL)
                })
            });
            QueryFilter filter = new AndFilter(new QueryFilter[]
            {
                queryFilter,
                queryFilter2
            });

            ADRecipient[] array = recipientSession.Find(null, QueryScope.SubTree, filter, null, 1000);
            if (array == null || array.Length == 0)
            {
                MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves(): No move requests found for DB {0}", new object[]
                {
                    dbGuid
                });
                return;
            }
            bool needUpdateAD = false;

            ADRecipient[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                ADRecipient request = array2[i];
                CommonUtils.CatchKnownExceptions(delegate
                {
                    needUpdateAD  = false;
                    ADUser aduser = request as ADUser;
                    MoveRequestStatistics moveRequestStatistics = (MoveRequestStatistics)rjProvider.Read <MoveRequestStatistics>(new RequestJobObjectId(aduser.ExchangeGuid, dbGuid, null));
                    if (moveRequestStatistics == null || (!moveRequestStatistics.IsFake && moveRequestStatistics.Status == RequestStatus.None))
                    {
                        MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():AD orphan {0} found for DB {1}", new object[]
                        {
                            aduser.ExchangeGuid,
                            dbGuid
                        });
                        CommonUtils.CleanupMoveRequestInAD(recipientSession, null, aduser);
                        return;
                    }
                    if (moveRequestStatistics.IsFake)
                    {
                        MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():request {0} is uplevel/Fake, ignore it", new object[]
                        {
                            aduser.ExchangeGuid
                        });
                        return;
                    }
                    if (moveRequestStatistics.User == null)
                    {
                        MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():request {0} has been deleted from AD, ignore it", new object[]
                        {
                            aduser.ExchangeGuid
                        });
                        return;
                    }
                    if (moveRequestStatistics.TimeTracker.GetCurrentDurationChunk() > ADInconsistencyCheck.updateLatencyThreshhold)
                    {
                        RequestStatus versionAppropriateStatus = RequestJobBase.GetVersionAppropriateStatus(moveRequestStatistics.Status, aduser.ExchangeVersion);
                        if (versionAppropriateStatus != moveRequestStatistics.User.MailboxMoveStatus)
                        {
                            MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():AD inconsistency {0} found for DB {1}, AD status is {2} but store status is {3} ({4})", new object[]
                            {
                                aduser.ExchangeGuid,
                                dbGuid,
                                aduser.MailboxMoveStatus,
                                moveRequestStatistics.Status,
                                versionAppropriateStatus
                            });
                            aduser.MailboxMoveStatus = versionAppropriateStatus;
                            needUpdateAD             = true;
                        }
                        RequestFlags versionAppropriateFlags = RequestJobBase.GetVersionAppropriateFlags(moveRequestStatistics.Flags, aduser.ExchangeVersion);
                        if (versionAppropriateFlags != moveRequestStatistics.User.MailboxMoveFlags)
                        {
                            MrsTracer.Service.Debug("CleanADOrphanAndInconsistencyForMoves():AD inconsistency {0} found for DB {1}, AD flags is {2} but store flags is {3} ({4})", new object[]
                            {
                                aduser.ExchangeGuid,
                                dbGuid,
                                aduser.MailboxMoveFlags,
                                moveRequestStatistics.Flags,
                                versionAppropriateFlags
                            });
                            aduser.MailboxMoveFlags = versionAppropriateFlags;
                            needUpdateAD            = true;
                        }
                        if (needUpdateAD)
                        {
                            recipientSession.Save(request);
                        }
                    }
                }, delegate(Exception f)
                {
                    MrsTracer.Service.Error("CleanADOrphanAndInconsistencyForMoves() failed for DB {0}. move request {1} Error: {2}", new object[]
                    {
                        dbGuid,
                        ((ADUser)request).ExchangeGuid,
                        CommonUtils.FullExceptionMessage(f, true)
                    });
                    MRSService.LogEvent(MRSEventLogConstants.Tuple_ScanADInconsistencyRequestFailEvent, new object[]
                    {
                        dbGuid,
                        MRSRequestType.Move.ToString(),
                        ((ADUser)request).ExchangeGuid,
                        CommonUtils.FullExceptionMessage(f, true)
                    });
                });
            }
        }
Example #21
0
        internal static object[][] GetManagementChainView(IRecipientSession adSession, IADOrgPerson person, bool getPeers, params PropertyDefinition[] returnProperties)
        {
            if (returnProperties == null)
            {
                throw new ArgumentNullException("returnProperties");
            }
            int?num = null;

            for (int i = 0; i < returnProperties.Length; i++)
            {
                if (returnProperties[i] == ADOrgPersonSchema.ViewDepth)
                {
                    num = new int?(i);
                    break;
                }
            }
            PropertyDefinition[] array = new PropertyDefinition[returnProperties.Length + 1];
            returnProperties.CopyTo(array, 1);
            array[0] = ADOrgPersonSchema.Manager;
            Collection <IADRecipient[]> collection  = new Collection <IADRecipient[]>();
            Collection <Guid>           collection2 = new Collection <Guid>();
            int num2 = 0;

            if (getPeers)
            {
                ADObjectId adobjectId = person.Manager;
                while (adobjectId != null && num2 < 100)
                {
                    if (collection2.Contains(adobjectId.ObjectGuid))
                    {
                        break;
                    }
                    QueryFilter    filter = new ComparisonFilter(ComparisonOperator.Equal, ADOrgPersonSchema.Manager, adobjectId);
                    IADRecipient[] item   = adSession.Find(adSession.SearchRoot, QueryScope.SubTree, filter, null, 0);
                    collection2.Add(adobjectId.ObjectGuid);
                    collection.Add(item);
                    IADOrgPerson iadorgPerson = adSession.Read(adobjectId) as IADOrgPerson;
                    if (iadorgPerson == null)
                    {
                        adobjectId = null;
                    }
                    else if (iadorgPerson.Manager == null || iadorgPerson.Manager.ObjectGuid == adobjectId.ObjectGuid)
                    {
                        item = new IADRecipient[]
                        {
                            iadorgPerson
                        };
                        collection.Add(item);
                        num2++;
                        adobjectId = null;
                    }
                    else
                    {
                        adobjectId = iadorgPerson.Manager;
                    }
                    num2++;
                }
            }
            else
            {
                ADObjectId adobjectId = person.Id;
                while (adobjectId != null && num2 < 100 && !collection2.Contains(adobjectId.ObjectGuid))
                {
                    new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Id, adobjectId);
                    IADOrgPerson iadorgPerson2 = adSession.Read(adobjectId) as IADOrgPerson;
                    collection2.Add(adobjectId.ObjectGuid);
                    if (iadorgPerson2 == null)
                    {
                        adobjectId = null;
                    }
                    else
                    {
                        collection.Add(new IADRecipient[]
                        {
                            iadorgPerson2
                        });
                        if (iadorgPerson2.Manager != null && iadorgPerson2.Manager.ObjectGuid == adobjectId.ObjectGuid)
                        {
                            adobjectId = null;
                        }
                        else
                        {
                            adobjectId = iadorgPerson2.Manager;
                        }
                        num2++;
                    }
                }
            }
            int count = collection.Count;
            int num3  = 0;

            for (int j = 0; j < count; j++)
            {
                num3 += collection[j].Length;
            }
            object[][] array2 = new object[num3][];
            int        k      = count - 1;
            int        num4   = 0;

            while (k >= 0)
            {
                for (int l = 0; l < collection[k].Length; l++)
                {
                    array2[num4] = collection[k][l].GetProperties(returnProperties);
                    if (num != null)
                    {
                        array2[num4][num.Value] = count - 1 - k;
                    }
                    num4++;
                }
                k--;
            }
            return(array2);
        }
Example #22
0
        public UnifiedGroupMemberType GetMembershipType()
        {
            if (this.DenyCurrentLogon())
            {
                GroupMailboxAuthorizationHandler.Tracer.TraceWarning <string>(0L, "Not OWA logon and flight not enabled for group. ClientInfoString:{0} ", this.clientInfoString);
                return(UnifiedGroupMemberType.Unknown);
            }
            IRecipientSession recipientSession = AccessingUserInfo.GetRecipientSession(this.organizationId);

            ArgumentValidator.ThrowIfNull("recipientSession", recipientSession);
            ArgumentValidator.ThrowIfInvalidValue <IRecipientSession>("recipientSession.ReadOnly", recipientSession, (IRecipientSession x) => x.ReadOnly);
            if (this.accessingUserInfo.UserObjectId != null)
            {
                ADRecipient adrecipient = recipientSession.FindByExchangeGuid(this.groupMailboxToLogon.MailboxInfo.MailboxGuid);
                if (adrecipient != null)
                {
                    recipientSession.DomainController = adrecipient.OriginatingServer;
                    MultiValuedProperty <ADObjectId> multiValuedProperty = (MultiValuedProperty <ADObjectId>)adrecipient[ADUserSchema.Owners];
                    if (multiValuedProperty.Contains(this.accessingUserInfo.UserObjectId))
                    {
                        this.TraceMembershipType(UnifiedGroupMemberType.Owner);
                        return(UnifiedGroupMemberType.Owner);
                    }
                }
                if (this.groupMailboxToLogon.ModernGroupType == ModernGroupObjectType.Public)
                {
                    this.TraceMembershipType(UnifiedGroupMemberType.Member);
                    return(UnifiedGroupMemberType.Member);
                }
                if (this.groupMailboxToLogon.ModernGroupType == ModernGroupObjectType.Private)
                {
                    QueryFilter  queryFilter  = new ComparisonFilter(ComparisonOperator.Equal, IUnifiedGroupMailboxSchema.UnifiedGroupMembersLink, this.accessingUserInfo.UserObjectId);
                    QueryFilter  queryFilter2 = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Id, this.groupMailboxToLogon.ObjectId);
                    ADRawEntry[] array        = recipientSession.Find(null, QueryScope.SubTree, new AndFilter(new QueryFilter[]
                    {
                        queryFilter2,
                        queryFilter
                    }), null, 0, GroupMailboxAuthorizationHandler.PropertiesToReturnForGroupQuery);
                    if (array != null && array.Length == 1)
                    {
                        this.TraceMembershipType(UnifiedGroupMemberType.Member);
                        return(UnifiedGroupMemberType.Member);
                    }
                }
            }
            else
            {
                GroupMailboxAuthorizationHandler.Tracer.TraceError <string>((long)this.GetHashCode(), "Unable to retrieve object identity of user {0} from AD", this.accessingUserInfo.Identity);
            }
            if (this.groupMailboxToLogon.ModernGroupType == ModernGroupObjectType.Public)
            {
                this.TraceMembershipType(UnifiedGroupMemberType.Member);
                return(UnifiedGroupMemberType.Member);
            }
            if (this.groupMailboxToLogon.ModernGroupType == ModernGroupObjectType.Private && this.IsGroupMemberInMailboxAssociation())
            {
                this.TraceMembershipType(UnifiedGroupMemberType.Member);
                return(UnifiedGroupMemberType.Member);
            }
            this.TraceMembershipType(UnifiedGroupMemberType.None);
            return(UnifiedGroupMemberType.None);
        }
Example #23
0
        public static void AddRecipientsToDraft(string[] ids, Item draft, RecipientItemType type, UserContext userContext)
        {
            if (draft == null)
            {
                throw new ArgumentNullException("draft");
            }
            MessageItem      messageItem      = draft as MessageItem;
            CalendarItemBase calendarItemBase = draft as CalendarItemBase;

            if (messageItem == null && calendarItemBase == null)
            {
                throw new ArgumentException("The draft should be a MessageItem or a CalendarItemBase while it is now a " + draft.GetType().Name);
            }
            if (userContext == null)
            {
                throw new ArgumentNullException("usercontext");
            }
            if (ids == null || ids.Length == 0)
            {
                throw new ArgumentException("ids is null or empty.", "ids");
            }
            IRecipientSession recipientSession = Utilities.CreateADRecipientSession(ConsistencyMode.IgnoreInvalid, userContext);
            SortBy            sortBy           = new SortBy(ADRecipientSchema.DisplayName, SortOrder.Descending);
            RecipientCache    recipientCache   = AutoCompleteCache.TryGetCache(OwaContext.Current.UserContext);

            for (int i = 0; i < ids.Length; i++)
            {
                Guid          guidFromBase64String = Utilities.GetGuidFromBase64String(ids[i]);
                QueryFilter   filter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Guid, guidFromBase64String);
                ADRecipient[] array  = recipientSession.Find(null, QueryScope.SubTree, filter, sortBy, 1);
                if (array != null && array.Length != 0)
                {
                    Participant participant = new Participant(array[0]);
                    if (participant != null)
                    {
                        AddressBookHelper.AddParticipantToItem(draft, type, participant);
                        int recipientFlags = 0;
                        if (draft is CalendarItem && DirectoryAssistance.IsADRecipientRoom(array[0]))
                        {
                            recipientFlags = 2;
                        }
                        if (recipientCache != null && userContext.UserOptions.AddRecipientsToAutoCompleteCache)
                        {
                            string participantProperty = Utilities.GetParticipantProperty <string>(participant, ParticipantSchema.SmtpAddress, null);
                            recipientCache.AddEntry(array[0].DisplayName, participantProperty, array[0].LegacyExchangeDN, string.Empty, "EX", AddressOrigin.Directory, recipientFlags, null, EmailAddressIndex.None);
                        }
                    }
                }
            }
            if (recipientCache != null && recipientCache.IsDirty)
            {
                recipientCache.Commit(true);
            }
            if (messageItem != null)
            {
                AddressBookHelper.SaveItem(draft);
                return;
            }
            if (calendarItemBase != null)
            {
                EditCalendarItemHelper.CreateUserContextData(userContext, calendarItemBase);
            }
        }