Ejemplo n.º 1
0
        private async Task <VerifiedDomain> GetTenantDefualtDomain()
        {
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail  tenant        = null;
            var            tenantId      = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            var pageList = await this.client.TenantDetails
                           .Where(tenantDetail => tenantDetail.ObjectId.Equals(tenantId))
                           .ExecuteAsync();

            List <ITenantDetail> tenantList = pageList.CurrentPage.ToList <ITenantDetail>();

            if (tenantList.Count > 0)
            {
                tenant = tenantList.First();
            }

            if (tenant != null)
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                return(defaultDomain);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 2
0
        public async Task <string> GetTenantCoordinates(long tenantId)
        {
            IRepository <TenantDetail, long> repository = this._tenantDetailRepository;
            List <TenantDetail> allListAsync            = await repository.GetAllListAsync((TenantDetail m) => (long)m.TenantId == tenantId);

            TenantDetail item  = allListAsync[0];
            string       empty = string.Empty;

            if (!(item != null) || !item.Latitude.HasValue || !item.Longitude.HasValue)
            {
                empty = "{lat:40.758701,lng:-111.876183}";
            }
            else
            {
                object[] value    = new object[] { "{lat:", null, null, null, null };
                double?  latitude = item.Latitude;
                value[1] = latitude.Value;
                value[2] = ",lng:";
                latitude = item.Longitude;
                value[3] = latitude.Value;
                value[4] = "}";
                empty    = string.Concat(value);
            }
            return(empty);
        }
Ejemplo n.º 3
0
        private static async Task <ITenantDetail> GetTenantDetails(IActiveDirectoryClient client, string tenantId)
        {
            //*********************************************************************
            // The following section may be run by any user, as long as the app
            // has been granted the minimum of User.Read (and User.ReadWrite to update photo)
            // and User.ReadBasic.All scope permissions. Directory.ReadWrite.All
            // or Directory.AccessAsUser.All will also work, but are much more privileged.
            //*********************************************************************


            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************

            ITenantDetail tenant = null;

            IPagedCollection <ITenantDetail> tenantsCollection = await client.TenantDetails
                                                                 .Where(tenantDetail => tenantDetail.ObjectId.Equals(tenantId)).ExecuteAsync();

            List <ITenantDetail> tenantsList = tenantsCollection.CurrentPage.ToList();

            if (tenantsList.Count > 0)
            {
                tenant = tenantsList.First();
            }

            if (tenant == null)
            {
                _dialogService.Show(DialogType.Error, "Tenant not found");
                return(null);
            }
            else
            {
                TenantDetail  tenantDetail = (TenantDetail)tenant;
                StringBuilder sb           = new StringBuilder();
                sb.AppendLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                var initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                sb.AppendLine("Initial Domain Name: " + initialDomain.Name);
                var defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                sb.AppendLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    sb.AppendLine("Tenant Tech Contact: " + techContact);
                }
                sb.Remove(sb.Length - 2, 2);
                _dialogService.Show(DialogType.Success, sb.ToString());
                return(tenantDetail);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get a user from the list of Izenda Users by the provided tenant
        /// </summary>
        public static async Task <UserDetail> GetIzendaUserByTenantAndName(string userName, string tenantName, string authToken)
        {
            TenantDetail tenant = await GetIzendaTenantByName(tenantName, authToken);

            Guid?tnId = null;

            if (tenant != null)
            {
                tnId = tenant.Id;
            }
            IList <UserDetail> userList = await GetIzendaUsersByTenant(tnId, authToken);

            return(userList.FirstOrDefault(u => u.UserName.Equals(userName, StringComparison.InvariantCultureIgnoreCase)));
        }
Ejemplo n.º 5
0
        public static async Task CreateTenant(string tenantName, string authToken)
        {
            var existingTenant = await GetIzendaTenantByName(tenantName, authToken);

            if (existingTenant != null)
            {
                return;
            }

            var tenantDetail = new TenantDetail
            {
                Active   = true,
                Disable  = false,
                Name     = tenantName,
                TenantId = tenantName
            };

            await WebApiService.Instance.PostAsync("tenant", tenantDetail, authToken);
        }
        private static void PrintTenantDetails(ITenantDetail tenant)
        {
            TenantDetail tenantDetail = (TenantDetail)tenant;

            Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

            var initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);

            Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
            var defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);

            Console.WriteLine("Default Domain Name: " + defaultDomain.Name);

            // Get Tenant's Tech Contacts
            foreach (string techContact in tenantDetail.TechnicalNotificationMails)
            {
                Console.WriteLine("Tenant Tech Contact: " + techContact);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Create a tenant
        /// For more information, please refer to https://www.izenda.com/docs/ref/api_tenant.html#tenant-apis
        /// </summary>
        public static async Task <bool> CreateTenant(string tenantName, string tenantId, string authToken)
        {
            var existingTenant = await GetIzendaTenantByName(tenantId, authToken);

            if (existingTenant != null)
            {
                return(false);
            }

            var tenantDetail = new TenantDetail
            {
                Active   = true,
                Disable  = false,
                Name     = tenantName,
                TenantId = tenantId
            };

            // For more information, please refer to https://www.izenda.com/docs/ref/api_tenant.html#post-tenant
            return(await WebApiService.Instance.PostReturnBooleanAsync("tenant", tenantDetail, authToken));
        }
        public async Task <HttpResponseMessage> AddTenant(int id, TenantDetail tenantDetail)
        {
            if (await _db.User.AnyAsync(x => x.UserId == id))
            {
                Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"User {id} does not exist.");
            }
            if (tenantDetail == null)
            {
                Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Parameter tenantDetail userDetailsList can not empty.");
            }
            var tenant = new Tenant
            {
                CreateByUserId = id,
                CreateTime     = DateTime.Now,
                TenantDetail   = tenantDetail
            };

            _db.Tenant.Add(tenant);
            var result = await _db.SaveChangesAsync();

            return(Request.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(result)));
        }
Ejemplo n.º 9
0
        public static async Task <RoleDetail> CreateRole(string roleName, TenantDetail izendaTenant, string authToken)
        {
            var role = await GetIzendaRoleByTenantAndName(izendaTenant != null?(Guid?)izendaTenant.Id : null, roleName, authToken);

            if (role == null)
            {
                role = new RoleDetail
                {
                    Active          = true,
                    Deleted         = false,
                    NotAllowSharing = false,
                    Name            = roleName,
                    TenantId        = izendaTenant != null ? (Guid?)izendaTenant.Id : null
                };

                var response = await WebApiService.Instance.PostReturnValueAsync <AddRoleResponeMessage, RoleDetail>("role", role, authToken);

                role = response.Role;
            }

            return(role);
        }
Ejemplo n.º 10
0
 public static TenantDetail CreateTenantDetail(string objectId, global::System.Collections.ObjectModel.Collection<AssignedPlan> assignedPlans, global::System.Collections.ObjectModel.Collection<string> marketingNotificationEmails, global::System.Collections.ObjectModel.Collection<ProvisionedPlan> provisionedPlans, global::System.Collections.ObjectModel.Collection<ProvisioningError> provisioningErrors, global::System.Collections.ObjectModel.Collection<string> technicalNotificationMails, global::System.Collections.ObjectModel.Collection<VerifiedDomain> verifiedDomains)
 {
     TenantDetail tenantDetail = new TenantDetail();
     tenantDetail.objectId = objectId;
     if ((assignedPlans == null))
     {
         throw new global::System.ArgumentNullException("assignedPlans");
     }
     tenantDetail.assignedPlans = assignedPlans;
     if ((marketingNotificationEmails == null))
     {
         throw new global::System.ArgumentNullException("marketingNotificationEmails");
     }
     tenantDetail.marketingNotificationEmails = marketingNotificationEmails;
     if ((provisionedPlans == null))
     {
         throw new global::System.ArgumentNullException("provisionedPlans");
     }
     tenantDetail.provisionedPlans = provisionedPlans;
     if ((provisioningErrors == null))
     {
         throw new global::System.ArgumentNullException("provisioningErrors");
     }
     tenantDetail.provisioningErrors = provisioningErrors;
     if ((technicalNotificationMails == null))
     {
         throw new global::System.ArgumentNullException("technicalNotificationMails");
     }
     tenantDetail.technicalNotificationMails = technicalNotificationMails;
     if ((verifiedDomains == null))
     {
         throw new global::System.ArgumentNullException("verifiedDomains");
     }
     tenantDetail.verifiedDomains = verifiedDomains;
     return tenantDetail;
 }
Ejemplo n.º 11
0
        public async Task <List <TaxDto> > GetZoneTaxesByAddressId(int tenantId, long addressId, bool active)
        {
            List <TaxDto> taxDtos;

            if (addressId != (long)-1)
            {
                Address async = await this._addressRepository.GetAsync(addressId);

                IQueryable <Zone> all   = this._zoneRepository.GetAll();
                IQueryable <Zone> zones =
                    from p in all
                    where p.TenantId == tenantId
                    select p;
                bool flag = active;
                IQueryable <Zone> zones1    = zones.WhereIf <Zone>(flag, (Zone p) => p.IsActive == active);
                List <Zone>       listAsync = await System.Data.Entity.QueryableExtensions.Include <Zone, ICollection <ZoneTax> >(zones1, (Zone n) => n.Taxes).OrderBy <Zone>("Name", new object[0]).ToListAsync <Zone>();

                List <ZoneDto>  zoneDtos        = new List <ZoneDto>();
                CustomDbContext customDbContext = new CustomDbContext();
                foreach (Zone zone in listAsync)
                {
                    ZoneDto      zoneDto       = zone.MapTo <ZoneDto>();
                    object[]     sqlParameter  = new object[] { new SqlParameter("@ZoneId", (object)zoneDto.Id), new SqlParameter("@AddressId", (object)async.Id), null };
                    SqlParameter sqlParameter1 = new SqlParameter()
                    {
                        ParameterName = "@retVal",
                        SqlDbType     = SqlDbType.Int,
                        Direction     = ParameterDirection.Output,
                        Value         = 0
                    };
                    sqlParameter[2] = sqlParameter1;
                    if (customDbContext.Database.SqlQuery <int>("exec @retVal = Geo_AddressIdInZone @ZoneId, @AddressId", sqlParameter).Single <int>() != 1)
                    {
                        continue;
                    }
                    zoneDtos.Add(zoneDto);
                }
                customDbContext.Dispose();
                List <ZoneDto> zoneDtos1 = new List <ZoneDto>(zoneDtos.MapTo <List <ZoneDto> >());
                List <TaxDto>  taxDtos1  = new List <TaxDto>();
                List <long>    nums      = new List <long>();
                foreach (ZoneDto zoneDto1 in zoneDtos1)
                {
                    foreach (ZoneTaxDto taxis in zoneDto1.Taxes)
                    {
                        TaxDto taxDto = taxis.Tax.MapTo <TaxDto>();
                        if (nums.Contains(taxDto.Id))
                        {
                            continue;
                        }
                        nums.Add(taxDto.Id);
                        taxDtos1.Add(taxDto);
                    }
                }
                taxDtos = new List <TaxDto>(taxDtos1.Distinct <TaxDto>().MapTo <List <TaxDto> >());
            }
            else
            {
                IRepository <TenantDetail, long> repository = this._tenantDetailRepository;
                TenantDetail tenantDetail = await repository.FirstOrDefaultAsync((TenantDetail x) => x.TenantId == tenantId);

                TenantDetail      tenantDetail1 = tenantDetail;
                IQueryable <Zone> all1          = this._zoneRepository.GetAll();
                IQueryable <Zone> zones2        =
                    from p in all1
                    where p.TenantId == tenantId
                    select p;
                bool flag1 = active;
                IQueryable <Zone> zones3     = zones2.WhereIf <Zone>(flag1, (Zone p) => p.IsActive == active);
                List <Zone>       listAsync1 = await System.Data.Entity.QueryableExtensions.Include <Zone, ICollection <ZoneTax> >(zones3, (Zone n) => n.Taxes).OrderBy <Zone>("Name", new object[0]).ToListAsync <Zone>();

                List <ZoneDto>  zoneDtos2        = new List <ZoneDto>();
                CustomDbContext customDbContext1 = new CustomDbContext();
                foreach (Zone zone1 in listAsync1)
                {
                    ZoneDto      zoneDto2      = zone1.MapTo <ZoneDto>();
                    object[]     objArray      = new object[] { new SqlParameter("@ZoneId", (object)zoneDto2.Id), new SqlParameter("@CompanyAddressId", (object)tenantDetail1.Id), null };
                    SqlParameter sqlParameter2 = new SqlParameter()
                    {
                        ParameterName = "@retVal",
                        SqlDbType     = SqlDbType.Int,
                        Direction     = ParameterDirection.Output,
                        Value         = 0
                    };
                    objArray[2] = sqlParameter2;
                    if (customDbContext1.Database.SqlQuery <int>("exec @retVal = Geo_CompanyAddressIdInZone @ZoneId, @CompanyAddressId", objArray).Single <int>() != 1)
                    {
                        continue;
                    }
                    zoneDtos2.Add(zoneDto2);
                }
                customDbContext1.Dispose();
                List <ZoneDto> zoneDtos3 = new List <ZoneDto>(zoneDtos2.MapTo <List <ZoneDto> >());
                List <TaxDto>  taxDtos2  = new List <TaxDto>();
                List <long>    nums1     = new List <long>();
                foreach (ZoneDto zoneDto3 in zoneDtos3)
                {
                    foreach (ZoneTaxDto zoneTaxDto in zoneDto3.Taxes)
                    {
                        TaxDto taxDto1 = zoneTaxDto.Tax.MapTo <TaxDto>();
                        if (nums1.Contains(taxDto1.Id))
                        {
                            continue;
                        }
                        nums1.Add(taxDto1.Id);
                        taxDtos2.Add(taxDto1);
                    }
                }
                taxDtos = new List <TaxDto>(taxDtos2.Distinct <TaxDto>().MapTo <List <TaxDto> >());
            }
            return(taxDtos);
        }
Ejemplo n.º 12
0
        public async Task <decimal> GetZoneEmergencyDeliveryFeesByAddressId(int tenantId, long addressId, bool active)
        {
            decimal num;

            if (addressId != (long)-1)
            {
                Address async = await this._addressRepository.GetAsync(addressId);

                IQueryable <Zone> all   = this._zoneRepository.GetAll();
                IQueryable <Zone> zones =
                    from p in all
                    where p.TenantId == tenantId
                    select p;
                bool        flag      = active;
                List <Zone> listAsync = await zones.WhereIf <Zone>(flag, (Zone p) => p.IsActive == active).OrderBy <Zone>("Name", new object[0]).ToListAsync <Zone>();

                List <ZoneDto>  zoneDtos        = new List <ZoneDto>();
                CustomDbContext customDbContext = new CustomDbContext();
                foreach (Zone zone in listAsync)
                {
                    ZoneDto      zoneDto       = zone.MapTo <ZoneDto>();
                    object[]     sqlParameter  = new object[] { new SqlParameter("@ZoneId", (object)zoneDto.Id), new SqlParameter("@AddressId", (object)async.Id), null };
                    SqlParameter sqlParameter1 = new SqlParameter()
                    {
                        ParameterName = "@retVal",
                        SqlDbType     = SqlDbType.Int,
                        Direction     = ParameterDirection.Output,
                        Value         = 0
                    };
                    sqlParameter[2] = sqlParameter1;
                    if (customDbContext.Database.SqlQuery <int>("exec @retVal = Geo_AddressIdInZone @ZoneId, @AddressId", sqlParameter).Single <int>() != 1)
                    {
                        continue;
                    }
                    zoneDtos.Add(zoneDto);
                }
                customDbContext.Dispose();
                List <ZoneDto> zoneDtos1 = new List <ZoneDto>(zoneDtos.MapTo <List <ZoneDto> >());
                List <decimal> nums      = new List <decimal>();
                foreach (ZoneDto zoneDto1 in zoneDtos1)
                {
                    IRepository <EmergencyDeliveryFee, long> repository = this._emergencyDeliveryFeeRepository;
                    List <EmergencyDeliveryFee> allListAsync            = await repository.GetAllListAsync((EmergencyDeliveryFee m) => m.ZoneId == (long?)zoneDto1.Id);

                    foreach (EmergencyDeliveryFee emergencyDeliveryFee in allListAsync)
                    {
                        if (emergencyDeliveryFee.Fee <= decimal.Zero)
                        {
                            continue;
                        }
                        nums.Add(emergencyDeliveryFee.Fee);
                    }
                }
                if (!nums.Any <decimal>())
                {
                    num = new decimal(0);
                }
                else
                {
                    List <decimal> nums1 = nums;
                    num = nums1.Sum <decimal>((decimal d) => d);
                }
            }
            else
            {
                IRepository <TenantDetail, long> repository1 = this._tenantDetailRepository;
                TenantDetail tenantDetail = await repository1.FirstOrDefaultAsync((TenantDetail x) => x.TenantId == tenantId);

                TenantDetail      tenantDetail1 = tenantDetail;
                IQueryable <Zone> all1          = this._zoneRepository.GetAll();
                IQueryable <Zone> zones1        =
                    from p in all1
                    where p.TenantId == tenantId
                    select p;
                bool        flag1      = active;
                List <Zone> listAsync1 = await zones1.WhereIf <Zone>(flag1, (Zone p) => p.IsActive == active).OrderBy <Zone>("Name", new object[0]).ToListAsync <Zone>();

                List <ZoneDto>  zoneDtos2        = new List <ZoneDto>();
                CustomDbContext customDbContext1 = new CustomDbContext();
                foreach (Zone zone1 in listAsync1)
                {
                    ZoneDto      zoneDto2      = zone1.MapTo <ZoneDto>();
                    object[]     objArray      = new object[] { new SqlParameter("@ZoneId", (object)zoneDto2.Id), new SqlParameter("@CompanyAddressId", (object)tenantDetail1.Id), null };
                    SqlParameter sqlParameter2 = new SqlParameter()
                    {
                        ParameterName = "@retVal",
                        SqlDbType     = SqlDbType.Int,
                        Direction     = ParameterDirection.Output,
                        Value         = 0
                    };
                    objArray[2] = sqlParameter2;
                    if (customDbContext1.Database.SqlQuery <int>("exec @retVal = Geo_CompanyAddressIdInZone @ZoneId, @CompanyAddressId", objArray).Single <int>() != 1)
                    {
                        continue;
                    }
                    zoneDtos2.Add(zoneDto2);
                }
                customDbContext1.Dispose();
                List <ZoneDto> zoneDtos3 = new List <ZoneDto>(zoneDtos2.MapTo <List <ZoneDto> >());
                List <decimal> nums2     = new List <decimal>();
                foreach (ZoneDto zoneDto3 in zoneDtos3)
                {
                    IRepository <EmergencyDeliveryFee, long> repository2 = this._emergencyDeliveryFeeRepository;
                    List <EmergencyDeliveryFee> emergencyDeliveryFees    = await repository2.GetAllListAsync((EmergencyDeliveryFee m) => m.ZoneId == (long?)zoneDto3.Id);

                    foreach (EmergencyDeliveryFee emergencyDeliveryFee1 in emergencyDeliveryFees)
                    {
                        if (emergencyDeliveryFee1.Fee <= decimal.Zero)
                        {
                            continue;
                        }
                        nums2.Add(emergencyDeliveryFee1.Fee);
                    }
                }
                if (!nums2.Any <decimal>())
                {
                    num = new decimal(0);
                }
                else
                {
                    List <decimal> nums3 = nums2;
                    num = nums3.Sum <decimal>((decimal d) => d);
                }
            }
            return(num);
        }
Ejemplo n.º 13
0
        public async Task UpdateAllSettings(TenantSettingsEditDto input)
        {
            string          domain;
            string          userName;
            string          password;
            ISettingManager settingManager        = this.SettingManager;
            int             tenantId              = this.AbpSession.GetTenantId();
            bool            allowSelfRegistration = input.UserManagement.AllowSelfRegistration;
            await settingManager.ChangeSettingForTenantAsync(tenantId, "App.UserManagement.AllowSelfRegistration", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            ISettingManager settingManager1 = this.SettingManager;
            int             num             = this.AbpSession.GetTenantId();

            allowSelfRegistration = input.UserManagement.IsNewRegisteredUserActiveByDefault;
            await settingManager1.ChangeSettingForTenantAsync(num, "App.UserManagement.IsNewRegisteredUserActiveByDefault", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            ISettingManager settingManager2 = this.SettingManager;
            int             tenantId1       = this.AbpSession.GetTenantId();

            allowSelfRegistration = input.UserManagement.IsEmailConfirmationRequiredForLogin;
            await settingManager2.ChangeSettingForTenantAsync(tenantId1, "Abp.Zero.UserManagement.IsEmailConfirmationRequiredForLogin", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            ISettingManager settingManager3 = this.SettingManager;
            int             num1            = this.AbpSession.GetTenantId();

            allowSelfRegistration = input.UserManagement.UseCaptchaOnRegistration;
            await settingManager3.ChangeSettingForTenantAsync(num1, "App.UserManagement.UseCaptchaOnRegistration", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            ISettingManager settingManager4 = this.SettingManager;
            int             tenantId2       = this.AbpSession.GetTenantId();

            allowSelfRegistration = input.UserManagement.RequireOnePhoneNumberForRegistration;
            await settingManager4.ChangeSettingForTenantAsync(tenantId2, "App.UserManagement.RequireOnePhoneNumberForRegistration", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            ISettingManager settingManager5 = this.SettingManager;
            int             num2            = this.AbpSession.GetTenantId();

            allowSelfRegistration = input.UserManagement.SendEmailAfterRegistration;
            await settingManager5.ChangeSettingForTenantAsync(num2, "App.UserManagement.SendEmailAfterRegistration", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            await this.SettingManager.ChangeSettingForTenantAsync(this.AbpSession.GetTenantId(), "App.UserManagement.SendEmailAfterRegistrationMessage", input.UserManagement.SendEmailAfterRegistrationMessage.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            ISettingManager settingManager6 = this.SettingManager;
            int             tenantId3       = this.AbpSession.GetTenantId();

            allowSelfRegistration = input.UserManagement.EnableEmergencyDeliveryFees;
            await settingManager6.ChangeSettingForTenantAsync(tenantId3, "App.UserManagment.EnableEmergencyDeliveryFees", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

            if (!this._multiTenancyConfig.IsEnabled)
            {
                input.ValidateHostSettings();
                await this.SettingManager.ChangeSettingForApplicationAsync("App.General.WebSiteRootAddress", input.General.WebSiteRootAddress.EnsureEndsWith('/'));

                await this.SettingManager.ChangeSettingForApplicationAsync("Abp.Net.Mail.DefaultFromAddress", input.Email.DefaultFromAddress);

                await this.SettingManager.ChangeSettingForApplicationAsync("Abp.Net.Mail.DefaultFromDisplayName", input.Email.DefaultFromDisplayName);

                await this.SettingManager.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.Host", input.Email.SmtpHost);

                ISettingManager settingManager7 = this.SettingManager;
                int             smtpPort        = input.Email.SmtpPort;
                await settingManager7.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.Port", smtpPort.ToString(CultureInfo.InvariantCulture));

                await this.SettingManager.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.UserName", input.Email.SmtpUserName);

                await this.SettingManager.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.Password", input.Email.SmtpPassword);

                await this.SettingManager.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.Domain", input.Email.SmtpDomain);

                ISettingManager settingManager8 = this.SettingManager;
                allowSelfRegistration = input.Email.SmtpEnableSsl;
                await settingManager8.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.EnableSsl", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

                ISettingManager settingManager9 = this.SettingManager;
                allowSelfRegistration = input.Email.SmtpUseDefaultCredentials;
                await settingManager9.ChangeSettingForApplicationAsync("Abp.Net.Mail.Smtp.UseDefaultCredentials", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

                if (this._ldapModuleConfig.IsEnabled)
                {
                    ISettingManager settingManager10 = this.SettingManager;
                    int             num3             = this.AbpSession.GetTenantId();
                    allowSelfRegistration = input.Ldap.IsEnabled;
                    await settingManager10.ChangeSettingForTenantAsync(num3, "Abp.Zero.Ldap.IsEnabled", allowSelfRegistration.ToString(CultureInfo.InvariantCulture).ToLower(CultureInfo.InvariantCulture));

                    ISettingManager settingManager11 = this.SettingManager;
                    int             tenantId4        = this.AbpSession.GetTenantId();
                    if (input.Ldap.Domain.IsNullOrWhiteSpace())
                    {
                        domain = null;
                    }
                    else
                    {
                        domain = input.Ldap.Domain;
                    }
                    await settingManager11.ChangeSettingForTenantAsync(tenantId4, "Abp.Zero.Ldap.Domain", domain);

                    ISettingManager settingManager12 = this.SettingManager;
                    int             num4             = this.AbpSession.GetTenantId();
                    if (input.Ldap.UserName.IsNullOrWhiteSpace())
                    {
                        userName = null;
                    }
                    else
                    {
                        userName = input.Ldap.UserName;
                    }
                    await settingManager12.ChangeSettingForTenantAsync(num4, "Abp.Zero.Ldap.UserName", userName);

                    ISettingManager settingManager13 = this.SettingManager;
                    int             tenantId5        = this.AbpSession.GetTenantId();
                    if (input.Ldap.Password.IsNullOrWhiteSpace())
                    {
                        password = null;
                    }
                    else
                    {
                        password = input.Ldap.Password;
                    }
                    await settingManager13.ChangeSettingForTenantAsync(tenantId5, "Abp.Zero.Ldap.Password", password);
                }
            }
            if (input.Details != null)
            {
                if (input.Details.TenantId == 0)
                {
                    input.Details.TenantId = this.AbpSession.GetTenantId();
                }
                TenantDetail nullable  = input.Details.MapTo <TenantDetail>();
                double?      longitude = nullable.Longitude;
                if (longitude.HasValue)
                {
                    longitude = nullable.Latitude;
                    if (longitude.HasValue)
                    {
                        goto Label0;
                    }
                }
                string empty = string.Empty;
                if (nullable.CountryRegionId.HasValue)
                {
                    IRepository <CountryRegion> repository = this._countryRegionRepository;
                    int?countryRegionId = nullable.CountryRegionId;
                    empty = (await repository.GetAsync(countryRegionId.Value)).Code;
                }
                string[]  address   = new string[] { nullable.Address, ",", nullable.City, ",", empty, ",", nullable.PostalCode };
                string    str       = string.Concat(address);
                XDocument xDocument = XDocument.Load(WebRequest.Create(string.Format("http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false", str.Replace(",,", ",").Replace(" ", "+"))).GetResponse().GetResponseStream());
                if (!xDocument.ToString().Contains("<GeocodeResponse>") || xDocument.ToString().Contains("ZERO_RESULTS"))
                {
                    longitude          = null;
                    nullable.Longitude = longitude;
                    longitude          = null;
                    nullable.Latitude  = longitude;
                    nullable.Location  = null;
                }
                else
                {
                    XElement xElement = xDocument.Element("GeocodeResponse").Element("result").Element("geometry").Element("location");
                    nullable.Latitude  = new double?(double.Parse(xElement.Element("lat").Value));
                    nullable.Longitude = new double?(double.Parse(xElement.Element("lng").Value));
                }
                xDocument = null;
Label0:
                TenantDetail tenantDetail = nullable;
                longitude = nullable.Longitude;
                object value = longitude.Value;
                longitude             = nullable.Latitude;
                tenantDetail.Location = DbGeography.PointFromText(string.Format("POINT({0} {1})", value, longitude.Value), 4326);
                await this._tenantDetailRepository.InsertOrUpdateAsync(nullable);

                nullable = null;
            }
            if (input.CustomerService != null)
            {
                if (input.CustomerService.TenantId == 0)
                {
                    input.CustomerService.TenantId = this.AbpSession.GetTenantId();
                }
                await this._tenantCustomerServicesRepository.InsertOrUpdateAsync(input.CustomerService.MapTo <TenantCustomerService>());
            }
            if (input.Hours != null)
            {
                if (input.CustomerService.TenantId == 0)
                {
                    input.CustomerService.TenantId = this.AbpSession.GetTenantId();
                }
                await this._tenantHoursRepository.InsertOrUpdateAsync(input.Hours.MapTo <TenantHour>());
            }
            if (input.Notifications != null)
            {
                input.ValidateEmailLists();
                if (input.Notifications.TenantId == 0)
                {
                    input.Notifications.TenantId = this.AbpSession.GetTenantId();
                }
                await this._tenantNotificationsRepository.InsertOrUpdateAsync(input.Notifications.MapTo <TenantNotifications>());
            }
            if (input.PaymentSettings != null)
            {
                if (input.PaymentSettings.TenantId == 0)
                {
                    input.PaymentSettings.TenantId = this.AbpSession.GetTenantId();
                }
                await this._tenantPaymentSettingsRepository.InsertOrUpdateAsync(input.PaymentSettings.MapTo <TenantPaymentSettings>());
            }
            if (input.PaymentGatewaySettings != null)
            {
                if (input.PaymentGatewaySettings.TenantId == 0)
                {
                    input.PaymentGatewaySettings.TenantId = this.AbpSession.GetTenantId();
                }
                await this._tenantPaymentGatewaySettingsRepository.InsertOrUpdateAsync(input.PaymentGatewaySettings.MapTo <TenantPaymentGatewaySettings>());
            }
            if (input.DateTimeSettings != null)
            {
                if (input.DateTimeSettings.TenantId == 0)
                {
                    input.DateTimeSettings.TenantId = this.AbpSession.GetTenantId();
                }
                await this._tenantDateTimeSettingsRepository.InsertOrUpdateAsync(input.DateTimeSettings.MapTo <TenantDateTimeSettings>());
            }
        }
Ejemplo n.º 14
0
        private static void Main()
        {
            // record start DateTime of execution
            string currentDateTime = DateTime.Now.ToUniversalTime().ToString();

            #region Setup Active Directory Client

            //*********************************************************************
            // setup Active Directory Client
            //*********************************************************************
            ActiveDirectoryClient activeDirectoryClient;
            try
            {
                activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            #endregion

            #region TenantDetails

            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            VerifiedDomain initialDomain = new VerifiedDomain();
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail  tenant        = null;
            Console.WriteLine("\n Retrieving Tenant Details");
            try
            {
                List <ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails
                                                   .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId))
                                                   .ExecuteAsync().Result.CurrentPage.ToList();
                if (tenantsList.Count > 0)
                {
                    tenant = tenantsList.First();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting TenantDetails {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }

            #endregion

            #region Create a new User



            IUser newUser = new User();
            if (defaultDomain.Name != null)
            {
                newUser.DisplayName       = "demo1";
                newUser.UserPrincipalName = "xuhua00101" + "@" + defaultDomain.Name;
                newUser.AccountEnabled    = true;
                newUser.MailNickname      = "SampleAppDemoUserManager";
                newUser.PasswordPolicies  = "DisablePasswordExpiration";
                newUser.PasswordProfile   = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = true
                };
                newUser.UsageLocation = "US";
                try
                {
                    //activeDirectoryClient.Users.AddUserAsync(newUser).Wait();
                    Console.WriteLine("\nNew User {0} was created", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError creating new user {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }


            #endregion

            // IApplication APPl = new Application();
            //// APPl.AppId = "12345678";
            // // APPl.AppRoles =
            // APPl.AvailableToOtherTenants = false;
            // APPl.DisplayName = "vik00de";
            //// APPl.IdentifierUris
            // APPl.Homepage = "https://ww.baidu.com";
            // // APPl.IdentifierUris = "https://ww.baidu.com1";
            // APPl.LogoutUrl = "https://ww.baidu.com";
            // APPl.ErrorUrl = "https://ww.baidu.com1/1";
            //// IList<string> ls = APPl.IdentifierUris;
            //APPl.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid());

            Application newApp = new Application {
                DisplayName = "wode" + Helper.GetRandomString(8)
            };
            newApp.IdentifierUris.Add("https://localhost/demo1/" + Guid.NewGuid());
            newApp.ReplyUrls.Add("https://localhost/demo1");
            newApp.PublicClient = null;
            AppRole appRole = new AppRole()
            {
                Id          = Guid.NewGuid(),
                IsEnabled   = true,
                DisplayName = "Something",
                Description = "Anything",
                Value       = "policy.write"
            };
            appRole.AllowedMemberTypes.Add("User");
            newApp.AppRoles.Add(appRole);



            //AzureADServicePrincipal
            //PasswordCredential password = new PasswordCredential
            //{
            //    StartDate = DateTime.UtcNow,
            //    EndDate = DateTime.UtcNow.AddYears(1),
            //    Value = "password",
            //    KeyId = Guid.NewGuid()
            //};
            //newApp.PasswordCredentials.Add(password);
            try
            {
                activeDirectoryClient.Applications.AddApplicationAsync(newApp).Wait();
                Console.WriteLine("New Application created: " + newApp.DisplayName);
            }
            catch (Exception e)
            {
                string a = e.Message.ToString();
                // Program.WriteError("\nError ceating Application: {0}", Program.ExtractErrorMessage(e));
            }

            ServicePrincipal s = new ServicePrincipal();
            s.Tags.Add("WindowsAzureActiveDirectoryIntegratedApp");
            s.AppId = newApp.AppId;
            try
            {
                activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(s).Wait();
            }
            catch (Exception e) {
                string a = e.Message.ToString();
            }

            //try
            //{
            //    activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();
            //}
            //catch (Exception e) {
            //    string mess = e.Message.ToString();
            //    string a = "";
            //}

            #region Create a User with a temp Password

            //*********************************************************************************************
            // Create a new User with a temp Password
            //*********************************************************************************************
            IUser userToBeAdded = new User();

            userToBeAdded.DisplayName       = "Sample App Demo User";
            userToBeAdded.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
            userToBeAdded.AccountEnabled    = true;
            userToBeAdded.MailNickname      = "SampleAppDemoUser";


            userToBeAdded.PasswordProfile = new PasswordProfile
            {
                Password = "******",
                ForceChangePasswordNextLogin = true
            };
            userToBeAdded.UsageLocation = "US";
            try
            {
                activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait();
                Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new user. {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            //  activeDirectoryClient.Applications.AddApplicationAsync(iApp);
            #endregion

            #region Create a new Group

            //*********************************************************************************************
            // Create a new Group
            //*********************************************************************************************
            Group californiaEmployees = new Group
            {
                DisplayName     = "California Employees" + Helper.GetRandomString(8),
                Description     = "Employees in the state of California",
                MailNickname    = "CalEmployees",
                MailEnabled     = false,
                SecurityEnabled = true
            };
            try
            {
                activeDirectoryClient.Groups.AddGroupAsync(californiaEmployees).Wait();
                Console.WriteLine("\nNew Group {0} was created", californiaEmployees.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new Group {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Search for Group using StartWith filter

            //*********************************************************************
            // Search for a group using a startsWith filter (displayName property)
            //*********************************************************************
            Group         retrievedGroup = new Group();
            string        searchString   = "California Employees";
            List <IGroup> foundGroups    = null;
            try
            {
                foundGroups = activeDirectoryClient.Groups
                              .Where(group => group.DisplayName.StartsWith(searchString))
                              .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Group {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (foundGroups != null && foundGroups.Count > 0)
            {
                retrievedGroup = foundGroups.First() as Group;
            }
            else
            {
                Console.WriteLine("Group Not Found");
            }

            #endregion

            #region Assign Member to Group

            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    retrievedGroup.Members.Add(newUser as DirectoryObject);
                    retrievedGroup.UpdateAsync().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError assigning member to group. {0} {1}",
                                      e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion


            #region Add User to Group

            //*********************************************************************************************
            // Add User to the "WA" Group
            //*********************************************************************************************
            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    retrievedGroup.Members.Add(userToBeAdded as DirectoryObject);
                    retrievedGroup.UpdateAsync().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nAdding user to group failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion


            #region Get Group members

            if (retrievedGroup.ObjectId != null)
            {
                Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + "  " + retrievedGroup.Description);

                //*********************************************************************
                // get the groups' membership -
                // Note this method retrieves ALL links in one request - please use this method with care - this
                // may return a very large number of objects
                //*********************************************************************
                IGroupFetcher retrievedGroupFetcher = retrievedGroup;
                try
                {
                    IPagedCollection <IDirectoryObject> members = retrievedGroupFetcher.Members.ExecuteAsync().Result;
                    Console.WriteLine(" Members:");
                    do
                    {
                        List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                        foreach (IDirectoryObject member in directoryObjects)
                        {
                            if (member is User)
                            {
                                User user = member as User;
                                Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                                                  user.DisplayName,
                                                  user.UserPrincipalName);
                            }
                            if (member is Group)
                            {
                                Group group = member as Group;
                                Console.WriteLine("Group DisplayName: {0}", group.DisplayName);
                            }
                            if (member is Contact)
                            {
                                Contact contact = member as Contact;
                                Console.WriteLine("Contact DisplayName: {0}", contact.DisplayName);
                            }
                        }
                        members = members.GetNextPageAsync().Result;
                    } while (members != null);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting groups' membership. {0} {1}",
                                      e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion



            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************

            Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime);
            // Console.ReadKey();
            Console.WriteLine();
            #region Search User by UPN

            // search for a single user by UPN
            searchString = "" + "@" + initialDomain.Name;
            Console.WriteLine("\n Retrieving user with UPN {0}", searchString);
            User         retrievedUser  = new User();
            List <IUser> retrievedUsers = null;
            try
            {
                retrievedUsers = activeDirectoryClient.Users
                                 .Where(user => user.UserPrincipalName.Equals(searchString))
                                 .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting new user {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            // should only find one user with the specified UPN
            if (retrievedUsers != null && retrievedUsers.Count == 1)
            {
                retrievedUser = (User)retrievedUsers.First();
            }
            else
            {
                Console.WriteLine("User not found {0}", searchString);
            }

            #endregion
            Console.WriteLine("\n {0} is a member of the following Group and Roles (IDs)", retrievedUser.DisplayName);
            IUserFetcher retrievedUserFetcher = retrievedUser;
            try
            {
                IPagedCollection <IDirectoryObject> pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync().Result;
                do
                {
                    List <IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                    foreach (IDirectoryObject directoryObject in directoryObjects)
                    {
                        if (directoryObject is Group)
                        {
                            Group group = directoryObject as Group;
                            Console.WriteLine(" Group: {0}  Description: {1}", group.DisplayName, group.Description);
                        }
                        if (directoryObject is DirectoryRole)
                        {
                            DirectoryRole role = directoryObject as DirectoryRole;
                            Console.WriteLine(" Role: {0}  Description: {1}", role.DisplayName, role.Description);
                        }
                    }
                    pagedCollection = pagedCollection.GetNextPageAsync().Result;
                } while (pagedCollection != null);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting user's groups and roles memberships. {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            Console.WriteLine("Press any key to continue....");
            Console.ReadKey();
        }
Ejemplo n.º 15
0
        private static void Main()
        {
            // record start DateTime of execution
            string currentDateTime = DateTime.Now.ToUniversalTime().ToString(CultureInfo.InvariantCulture);

            var activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsUser();

            #region TenantDetails
            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail  tenant        = null;
            Console.WriteLine("\n Retrieving Tenant Details");
            try
            {
                List <ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails
                                                   .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId))
                                                   .ExecuteAsync().Result.CurrentPage.ToList();
                if (tenantsList.Count > 0)
                {
                    tenant = tenantsList.First();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting TenantDetails {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                var initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }
            #endregion



            #region Create a random users
            try
            {
                var batchSize = 0;
                foreach (var randomUser in RandomUserGeneratorClient.GenerateRandomUsers(defaultDomain.Name, 100))
                {
                    Console.WriteLine("\nCreating creating new user: "******"\nError creating new user {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            #endregion

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************
            Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime);
            Console.ReadKey();
        }
Ejemplo n.º 16
0
        static void Main()
        {
            // get OAuth token using Client Credentials
            string tenantName = "GraphDir1.onMicrosoft.com";
            string authString = "https://login.windows.net/" + tenantName;

            AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

            // Config for OAuth client credentials
            string           clientId     = "118473c2-7619-46e3-a8e4-6da8d5f56e12";
            string           clientSecret = "hOrJ0r0TZ4GQ3obp+vk3FZ7JBVP+TX353kNo6QwNq7Q=";
            ClientCredential clientCred   = new ClientCredential(clientId, clientSecret);
            string           resource     = "https://graph.windows.net";
            string           token;

            try
            {
                AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resource, clientCred);
                token = authenticationResult.AccessToken;
            }

            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }


            // record start DateTime of execution
            string CurrentDateTime = DateTime.Now.ToUniversalTime().ToString();

            //*********************************************************************
            // setup Graph connection
            //*********************************************************************
            Guid          ClientRequestId = Guid.NewGuid();
            GraphSettings graphSettings   = new GraphSettings();

            graphSettings.ApiVersion      = "2013-11-08";
            graphSettings.GraphDomainName = "graph.windows.net";
            GraphConnection graphConnection = new GraphConnection(token, ClientRequestId, graphSettings);
            VerifiedDomain  initialDomain   = new VerifiedDomain();
            VerifiedDomain  defaultDomain   = new VerifiedDomain();

            //*********************************************************************
            // Get Tenant Details
            // Note: update the string tenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your tenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            string      tenantId = "4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34";
            GraphObject tenant   = graphConnection.Get(typeof(TenantDetail), tenantId);

            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => x.Default.HasValue && x.Default.Value);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }
            //*********************************************************************
            // Demonstrate Getting a list of Users with paging (get 4 users), sort by displayName
            //*********************************************************************
            Console.WriteLine("\n Retrieving Users");

            FilterGenerator userFilter = new FilterGenerator();

            userFilter.Top             = 4;
            userFilter.OrderByProperty = GraphProperty.DisplayName;
            PagedResults <User> users = graphConnection.List <User>(null, userFilter);

            foreach (User user in users.Results)
            {
                Console.WriteLine("UserObjectId: {0}  UPN: {1}", user.ObjectId, user.UserPrincipalName);
            }

            // if there are more users to retrieve, get the rest of the users, and specify maximum page size 999
            do
            {
                userFilter.Top = 999;
                if (users.PageToken != null)
                {
                    users = graphConnection.List <User>(users.PageToken, userFilter);
                    Console.WriteLine("\n Next page of results");
                }

                foreach (User user in users.Results)
                {
                    Console.WriteLine("DisplayName: {0}  UPN: {1}", user.DisplayName, user.UserPrincipalName);
                }
            } while (users.PageToken != null);

            // search for a single user by UPN
            string          searchString     = "adam@" + initialDomain.Name;
            FilterGenerator filter           = new FilterGenerator();
            Expression      filterExpression = ExpressionHelper.CreateEqualsExpression(typeof(User), GraphProperty.UserPrincipalName, searchString);

            filter.QueryFilter = filterExpression;


            User retrievedUser = new User();
            PagedResults <User> pagedUserResults = graphConnection.List <User>(null, filter);

            // should only find one user with the specified UPN
            if (pagedUserResults.Results.Count == 1)
            {
                retrievedUser = pagedUserResults.Results[0] as User;
            }
            else
            {
                Console.WriteLine("User not found {0}", searchString);
            }

            if (retrievedUser.UserPrincipalName != null)
            {
                Console.WriteLine("\n Found User: "******"  UPN: " + retrievedUser.UserPrincipalName);

                // get the user's Manager
                int count = 0;
                PagedResults <GraphObject> managers = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.Manager, null);
                foreach (GraphObject managerObject in managers.Results)
                {
                    if (managerObject.ODataTypeName.Contains("User"))
                    {
                        User manager = (User)managers.Results[count];
                        Console.WriteLine(" Manager: {0}  UPN: {1}", manager.DisplayName, manager.UserPrincipalName);
                    }
                    count++;
                }
                //*********************************************************************
                // get the user's Direct Reports
                //*********************************************************************
                int top = 99;
                PagedResults <GraphObject> directReportObjects = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.DirectReports, null, top);
                foreach (GraphObject graphObject in directReportObjects.Results)
                {
                    if (graphObject.ODataTypeName.Contains("User"))
                    {
                        User User = (User)graphObject;
                        Console.WriteLine(" DirectReport {0}: {1}  UPN: {2}", User.ObjectType, User.DisplayName, User.UserPrincipalName);
                    }

                    if (graphObject.ODataTypeName.Contains("Contact"))
                    {
                        Contact Contact = (Contact)graphObject;
                        Console.WriteLine(" DirectReport {0}: {1}  Mail: {2} ", Contact.ObjectType, Contact.DisplayName, Contact.Mail);
                    }
                }
                //*********************************************************************
                // get a list of Group IDs that the user is a member of
                //*********************************************************************
                Console.WriteLine("\n {0} is a member of the following Groups (IDs)", retrievedUser.DisplayName);
                bool           securityGroupsOnly   = false;
                IList <string> usersGroupMembership = graphConnection.GetMemberGroups(retrievedUser, securityGroupsOnly);
                foreach (String groupId in usersGroupMembership)
                {
                    Console.WriteLine("Member of Group ID: " + groupId);
                }


                //*********************************************************************
                // get the User's Group and Role membership, getting the complete set of objects
                //*********************************************************************
                PagedResults <GraphObject> memberOfObjects = graphConnection.GetLinkedObjects(retrievedUser, LinkProperty.MemberOf, null, top);
                foreach (GraphObject graphObject in memberOfObjects.Results)
                {
                    if (graphObject.ODataTypeName.Contains("Group"))
                    {
                        Group Group = (Group)graphObject;
                        Console.WriteLine(" Group: {0}  Description: {1}", Group.DisplayName, Group.Description);
                    }

                    if (graphObject.ODataTypeName.Contains("Role"))
                    {
                        Role Role = (Role)graphObject;
                        Console.WriteLine(" Role: {0}  Description: {1}", Role.DisplayName, Role.Description);
                    }
                }
            }
            //*********************************************************************
            // People picker
            // Search for a user using text string "ad" match against userPrincipalName, proxyAddresses, displayName, giveName, surname
            //*********************************************************************
            searchString = "ad";
            Console.WriteLine("\nSearching for any user with string {0} in UPN,ProxyAddresses,DisplayName,First or Last Name", searchString);

            FilterGenerator userMatchFilter = new FilterGenerator();

            userMatchFilter.Top = 19;
            Expression firstExpression  = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.UserPrincipalName, searchString);
            Expression secondExpression = ExpressionHelper.CreateAnyExpression(typeof(User), GraphProperty.ProxyAddresses, "smtp:" + searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(firstExpression, secondExpression, ExpressionType.Or);

            Expression thirdExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.DisplayName, searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, thirdExpression, ExpressionType.Or);

            Expression fourthExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.GivenName, searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, fourthExpression, ExpressionType.Or);

            Expression fifthExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.Surname, searchString);

            userMatchFilter.QueryFilter = ExpressionHelper.JoinExpressions(userMatchFilter.QueryFilter, fifthExpression, ExpressionType.Or);

            PagedResults <User> serachResults = graphConnection.List <User>(null, userMatchFilter);

            if (serachResults.Results.Count > 0)
            {
                foreach (User User in serachResults.Results)
                {
                    Console.WriteLine("User DisplayName: {0}  UPN: {1}", User.DisplayName, User.UserPrincipalName);
                }
            }
            else
            {
                Console.WriteLine("User not found");
            }

            //*********************************************************************
            // Search for a group using a startsWith filter (displayName property)
            //*********************************************************************
            Group retrievedGroup = new Group();

            searchString       = "Wash";
            filter.QueryFilter = ExpressionHelper.CreateStartsWithExpression(typeof(Group), GraphProperty.DisplayName, searchString);
            filter.Top         = 99;

            PagedResults <Group> pagedGroupResults = graphConnection.List <Group>(null, filter);

            if (pagedGroupResults.Results.Count > 0)
            {
                retrievedGroup = pagedGroupResults.Results[0] as Group;
            }
            else
            {
                Console.WriteLine("Group Not Found");
            }

            if (retrievedGroup.ObjectId != null)
            {
                Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + "  " + retrievedGroup.Description);

                //*********************************************************************
                // get the groups' membership using GetAllDirectLinks -
                // Note this method retrieves ALL links in one request - please use this method with care - this
                // may return a very large number of objects
                //*********************************************************************

                GraphObject graphObj = (GraphObject)retrievedGroup;

                IList <GraphObject> members = graphConnection.GetAllDirectLinks(graphObj, LinkProperty.Members);
                if (members.Count > 0)
                {
                    Console.WriteLine(" Members:");
                    foreach (GraphObject graphObject in members)
                    {
                        if (graphObject.ODataTypeName.Contains("User"))
                        {
                            User User = (User)graphObject;
                            Console.WriteLine("User DisplayName: {0}  UPN: {1}", User.DisplayName, User.UserPrincipalName);
                        }

                        if (graphObject.ODataTypeName.Contains("Group"))
                        {
                            Group Group = (Group)graphObject;
                            Console.WriteLine("Group DisplayName: {0}", Group.DisplayName);
                        }

                        if (graphObject.ODataTypeName.Contains("Contact"))
                        {
                            Contact Contact = (Contact)graphObject;
                            Console.WriteLine("Contact DisplayName: {0}", Contact.DisplayName);
                        }
                    }
                }
            }
            //*********************************************************************
            // Search for a Role by displayName
            //*********************************************************************
            searchString       = "Company Administrator";
            filter.QueryFilter = ExpressionHelper.CreateStartsWithExpression(typeof(Role), GraphProperty.DisplayName, searchString);
            PagedResults <Role> pagedRoleResults = graphConnection.List <Role>(null, null);

            if (pagedRoleResults.Results.Count > 0)
            {
                foreach (GraphObject graphObject in pagedRoleResults.Results)
                {
                    Role role = graphObject as Role;
                    if (role.DisplayName == searchString.Trim())
                    {
                        Console.WriteLine("\n Found Role: {0} {1} {2} ", role.DisplayName, role.Description, role.ObjectId);
                    }
                }
            }
            else
            {
                Console.WriteLine("Role Not Found {0}", searchString);
            }

            //*********************************************************************
            // get the Service Principals
            //*********************************************************************
            filter.Top         = 999;
            filter.QueryFilter = null;
            PagedResults <ServicePrincipal> servicePrincipals = new PagedResults <ServicePrincipal>();

            do
            {
                servicePrincipals = graphConnection.List <ServicePrincipal>(servicePrincipals.PageToken, filter);
                if (servicePrincipals != null)
                {
                    foreach (ServicePrincipal servicePrincipal in servicePrincipals.Results)
                    {
                        Console.WriteLine("Service Principal AppId: {0}  Name: {1}", servicePrincipal.AppId, servicePrincipal.DisplayName);
                    }
                }
            } while (servicePrincipals.PageToken != null);

            //*********************************************************************
            // get the  Application objects
            //*********************************************************************
            filter.Top = 999;
            PagedResults <Application> applications = new PagedResults <Application>();

            do
            {
                applications = graphConnection.List <Application>(applications.PageToken, filter);
                if (applications != null)
                {
                    foreach (Application application in applications.Results)
                    {
                        Console.WriteLine("Application AppId: {0}  Name: {1}", application.AppId, application.DisplayName);
                    }
                }
            }while (applications.PageToken != null);

            string targetAppId = applications.Results[0].ObjectId;


            //********************************************************************************************
            //  We'll now switch to Authenticating using OAuth Authorization Code Grant
            //  which includes user Authentication/Delegation
            //*********************************************************************************************
            var    redirectUri                   = new Uri("https://localhost");
            string clientIdForUserAuthn          = "66133929-66a4-4edc-aaee-13b04b03207d";
            AuthenticationResult userAuthnResult = null;

            try
            {
                userAuthnResult = authenticationContext.AcquireToken(resource, clientIdForUserAuthn, redirectUri, PromptBehavior.Always);
                token           = userAuthnResult.AccessToken;
                Console.WriteLine("\n Welcome " + userAuthnResult.UserInfo.GivenName + " " + userAuthnResult.UserInfo.FamilyName);
            }
            catch (AuthenticationException ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += "InnerException : " + ex.InnerException.Message;
                }
                Console.WriteLine(message);
                Console.ReadKey();
                return;
            }

            // re-establish Graph connection using the new token
            graphConnection = new GraphConnection(token, ClientRequestId, graphSettings);

            //*********************************************************************************************
            // Create a new User with a temp password
            //*********************************************************************************************
            User userToBeAdded = new User();

            userToBeAdded.DisplayName              = "Sample App Demo User";
            userToBeAdded.UserPrincipalName        = "SampleAppDemoUser@" + defaultDomain.Name;
            userToBeAdded.AccountEnabled           = true;
            userToBeAdded.MailNickname             = "SampleAppDemoUser";
            userToBeAdded.PasswordProfile          = new PasswordProfile();
            userToBeAdded.PasswordProfile.Password = "******";
            userToBeAdded.PasswordProfile.ForceChangePasswordNextLogin = true;
            userToBeAdded.UsageLocation = "US";
            User newlyCreatedUser = new User();

            try
            {
                newlyCreatedUser = graphConnection.Add <User>(userToBeAdded);
                Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName);
            }
            catch (GraphException graphException)
            {
                Console.WriteLine("\nError creating new user {0} {1}", graphException.Code, graphException.Message);
            }

            //*********************************************************************************************
            // update the newly created user's Password, PasswordPolicies and City
            //*********************************************************************************************
            if (newlyCreatedUser.ObjectId != null)
            {
                string userObjectId = newlyCreatedUser.ObjectId;

                // update User's city and reset their User's password
                User updateUser = graphConnection.Get <User>(userObjectId);
                updateUser.City = "Seattle";
                PasswordProfile passwordProfile = new PasswordProfile();
                passwordProfile.Password = "******";
                passwordProfile.ForceChangePasswordNextLogin = false;
                updateUser.PasswordProfile  = passwordProfile;
                updateUser.PasswordPolicies = "DisablePasswordExpiration, DisableStrongPassword";
                try
                {
                    graphConnection.Update(updateUser);
                    Console.WriteLine("\nUser {0} was updated", updateUser.DisplayName);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("\nError Updating the user {0} {1}", graphException.Code, graphException.Message);
                }


                //*********************************************************************************************
                // Add, then retrieve a thumbnailPhoto for the newly created user
                //*********************************************************************************************
                Bitmap thumbnailPhoto = new Bitmap(20, 20);
                thumbnailPhoto.SetPixel(5, 5, Color.Beige);
                thumbnailPhoto.SetPixel(5, 6, Color.Beige);
                thumbnailPhoto.SetPixel(6, 5, Color.Beige);
                thumbnailPhoto.SetPixel(6, 6, Color.Beige);

                using (MemoryStream ms = new MemoryStream())
                {
                    thumbnailPhoto.Save(ms, ImageFormat.Jpeg);
                    graphConnection.SetStreamProperty(newlyCreatedUser, GraphProperty.ThumbnailPhoto, ms, "image/jpeg");
                    //  graphConnection.SetStreamProperty(newlyCreatedUser, "thumbnailPhoto", ms, "image/jpeg");
                }

                using (Stream ms = graphConnection.GetStreamProperty(newlyCreatedUser, GraphProperty.ThumbnailPhoto, "image/jpeg"))
                {
                    Image jpegImage = Image.FromStream(ms);
                }



                //*********************************************************************************************
                // User License Assignment - assign EnterprisePack license to new user, and disable SharePoint service
                //   first get a list of Tenant's subscriptions and find the "Enterprisepack" one
                //   Enterprise Pack includes service Plans for ExchangeOnline, SharePointOnline and LyncOnline
                //   validate that Subscription is Enabled and there are enough units left to assign to users
                //*********************************************************************************************
                PagedResults <SubscribedSku> skus = graphConnection.List <SubscribedSku>(null, null);
                foreach (SubscribedSku sku in skus.Results)
                {
                    if (sku.SkuPartNumber == "ENTERPRISEPACK")
                    {
                        if ((sku.PrepaidUnits.Enabled.Value > sku.ConsumedUnits) && (sku.CapabilityStatus == "Enabled"))
                        {
                            // create addLicense object and assign the Enterprise Sku GUID to the skuId
                            //
                            AssignedLicense addLicense = new AssignedLicense();
                            addLicense.SkuId = sku.SkuId.Value;

                            // find plan id of SharePoint Service Plan
                            foreach (ServicePlanInfo servicePlan in sku.ServicePlans)
                            {
                                if (servicePlan.ServicePlanName.Contains("SHAREPOINT"))
                                {
                                    addLicense.DisabledPlans.Add(servicePlan.ServicePlanId.Value);
                                    break;
                                }
                            }

                            IList <AssignedLicense> licensesToAdd    = new AssignedLicense[] { addLicense };
                            IList <Guid>            licensesToRemove = new Guid[] { };

                            // attempt to assign the license object to the new user
                            try
                            {
                                graphConnection.AssignLicense(newlyCreatedUser, licensesToAdd, licensesToRemove);
                                Console.WriteLine("\n User {0} was assigned license {1}", newlyCreatedUser.DisplayName, addLicense.SkuId);
                            }
                            catch (GraphException graphException)
                            {
                                Console.WriteLine("\nLicense assingment failed {0} {1}", graphException.Code, graphException.Message);
                            }
                        }
                    }
                }

                //*********************************************************************************************
                // Add User to the "WA" Group
                //*********************************************************************************************
                if (retrievedGroup.ObjectId != null)
                {
                    try
                    {
                        graphConnection.AddLink(retrievedGroup, newlyCreatedUser, LinkProperty.Members);
                        Console.WriteLine("\nUser {0} was added to Group {1}", newlyCreatedUser.DisplayName, retrievedGroup.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("\nAdding user to group failed {0} {1}", graphException.Code, graphException.Message);
                    }
                }

                //*********************************************************************************************
                // Create a new Group
                //*********************************************************************************************
                Group CaliforniaEmployees = new Group();
                CaliforniaEmployees.DisplayName     = "California Employees";
                CaliforniaEmployees.Description     = "Employees in the state of California";
                CaliforniaEmployees.MailNickname    = "CalEmployees";
                CaliforniaEmployees.MailEnabled     = false;
                CaliforniaEmployees.SecurityEnabled = true;
                Group newGroup = null;
                try
                {
                    newGroup = graphConnection.Add <Group>(CaliforniaEmployees);
                    Console.WriteLine("\nNew Group {0} was created", newGroup.DisplayName);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("\nError creating new Group {0} {1}", graphException.Code, graphException.Message);
                }

                //*********************************************************************************************
                // Add the new User member to the new Group
                //*********************************************************************************************
                if (newGroup.ObjectId != null)
                {
                    try
                    {
                        graphConnection.AddLink(newGroup, newlyCreatedUser, LinkProperty.Members);
                        Console.WriteLine("\nUser {0} was added to Group {1}", newlyCreatedUser.DisplayName, newGroup.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("\nAdding user to group failed {0} {1}", graphException.Code, graphException.Message);
                    }
                }


                //*********************************************************************************************
                // Delete the user that we just created
                //*********************************************************************************************
                if (newlyCreatedUser.ObjectId != null)
                {
                    try
                    {
                        graphConnection.Delete(newlyCreatedUser);
                        Console.WriteLine("\nUser {0} was deleted", newlyCreatedUser.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Deleting User failed {0} {1}", graphException.Code, graphException.Message);
                    }
                }

                //*********************************************************************************************
                // Delete the Group that we just created
                //*********************************************************************************************
                if (newGroup.ObjectId != null)
                {
                    try
                    {
                        graphConnection.Delete(newGroup);
                        Console.WriteLine("\nGroup {0} was deleted", newGroup.DisplayName);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Deleting Group failed: {0} {1}", graphException.Code, graphException.Message);
                    }
                }
            }

            //*********************************************************************************************
            // Get a list of Mobile Devices from tenant
            //*********************************************************************************************
            Console.WriteLine("\nGetting Devices");
            FilterGenerator deviceFilter = new FilterGenerator();

            deviceFilter.Top = 999;
            PagedResults <Device> devices = graphConnection.List <Device>(null, deviceFilter);

            foreach (Device device in devices.Results)
            {
                if (device.ObjectId != null)
                {
                    Console.WriteLine("Device ID: {0}, Type: {1}", device.DeviceId, device.DeviceOSType);
                    foreach (GraphObject owner in device.RegisteredOwners)
                    {
                        Console.WriteLine("Device Owner ID: " + owner.ObjectId);
                    }
                }
            }

            //*********************************************************************************************
            // Create a new Application object
            //*********************************************************************************************
            Application appObject = new Application();

            appObject.DisplayName = "Test-Demo App";
            appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid().ToString());
            appObject.ReplyUrls.Add("https://localhost/demo");

            // created Keycredential object for the new App object
            KeyCredential KeyCredential = new KeyCredential();

            KeyCredential.StartDate = DateTime.UtcNow;
            KeyCredential.EndDate   = DateTime.UtcNow.AddYears(1);
            KeyCredential.Type      = "Symmetric";
            KeyCredential.Value     = Convert.FromBase64String("g/TMLuxgzurjQ0Sal9wFEzpaX/sI0vBP3IBUE/H/NS4=");
            KeyCredential.Usage     = "Verify";
            appObject.KeyCredentials.Add(KeyCredential);

            GraphObject newApp = null;

            try
            {
                newApp = graphConnection.Add(appObject);
                Console.WriteLine("New Application created: " + newApp.ObjectId);
            }
            catch (GraphException graphException)
            {
                Console.WriteLine("Application Creation execption: {0} {1}", graphException.Code, graphException.Message);
            }

            // Get the application object that was just created
            if (newApp != null)
            {
                GraphObject app          = graphConnection.Get(typeof(Application), newApp.ObjectId);
                Application retrievedApp = (Application)app;

                //*********************************************************************************************
                // create a new Service principal
                //*********************************************************************************************
                ServicePrincipal newServicePrincpal = new ServicePrincipal();
                newServicePrincpal.DisplayName    = "Test-Demo App";
                newServicePrincpal.AccountEnabled = true;
                newServicePrincpal.AppId          = retrievedApp.AppId;

                GraphObject newSP = null;
                try
                {
                    newSP = graphConnection.Add <ServicePrincipal>(newServicePrincpal);
                    //    newSP = graphConnection.Add(newServicePrincpal);
                    Console.WriteLine("New Service Principal created: " + newSP.ObjectId);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("Service Principal Creation execption: {0} {1}", graphException.Code, graphException.Message);
                }


                //*********************************************************************************************
                // get all Permission Objects
                //*********************************************************************************************
                Console.WriteLine("\n Getting Permissions");
                filter.Top = 999;
                PagedResults <Permission> permissions = new PagedResults <Permission>();
                do
                {
                    try
                    {
                        permissions = graphConnection.List <Permission>(permissions.PageToken, filter);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Error: {0} {1}", graphException.Code, graphException.Message);
                        break;
                    }

                    foreach (Permission permission in permissions.Results)
                    {
                        Console.WriteLine("Permission: {0}  Name: {1}", permission.ClientId, permission.Scope);
                    }
                } while (permissions.PageToken != null);

                //*********************************************************************************************
                // Create new permission object
                //*********************************************************************************************
                Permission permissionObject = new Permission();
                permissionObject.ConsentType = "AllPrincipals";
                permissionObject.Scope       = "user_impersonation";
                permissionObject.StartTime   = DateTime.Now;
                permissionObject.ExpiryTime  = (DateTime.Now).AddMonths(12);

                // resourceId is objectId of the resource, in this case objectId of AzureAd (Graph API)
                permissionObject.ResourceId = "dbf73c3e-e80b-495b-a82f-2f772bb0a417";

                //ClientId = objectId of servicePrincipal
                permissionObject.ClientId = newSP.ObjectId;

                GraphObject newPermission = null;
                try
                {
                    newPermission = graphConnection.Add(permissionObject);
                    Console.WriteLine("New Permission object created: " + newPermission.ObjectId);
                }
                catch (GraphException graphException)
                {
                    Console.WriteLine("Permission Creation exception: {0} {1}", graphException.Code, graphException.Message);
                }

                //*********************************************************************************************
                // Delete Application Objects
                //*********************************************************************************************

                if (retrievedApp.ObjectId != null)
                {
                    try
                    {
                        graphConnection.Delete(retrievedApp);
                        Console.WriteLine("Deleting Application object: " + retrievedApp.ObjectId);
                    }
                    catch (GraphException graphException)
                    {
                        Console.WriteLine("Application Deletion execption: {0} {1}", graphException.Code, graphException.Message);
                    }
                }
            }

            //*********************************************************************************************
            // Show Batching with 3 operators.  Note: up to 5 operations can be in a batch
            //*********************************************************************************************
            // get users
            Console.WriteLine("\n Executing Batch Request");
            BatchRequestItem firstItem = new BatchRequestItem(
                "GET",
                false,
                Utils.GetListUri <User>(graphConnection, null, new FilterGenerator()),
                null,
                String.Empty);

            // get members of a Group
            Uri membersUri = Utils.GetRequestUri <Group>(graphConnection, retrievedGroup.ObjectId, "members");

            BatchRequestItem secondItem = new BatchRequestItem(
                "GET",
                false,
                new Uri(membersUri.ToString()),
                null,
                String.Empty);

            // update an existing group's Description property

            retrievedGroup.Description = "New Employees in Washington State";

            BatchRequestItem thirdItem = new BatchRequestItem(
                "Patch",
                true,
                Utils.GetRequestUri <Group>(graphConnection, retrievedGroup.ObjectId),
                null,
                retrievedGroup.ToJson(true));

            // Execute the batch requst
            IList <BatchRequestItem>  batchRequest   = new BatchRequestItem[] { firstItem, secondItem, thirdItem };
            IList <BatchResponseItem> batchResponses = graphConnection.ExecuteBatch(batchRequest);

            int responseCount = 0;

            foreach (BatchResponseItem responseItem in batchResponses)
            {
                if (responseItem.Failed)
                {
                    Console.WriteLine("Failed: {0} {1}",
                                      responseItem.Exception.Code,
                                      responseItem.Exception.ErrorMessage);
                }
                else
                {
                    Console.WriteLine("Batch Item Result {0} succeeded {1}",
                                      responseCount++,
                                      !responseItem.Failed);
                }
            }

            // this next section shows how to access the signed-in user's mailbox.
            // First we get a new token for Office365 Exchange Online Resource
            // using the multi-resource refresh token tha was included when the previoius
            // token was acquired.
            // We can now request a new token for Office365 Exchange Online.
            //
            string office365Emailresource = "https://outlook.office365.com/";
            string office365Token         = null;

            if (userAuthnResult.IsMultipleResourceRefreshToken)
            {
                userAuthnResult = authenticationContext.AcquireTokenByRefreshToken(userAuthnResult.RefreshToken, clientIdForUserAuthn, office365Emailresource);
                office365Token  = userAuthnResult.AccessToken;

                //
                // Call the Office365 API and retrieve the top item from the user's mailbox.
                //
                string     requestUrl = "https://outlook.office365.com/EWS/OData/Me/Inbox/Messages?$top=1";
                WebRequest getMailboxRequest;
                getMailboxRequest = WebRequest.Create(requestUrl);
                getMailboxRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + office365Token);
                Console.WriteLine("\n Getting the User's Mailbox Contents \n");

                //
                // Read the contents of the user's mailbox, and display to the console.
                //
                Stream objStream = null;
                try
                {
                    objStream = getMailboxRequest.GetResponse().GetResponseStream();
                    StreamReader objReader = new StreamReader(objStream);

                    string sLine = "";
                    int    i     = 0;

                    while (sLine != null)
                    {
                        i++;
                        sLine = objReader.ReadLine();
                        if (sLine != null)
                        {
                            Console.WriteLine("{0}:{1}", i, sLine);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\n Error Getting User's Mailbox: {0} \n", ex.Message);
                }
            }

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************
            Console.WriteLine("\nCompleted at {0} \n ClientRequestId: {1}", CurrentDateTime, ClientRequestId);
            Console.ReadKey();
            return;
        }
Ejemplo n.º 17
0
        public async Task <TenantSettingsEditDto> GetAllSettings(int?tenantId = null)
        {
            int?countryRegionId;
            CountryRegionDto countryRegionDto;
            CountryDto       countryDto;
            int num;
            TenantDetailEditDto details;

            num = (tenantId.HasValue ? tenantId.Value : this.AbpSession.GetTenantId());
            int num1 = num;
            TenantSettingsEditDto tenantSettingsEditDto  = new TenantSettingsEditDto();
            TenantSettingsEditDto tenantSettingsEditDto1 = tenantSettingsEditDto;
            TenantUserManagementSettingsEditDto tenantUserManagementSettingsEditDto  = new TenantUserManagementSettingsEditDto();
            TenantUserManagementSettingsEditDto tenantUserManagementSettingsEditDto1 = tenantUserManagementSettingsEditDto;
            bool settingValueAsync = await this.SettingManager.GetSettingValueAsync <bool>("App.UserManagement.AllowSelfRegistration");

            tenantUserManagementSettingsEditDto1.AllowSelfRegistration = settingValueAsync;
            TenantUserManagementSettingsEditDto tenantUserManagementSettingsEditDto2 = tenantUserManagementSettingsEditDto;
            bool flag = await this.SettingManager.GetSettingValueAsync <bool>("App.UserManagement.IsNewRegisteredUserActiveByDefault");

            tenantUserManagementSettingsEditDto2.IsNewRegisteredUserActiveByDefault = flag;
            TenantUserManagementSettingsEditDto tenantUserManagementSettingsEditDto3 = tenantUserManagementSettingsEditDto;
            bool settingValueAsync1 = await this.SettingManager.GetSettingValueAsync <bool>("Abp.Zero.UserManagement.IsEmailConfirmationRequiredForLogin");

            tenantUserManagementSettingsEditDto3.IsEmailConfirmationRequiredForLogin = settingValueAsync1;
            TenantUserManagementSettingsEditDto tenantUserManagementSettingsEditDto4 = tenantUserManagementSettingsEditDto;
            bool flag1 = await this.SettingManager.GetSettingValueAsync <bool>("App.UserManagement.UseCaptchaOnRegistration");

            tenantUserManagementSettingsEditDto4.UseCaptchaOnRegistration            = flag1;
            tenantUserManagementSettingsEditDto.RequireOnePhoneNumberForRegistration = this.SettingManager.GetSettingValue <bool>("App.UserManagement.RequireOnePhoneNumberForRegistration");
            tenantUserManagementSettingsEditDto.SendEmailAfterRegistration           = this.SettingManager.GetSettingValue <bool>("App.UserManagement.SendEmailAfterRegistration");
            tenantUserManagementSettingsEditDto.SendEmailAfterRegistrationMessage    = this.SettingManager.GetSettingValue("App.UserManagement.SendEmailAfterRegistrationMessage");
            TenantUserManagementSettingsEditDto tenantUserManagementSettingsEditDto5 = tenantUserManagementSettingsEditDto;
            bool settingValueAsync2 = await this.SettingManager.GetSettingValueAsync <bool>("App.UserManagment.EnableEmergencyDeliveryFees");

            tenantUserManagementSettingsEditDto5.EnableEmergencyDeliveryFees = settingValueAsync2;
            tenantSettingsEditDto1.UserManagement = tenantUserManagementSettingsEditDto;
            TenantSettingsEditDto tenantHoursEditDto = tenantSettingsEditDto;

            tenantSettingsEditDto1 = null;
            tenantUserManagementSettingsEditDto1 = null;
            tenantUserManagementSettingsEditDto2 = null;
            tenantUserManagementSettingsEditDto3 = null;
            tenantUserManagementSettingsEditDto4 = null;
            tenantUserManagementSettingsEditDto5 = null;
            tenantUserManagementSettingsEditDto  = null;
            tenantSettingsEditDto = null;
            Tenant currentTenantById = this.GetCurrentTenantById(num1);
            IRepository <TenantDetail, long> repository = this._tenantDetailRepository;
            TenantDetail tenantDetail = await repository.FirstOrDefaultAsync((TenantDetail m) => m.TenantId == currentTenantById.Id);

            TenantDetail tenantDetail1 = tenantDetail;

            if (tenantDetail1 == null)
            {
                TenantSettingsEditDto tenantSettingsEditDto2 = tenantHoursEditDto;
                TenantDetailEditDto   tenantDetailEditDto    = new TenantDetailEditDto()
                {
                    TenantId          = currentTenantById.Id,
                    CountryRegion     = new CountryRegionDto(),
                    MailCountryRegion = new CountryRegionDto(),
                    Country           = new CountryDto(),
                    MailCountry       = new CountryDto()
                };
                tenantSettingsEditDto2.Details = tenantDetailEditDto;
            }
            else
            {
                tenantHoursEditDto.Details = tenantDetail1.MapTo <TenantDetailEditDto>();
                if (!tenantHoursEditDto.Details.CountryRegionId.HasValue)
                {
                    tenantHoursEditDto.Details.CountryRegion = new CountryRegionDto();
                }
                else
                {
                    details = tenantHoursEditDto.Details;
                    IRepository <CountryRegion> repository1 = this._countryRegionRepository;
                    countryRegionId = tenantHoursEditDto.Details.CountryRegionId;
                    CountryRegion async = await repository1.GetAsync(countryRegionId.Value);

                    countryRegionDto      = async.MapTo <CountryRegionDto>();
                    details.CountryRegion = countryRegionDto;
                    details = null;
                }
                if (tenantHoursEditDto.Details.CountryId <= 0)
                {
                    tenantHoursEditDto.Details.Country = new CountryDto();
                }
                else
                {
                    details = tenantHoursEditDto.Details;
                    Country country = await this._countryRepository.GetAsync(tenantHoursEditDto.Details.CountryId);

                    countryDto      = country.MapTo <CountryDto>();
                    details.Country = countryDto;
                    details         = null;
                }
                if (!tenantHoursEditDto.Details.MailCountryRegionId.HasValue)
                {
                    tenantHoursEditDto.Details.MailCountryRegion = new CountryRegionDto();
                }
                else
                {
                    details = tenantHoursEditDto.Details;
                    IRepository <CountryRegion> repository2 = this._countryRegionRepository;
                    countryRegionId = tenantHoursEditDto.Details.MailCountryRegionId;
                    CountryRegion countryRegion = await repository2.GetAsync(countryRegionId.Value);

                    countryRegionDto          = countryRegion.MapTo <CountryRegionDto>();
                    details.MailCountryRegion = countryRegionDto;
                    details = null;
                }
                if (tenantHoursEditDto.Details.MailCountryId <= 0)
                {
                    tenantHoursEditDto.Details.MailCountry = new CountryDto();
                }
                else
                {
                    details = tenantHoursEditDto.Details;
                    Country async1 = await this._countryRepository.GetAsync(tenantHoursEditDto.Details.MailCountryId);

                    countryDto          = async1.MapTo <CountryDto>();
                    details.MailCountry = countryDto;
                    details             = null;
                }
            }
            IRepository <TenantHour, long> repository3 = this._tenantHoursRepository;
            TenantHour tenantHour = await repository3.FirstOrDefaultAsync((TenantHour m) => m.TenantId == currentTenantById.Id);

            TenantHour tenantHour1 = tenantHour;

            if (tenantHour1 == null)
            {
                tenantHoursEditDto.Hours = new TenantHoursEditDto()
                {
                    TenantId = currentTenantById.Id
                };
            }
            else
            {
                tenantHoursEditDto.Hours = tenantHour1.MapTo <TenantHoursEditDto>();
            }
            IRepository <TenantCustomerService, long> repository4 = this._tenantCustomerServicesRepository;
            TenantCustomerService tenantCustomerService           = await repository4.FirstOrDefaultAsync((TenantCustomerService m) => m.TenantId == currentTenantById.Id);

            TenantCustomerService tenantCustomerService1 = tenantCustomerService;

            if (tenantCustomerService1 == null)
            {
                tenantHoursEditDto.CustomerService = new TenantCustomerServiceEditDto()
                {
                    TenantId = currentTenantById.Id
                };
            }
            else
            {
                tenantHoursEditDto.CustomerService = tenantCustomerService1.MapTo <TenantCustomerServiceEditDto>();
            }
            IRepository <TenantNotifications, long> repository5 = this._tenantNotificationsRepository;
            TenantNotifications tenantNotification = await repository5.FirstOrDefaultAsync((TenantNotifications m) => m.TenantId == currentTenantById.Id);

            TenantNotifications tenantNotification1 = tenantNotification;

            if (tenantNotification1 == null)
            {
                tenantHoursEditDto.Notifications = new TenantNotificationsEditDto()
                {
                    TenantId = currentTenantById.Id
                };
            }
            else
            {
                tenantHoursEditDto.Notifications = tenantNotification1.MapTo <TenantNotificationsEditDto>();
            }
            IRepository <TenantPaymentSettings, long> repository6 = this._tenantPaymentSettingsRepository;
            TenantPaymentSettings tenantPaymentSetting            = await repository6.FirstOrDefaultAsync((TenantPaymentSettings m) => m.TenantId == currentTenantById.Id);

            TenantPaymentSettings tenantPaymentSetting1 = tenantPaymentSetting;

            if (tenantPaymentSetting1 == null)
            {
                tenantHoursEditDto.PaymentSettings = new TenantPaymentSettingsEditDto()
                {
                    TenantId = currentTenantById.Id
                };
            }
            else
            {
                tenantHoursEditDto.PaymentSettings = tenantPaymentSetting1.MapTo <TenantPaymentSettingsEditDto>();
            }
            IRepository <TenantPaymentGatewaySettings, long> repository7 = this._tenantPaymentGatewaySettingsRepository;
            TenantPaymentGatewaySettings tenantPaymentGatewaySetting     = await repository7.FirstOrDefaultAsync((TenantPaymentGatewaySettings m) => m.TenantId == currentTenantById.Id);

            TenantPaymentGatewaySettings tenantPaymentGatewaySetting1 = tenantPaymentGatewaySetting;

            if (tenantPaymentGatewaySetting1 == null)
            {
                tenantHoursEditDto.PaymentGatewaySettings = new TenantPaymentGatewaySettingsEditDto()
                {
                    TenantId = currentTenantById.Id
                };
            }
            else
            {
                tenantHoursEditDto.PaymentGatewaySettings = tenantPaymentGatewaySetting1.MapTo <TenantPaymentGatewaySettingsEditDto>();
            }
            IRepository <TenantDateTimeSettings, long> repository8 = this._tenantDateTimeSettingsRepository;
            TenantDateTimeSettings tenantDateTimeSetting           = await repository8.FirstOrDefaultAsync((TenantDateTimeSettings m) => m.TenantId == currentTenantById.Id);

            TenantDateTimeSettings tenantDateTimeSetting1 = tenantDateTimeSetting;

            if (tenantDateTimeSetting1 == null)
            {
                tenantHoursEditDto.DateTimeSettings = new TenantDateTimeSettingsEditDto()
                {
                    TenantId = currentTenantById.Id
                };
            }
            else
            {
                tenantHoursEditDto.DateTimeSettings = tenantDateTimeSetting1.MapTo <TenantDateTimeSettingsEditDto>();
            }
            tenantSettingsEditDto      = tenantHoursEditDto;
            tenantSettingsEditDto.Logo = await this.GetTenantLogo(num1);

            tenantSettingsEditDto = null;
            if (!this._multiTenancyConfig.IsEnabled)
            {
                tenantSettingsEditDto = tenantHoursEditDto;
                GeneralSettingsEditDto generalSettingsEditDto  = new GeneralSettingsEditDto();
                GeneralSettingsEditDto generalSettingsEditDto1 = generalSettingsEditDto;
                generalSettingsEditDto1.WebSiteRootAddress = await this.SettingManager.GetSettingValueAsync("App.General.WebSiteRootAddress");

                tenantSettingsEditDto.General = generalSettingsEditDto;
                tenantSettingsEditDto         = null;
                generalSettingsEditDto1       = null;
                generalSettingsEditDto        = null;
                tenantSettingsEditDto         = tenantHoursEditDto;
                EmailSettingsEditDto emailSettingsEditDto  = new EmailSettingsEditDto();
                EmailSettingsEditDto emailSettingsEditDto1 = emailSettingsEditDto;
                emailSettingsEditDto1.DefaultFromAddress = await this.SettingManager.GetSettingValueAsync("Abp.Net.Mail.DefaultFromAddress");

                EmailSettingsEditDto emailSettingsEditDto2 = emailSettingsEditDto;
                emailSettingsEditDto2.DefaultFromDisplayName = await this.SettingManager.GetSettingValueAsync("Abp.Net.Mail.DefaultFromDisplayName");

                EmailSettingsEditDto settingValueAsync3 = emailSettingsEditDto;
                settingValueAsync3.SmtpHost = await this.SettingManager.GetSettingValueAsync("Abp.Net.Mail.Smtp.Host");

                EmailSettingsEditDto emailSettingsEditDto3 = emailSettingsEditDto;
                int num2 = await this.SettingManager.GetSettingValueAsync <int>("Abp.Net.Mail.Smtp.Port");

                emailSettingsEditDto3.SmtpPort = num2;
                EmailSettingsEditDto settingValueAsync4 = emailSettingsEditDto;
                settingValueAsync4.SmtpUserName = await this.SettingManager.GetSettingValueAsync("Abp.Net.Mail.Smtp.UserName");

                EmailSettingsEditDto emailSettingsEditDto4 = emailSettingsEditDto;
                emailSettingsEditDto4.SmtpPassword = await this.SettingManager.GetSettingValueAsync("Abp.Net.Mail.Smtp.Password");

                EmailSettingsEditDto settingValueAsync5 = emailSettingsEditDto;
                settingValueAsync5.SmtpDomain = await this.SettingManager.GetSettingValueAsync("Abp.Net.Mail.Smtp.Domain");

                EmailSettingsEditDto emailSettingsEditDto5 = emailSettingsEditDto;
                bool flag2 = await this.SettingManager.GetSettingValueAsync <bool>("Abp.Net.Mail.Smtp.EnableSsl");

                emailSettingsEditDto5.SmtpEnableSsl = flag2;
                EmailSettingsEditDto emailSettingsEditDto6 = emailSettingsEditDto;
                bool flag3 = await this.SettingManager.GetSettingValueAsync <bool>("Abp.Net.Mail.Smtp.UseDefaultCredentials");

                emailSettingsEditDto6.SmtpUseDefaultCredentials = flag3;
                tenantSettingsEditDto.Email = emailSettingsEditDto;
                tenantSettingsEditDto       = null;
                emailSettingsEditDto1       = null;
                emailSettingsEditDto2       = null;
                settingValueAsync3          = null;
                emailSettingsEditDto3       = null;
                settingValueAsync4          = null;
                emailSettingsEditDto4       = null;
                settingValueAsync5          = null;
                emailSettingsEditDto5       = null;
                emailSettingsEditDto6       = null;
                emailSettingsEditDto        = null;
                if (!this._ldapModuleConfig.IsEnabled)
                {
                    tenantHoursEditDto.Ldap = new LdapSettingsEditDto()
                    {
                        IsModuleEnabled = false
                    };
                }
                else
                {
                    tenantSettingsEditDto = tenantHoursEditDto;
                    LdapSettingsEditDto ldapSettingsEditDto = new LdapSettingsEditDto()
                    {
                        IsModuleEnabled = true
                    };
                    LdapSettingsEditDto ldapSettingsEditDto1 = ldapSettingsEditDto;
                    bool flag4 = await this.SettingManager.GetSettingValueAsync <bool>("Abp.Zero.Ldap.IsEnabled");

                    ldapSettingsEditDto1.IsEnabled = flag4;
                    LdapSettingsEditDto ldapSettingsEditDto2 = ldapSettingsEditDto;
                    ldapSettingsEditDto2.Domain = await this.SettingManager.GetSettingValueAsync("Abp.Zero.Ldap.Domain");

                    LdapSettingsEditDto ldapSettingsEditDto3 = ldapSettingsEditDto;
                    ldapSettingsEditDto3.UserName = await this.SettingManager.GetSettingValueAsync("Abp.Zero.Ldap.UserName");

                    LdapSettingsEditDto ldapSettingsEditDto4 = ldapSettingsEditDto;
                    ldapSettingsEditDto4.Password = await this.SettingManager.GetSettingValueAsync("Abp.Zero.Ldap.Password");

                    tenantSettingsEditDto.Ldap = ldapSettingsEditDto;
                    tenantSettingsEditDto      = null;
                    ldapSettingsEditDto1       = null;
                    ldapSettingsEditDto2       = null;
                    ldapSettingsEditDto3       = null;
                    ldapSettingsEditDto4       = null;
                    ldapSettingsEditDto        = null;
                }
            }
            return(tenantHoursEditDto);
        }
 /// <summary>
 /// Helper method for adding an object to tenantDetails collection.
 /// </summary>
 /// <param name="group"></param>
 public void AddTotenantDetails(TenantDetail tenantDetail)
 {
     base.AddObject("directoryObjects", tenantDetail);
 }
 public static TenantDetail CreateTenantDetail(string objectReference, global::System.Collections.ObjectModel.ObservableCollection<AssignedPlan> assignedPlans, global::System.Collections.ObjectModel.ObservableCollection<string> authorizedServiceInstances, global::System.Collections.ObjectModel.ObservableCollection<string> marketingNotificationEmails, global::System.Collections.ObjectModel.ObservableCollection<ProvisionedPlan> provisionedPlans, global::System.Collections.ObjectModel.ObservableCollection<ProvisioningError> provisioningErrors, global::System.Collections.ObjectModel.ObservableCollection<string> technicalNotificationMails, global::System.Collections.ObjectModel.ObservableCollection<VerifiedDomain> verifiedDomains)
 {
     TenantDetail tenantDetail = new TenantDetail();
     tenantDetail.ObjectReference = objectReference;
     if ((assignedPlans == null))
     {
         throw new global::System.ArgumentNullException("assignedPlans");
     }
     tenantDetail.AssignedPlans = assignedPlans;
     if ((authorizedServiceInstances == null))
     {
         throw new global::System.ArgumentNullException("authorizedServiceInstances");
     }
     tenantDetail.AuthorizedServiceInstances = authorizedServiceInstances;
     if ((marketingNotificationEmails == null))
     {
         throw new global::System.ArgumentNullException("marketingNotificationEmails");
     }
     tenantDetail.MarketingNotificationEmails = marketingNotificationEmails;
     if ((provisionedPlans == null))
     {
         throw new global::System.ArgumentNullException("provisionedPlans");
     }
     tenantDetail.ProvisionedPlans = provisionedPlans;
     if ((provisioningErrors == null))
     {
         throw new global::System.ArgumentNullException("provisioningErrors");
     }
     tenantDetail.ProvisioningErrors = provisioningErrors;
     if ((technicalNotificationMails == null))
     {
         throw new global::System.ArgumentNullException("technicalNotificationMails");
     }
     tenantDetail.TechnicalNotificationMails = technicalNotificationMails;
     if ((verifiedDomains == null))
     {
         throw new global::System.ArgumentNullException("verifiedDomains");
     }
     tenantDetail.VerifiedDomains = verifiedDomains;
     return tenantDetail;
 }
 public void AddToTenantDetails(TenantDetail tenantDetail)
 {
     base.AddObject("TenantDetails", tenantDetail);
 }
Ejemplo n.º 21
0
        private void btnGetTenantDetails_Click(object sender, EventArgs e)
        {
            string currentDateTime = DateTime.Now.ToUniversalTime().ToString();

            #region Setup Active Directory Client
            ActiveDirectoryClient activeDirectoryClient;
            try
            {
                activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
            }
            catch (AuthenticationException ex)
            {
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    txtOutput.Text += $"Error detail: {ex.InnerException.Message}";
                }
                return;
            }

            #endregion

            #region TenantDetails
            VerifiedDomain initialDomain = new VerifiedDomain();
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail  tenant        = null;
            txtOutput.Text += "Retrieving Tenant Details" + NewLine;
            try
            {
                List <ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails
                                                   .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId))
                                                   .ExecuteAsync().Result.CurrentPage.ToList();
                if (tenantsList.Count > 0)
                {
                    tenant = tenantsList.First();
                }
            }
            catch (Exception ex)
            {
                txtOutput.Text += $"Error getting TenantDetails {ex.Message} {ex.InnerException?.Message}" + NewLine;
            }
            if (tenant == null)
            {
                txtOutput.Text += "Tenant not found" + NewLine;
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                txtDetails.Text = $"Display Name: {tenantDetail.DisplayName}" + NewLine;

                // Get the Tenant's Verified Domains
                initialDomain    = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                txtDetails.Text += $"Initial Domain Name: {initialDomain.Name}" + NewLine;
                defaultDomain    = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                txtDetails.Text += $"Default Domain Name: {defaultDomain.Name}" + NewLine;

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    txtDetails.Text += $"Tech Contact: {techContact}" + NewLine;
                }

                txtDetails.Text += $"Street: {tenantDetail.Street}" + NewLine;
                txtDetails.Text += $"Zip: {tenantDetail.PostalCode}" + NewLine;
                txtDetails.Text += $"City: {tenantDetail.City}" + NewLine;
                txtDetails.Text += $"State: {tenantDetail.State}" + NewLine;
                txtDetails.Text += $"Country: {tenantDetail.Country}" + NewLine;
                txtDetails.Text += $"Phone: {tenantDetail.TelephoneNumber }" + NewLine;

                txtDetails.Text += $"Dirsync: {tenantDetail.DirSyncEnabled}" + NewLine;
                txtDetails.Text += $"Last Dirsync: {tenantDetail.CompanyLastDirSyncTime}" + NewLine;
            }

            #endregion
        }
Ejemplo n.º 22
0
        private static void Main()
        {
            // record start DateTime of execution
            string currentDateTime = DateTime.Now.ToUniversalTime().ToString();

            #region Setup Active Directory Client

            //*********************************************************************
            // setup Active Directory Client
            //*********************************************************************
            ActiveDirectoryClient activeDirectoryClient;
            try
            {
                activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsApplication();
            }
            catch (AuthenticationException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
                    //InnerException Message will contain the HTTP error status codes mentioned in the link above
                    Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
                }
                Console.ResetColor();
                Console.ReadKey();
                return;
            }

            #endregion

            #region TenantDetails

            //*********************************************************************
            // Get Tenant Details
            // Note: update the string TenantId with your TenantId.
            // This can be retrieved from the login Federation Metadata end point:
            // https://login.windows.net/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml
            //  Replace "GraphDir1.onMicrosoft.com" with any domain owned by your organization
            // The returned value from the first xml node "EntityDescriptor", will have a STS URL
            // containing your TenantId e.g. "https://sts.windows.net/4fd2b2f2-ea27-4fe5-a8f3-7b1a7c975f34/" is returned for GraphDir1.onMicrosoft.com
            //*********************************************************************
            VerifiedDomain initialDomain = new VerifiedDomain();
            VerifiedDomain defaultDomain = new VerifiedDomain();
            ITenantDetail  tenant        = null;
            Console.WriteLine("\n Retrieving Tenant Details");
            try
            {
                List <ITenantDetail> tenantsList = activeDirectoryClient.TenantDetails
                                                   .Where(tenantDetail => tenantDetail.ObjectId.Equals(Constants.TenantId))
                                                   .ExecuteAsync().Result.CurrentPage.ToList();
                if (tenantsList.Count > 0)
                {
                    tenant = tenantsList.First();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting TenantDetails {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            if (tenant == null)
            {
                Console.WriteLine("Tenant not found");
            }
            else
            {
                TenantDetail tenantDetail = (TenantDetail)tenant;
                Console.WriteLine("Tenant Display Name: " + tenantDetail.DisplayName);

                // Get the Tenant's Verified Domains
                initialDomain = tenantDetail.VerifiedDomains.First(x => x.Initial.HasValue && x.Initial.Value);
                Console.WriteLine("Initial Domain Name: " + initialDomain.Name);
                defaultDomain = tenantDetail.VerifiedDomains.First(x => [email protected] && [email protected]);
                Console.WriteLine("Default Domain Name: " + defaultDomain.Name);

                // Get Tenant's Tech Contacts
                foreach (string techContact in tenantDetail.TechnicalNotificationMails)
                {
                    Console.WriteLine("Tenant Tech Contact: " + techContact);
                }
            }

            #endregion

            #region Create a new User

            IUser newUser = new User();
            if (defaultDomain.Name != null)
            {
                newUser.DisplayName       = "Sample App Demo User (Manager)";
                newUser.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
                newUser.AccountEnabled    = true;
                newUser.MailNickname      = "SampleAppDemoUserManager";
                newUser.PasswordProfile   = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = true
                };
                newUser.UsageLocation = "US";
                try
                {
                    activeDirectoryClient.Users.AddUserAsync(newUser).Wait();
                    Console.WriteLine("\nNew User {0} was created", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError creating new user {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region List of max 4 Users by UPN

            //*********************************************************************
            // Demonstrate Getting a list of Users with paging (get 4 users), sorted by displayName
            //*********************************************************************
            int maxUsers = 4;
            try
            {
                Console.WriteLine("\n Retrieving Users");
                List <IUser> users = activeDirectoryClient.Users.OrderBy(user =>
                                                                         user.UserPrincipalName).Take(maxUsers).ExecuteAsync().Result.CurrentPage.ToList();
                foreach (IUser user in users)
                {
                    Console.WriteLine("UserObjectId: {0}  UPN: {1}", user.ObjectId, user.UserPrincipalName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Users. {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Create a User with a temp Password

            //*********************************************************************************************
            // Create a new User with a temp Password
            //*********************************************************************************************
            IUser userToBeAdded = new User();
            userToBeAdded.DisplayName       = "Sample App Demo User";
            userToBeAdded.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;
            userToBeAdded.AccountEnabled    = true;
            userToBeAdded.MailNickname      = "SampleAppDemoUser";
            userToBeAdded.PasswordProfile   = new PasswordProfile
            {
                Password = "******",
                ForceChangePasswordNextLogin = true
            };
            userToBeAdded.UsageLocation = "US";
            try
            {
                activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait();
                Console.WriteLine("\nNew User {0} was created", userToBeAdded.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new user. {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Update newly created User

            //*******************************************************************************************
            // update the newly created user's Password, PasswordPolicies and City
            //*********************************************************************************************
            if (userToBeAdded.ObjectId != null)
            {
                // update User's city and reset their User's Password
                userToBeAdded.City    = "Seattle";
                userToBeAdded.Country = "UK";
                PasswordProfile PasswordProfile = new PasswordProfile
                {
                    Password = "******",
                    ForceChangePasswordNextLogin = false
                };
                userToBeAdded.PasswordProfile  = PasswordProfile;
                userToBeAdded.PasswordPolicies = "DisablePasswordExpiration, DisableStrongPassword";
                try
                {
                    userToBeAdded.UpdateAsync().Wait();
                    Console.WriteLine("\nUser {0} was updated", userToBeAdded.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError Updating the user {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Search User by UPN

            // search for a single user by UPN
            string searchString = "admin@" + initialDomain.Name;
            Console.WriteLine("\n Retrieving user with UPN {0}", searchString);
            User         retrievedUser  = new User();
            List <IUser> retrievedUsers = null;
            try
            {
                retrievedUsers = activeDirectoryClient.Users
                                 .Where(user => user.UserPrincipalName.Equals(searchString))
                                 .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting new user {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            // should only find one user with the specified UPN
            if (retrievedUsers != null && retrievedUsers.Count == 1)
            {
                retrievedUser = (User)retrievedUsers.First();
            }
            else
            {
                Console.WriteLine("User not found {0}", searchString);
            }

            #endregion

            #region User Operations

            if (retrievedUser.UserPrincipalName != null)
            {
                Console.WriteLine("\n Found User: "******"  UPN: " +
                                  retrievedUser.UserPrincipalName);

                #region Assign User a Manager

                //Assigning User a new manager.
                if (newUser.ObjectId != null)
                {
                    Console.WriteLine("\n Assign User {0}, {1} as Manager.", retrievedUser.DisplayName,
                                      newUser.DisplayName);
                    retrievedUser.Manager = newUser as DirectoryObject;
                    try
                    {
                        newUser.UpdateAsync().Wait();
                        Console.Write("User {0} is successfully assigned {1} as Manager.", retrievedUser.DisplayName,
                                      newUser.DisplayName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\nError assigning manager to user. {0} {1}", e.Message,
                                          e.InnerException != null ? e.InnerException.Message : "");
                    }
                }

                #endregion

                #region Get User's Manager

                //Get the retrieved user's manager.
                Console.WriteLine("\n Retrieving User {0}'s Manager.", retrievedUser.DisplayName);
                DirectoryObject usersManager = retrievedUser.Manager;
                if (usersManager != null)
                {
                    User manager = usersManager as User;
                    if (manager != null)
                    {
                        Console.WriteLine("User {0} Manager details: \nManager: {1}  UPN: {2}",
                                          retrievedUser.DisplayName, manager.DisplayName, manager.UserPrincipalName);
                    }
                }
                else
                {
                    Console.WriteLine("Manager not found.");
                }

                #endregion

                #region Get User's Direct Reports

                //*********************************************************************
                // get the user's Direct Reports
                //*********************************************************************
                if (newUser.ObjectId != null)
                {
                    Console.WriteLine("\n Getting User{0}'s Direct Reports.", newUser.DisplayName);
                    IUserFetcher newUserFetcher = (IUserFetcher)newUser;
                    try
                    {
                        IPagedCollection <IDirectoryObject> directReports =
                            newUserFetcher.DirectReports.ExecuteAsync().Result;
                        do
                        {
                            List <IDirectoryObject> directoryObjects = directReports.CurrentPage.ToList();
                            foreach (IDirectoryObject directoryObject in directoryObjects)
                            {
                                if (directoryObject is User)
                                {
                                    User directReport = directoryObject as User;
                                    Console.WriteLine("User {0} Direct Report is {1}", newUser.UserPrincipalName,
                                                      directReport.UserPrincipalName);
                                }
                            }
                            directReports = directReports.GetNextPageAsync().Result;
                        } while (directReports != null && directReports.MorePagesAvailable);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("\nError getting direct reports of user. {0} {1}", e.Message,
                                          e.InnerException != null ? e.InnerException.Message : "");
                    }
                }

                #endregion

                #region Get list of Group IDS, user is member of

                //*********************************************************************
                // get a list of Group IDs that the user is a member of
                //*********************************************************************
                //const bool securityEnabledOnly = false;
                //IEnumerable<string> memberGroups = retrievedUser.GetMemberGroupsAsync(securityEnabledOnly).Result;
                //Console.WriteLine("\n {0} is a member of the following Groups (IDs)", retrievedUser.DisplayName);
                //foreach (String memberGroup in memberGroups)
                //{
                //    Console.WriteLine("Member of Group ID: " + memberGroup);
                //}

                #endregion

                #region Get User's Group And Role Membership, Getting the complete set of objects

                //*********************************************************************
                // get the User's Group and Role membership, getting the complete set of objects
                //*********************************************************************
                Console.WriteLine("\n {0} is a member of the following Group and Roles (IDs)", retrievedUser.DisplayName);
                IUserFetcher retrievedUserFetcher = retrievedUser;
                try
                {
                    IPagedCollection <IDirectoryObject> pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync().Result;
                    do
                    {
                        List <IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                        foreach (IDirectoryObject directoryObject in directoryObjects)
                        {
                            if (directoryObject is Group)
                            {
                                Group group = directoryObject as Group;
                                Console.WriteLine(" Group: {0}  Description: {1}", group.DisplayName, group.Description);
                            }
                            if (directoryObject is DirectoryRole)
                            {
                                DirectoryRole role = directoryObject as DirectoryRole;
                                Console.WriteLine(" Role: {0}  Description: {1}", role.DisplayName, role.Description);
                            }
                        }
                        pagedCollection = pagedCollection.GetNextPageAsync().Result;
                    } while (pagedCollection != null && pagedCollection.MorePagesAvailable);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting user's groups and roles memberships. {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }

                #endregion
            }

            #endregion

            #region Search for User (People Picker)

            //*********************************************************************
            // People picker
            // Search for a user using text string "Us" match against userPrincipalName, displayName, giveName, surname
            //*********************************************************************
            searchString = "Us";
            Console.WriteLine("\nSearching for any user with string {0} in UPN,DisplayName,First or Last Name",
                              searchString);
            List <IUser>             usersList     = null;
            IPagedCollection <IUser> searchResults = null;
            try
            {
                IUserCollection userCollection = activeDirectoryClient.Users;
                searchResults = userCollection.Where(user =>
                                                     user.UserPrincipalName.StartsWith(searchString) ||
                                                     user.DisplayName.StartsWith(searchString) ||
                                                     user.GivenName.StartsWith(searchString) ||
                                                     user.Surname.StartsWith(searchString)).ExecuteAsync().Result;
                usersList = searchResults.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting User {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (usersList != null && usersList.Count > 0)
            {
                do
                {
                    usersList = searchResults.CurrentPage.ToList();
                    foreach (IUser user in usersList)
                    {
                        Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                                          user.DisplayName, user.UserPrincipalName);
                    }
                    searchResults = searchResults.GetNextPageAsync().Result;
                } while (searchResults != null && searchResults.MorePagesAvailable);
            }
            else
            {
                Console.WriteLine("User not found");
            }

            #endregion

            #region Search for Group using StartWith filter

            //*********************************************************************
            // Search for a group using a startsWith filter (displayName property)
            //*********************************************************************
            Group retrievedGroup = new Group();
            searchString = "US";
            List <IGroup> foundGroups = null;
            try
            {
                foundGroups = activeDirectoryClient.Groups
                              .Where(group => group.DisplayName.StartsWith(searchString))
                              .ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Group {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (foundGroups != null && foundGroups.Count > 0)
            {
                retrievedGroup = foundGroups.First() as Group;
            }
            else
            {
                Console.WriteLine("Group Not Found");
            }

            #endregion

            #region Assign Member to Group

            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    activeDirectoryClient.Context.AddLink(retrievedGroup, "members", newUser);
                    activeDirectoryClient.Context.SaveChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError assigning member to group. {0} {1}",
                                      e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Get Group members

            if (retrievedGroup.ObjectId != null)
            {
                Console.WriteLine("\n Found Group: " + retrievedGroup.DisplayName + "  " + retrievedGroup.Description);

                //*********************************************************************
                // get the groups' membership -
                // Note this method retrieves ALL links in one request - please use this method with care - this
                // may return a very large number of objects
                //*********************************************************************
                IGroupFetcher retrievedGroupFetcher = retrievedGroup;
                try
                {
                    IPagedCollection <IDirectoryObject> members = retrievedGroupFetcher.Members.ExecuteAsync().Result;
                    Console.WriteLine(" Members:");
                    do
                    {
                        List <IDirectoryObject> directoryObjects = members.CurrentPage.ToList();
                        foreach (IDirectoryObject member in directoryObjects)
                        {
                            if (member is User)
                            {
                                User user = member as User;
                                Console.WriteLine("User DisplayName: {0}  UPN: {1}",
                                                  user.DisplayName,
                                                  user.UserPrincipalName);
                            }
                            if (member is Group)
                            {
                                Group group = member as Group;
                                Console.WriteLine("Group DisplayName: {0}", group.DisplayName);
                            }
                            if (member is Contact)
                            {
                                Contact contact = member as Contact;
                                Console.WriteLine("Contact DisplayName: {0}", contact.DisplayName);
                            }
                        }
                    } while (members != null && members.MorePagesAvailable);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nError getting groups' membership. {0} {1}",
                                      e.Message, e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Add User to Group

            //*********************************************************************************************
            // Add User to the "WA" Group
            //*********************************************************************************************
            if (retrievedGroup.ObjectId != null)
            {
                try
                {
                    activeDirectoryClient.Context.AddLink(retrievedGroup, "members", userToBeAdded);
                    activeDirectoryClient.Context.SaveChangesAsync().Wait();
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nAdding user to group failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Create a new Group

            //*********************************************************************************************
            // Create a new Group
            //*********************************************************************************************
            Group californiaEmployees = new Group
            {
                DisplayName     = "California Employees" + Helper.GetRandomString(8),
                Description     = "Employees in the state of California",
                MailNickname    = "CalEmployees",
                MailEnabled     = false,
                SecurityEnabled = true
            };
            try
            {
                activeDirectoryClient.Groups.AddGroupAsync(californiaEmployees).Wait();
                Console.WriteLine("\nNew Group {0} was created", californiaEmployees.DisplayName);
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError creating new Group {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Delete User

            //*********************************************************************************************
            // Delete the user that we just created
            //*********************************************************************************************
            if (userToBeAdded.ObjectId != null)
            {
                try
                {
                    userToBeAdded.DeleteAsync().Wait();
                    Console.WriteLine("\nUser {0} was deleted", userToBeAdded.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting User failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }
            if (newUser.ObjectId != null)
            {
                try
                {
                    newUser.DeleteAsync().Wait();
                    Console.WriteLine("\nUser {0} was deleted", newUser.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting User failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Delete Group

            //*********************************************************************************************
            // Delete the Group that we just created
            //*********************************************************************************************
            if (californiaEmployees.ObjectId != null)
            {
                try
                {
                    californiaEmployees.DeleteAsync().Wait();
                    Console.WriteLine("\nGroup {0} was deleted", californiaEmployees.DisplayName);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Deleting Group failed {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Get All Roles

            //*********************************************************************
            // Get All Roles
            //*********************************************************************
            List <IDirectoryRole> foundRoles = null;
            try
            {
                foundRoles = activeDirectoryClient.DirectoryRoles.ExecuteAsync().Result.CurrentPage.ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Roles {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (foundRoles != null && foundRoles.Count > 0)
            {
                foreach (IDirectoryRole role in foundRoles)
                {
                    Console.WriteLine("\n Found Role: {0} {1} {2} ",
                                      role.DisplayName, role.Description, role.ObjectId);
                }
            }
            else
            {
                Console.WriteLine("Role Not Found {0}", searchString);
            }

            #endregion

            #region Get Service Principals

            //*********************************************************************
            // get the Service Principals
            //*********************************************************************
            IPagedCollection <IServicePrincipal> servicePrincipals = null;
            try
            {
                servicePrincipals = activeDirectoryClient.ServicePrincipals.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Service Principal {0} {1}",
                                  e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (servicePrincipals != null)
            {
                do
                {
                    List <IServicePrincipal> servicePrincipalsList = servicePrincipals.CurrentPage.ToList();
                    foreach (IServicePrincipal servicePrincipal in servicePrincipalsList)
                    {
                        Console.WriteLine("Service Principal AppId: {0}  Name: {1}", servicePrincipal.AppId,
                                          servicePrincipal.DisplayName);
                    }
                    servicePrincipals = servicePrincipals.GetNextPageAsync().Result;
                } while (servicePrincipals != null && servicePrincipals.MorePagesAvailable);
            }

            #endregion

            #region Get Applications

            //*********************************************************************
            // get the Application objects
            //*********************************************************************
            IPagedCollection <IApplication> applications = null;
            try
            {
                applications = activeDirectoryClient.Applications.Take(999).ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Applications {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            if (applications != null)
            {
                do
                {
                    List <IApplication> appsList = applications.CurrentPage.ToList();
                    foreach (IApplication app in appsList)
                    {
                        Console.WriteLine("Application AppId: {0}  Name: {1}", app.AppId, app.DisplayName);
                    }
                    applications = applications.GetNextPageAsync().Result;
                } while (applications != null && applications.MorePagesAvailable);
            }

            #endregion

            #region User License Assignment

            //*********************************************************************************************
            // User License Assignment - assign EnterprisePack license to new user, and disable SharePoint service
            //   first get a list of Tenant's subscriptions and find the "Enterprisepack" one
            //   Enterprise Pack includes service Plans for ExchangeOnline, SharePointOnline and LyncOnline
            //   validate that Subscription is Enabled and there are enough units left to assign to users
            //*********************************************************************************************
            IPagedCollection <ISubscribedSku> skus = null;
            try
            {
                skus = activeDirectoryClient.SubscribedSkus.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("\nError getting Applications {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }
            if (skus != null)
            {
                do
                {
                    List <ISubscribedSku> subscribedSkus = skus.CurrentPage.ToList();
                    foreach (ISubscribedSku sku in subscribedSkus)
                    {
                        if (sku.SkuPartNumber == "ENTERPRISEPACK")
                        {
                            if ((sku.PrepaidUnits.Enabled.Value > sku.ConsumedUnits) &&
                                (sku.CapabilityStatus == "Enabled"))
                            {
                                // create addLicense object and assign the Enterprise Sku GUID to the skuId
                                //
                                AssignedLicense addLicense = new AssignedLicense {
                                    SkuId = sku.SkuId.Value
                                };

                                // find plan id of SharePoint Service Plan
                                foreach (ServicePlanInfo servicePlan in sku.ServicePlans)
                                {
                                    if (servicePlan.ServicePlanName.Contains("SHAREPOINT"))
                                    {
                                        addLicense.DisabledPlans.Add(servicePlan.ServicePlanId.Value);
                                        break;
                                    }
                                }

                                IList <AssignedLicense> licensesToAdd    = new[] { addLicense };
                                IList <Guid>            licensesToRemove = new Guid[] {};

                                // attempt to assign the license object to the new user
                                try
                                {
                                    if (newUser.ObjectId != null)
                                    {
                                        newUser.AssignLicenseAsync(licensesToAdd, licensesToRemove).Wait();
                                        Console.WriteLine("\n User {0} was assigned license {1}",
                                                          newUser.DisplayName,
                                                          addLicense.SkuId);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("\nLicense assingment failed {0} {1}", e.Message,
                                                      e.InnerException != null ? e.InnerException.Message : "");
                                }
                            }
                        }
                    }
                    skus = skus.GetNextPageAsync().Result;
                } while (skus != null && skus.MorePagesAvailable);
            }

            #endregion

            #region Switch to OAuth Authorization Code Grant (Acting as a user)

            activeDirectoryClient = AuthenticationHelper.GetActiveDirectoryClientAsUser();

            #endregion

            #region Create Application

            //*********************************************************************************************
            // Create a new Application object with App Role Assignment (Direct permission)
            //*********************************************************************************************
            Application appObject = new Application {
                DisplayName = "Test-Demo App" + Helper.GetRandomString(8)
            };
            appObject.IdentifierUris.Add("https://localhost/demo/" + Guid.NewGuid());
            appObject.ReplyUrls.Add("https://localhost/demo");
            AppRole appRole = new AppRole();
            appRole.Id        = Guid.NewGuid();
            appRole.IsEnabled = true;
            appRole.AllowedMemberTypes.Add("User");
            appRole.DisplayName = "Something";
            appRole.Description = "Anything";
            appRole.Value       = "policy.write";
            appObject.AppRoles.Add(appRole);

            // created Keycredential object for the new App object
            KeyCredential keyCredential = new KeyCredential
            {
                StartDate = DateTime.UtcNow,
                EndDate   = DateTime.UtcNow.AddYears(1),
                Type      = "Symmetric",
                Value     = Convert.FromBase64String("g/TMLuxgzurjQ0Sal9wFEzpaX/sI0vBP3IBUE/H/NS4="),
                Usage     = "Verify"
            };
            appObject.KeyCredentials.Add(keyCredential);

            try
            {
                activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();
                Console.WriteLine("New Application created: " + appObject.ObjectId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Application Creation execption: {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Create Service Principal

            //*********************************************************************************************
            // create a new Service principal
            //*********************************************************************************************
            ServicePrincipal newServicePrincpal = new ServicePrincipal();
            if (appObject != null)
            {
                newServicePrincpal.DisplayName    = appObject.DisplayName;
                newServicePrincpal.AccountEnabled = true;
                newServicePrincpal.AppId          = appObject.AppId;
                try
                {
                    activeDirectoryClient.ServicePrincipals.AddServicePrincipalAsync(newServicePrincpal).Wait();
                    Console.WriteLine("New Service Principal created: " + newServicePrincpal.ObjectId);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Service Principal Creation execption: {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Assign Direct Permission
            try
            {
                User user =
                    (User)activeDirectoryClient.Users.ExecuteAsync().Result.CurrentPage.ToList().FirstOrDefault();
                if (appObject.ObjectId != null && user != null && newServicePrincpal.ObjectId != null)
                {
                    AppRoleAssignment appRoleAssignment = new AppRoleAssignment();
                    appRoleAssignment.Id            = appRole.Id;
                    appRoleAssignment.ResourceId    = Guid.Parse(newServicePrincpal.ObjectId);
                    appRoleAssignment.PrincipalType = "User";
                    appRoleAssignment.PrincipalId   = Guid.Parse(user.ObjectId);
                    user.AppRoleAssignments.Add(appRoleAssignment);
                    user.UpdateAsync().Wait();
                    Console.WriteLine("User {0} is successfully assigned direct permission.", retrievedUser.DisplayName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Direct Permission Assignment failed: {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get Devices

            //*********************************************************************************************
            // Get a list of Mobile Devices from tenant
            //*********************************************************************************************
            Console.WriteLine("\nGetting Devices");
            IPagedCollection <IDevice> devices = null;
            try
            {
                devices = activeDirectoryClient.Devices.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("/nError getting devices {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            if (devices != null)
            {
                do
                {
                    List <IDevice> devicesList = devices.CurrentPage.ToList();
                    foreach (IDevice device in devicesList)
                    {
                        if (device.ObjectId != null)
                        {
                            Console.WriteLine("Device ID: {0}, Type: {1}", device.DeviceId, device.DeviceOSType);
                            IPagedCollection <IDirectoryObject> registeredOwners = device.RegisteredOwners;
                            if (registeredOwners != null)
                            {
                                do
                                {
                                    List <IDirectoryObject> registeredOwnersList = registeredOwners.CurrentPage.ToList();
                                    foreach (IDirectoryObject owner in registeredOwnersList)
                                    {
                                        Console.WriteLine("Device Owner ID: " + owner.ObjectId);
                                    }
                                    registeredOwners = registeredOwners.GetNextPageAsync().Result;
                                } while (registeredOwners != null && registeredOwners.MorePagesAvailable);
                            }
                        }
                    }
                    devices = devices.GetNextPageAsync().Result;
                } while (devices != null && devices.MorePagesAvailable);
            }

            #endregion

            #region Create New Permission

            //*********************************************************************************************
            // Create new permission object
            //*********************************************************************************************
            OAuth2PermissionGrant permissionObject = new OAuth2PermissionGrant();
            permissionObject.ConsentType = "AllPrincipals";
            permissionObject.Scope       = "user_impersonation";
            permissionObject.StartTime   = DateTime.Now;
            permissionObject.ExpiryTime  = (DateTime.Now).AddMonths(12);

            // resourceId is objectId of the resource, in this case objectId of AzureAd (Graph API)
            permissionObject.ResourceId = "52620afb-80de-4096-a826-95f4ad481686";

            //ClientId = objectId of servicePrincipal
            permissionObject.ClientId = newServicePrincpal.ObjectId;
            try
            {
                activeDirectoryClient.Oauth2PermissionGrants.AddOAuth2PermissionGrantAsync(permissionObject).Wait();
                Console.WriteLine("New Permission object created: " + permissionObject.ObjectId);
            }
            catch (Exception e)
            {
                Console.WriteLine("Permission Creation exception: {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            #region Get All Permissions

            //*********************************************************************************************
            // get all Permission Objects
            //*********************************************************************************************
            Console.WriteLine("\n Getting Permissions");
            IPagedCollection <IOAuth2PermissionGrant> permissions = null;
            try
            {
                permissions = activeDirectoryClient.Oauth2PermissionGrants.ExecuteAsync().Result;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0} {1}", e.Message, e.InnerException != null ? e.InnerException.Message : "");
            }
            if (permissions != null)
            {
                do
                {
                    List <IOAuth2PermissionGrant> perms = permissions.CurrentPage.ToList();
                    foreach (IOAuth2PermissionGrant perm in perms)
                    {
                        Console.WriteLine("Permission: {0}  Name: {1}", perm.ClientId, perm.Scope);
                    }
                } while (permissions != null && permissions.MorePagesAvailable);
            }

            #endregion

            #region Delete Application

            //*********************************************************************************************
            // Delete Application Objects
            //*********************************************************************************************
            if (appObject.ObjectId != null)
            {
                try
                {
                    appObject.DeleteAsync().Wait();
                    Console.WriteLine("Deleted Application object: " + appObject.ObjectId);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Application Deletion execption: {0} {1}", e.Message,
                                      e.InnerException != null ? e.InnerException.Message : "");
                }
            }

            #endregion

            #region Batch Operations

            //*********************************************************************************************
            // Show Batching with 3 operators.  Note: up to 5 operations can be in a batch
            //*********************************************************************************************
            IReadOnlyQueryableSet <User>          userQuery   = activeDirectoryClient.DirectoryObjects.OfType <User>();
            IReadOnlyQueryableSet <Group>         groupsQuery = activeDirectoryClient.DirectoryObjects.OfType <Group>();
            IReadOnlyQueryableSet <DirectoryRole> rolesQuery  =
                activeDirectoryClient.DirectoryObjects.OfType <DirectoryRole>();
            try
            {
                IBatchElementResult[] batchResult =
                    activeDirectoryClient.Context.ExecuteBatchAsync(userQuery, groupsQuery, rolesQuery).Result;
                int responseCount = 1;
                foreach (IBatchElementResult result in batchResult)
                {
                    if (result.FailureResult != null)
                    {
                        Console.WriteLine("Failed: {0} ",
                                          result.FailureResult.InnerException);
                    }
                    if (result.SuccessResult != null)
                    {
                        Console.WriteLine("Batch Item Result {0} succeeded",
                                          responseCount++);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Batch execution failed. : {0} {1}", e.Message,
                                  e.InnerException != null ? e.InnerException.Message : "");
            }

            #endregion

            //*********************************************************************************************
            // End of Demo Console App
            //*********************************************************************************************

            Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime);
            Console.ReadKey();
        }