Ejemplo n.º 1
0
        private static CustomerUser CreateCustomerUser(IAggregatePartner partner, Customer existingCustomer, string userName)
        {
            string existingCustomerId = existingCustomer.Id;
            var    userToCreate       = new CustomerUser()
            {
                PasswordProfile = new PasswordProfile()
                {
                    ForceChangePassword = true,
                    Password            = "******"
                },
                DisplayName       = "Thiago",
                FirstName         = "Thiago",
                LastName          = "Nogueira",
                UsageLocation     = "US",
                UserPrincipalName = userName + "@" + existingCustomer.CompanyProfile.Domain
            };

            CustomerUser createdCustomerUser = partner.Customers
                                               .ById(existingCustomerId).Users
                                               .Create(userToCreate);

            Helpers.WriteObject(createdCustomerUser, "Created Customer User");

            return(createdCustomerUser);
        }
        private static async Task Run()
        {
            // The following properties indicate which partner and customer context the calls are going to be made.
            string PartnerId  = "<Partner tenant id>";
            string CustomerId = "<Customer tenant id>";

            Console.WriteLine(" ===================== Partner center  API calls ============================", DateTime.Now);
            IAggregatePartner ops = await GetUserPartnerOperationsAsync(PartnerId);

            SeekBasedResourceCollection <CustomerUser> customerUsers = ops.Customers.ById(CustomerId).Users.Get();

            Console.WriteLine(JsonConvert.SerializeObject(customerUsers));

            Console.WriteLine(" ===================== Partner graph  API calls ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenResult = await LoginToGraph(PartnerId);

            Newtonsoft.Json.Linq.JObject mydetails = await ApiCalls.GetAsync(tokenResult.Item1, "https://graph.microsoft.com/v1.0/me");

            Console.WriteLine(JsonConvert.SerializeObject(mydetails));

            // CSP partner applications are pre-consented into customer tenant, so they do not need a custom consent from customer.
            // direct token acquire to a customer tenant should work.
            Console.WriteLine(" ===================== Customer graph  API calls ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenCustomerResult = await LoginToCustomerGraph(PartnerId, CustomerId);

            Newtonsoft.Json.Linq.JObject customerDomainsUsingGraph = await ApiCalls.GetAsync(tokenCustomerResult.Item1, "https://graph.windows.net/" + CustomerId + "/domains?api-version=1.6");

            Console.WriteLine(JsonConvert.SerializeObject(customerDomainsUsingGraph));

            Console.ReadLine();
        }
Ejemplo n.º 3
0
        private static void AssignLicensesToCustomerUser(IAggregatePartner partner, string customerId, string customerUserId, SubscribedSku sku)
        {
            LicenseAssignment license = new LicenseAssignment
            {
                SkuId         = sku.ProductSku.Id,
                ExcludedPlans = null
            };

            LicenseUpdate licenseUpdate = new LicenseUpdate()
            {
                LicensesToAssign = new List <LicenseAssignment>()
                {
                    license
                }
            };

            var assigndLicensesUpdate = partner.Customers.ById(customerId)
                                        .Users.ById(customerUserId)
                                        .LicenseUpdates.Create(licenseUpdate);

            Helpers.WriteObject(assigndLicensesUpdate, "Assign License update for customer user : "******"Assigned Licenses for the customer user : " + customerUserId);
        }
Ejemplo n.º 4
0
        private static void RemoveLicensesFromCustomerUser(IAggregatePartner partner, string customerId, string customerUserId, SubscribedSku sku)
        {
            LicenseAssignment license = new LicenseAssignment();

            license.SkuId         = sku.ProductSku.Id;
            license.ExcludedPlans = null;

            LicenseUpdate licenseUpdate = new LicenseUpdate()
            {
                LicensesToAssign = null,
                LicensesToRemove = new List <string>()
                {
                    sku.ProductSku.Id
                }
            };

            var removeLicensesUpdate = partner.Customers.ById(customerId).Users.ById(customerUserId).LicenseUpdates.Create(licenseUpdate);

            Helpers.WriteObject(removeLicensesUpdate, "Remove License update for customer user: "******"Assigned licenses for customer user: " + customerUserId);
        }
Ejemplo n.º 5
0
        private static Customer CreateCustomer(IAggregatePartner partner)
        {
            var customerToCreate = new Customer()
            {
                CompanyProfile = new CustomerCompanyProfile()
                {
                    Domain = "xpto123456.onmicrosoft.com"
                },
                BillingProfile = new CustomerBillingProfile()
                {
                    Culture        = "PT-BR",
                    Email          = "*****@*****.**",
                    Language       = "PT-BR",
                    CompanyName    = "Alguma CIA",
                    DefaultAddress = new Address()
                    {
                        FirstName    = "First",
                        LastName     = "Last",
                        AddressLine1 = "One M Way",
                        City         = "Sao Paulo",
                        State        = "sp",
                        Country      = "BR",
                        PostalCode   = "03103001",
                        PhoneNumber  = "4257778899"
                    }
                }
            };

            Customer newCustomer = partner.Customers.Create(customerToCreate);

            Helpers.WriteObject(newCustomer, "New Customer");
            return(newCustomer);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Authenticates with the Partner Center APIs user.
        /// </summary>
        /// <returns>A Partner Center API client User.</returns>
        //private static async Task<IAggregatePartner> AcquireUserCenterAccessAsync()
        //{
        //    PartnerService.Instance.ApiRootUrl = System.Configuration.ConfigurationManager.AppSettings["partnerCenter.apiEndPoint"];
        //    PartnerService.Instance.ApplicationName = "Web Store Front V1.6";
        //    IPartnerCredentials credentials=null;
        //    //IPartnerCredentials credentials = await PartnerCredentials.Instance.GenerateByUserCredentialsAsync(
        //    //   System.Configuration.ConfigurationManager.AppSettings["User.ApplicationId"],

        //    AuthenticationResult aadAuthenticationResult = LoginUserToAad();


        //    AuthenticationResult token = await provider.AccessToken.GetAccessTokenAsync(
        //        $"{provider.Configuration.ActiveDirectoryEndpoint}/{provider.Configuration.PartnerCenterAccountId}",
        //        provider.Configuration.PartnerCenterEndpoint,
        //        new Models.ApplicationCredential
        //        {
        //            ApplicationId = provider.Configuration.ApplicationId,
        //            ApplicationSecret = provider.Configuration.ApplicationSecret,
        //            UseCache = true
        //        },
        //        provider.AccessToken.UserAssertionToken).ConfigureAwait(false);


        //    // Authenticate by user context with the partner service
        //    IPartnerCredentials userCredentials = PartnerCredentials.Instance.GenerateByUserCredentials(
        //        Configuration.UserAuthentication.ApplicationId,
        //        new AuthenticationToken(token.AccessToken, token.ExpiresOn));


        //            //System.Configuration.ConfigurationManager.AppSettings["partnercenter.applicationSecret"],
        //            //System.Configuration.ConfigurationManager.AppSettings["partnercenter.AadTenantId"],
        //            //     System.Configuration.ConfigurationManager.AppSettings["aadEndpoint"],
        //            //     System.Configuration.ConfigurationManager.AppSettings["aadGraphEndpoint"]).ConfigureAwait(false);

        //            return PartnerService.Instance.CreatePartnerOperations(credentials);
        //}


        public static async Task <IPartner> GetUserOperationsAsync(Guid correlationId)
        {
            //AuthenticationResult token = await provider.AccessToken.GetAccessTokenAsync(
            //   $"{System.Configuration.ConfigurationManager.AppSettings["aadEndpoint"].ToString()}/{System.Configuration.ConfigurationManager.AppSettings["partnercenter.AadTenantId"]}",
            //   System.Configuration.ConfigurationManager.AppSettings["partnerCenter.apiEndPoint"],
            //   new Models.ApplicationCredential
            //   {
            //       ApplicationId = System.Configuration.ConfigurationManager.AppSettings["partnercenter.applicationId"],
            //       ApplicationSecret = System.Configuration.ConfigurationManager.AppSettings["partnercenter.applicationSecret"],
            //       UseCache = true
            //   },
            //   provider.AccessToken.UserAssertionToken).ConfigureAwait(false);

            AuthenticationResult token = await provider.AccessToken.GetAccessTokenAsync(
                $"{provider.Configuration.ActiveDirectoryEndpoint}/{provider.Configuration.PartnerCenterAccountId}",
                provider.Configuration.PartnerCenterEndpoint,
                new Models.ApplicationCredential
            {
                ApplicationId     = provider.Configuration.ApplicationId,
                ApplicationSecret = provider.Configuration.ApplicationSecret,
                UseCache          = true
            },
                provider.AccessToken.UserAssertionToken).ConfigureAwait(false);

            IPartnerCredentials credentials = await PartnerCredentials.Instance.GenerateByUserCredentialsAsync(
                provider.Configuration.ApplicationId,
                new AuthenticationToken(token.AccessToken, token.ExpiresOn)).ConfigureAwait(false);

            IAggregatePartner userOperations = PartnerService.Instance.CreatePartnerOperations(credentials);

            return(userOperations.With(RequestContextFactory.Instance.Create(correlationId)));
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("################################");
                    Console.WriteLine("Help");
                    Console.WriteLine("Extract activation information to CSV: " + System.AppDomain.CurrentDomain.FriendlyName + " activationCSV");
                    Console.WriteLine("Extract customer usage information to CSV: " + System.AppDomain.CurrentDomain.FriendlyName + " customerUsageCSV");
                    Console.WriteLine("Extract activation information to Database: " + System.AppDomain.CurrentDomain.FriendlyName + " activationBD");
                    Console.WriteLine("################################");
                    return;
                }

                _stopwatch.Start();

                _logger.Info("#### Start date: " + DateTime.Now);

                #region Initialize APIs & Tokens

                _azureADGraphApiHelper  = new AzureADGraphApiHelper();
                _partnerCenterSdkHelper = new PartnerCenterSdkHelper(isTokenForUserPlusApplication: true);
                _partnerOperations      = _partnerCenterSdkHelper.GetPartnerCenterSdkClientAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                #endregion

                #region Parse command parameter

                if (args[0] == "activationCSV")
                {
                    _reportProcessor = new ActivationReportProcessor(OutputChannel.CSV);
                }
                if (args[0] == "customerUsageCSV")
                {
                    _reportProcessor = new CustomerUsageReportProcessor(OutputChannel.CSV);
                }
                if (args[0] == "activationBD")
                {
                    _reportProcessor = new ActivationReportProcessor(OutputChannel.DATABASE);
                }

                ExtractReportInformationWithProcessor().ConfigureAwait(false).GetAwaiter().GetResult();

                #endregion
            }
            catch (Exception ex)
            {
                _logger.Error("Error: " + ex.ToString());
            }
            finally
            {
                _stopwatch.Stop();

                _logger.Info("#### End date: " + DateTime.Now + ". Duration: " + FormatStopwatch());

                //Console.WriteLine("Press any key to end.");
                //Console.ReadLine();
            }
        }
Ejemplo n.º 8
0
        public static void PlaceOrder(IAggregatePartner partnerOperations, string customerId)
        {
            // create the order line items
            var lineItems = new List <OrderLineItem>();

            lineItems.Add(new OrderLineItem {
                LineItemNumber = 0,
                OfferId        = "031C9E47-4802-4248-838E-778FB1D2CC05",
                FriendlyName   = "Office 365 Business Premium",
                Quantity       = 1
            });

            // create the order
            var order = new Order {
                ReferenceCustomerId = customerId,
                LineItems           = lineItems
            };

            // submit the order
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Placing order...");

            try {
                partnerOperations.Customers.ById(customerId).Orders.Create(order);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Successully placed order!");
            } catch (Exception ex) {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error occured", ex);
            }
        }
        private async Task InitializePartnerCenterSdkClient()
        {
            // Get token
            AuthorizationToken token = await GetAADTokenForRequestsAsync();

            IPartnerCredentials credentials = null;

            if (_isTokenForUserPlusApplication)
            {
                // Authenticate by user context with the partner service
                credentials = await PartnerCredentials.Instance.GenerateByUserCredentialsAsync(
                    _userPlusApplicationAppId,
                    new AuthenticationToken(
                        token.AccessToken,
                        token.ExpiresOn),
                    async delegate
                {
                    // token has expired, re-Login to Azure Active Directory
                    var aadToken = await GetAADTokenForRequestsAsync();
                    return(new AuthenticationToken(aadToken.AccessToken, aadToken.ExpiresOn));
                });
            }
            else
            {
                //credentials = await PartnerCredentials.Instance.GenerateByApplicationCredentialsAsync(
                //    SettingsHelper.PARTNER_CENTER_SDK_APP_ID, SettingsHelper.PARTNER_CENTER_SDK_APP_KEY,
                //    SettingsHelper.CSP_TENANT_NAME);
            }

            // Create the partner operations
            _partnerCenterSdkClient = PartnerService.Instance.CreatePartnerOperations(credentials);
        }
Ejemplo n.º 10
0
        public String GetMyCspDomain()
        {
            IAggregatePartner partner = GetPartnerCenterTokenUsingAppCredentials();
            var billingProfile        = partner.Profiles.BillingProfile;

            return(billingProfile.Partner.Domains.ToString());
        }
        private static async Task RunAsync()
        {
            // The following properties indicate which partner and customer context the calls are going to be made.
            string PartnerId  = "<Partner tenant id>";
            string CustomerId = "<Customer tenant id>";

            Console.WriteLine(" ===================== Partner Center operations ============================", DateTime.Now);
            IAggregatePartner ops = await GetUserPartnerOperationsAsync(PartnerId);

            SeekBasedResourceCollection <CustomerUser> customerUsers = ops.Customers.ById(CustomerId).Users.Get();

            Console.WriteLine(JsonConvert.SerializeObject(customerUsers));

            Console.WriteLine(" ===================== Partner graph operations ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenResult = await LoginToGraph(PartnerId);

            Newtonsoft.Json.Linq.JObject mydetails = await ApiCalls.GetAsync(tokenResult.Item1, "https://graph.microsoft.com/v1.0/me");

            Console.WriteLine(JsonConvert.SerializeObject(mydetails));

            /**
             * Cloud Solution Provider partners can configure application for pre-consent. This means they do not need a
             * custom consent from the customer. This is possible because the partner can consent on behalf of the customer.
             */

            Console.WriteLine(" ===================== Customer graph operations ============================", DateTime.Now);
            Tuple <string, DateTimeOffset> tokenCustomerResult = await LoginToCustomerGraph(PartnerId, CustomerId);

            Newtonsoft.Json.Linq.JObject customerDomainsUsingGraph = await ApiCalls.GetAsync(tokenCustomerResult.Item1, "https://graph.windows.net/" + CustomerId + "/domains?api-version=1.6");

            Console.WriteLine(JsonConvert.SerializeObject(customerDomainsUsingGraph));

            Console.ReadLine();
        }
Ejemplo n.º 12
0
        private static ResourceCollection <ServiceRequest> GetServiceRequests(IAggregatePartner partner)
        {
            ResourceCollection <ServiceRequest> serviceRequests = partner.ServiceRequests.Query(QueryFactory.Instance.BuildIndexedQuery(5));

            Helpers.WriteObject(serviceRequests, "Service Requests");

            return(serviceRequests);
        }
Ejemplo n.º 13
0
        private static ResourceCollection <License> GetCustomerUserSubscribedSkus(IAggregatePartner partner, string customerId, string customerUserId)
        {
            var customerUserAssignedLicenses = partner.Customers.ById(customerId).Users.ById(customerUserId).Licenses.Get();

            Helpers.WriteObject(customerUserAssignedLicenses, "Customer User assigned Licences: " + customerUserAssignedLicenses.ToString());

            return(customerUserAssignedLicenses);
        }
Ejemplo n.º 14
0
        private static ResourceCollection <Offer> GetOffers(IAggregatePartner partner)
        {
            ResourceCollection <Offer> offers = partner.Offers.ByCountry("BR").Get();

            Helpers.WriteObject(offers, "Offer list");

            return(offers);
        }
Ejemplo n.º 15
0
        private static async Task <IAggregatePartner> GetPartner()
        {
            if (_partner == null)
            {
                _partner = await PcAuthHelper.GetPartnerCenterOps();
            }

            return(_partner);
        }
Ejemplo n.º 16
0
        private static ResourceCollection <Customer> QueryCustomers(IAggregatePartner partner)
        {
            IQuery customerQuery = QueryFactory.Instance.BuildIndexedQuery(10);
            ResourceCollection <Customer> customers = partner.Customers.Query(customerQuery);

            Helpers.WriteObject(customers, "Customer List");

            return(customers);
        }
Ejemplo n.º 17
0
        private static Customer GetExistingCustomer(IAggregatePartner partner)
        {
            var customers = partner.Customers.Get();
            var customer  = customers.Items.FirstOrDefault();

            Helpers.WriteObject(customer, "Existing Customer");

            return(customer);
        }
Ejemplo n.º 18
0
        private static ResourceCollection <CustomerUser> GetCustomerUsers(IAggregatePartner partner, string customerId)
        {
            IQuery customerUsersQuery     = QueryFactory.Instance.BuildIndexedQuery(10);
            var    customerUserPageResult = partner.Customers.ById(customerId).Users
                                            .Query(customerUsersQuery);

            Helpers.WriteObject(customerUserPageResult, "Customer Users List");

            return(customerUserPageResult);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Get the audit records for the specified date range using the Partner Center API.
        /// </summary>
        /// <param name="endDate">The end date of the audit record logs.</param>
        /// <param name="startDate">The start date of the audit record logs.</param>
        /// <returns>A partial view containing the requested audit record logs.</returns>
        public async Task <PartialViewResult> GetRecords(DateTime endDate, DateTime startDate)
        {
            IAggregatePartner operations = await new SdkContext().GetPartnerOperationsAysnc();

            AuditRecordsModel auditRecordsModel = new AuditRecordsModel()
            {
                Records = operations.AuditRecords.Query(startDate, endDate, QueryFactory.Instance.BuildSimpleQuery())
            };

            return(PartialView("Records", auditRecordsModel));
        }
        /// <summary>
        /// Handles the index view request.
        /// </summary>
        /// <returns>A view containing the InvoicesModel model.</returns>
        public async Task <ActionResult> Index()
        {
            IAggregatePartner operations = await new SdkContext().GetPartnerOperationsAysnc();

            InvoicesModel invoicesModel = new InvoicesModel()
            {
                Invoices = await operations.Invoices.GetAsync()
            };

            return(View(invoicesModel));
        }
Ejemplo n.º 21
0
        public static async Task <MyOffer> GetOffer(string offerId)
        {
            _partner = await GetPartner();

            // get offer from PC & convert to local model
            var pcOffer = await _partner.Offers.ByCountry("US").ById(offerId).GetAsync();

            var offer = await ConvertOffer(pcOffer);

            return(offer);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Gets an aptly configured instance of the partner service.
        /// </summary>
        /// <param name="correlationId">Correlation identifier used when communicating with Partner Center</param>
        /// <returns>An aptly populated instance of the partner service.</returns>
        /// <remarks>
        /// This function will request the necessary access token to communicate with Partner Center and initialize
        /// an instance of the partner service. The application name and correlation identifier are optional values, however,
        /// they have been included here because it is considered best practice. Including the application name makes it where
        /// Microsoft can quickly identify what application is communicating with Partner Center. Specifying the correlation
        /// identifier should be done to easily correlate a series of calls to Partner Center. Both of these properties will
        /// help Microsoft with identifying issues and supporting you.
        /// </remarks>
        private static IPartner GetPartnerService(Guid correlationId)
        {
            IPartnerCredentials credentials = PartnerCredentials.Instance.GenerateByApplicationCredentials(
                ConfigurationManager.AppSettings["PartnerCenter.ApplicationId"],
                ConfigurationManager.AppSettings["PartnerCenter.ApplicationSecret"],
                ConfigurationManager.AppSettings["PartnerCenter.AccountId"]);

            IAggregatePartner partner = PartnerService.Instance.CreatePartnerOperations(credentials);

            PartnerService.Instance.ApplicationName = ApplicationName;

            return(partner.With(RequestContextFactory.Instance.Create(correlationId)));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Determines whether the specified domain is available or not.
        /// </summary>
        /// <param name="primaryDomain">The domain prefix to be checked.</param>
        /// <returns><c>true</c> if the domain available; otherwise <c>false</c> is returned.</returns>
        /// <remarks>
        /// This checks if the specified domain is available using the Partner Center API. A domain is
        /// considered to be available if the domain is not already in used by another Azure AD tenant.
        /// </remarks>
        public async Task <JsonResult> IsDomainAvailable(string primaryDomain)
        {
            IAggregatePartner operations = await new SdkContext().GetPartnerOperationsAysnc();

            if (string.IsNullOrEmpty(primaryDomain))
            {
                return(Json(false, JsonRequestBehavior.AllowGet));
            }

            bool exists = await operations.Domains.ByDomain(primaryDomain + ".onmicrosoft.com").ExistsAsync();

            return(Json(!exists, JsonRequestBehavior.AllowGet));
        }
        private void InitializeConnector(KeyedCollection <string, ConfigParameter> configParameters)
        {
            SecureString appSecret = GetEncryptedParameterValue(configParameters, "AppSecret");
            SecureString password  = GetEncryptedParameterValue(configParameters, "Password");
            string       appId     = GetParameterValue(configParameters, "AppId");
            string       username  = GetParameterValue(configParameters, "Username");

            if (_operations == null)
            {
                _operations = new PartnerCenterContext(
                    appId, appSecret, username, password).GetOperations();
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets an instance of the partner service that utilizes app plus user authentication.
        /// </summary>
        /// <param name="correlationId">Correlation identifier for the operation.</param>
        /// <returns>An instance of the partner service.</returns>
        private async ValueTask <IPartner> GetUserOperationsAsync(Guid correlationId)
        {
            if (this.userOperations == null || this.userOperations.Credentials.ExpiresAt > DateTime.UtcNow)
            {
                IPartnerCredentials credentials = await this.service.TokenManagement
                                                  .GetPartnerCenterAppPlusUserCredentialsAsync(
                    $"{this.service.Configuration.ActiveDirectoryEndpoint}/{this.service.Configuration.PartnerCenterApplicationTenantId}");

                this.userOperations = PartnerService.Instance.CreatePartnerOperations(credentials);
            }

            return(this.userOperations.With(RequestContextFactory.Instance.Create(correlationId)));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets the an instance of <see cref="IAggregatePartner" /> used to interact with Partner Center.
        /// </summary>
        /// <returns>
        /// An instance of <see cref="IAggregatePartner" /> connected to the CSP reseller in the app.config.
        /// </returns>
        /// <remarks>
        /// Various operations with the Partner Center SDK require App + User authorization. More details
        /// regarding Partner Center authentication can be found at
        /// https://msdn.microsoft.com/en-us/library/partnercenter/mt634709.aspx.
        /// </remarks>
        public IAggregatePartner GetPartnerOperations(string username, string password)
        {
            AuthorizationToken  token;
            IPartnerCredentials credentials;

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password));
            }
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username));
            }

            try
            {
                if (_partner != null)
                {
                    return(_partner);
                }

                token = TokenContext.GetAADToken(
                    $"{Settings.Authority}/{Settings.TenantId}/oauth2/token",
                    "https://api.partnercenter.microsoft.com",
                    username,
                    password);

                credentials = PartnerCredentials.Instance.GenerateByUserCredentials(
                    Settings.ApplicationId,
                    new AuthenticationToken(token.AccessToken, token.ExpiresOn), authenticationToken =>
                {
                    token = TokenContext.GetAADToken(
                        $"{Settings.Authority}/{Settings.TenantId}/oauth2/token",
                        "https://api.partnercenter.microsoft.com",
                        username,
                        password);

                    return(Task.FromResult(new AuthenticationToken(token.AccessToken, token.ExpiresOn)));
                });


                _partner = PartnerService.Instance.CreatePartnerOperations(credentials);

                return(_partner);
            }
            finally
            {
                credentials = null;
                token       = null;
            }
        }
Ejemplo n.º 27
0
        public async Task <string> CreateCspCustomerAsync(string customerName, bool CreateSubscription = false)
        {
            // IAggregatePartner partnerOperations;
            IAggregatePartner partner = GetPartnerCenterTokenUsingAppCredentials();

            // Get an unique domain, based on the current day/time
            DateTime myDate         = DateTime.Now;
            string   TimePrefix     = myDate.Year.ToString() + myDate.Month.ToString() + myDate.Day.ToString() + myDate.Hour.ToString() + myDate.Minute.ToString() + myDate.Second.ToString();
            string   myUniqueDomain = TimePrefix + ".onmicrosoft.com";

            var customerToCreate = new Microsoft.Store.PartnerCenter.Models.Customers.Customer()
            {
                CompanyProfile = new CustomerCompanyProfile()
                {
                    Domain = myUniqueDomain
                },

                BillingProfile = new CustomerBillingProfile()
                {
                    Culture        = "EN-US",
                    Email          = "*****@*****.**",
                    Language       = "En",
                    CompanyName    = customerName,
                    DefaultAddress = new Address()
                    {
                        FirstName    = "Fake",
                        LastName     = "Name",
                        AddressLine1 = "One Microsoft Way",
                        City         = "Redmond",
                        State        = "WA",
                        Country      = "US",
                        PostalCode   = "98052",
                        PhoneNumber  = ""
                    }
                }
            };
            var newCustomer = await partner.Customers.CreateAsync(customerToCreate);

            if (CreateSubscription)
            {
                string SubscriptionId = await CreateCspSubscriptionAsync(newCustomer.Id);

                //Testing the ARM API does not work until some time (2 minutes) after having created the user
                //Thread.Sleep(120000);
                //ARM.createResourceGroup(newCustomer.Id, SubscriptionId, "testRg", "westeurope");
                //ARM.createSRVault(newCustomer.Id, SubscriptionId, "testRg", "testVault", "westeurope");
            }
            return(newCustomer.Id);
        }
        public async Task <PartialViewResult> Create()
        {
            IAggregatePartner operations = await new SdkContext().GetPartnerOperationsAysnc();

            PartnerCenter.Models.CountryValidationRules.CountryValidationRules rules
                = await operations.CountryValidationRules.ByCountry(AppConfig.CountryCode).GetAsync();

            // TODO - Do not get the supported states list each time. This data should be cached so the forms will load more rapidly.
            NewCustomerModel newCustomerModel = new NewCustomerModel()
            {
                SupportedStates = rules.SupportedStatesList
            };

            return(PartialView(newCustomerModel));
        }
Ejemplo n.º 29
0
        public async Task <HttpResponseMessage> Delete(string customerId, string userId)
        {
            if (string.IsNullOrEmpty(customerId))
            {
                throw new ArgumentNullException(nameof(customerId));
            }
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentNullException(nameof(userId));
            }

            IAggregatePartner operations = await new SdkContext().GetPartnerOperationsAysnc();
            await operations.Customers.ById(customerId).Users.ById(userId).DeleteAsync();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Ejemplo n.º 30
0
        private static ServiceRequest CreateServiceRequest(IAggregatePartner partner, string supportTopicId)
        {
            ServiceRequest serviceRequestToCreate = new ServiceRequest()
            {
                Title          = "Trial Service Request",
                Description    = "Some service is down",
                Severity       = ServiceRequestSeverity.Moderate,
                SupportTopicId = supportTopicId
            };

            ServiceRequest serviceRequest = partner.ServiceRequests.Create(serviceRequestToCreate, "en-US");

            Helpers.WriteObject(serviceRequest, "Created Service Request");

            return(serviceRequest);
        }