private void RemoveInvalidRoleGroups(RoleGroupCollection roleGroups)
 {
     foreach (RoleGroupDefinition roleGroupDefinition in roleGroups)
     {
         DNWithBinary dnwithBinary = DirectoryCommon.FindWellKnownObjectEntry(this.configurationUnit.OtherWellKnownObjects, roleGroupDefinition.RoleGroupGuid);
         if (null != dnwithBinary)
         {
             this.configurationUnit.OtherWellKnownObjects.Remove(dnwithBinary);
             this.configurationSession.Save(this.configurationUnit);
             base.LogWriteObject(this.configurationUnit);
             ADObjectId adobjectId = new ADObjectId(dnwithBinary.DistinguishedName);
             foreach (ExchangeRoleAssignment exchangeRoleAssignment in this.configurationSession.FindPaged <ExchangeRoleAssignment>(base.OrgContainerId.GetDescendantId(ExchangeRoleAssignment.RdnContainer), QueryScope.OneLevel, new ComparisonFilter(ComparisonOperator.Equal, ExchangeRoleAssignmentSchema.User, adobjectId), null, 0))
             {
                 this.configurationSession.Delete(exchangeRoleAssignment);
                 base.LogWriteObject(exchangeRoleAssignment);
             }
             if (!adobjectId.IsDeleted)
             {
                 ADRecipient adrecipient = this.orgDomainRecipientSession.Read(adobjectId);
                 base.LogReadObject(adrecipient);
                 this.orgDomainRecipientSession.Delete(adrecipient);
                 base.LogWriteObject(adrecipient);
             }
         }
     }
 }
 private void ValidateCreatedRoleGroups(RoleGroupCollection roleGroups)
 {
     foreach (RoleGroupDefinition roleGroupDefinition in roleGroups)
     {
         base.ResolveHostedExchangeGroupGuid <ADGroup>(roleGroupDefinition.RoleGroupGuid, this.organization.OrganizationId);
     }
 }
        private void CreateAndValidateRoleGroups(ADObjectId usgContainerId, RoleGroupCollection roleGroups)
        {
            RoleGroupDefinition roleGroupDefinition = roleGroups.FirstOrDefault((RoleGroupDefinition x) => x.RoleGroupGuid.Equals(RoleGroup.OrganizationManagement_InitInfo.WellKnownGuid));

            if (roleGroupDefinition == null)
            {
                base.WriteError(new ExOrgAdminSGroupNotFoundException(WellKnownGuid.EoaWkGuid), ErrorCategory.ObjectNotFound, null);
            }
            roleGroups.Remove(roleGroupDefinition);
            roleGroupDefinition.ADGroup = this.CreateRoleGroup(usgContainerId, roleGroupDefinition, null);
            if (!roleGroupDefinition.ADGroup.ManagedBy.Contains(roleGroupDefinition.ADGroup.Id))
            {
                roleGroupDefinition.ADGroup.ManagedBy.Add(roleGroupDefinition.ADGroup.Id);
                this.orgDomainRecipientSession.Save(roleGroupDefinition.ADGroup);
                base.LogWriteObject(roleGroupDefinition.ADGroup);
            }
            List <ADObjectId> manageBy = new List <ADObjectId>
            {
                roleGroupDefinition.ADGroup.Id
            };

            foreach (RoleGroupDefinition roleGroupDefinition2 in roleGroups)
            {
                roleGroupDefinition2.ADGroup = this.CreateRoleGroup(usgContainerId, roleGroupDefinition2, manageBy);
            }
            roleGroups.Add(roleGroupDefinition);
        }
        private RoleGroupCollection GetInvalidRoleGroups()
        {
            bool flag = Datacenter.IsPartnerHostedOnly(false);
            RoleGroupCollection roleGroupCollection = new RoleGroupCollection();
            List <string>       enabledRoleGroupRoleAssignmentFeatures = this.ServicePlanSettings.Organization.GetEnabledRoleGroupRoleAssignmentFeatures();

            using (List <RoleGroupDefinition> .Enumerator enumerator = RoleGroupDefinitions.RoleGroups.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    RoleGroupDefinition  roleGroupDefinition = enumerator.Current;
                    RoleGroupRoleMapping roleGroupRoleMapping;
                    if (flag)
                    {
                        roleGroupRoleMapping = HostedTenant_RoleGroupDefinition.Definition.FirstOrDefault((RoleGroupRoleMapping x) => x.RoleGroup.Equals(roleGroupDefinition.Name, StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        roleGroupRoleMapping = Tenant_RoleGroupDefinition.Definition.FirstOrDefault((RoleGroupRoleMapping x) => x.RoleGroup.Equals(roleGroupDefinition.Name, StringComparison.OrdinalIgnoreCase));
                    }
                    if (roleGroupRoleMapping != null && roleGroupRoleMapping.GetRolesAssignments(enabledRoleGroupRoleAssignmentFeatures).Count == 0)
                    {
                        roleGroupCollection.Add(new RoleGroupDefinition(roleGroupDefinition));
                    }
                }
            }
            return(roleGroupCollection);
        }
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            RoleGroupCollection roleGroupsToCreate = this.GetRoleGroupsToCreate();

            this.CreateAndValidateRoleGroups(this.organization.Id, roleGroupsToCreate);
            this.RemoveInvalidRoleGroups(this.GetInvalidRoleGroups());
            TaskLogger.LogExit();
        }
        private void CreateAndValidateRoleGroups(ADOrganizationalUnit usgContainer, RoleGroupCollection roleGroups)
        {
            foreach (RoleGroupDefinition roleGroup in roleGroups)
            {
                this.CreateRoleGroup(usgContainer, roleGroup);
            }
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            string           name             = windowsPrincipal.Identity.Name;

            string[] array = name.Split(new char[]
            {
                '\\'
            }, 2);
            ADRecipient adrecipient = (ADRecipient)this.recipientSession.FindByAccountName <ADRecipient>(array[0], array[1]);

            if (adrecipient != null)
            {
                TaskLogger.Trace("Didn't find user {0})", new object[]
                {
                    name
                });
            }
            ADGroup adgroup = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.EoaWkGuid);

            if (adgroup == null)
            {
                base.WriteError(new ExOrgAdminSGroupNotFoundException(WellKnownGuid.EoaWkGuid), ErrorCategory.ObjectNotFound, null);
            }
            else if (adrecipient != null)
            {
                base.LogReadObject(adrecipient);
                TaskLogger.Trace("User {0} is being set as member of RoleGroup {1}", new object[]
                {
                    adrecipient.DistinguishedName,
                    adgroup.Name
                });
                InitializeExchangeUniversalGroups.AddMember(adrecipient, this.rootDomainRecipientSession, adgroup, new WriteVerboseDelegate(base.WriteVerbose));
            }
            foreach (RoleGroupDefinition roleGroupDefinition in roleGroups)
            {
                if (roleGroupDefinition.ADGroup == null)
                {
                    roleGroupDefinition.ADGroup = base.ResolveExchangeGroupGuid <ADGroup>(roleGroupDefinition.RoleGroupGuid);
                    if (roleGroupDefinition.ADGroup == null)
                    {
                        base.WriteError(roleGroupDefinition.GuidNotFoundException, ErrorCategory.ObjectNotFound, null);
                    }
                    base.LogReadObject(roleGroupDefinition.ADGroup);
                }
                if (roleGroupDefinition.ADGroup != null && !roleGroupDefinition.ADGroup.ManagedBy.Contains(adgroup.Id))
                {
                    roleGroupDefinition.ADGroup.ManagedBy.Add(adgroup.Id);
                    this.rootDomainRecipientSession.Save(roleGroupDefinition.ADGroup);
                    base.LogWriteObject(roleGroupDefinition.ADGroup);
                }
            }
        }
        internal static RoleGroupCollection RoleGroupsToCreate()
        {
            RoleGroupCollection roleGroupCollection = new RoleGroupCollection();

            Datacenter.ExchangeSku exchangeSku = Datacenter.GetExchangeSku();
            RoleGroupRoleMapping[] definition;
            if (Datacenter.IsMicrosoftHostedOnly(false))
            {
                definition = Datacenter_RoleGroupDefinition.Definition;
            }
            else if (Datacenter.IsPartnerHostedOnly(false))
            {
                definition = Hosting_RoleGroupDefinition.Definition;
            }
            else if (Datacenter.IsDatacenterDedicated(false))
            {
                definition = Dedicated_RoleGroupDefinition.Definition;
            }
            else
            {
                definition = Enterprise_RoleGroupDefinition.Definition;
            }
            using (List <RoleGroupDefinition> .Enumerator enumerator = RoleGroupDefinitions.RoleGroups.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    RoleGroupDefinition roleGroup = enumerator.Current;
                    if (roleGroup.AlwaysCreateOnSku != null && roleGroup.AlwaysCreateOnSku.Contains(exchangeSku))
                    {
                        roleGroupCollection.Add(new RoleGroupDefinition(roleGroup));
                    }
                    else
                    {
                        RoleGroupRoleMapping roleGroupRoleMapping = definition.FirstOrDefault((RoleGroupRoleMapping x) => x.RoleGroup.Equals(roleGroup.Name, StringComparison.OrdinalIgnoreCase));
                        if (roleGroupRoleMapping != null)
                        {
                            roleGroupCollection.Add(new RoleGroupDefinition(roleGroup));
                        }
                    }
                }
            }
            return(roleGroupCollection);
        }
        protected override void InternalProcessRecord()
        {
            TaskLogger.LogEnter();
            RoleGroupCollection roleGroupCollection = InitializeExchangeUniversalGroups.RoleGroupsToCreate();
            bool flag = false;

            foreach (RoleGroupDefinition roleGroupDefinition in roleGroupCollection)
            {
                roleGroupDefinition.ADGroup = base.ResolveExchangeGroupGuid <ADGroup>(roleGroupDefinition.RoleGroupGuid);
                if (roleGroupDefinition.ADGroup == null)
                {
                    flag = true;
                }
            }
            ADGroup adgroup  = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.ExSWkGuid);
            ADGroup adgroup2 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.E3iWkGuid);
            ADGroup adgroup3 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.EtsWkGuid);
            ADGroup adgroup4 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.EwpWkGuid);

            this.adSplitPermissionMode = false;
            if (this.ActiveDirectorySplitPermissions != null)
            {
                if (this.ActiveDirectorySplitPermissions.Value)
                {
                    this.adSplitPermissionMode = true;
                }
                else
                {
                    this.adSplitPermissionMode = false;
                }
            }
            else if (adgroup3 == null)
            {
                this.adSplitPermissionMode = false;
            }
            else if (adgroup4 == null)
            {
                this.adSplitPermissionMode = false;
            }
            else if (!adgroup4.Members.Contains(adgroup3.Id))
            {
                this.adSplitPermissionMode = true;
            }
            else
            {
                this.adSplitPermissionMode = false;
            }
            ADOrganizationalUnit adorganizationalUnit = this.FindExchangeUSGContainer("Microsoft Exchange Protected Groups", this.domainConfigurationSession, this.rootDomain.Id);

            if (this.adSplitPermissionMode && adorganizationalUnit == null)
            {
                adorganizationalUnit = this.CreateExchangeUSGContainer("Microsoft Exchange Protected Groups", this.domainConfigurationSession, this.rootDomain.Id);
                if (adorganizationalUnit == null)
                {
                    base.WriteError(new USGContainerNotFoundException("Microsoft Exchange Protected Groups", this.rootDomain.DistinguishedName), ErrorCategory.ObjectNotFound, null);
                }
            }
            ADOrganizationalUnit adorganizationalUnit2 = null;

            if (flag || adgroup == null || adgroup2 == null || adgroup3 == null || (!this.adSplitPermissionMode && adgroup4 == null))
            {
                adorganizationalUnit2 = this.CreateExchangeUSGContainer("Microsoft Exchange Security Groups", this.domainConfigurationSession, this.rootDomain.Id);
                if (adorganizationalUnit2 == null)
                {
                    base.WriteError(new USGContainerNotFoundException("Microsoft Exchange Security Groups", this.rootDomain.DistinguishedName), ErrorCategory.ObjectNotFound, null);
                }
            }
            else
            {
                adorganizationalUnit2 = this.FindExchangeUSGContainer("Microsoft Exchange Security Groups", this.domainConfigurationSession, this.rootDomain.Id);
            }
            this.CreateAndValidateRoleGroups(adorganizationalUnit2, roleGroupCollection);
            this.CreateGroup(adorganizationalUnit2, "Exchange Servers", 0, WellKnownGuid.ExSWkGuid, Strings.ExchangeServersUSGDescription);
            this.CreateGroup(adorganizationalUnit2, "Exchange Trusted Subsystem", 0, WellKnownGuid.EtsWkGuid, Strings.ExchangeTrustedSubsystemDescription);
            this.CreateGroup(adorganizationalUnit2, "Managed Availability Servers", 0, WellKnownGuid.MaSWkGuid, Strings.ManagedAvailabilityServersUSGDescription);
            if (this.adSplitPermissionMode)
            {
                this.CreateOrMoveEWPGroup(adgroup4, adorganizationalUnit);
            }
            else
            {
                this.CreateOrMoveEWPGroup(adgroup4, adorganizationalUnit2);
                if (adorganizationalUnit != null)
                {
                    this.domainConfigurationSession.Delete(adorganizationalUnit);
                    base.LogWriteObject(adorganizationalUnit);
                }
            }
            this.CreateGroup(adorganizationalUnit2, "ExchangeLegacyInterop", 0, WellKnownGuid.E3iWkGuid, Strings.ExchangeInteropUSGDescription);
            if (adgroup == null)
            {
                adgroup = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.ExSWkGuid);
                if (adgroup == null)
                {
                    base.WriteError(new ExSGroupNotFoundException(WellKnownGuid.ExSWkGuid), ErrorCategory.InvalidData, null);
                }
            }
            base.LogReadObject(adgroup);
            ADGroup adgroup5 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.MaSWkGuid);

            if (adgroup5 == null)
            {
                base.WriteError(new MaSGroupNotFoundException(WellKnownGuid.MaSWkGuid), ErrorCategory.InvalidData, null);
            }
            base.LogReadObject(adgroup5);
            InitializeExchangeUniversalGroups.AddMember(adgroup, this.rootDomainRecipientSession, adgroup5, new WriteVerboseDelegate(base.WriteVerbose));
            if (adgroup2 == null)
            {
                adgroup2 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.E3iWkGuid);
                if (adgroup2 == null)
                {
                    base.WriteError(new E2k3InteropGroupNotFoundException(WellKnownGuid.E3iWkGuid), ErrorCategory.InvalidData, null);
                }
            }
            base.LogReadObject(adgroup2);
            bool etsExisted = adgroup3 != null;

            if (adgroup3 == null)
            {
                adgroup3 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.EtsWkGuid);
                if (adgroup3 == null)
                {
                    base.WriteError(new ExTrustedSubsystemGroupNotFoundException(WellKnownGuid.EtsWkGuid), ErrorCategory.InvalidData, null);
                }
            }
            base.LogReadObject(adgroup3);
            bool ewpExisted = adgroup4 != null;

            if (adgroup4 == null)
            {
                adgroup4 = base.ResolveExchangeGroupGuid <ADGroup>(WellKnownGuid.EwpWkGuid);
                if (adgroup4 == null)
                {
                    base.WriteError(new ExWindowsPermissionsGroupNotFoundException(WellKnownGuid.EwpWkGuid), ErrorCategory.InvalidData, null);
                }
            }
            base.LogReadObject(adgroup4);
            this.GrantWriteMembershipPermission(adgroup3.Sid, adorganizationalUnit2);
            this.FixExchangeTrustedSubsystemGroupMembership(adgroup3, adgroup4, adgroup, roleGroupCollection.GetADGroupByGuid(WellKnownGuid.EmaWkGuid), etsExisted, ewpExisted);
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            string           name             = windowsPrincipal.Identity.Name;

            string[] array = name.Split(new char[]
            {
                '\\'
            }, 2);
            ADCrossRef[] domainPartitions = ADForest.GetLocalForest(base.DomainController).GetDomainPartitions();
            if (domainPartitions == null || domainPartitions.Length == 0)
            {
                base.WriteError(new DomainsNotFoundException(), ErrorCategory.InvalidData, null);
            }
            List <SecurityIdentifier> list = new List <SecurityIdentifier>();

            foreach (ADCrossRef adcrossRef in domainPartitions)
            {
                Exception ex = null;
                try
                {
                    this.domainConfigurationSession.DomainController = null;
                    ADDomain addomain = this.domainConfigurationSession.Read <ADDomain>(adcrossRef.NCName);
                    base.LogReadObject(addomain);
                    SecurityIdentifier item = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, addomain.Sid);
                    list.Add(item);
                }
                catch (ADExternalException ex2)
                {
                    ex = ex2;
                }
                catch (ADTransientException ex3)
                {
                    ex = ex3;
                }
                if (ex != null)
                {
                    this.WriteWarning(Strings.DomainNotReachableWarning(adcrossRef.DnsRoot[0]));
                }
            }
            this.domainConfigurationSession.DomainController = null;
            ADGroup adgroupByGuid  = roleGroupCollection.GetADGroupByGuid(WellKnownGuid.EoaWkGuid);
            ADGroup adgroupByGuid2 = roleGroupCollection.GetADGroupByGuid(WellKnownGuid.EpaWkGuid);
            ActiveDirectoryAccessRule        activeDirectoryAccessRule = new ActiveDirectoryAccessRule(adgroupByGuid.Sid, ActiveDirectoryRights.GenericAll, AccessControlType.Allow, ActiveDirectorySecurityInheritance.All);
            List <ActiveDirectoryAccessRule> list2 = new List <ActiveDirectoryAccessRule>();

            list2.Add(activeDirectoryAccessRule);
            Guid schemaPropertyGuid = DirectoryCommon.GetSchemaPropertyGuid(this.configurationSession, "member");

            foreach (SecurityIdentifier identity in list)
            {
                list2.Add(new ActiveDirectoryAccessRule(identity, ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty, AccessControlType.Allow, schemaPropertyGuid, ActiveDirectorySecurityInheritance.All));
            }
            DirectoryCommon.SetAces(new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), null, adgroup, list2.ToArray());
            try
            {
                DirectoryCommon.SetAces(new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), null, adgroupByGuid, new ActiveDirectoryAccessRule[]
                {
                    activeDirectoryAccessRule
                });
            }
            catch (ADOperationException ex4)
            {
                this.WriteWarning(Strings.UnableToGrantFullControlOnEOA(adgroupByGuid.Id.ToString(), adgroupByGuid.Id.ToString(), ex4.Message));
            }
            if (adgroupByGuid2 != null)
            {
                DirectoryCommon.SetAces(new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), null, adgroupByGuid2, new ActiveDirectoryAccessRule[]
                {
                    activeDirectoryAccessRule
                });
            }
            if (adorganizationalUnit2 != null)
            {
                base.WriteVerbose(Strings.InfoSetAces(adorganizationalUnit2.Id.DistinguishedName));
                DirectoryCommon.SetAces(new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), null, adorganizationalUnit2, new ActiveDirectoryAccessRule[]
                {
                    activeDirectoryAccessRule
                });
            }
            DirectoryCommon.SetAces(new Task.TaskVerboseLoggingDelegate(base.WriteVerbose), null, adgroup2, new ActiveDirectoryAccessRule[]
            {
                activeDirectoryAccessRule
            });
            bool useGlobalCatalog = this.recipientSession.UseGlobalCatalog;

            this.recipientSession.UseGlobalCatalog = true;
            try
            {
                ADRecipient adrecipient = (ADRecipient)this.recipientSession.FindByAccountName <ADRecipient>(array[0], array[1]);
                if (adrecipient != null)
                {
                    TaskLogger.Trace("Adding user {0} ({1}), to group {2}.", new object[]
                    {
                        name,
                        adrecipient.DistinguishedName,
                        adgroupByGuid.DistinguishedName
                    });
                    InitializeExchangeUniversalGroups.AddMember(adrecipient, this.rootDomainRecipientSession, adgroupByGuid, new WriteVerboseDelegate(base.WriteVerbose));
                }
                else
                {
                    TaskLogger.Trace("Didn't find user {0})", new object[]
                    {
                        name
                    });
                }
            }
            catch (ADOperationException ex5)
            {
                base.WriteVerbose(new LocalizedString(ex5.Message));
            }
            this.recipientSession.UseGlobalCatalog = useGlobalCatalog;
            TaskLogger.LogExit();
        }