/// <summary>
        /// Used by the management agent to allow for code cleanup.
        /// </summary>
        /// <param name="importRunStep"></param>
        /// <returns></returns>
        public CloseImportConnectionResults CloseImportConnection(CloseImportConnectionRunStep importRunStep)
        {
            _customersEnumerator = null;
            _customersInfo       = null;
            _customers           = null;
            _users           = null;
            _usersEnumerator = null;

            _customersInfoEnumerator.Dispose();

            return(new CloseImportConnectionResults());
        }
        private void ConfigureUserEnumerator()
        {
            try
            {
                // Obtain the collection of users broken out by page size. This is required because the synchronization
                // will only import a set size of entries at once. The page size is controlled by the ImportDefaultPageSize
                // and ImportMaxPageSize properties.
                _users = _operations.Customers.ById(_customersInfoEnumerator.Current.Value)
                         .Users.Query(QueryFactory.Instance.BuildIndexedQuery(ImportDefaultPageSize));
                // Create a customer user enumerator which will be used to traverse the pages of customer users.
                _usersEnumerator = _operations.Enumerators.CustomerUsers.Create(_users);

                _setupUsersEnumerators = false;
            }
            catch (PartnerException)
            {
                _customersInfoEnumerator.MoveNext();
                ConfigureUserEnumerator();
            }
        }
        /// <summary>
        /// Used to configure the import session and is called once at the beginning of the import.
        /// </summary>
        /// <param name="configParameters">A collection of <see cref="ConfigParameter"/> objects.</param>
        /// <param name="types">Contains a <see cref="Schema"/> that defines the management agent's schema</param>
        /// <param name="importRunStep">Contains an <see cref="OpenImportConnectionRunStep"/> object.</param>
        /// <returns></returns>
        public OpenImportConnectionResults OpenImportConnection(KeyedCollection <string, ConfigParameter> configParameters,
                                                                Schema types, OpenImportConnectionRunStep importRunStep)
        {
            InitializeConnector(configParameters);

            _setupCustomerIdsEnumerator = true;
            _setupUsersEnumerators      = true;

            // This dictionary will contain a complete list of all customer identifiers that are processed. These
            // identifiers will be used to obtain the users that belong to the customers that were processed.
            _customersInfo = new Dictionary <string, string>();
            // Obtain the collection of customer broken out by page size. This is required because the synchronization
            // will only import a set size of entries at once. The page size is controlled by the ImportDefaultPageSize
            // and ImportMaxPageSize properties.
            _customers = _operations.Customers.Query(QueryFactory.Instance.BuildIndexedQuery(ImportDefaultPageSize));
            // Create a customer enumerator which will be used to traverse the pages of customers.
            _customersEnumerator = _operations.Enumerators.Customers.Create(_customers);

            return(new OpenImportConnectionResults());
        }
Ejemplo n.º 4
0
        // CRON expressions format:: {second} {minute} {hour} {day} {month} {day-of-week}
        public static async Task RunAync([TimerTrigger("0 0 10 1/1 * *")] TimerInfo myTimer, TraceWriter log)
#endif
        {
            log.Info($"Get customers function execution started at {DateTime.UtcNow} UTC");
            try
            {
                log.Info($"Database initialization started.");
                DbInitializer.init(ConfigurationHelper.GetConnectionString(ConfigurationKeys.DbConnectoinString));
                log.Info($"Database initialization completed.");

                string partnerServiceApiRoot = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.PartnerServiceApiRoot),
                       authority             = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.Authority),
                       resourceUrl           = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ResourceUrl),
                       applicationId         = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationId),
                       applicationSecret     = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationSecret),
                       applicationDomian     = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationDomain);

                log.Verbose($"Partner Service Api Root {partnerServiceApiRoot}");
                log.Verbose($"Authority is {authority}");
                log.Verbose($"Resource URL is {resourceUrl}");
                log.Verbose($"Application Id is {applicationId}");
                log.Verbose($"Application Secret is {new string('*', applicationSecret.Length)}");
                log.Verbose($"Application Domain is {applicationDomian}");

                log.Info($"Connecting to MPN network");
                MpnApiClient mpnClient = await MpnApiClient.CreateAsync(partnerServiceApiRoot
                                                                        , authority
                                                                        , resourceUrl
                                                                        , applicationId
                                                                        , applicationSecret
                                                                        , applicationDomian);

                log.Info($"Connected to MPN network");

                SeekBasedResourceCollection <Customer> customers;
                //Page size is only supported between 1 to 999
                IResourceCollectionEnumerator <SeekBasedResourceCollection <Customer> > enumerator = await mpnClient.GetCustomersAsync(500);

                if (enumerator != null)
                {
                    while (enumerator.HasValue)
                    {
                        customers = enumerator.Current;
                        if (customers?.Items != null && customers?.TotalCount > 0)
                        {
                            await ProcessCustomers(customers, log);
                        }
                        else
                        {
                            log.Info($"0 customers found");
                        }
                        log.Verbose($"Fetching next page");
                        await enumerator.NextAsync();

                        log.Verbose($"Next page retrived");
                    }
                }
                log.Info($"Finished processing customers");
            }
            catch (Exception ex)
            {
                log.Error("Some error occured in function - 'GetCustomers'", ex);
            }
            log.Info($"Get customers function execution completed at {DateTime.UtcNow} UTC");
        }
        /// <summary>
        /// Retrieves the PreApproved Customers for rendering in UX.
        /// </summary>
        /// <returns>The PreApproved Customers.</returns>
        public async Task <PreApprovedCustomersViewModel> RetrieveCustomerDetailsAsync()
        {
            // retrieve the list of customers from Partner Center.
            IAggregatePartner sdkClient    = ApplicationDomain.Instance.PartnerCenterClient;
            List <Customer>   allCustomers = new List <Customer>();

            // create a customer enumerator which will aid us in traversing the customer pages
            IResourceCollectionEnumerator <SeekBasedResourceCollection <Customer> > customersEnumerator = sdkClient.Enumerators.Customers.Create(sdkClient.Customers.Query(QueryFactory.Instance.BuildIndexedQuery(100)));

            while (customersEnumerator.HasValue)
            {
                foreach (Customer c in customersEnumerator.Current.Items)
                {
                    allCustomers.Add(c);
                }

                await customersEnumerator.NextAsync().ConfigureAwait(false);
            }

            // if all customers are preapproved then every customer's IsPreApproved is true.
            bool allCustomersPreApproved = false;
            PreApprovedCustomersList currentPreApprovedCustomers = await RetrieveAsync().ConfigureAwait(false);

            if (currentPreApprovedCustomers.CustomerIds != null)
            {
                // Find if the all customers approved entry is present.
                allCustomersPreApproved = currentPreApprovedCustomers.CustomerIds.Any(cid => cid == Guid.Empty.ToString());
            }

            // populate portal customer list.
            List <PortalCustomer> preApprovedCustomerDetails = (from customer in allCustomers
                                                                select new PortalCustomer()
            {
                TenantId = customer.Id,
                CompanyName = customer.CompanyProfile.CompanyName,
                Domain = customer.CompanyProfile.Domain,
                IsPreApproved = false
            }).ToList();

            // identify the customers who are preapproved and update them.
            if (!allCustomersPreApproved && (currentPreApprovedCustomers.CustomerIds != null))
            {
                foreach (string customerId in currentPreApprovedCustomers.CustomerIds)
                {
                    try
                    {
                        // can raise an exception if a customer has been removed from PartnerCenter although preapproved in the portal.
                        preApprovedCustomerDetails.FirstOrDefault(customer => customer.TenantId == customerId).IsPreApproved = true;
                    }
                    catch (NullReferenceException)
                    {
                        // This has been intentionally left empty.
                    }
                }
            }

            PreApprovedCustomersViewModel viewModel = new PreApprovedCustomersViewModel
            {
                IsEveryCustomerPreApproved = allCustomersPreApproved,
                Items = preApprovedCustomerDetails.OrderBy(customer => customer.CompanyName)
            };

            if (!allCustomersPreApproved && currentPreApprovedCustomers.CustomerIds != null)
            {
                viewModel.CustomerIds = new List <string>();
                viewModel.CustomerIds.AddRange(currentPreApprovedCustomers.CustomerIds.ToList());
            }

            return(viewModel);
        }
Ejemplo n.º 6
0
        public static async Task RunAync([QueueTrigger("subscriptions")] SubscriptionMessage message, TraceWriter log)

//#if DEBUG
//		public static async Task RunAync([HttpTrigger(Route = "GetUtilizations")]HttpRequestMessage req, TraceWriter log)
//#else
//		public static async Task RunAync([QueueTrigger("subscriptions")]SubscriptionMessage message, TraceWriter log)
//#endif

        {
//#if DEBUG
//			var customerId = req.GetQueryNameValuePairs().FirstOrDefault(s => s.Key.Equals("customerid"));
//			var subscriptionId = req.GetQueryNameValuePairs().FirstOrDefault(s => s.Key.Equals("subscriptionid"));
//			SubscriptionMessage message = new SubscriptionMessage()
//			{
//				CustomerId = customerId.Value,
//				SubscriptionId = subscriptionId.Value
//			};
//#endif
            log.Info($"Get utilizations function execution started at {DateTime.UtcNow} UTC");
            try
            {
                log.Info($"Database initialization started.");
                DbInitializer.init(ConfigurationHelper.GetConnectionString(ConfigurationKeys.DbConnectoinString));
                log.Info($"Database initialization completed.");

                string partnerServiceApiRoot = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.PartnerServiceApiRoot),
                       authority             = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.Authority),
                       resourceUrl           = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ResourceUrl),
                       applicationId         = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationId),
                       applicationSecret     = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationSecret),
                       applicationDomian     = ConfigurationHelper.GetAppSetting(ConfigurationKeys.MPN.ApplicationDomain);

                log.Info($"Partner Service Api Root {partnerServiceApiRoot}");
                log.Info($"Authority is {authority}");
                log.Info($"Resource URL is {resourceUrl}");
                log.Info($"Application Id is {applicationId}");
                log.Info($"Application Secret is {new string('*', applicationSecret.Length)}");
                log.Info($"Application Domain is {applicationDomian}");

                log.Info($"Connecting to MPN network");
                MpnApiClient mpnClient = await MpnApiClient.CreateAsync(partnerServiceApiRoot
                                                                        , authority
                                                                        , resourceUrl
                                                                        , applicationId
                                                                        , applicationSecret
                                                                        , applicationDomian);

                log.Info($"Connected to MPN network");
                DateTimeOffset start = DateTimeOffset.UtcNow.Date.AddDays(-2),
                               end   = DateTimeOffset.UtcNow.Date.AddDays(-1);

                ResourceCollection <AzureUtilizationRecord> utilizations;
                IResourceCollectionEnumerator <ResourceCollection <AzureUtilizationRecord> > utilizationEnumerator = await mpnClient.GetUtilizationssAsync(message.CustomerId, message.SubscriptionId, start, end);

                if (utilizationEnumerator != null)
                {
                    while (utilizationEnumerator.HasValue)
                    {
                        utilizations = utilizationEnumerator.Current;
                        if (utilizations?.Items != null && utilizations?.TotalCount > 0)
                        {
                            ProcessUtilizations(utilizations, message.CustomerId, message.SubscriptionId, log);
                        }
                        else
                        {
                            log.Info($"0 utilizations found");
                        }
                        log.Verbose($"Fetching next page");
                        await utilizationEnumerator.NextAsync();

                        log.Verbose($"Next page retrived");
                    }
                }
                log.Info($"Finished processing utilizations");
            }
            catch (Exception ex)
            {
                log.Error("Some error occured in function - 'GetSubscriptions'", ex);
            }
            log.Info($"Get utilizations function execution completed at {DateTime.UtcNow} UTC");
        }