diff --git a/CHANGELOG.md b/CHANGELOG.md index 034da8e..826f1b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ # Change Log +## Upcoming Release + +* Authentication + * Addressed an issue where NullReferenceException exception was being encountered when invoking [Connect-PartnerCenter](https://docs.microsoft.com/powershell/module/partnercenter/Connect-PartnerCenter) using a certificate + * Addressed an issue where NullReferenceException exception was being encountered when invoking [New-PartnerAccessToken](https://docs.microsoft.com/powershell/module/partnercenter/New-PartnerAccessToken) using a certificate + * Defined the refresh token parameter set for the [New-PartnerAccessToken](https://docs.microsoft.com/powershell/module/partnercenter/New-PartnerAccessToken) command to make it easier to ensure all the appropriate parameters have been specified when exchanging a refresh token for an access token +* Module + * All commands now perform operations asynchronously + ## 3.0.3 - December 2019 * Authentication diff --git a/docs/help/Connect-PartnerCenter.md b/docs/help/Connect-PartnerCenter.md index 9a2983b..25ca998 100644 --- a/docs/help/Connect-PartnerCenter.md +++ b/docs/help/Connect-PartnerCenter.md @@ -28,9 +28,8 @@ Connect-PartnerCenter -AccessToken [-Environment ] [-T ### RefreshToken ```powershell -Connect-PartnerCenter -ApplicationId [-CertificateThumbprint ] [-Credential ] - [-Environment ] -RefreshToken [-Tenant ] [-WhatIf] [-Confirm] - [] +Connect-PartnerCenter -ApplicationId [-Credential ] [-Environment ] + -RefreshToken [-Tenant ] [-WhatIf] [-Confirm] [] ``` ### ServicePrincipalCertificate @@ -122,18 +121,6 @@ Accept wildcard characters: False ### -CertificateThumbprint Certificate Hash (Thumbprint) -```yaml -Type: String -Parameter Sets: RefreshToken -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ```yaml Type: String Parameter Sets: ServicePrincipalCertificate diff --git a/docs/help/Get-PartnerCustomerUser.md b/docs/help/Get-PartnerCustomerUser.md index 1bddf86..5cc3034 100644 --- a/docs/help/Get-PartnerCustomerUser.md +++ b/docs/help/Get-PartnerCustomerUser.md @@ -16,7 +16,7 @@ Gets a list of all customer users or a specified user for the tenant. ### ByCustomerId (Default) ```powershell -Get-PartnerCustomerUser [-CustomerId] [-ReturnDeletedUsers] [] +Get-PartnerCustomerUser [-CustomerId] [] ``` ### ByUserId @@ -24,6 +24,11 @@ Get-PartnerCustomerUser [-CustomerId] [-ReturnDeletedUsers] [ -UserId [] ``` +### ByUserState +```powershell +Get-PartnerCustomerUser [-CustomerId] [-ReturnDeletedUsers] [] +``` + ### ByUpn ```powershell Get-PartnerCustomerUser [-CustomerId] -UserPrincipalName [] @@ -77,10 +82,10 @@ Specifies whether to show deleted users. ```yaml Type: SwitchParameter -Parameter Sets: ByCustomerId +Parameter Sets: ByUserState Aliases: -Required: False +Required: True Position: Named Default value: None Accept pipeline input: False diff --git a/docs/help/Get-PartnerInvoiceLineItem.md b/docs/help/Get-PartnerInvoiceLineItem.md index 6ca4cd5..de7f1da 100644 --- a/docs/help/Get-PartnerInvoiceLineItem.md +++ b/docs/help/Get-PartnerInvoiceLineItem.md @@ -40,7 +40,7 @@ The billing provide for the line items. Type: BillingProvider Parameter Sets: (All) Aliases: -Accepted values: All, Azure, Office, OneTime, Marketplace +Accepted values: All, Azure, Marketplace, Office, OneTime Required: True Position: Named diff --git a/docs/help/New-PartnerAccessToken.md b/docs/help/New-PartnerAccessToken.md index 7566262..517bea5 100644 --- a/docs/help/New-PartnerAccessToken.md +++ b/docs/help/New-PartnerAccessToken.md @@ -17,33 +17,37 @@ Acquires an access token from Azure Active Directory. ### AccessToken ```powershell New-PartnerAccessToken -AccessToken -ApplicationId [-Credential ] - [-Environment ] [-RefreshToken ] -Scopes [-Tenant ] - [-UseAuthorizationCode] [] + [-Environment ] -Scopes [-Tenant ] [] +``` + +### RefreshToken +```powershell +New-PartnerAccessToken [-ApplicationId ] [-Credential ] [-Environment ] + [-Module ] -RefreshToken -Scopes [-ServicePrincipal] [-Tenant ] + [] ``` ### ServicePrincipal ```powershell New-PartnerAccessToken -ApplicationId -Credential [-Environment ] - [-RefreshToken ] -Scopes [-ServicePrincipal] -Tenant [-UseAuthorizationCode] - [] + -Scopes [-ServicePrincipal] -Tenant [-UseAuthorizationCode] [] ``` ### ServicePrincipalCertificate ```powershell New-PartnerAccessToken -ApplicationId -CertificateThumbprint [-Environment ] - [-RefreshToken ] -Scopes [-ServicePrincipal] -Tenant [-UseAuthorizationCode] - [] + -Scopes [-ServicePrincipal] -Tenant [-UseAuthorizationCode] [] ``` ### User ```powershell -New-PartnerAccessToken -ApplicationId [-Environment ] [-RefreshToken ] - -Scopes [-Tenant ] [-UseAuthorizationCode] [-UseDeviceAuthentication] [] +New-PartnerAccessToken -ApplicationId [-Environment ] -Scopes + [-Tenant ] [-UseAuthorizationCode] [-UseDeviceAuthentication] [] ``` ### ByModule ```powershell -New-PartnerAccessToken [-Environment ] -Module [-RefreshToken ] +New-PartnerAccessToken [-Environment ] -Module -Scopes [-Tenant ] [-UseAuthorizationCode] [] ``` @@ -103,6 +107,18 @@ Accept pipeline input: False Accept wildcard characters: False ``` +```yaml +Type: String +Parameter Sets: RefreshToken +Aliases: ClientId + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -CertificateThumbprint Certificate Hash (Thumbprint) @@ -123,7 +139,7 @@ Credentials that represents the service principal. ```yaml Type: PSCredential -Parameter Sets: AccessToken +Parameter Sets: AccessToken, RefreshToken Aliases: Required: False @@ -164,6 +180,19 @@ Accept wildcard characters: False ### -Module The module that an access token is being generated. +```yaml +Type: ModuleName +Parameter Sets: RefreshToken +Aliases: ModuleName +Accepted values: ExchangeOnline + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ```yaml Type: ModuleName Parameter Sets: ByModule @@ -182,10 +211,10 @@ The refresh token to use during authentication. ```yaml Type: String -Parameter Sets: (All) +Parameter Sets: RefreshToken Aliases: -Required: False +Required: True Position: Named Default value: None Accept pipeline input: False @@ -197,7 +226,7 @@ Scopes requested to access a protected API. ```yaml Type: String[] -Parameter Sets: AccessToken, ServicePrincipal, ServicePrincipalCertificate, User +Parameter Sets: (All) Aliases: Required: True @@ -212,10 +241,10 @@ Indicates that this account authenticates by providing service principal credent ```yaml Type: SwitchParameter -Parameter Sets: ServicePrincipal +Parameter Sets: RefreshToken, ServicePrincipalCertificate Aliases: -Required: True +Required: False Position: Named Default value: None Accept pipeline input: False @@ -224,10 +253,10 @@ Accept wildcard characters: False ```yaml Type: SwitchParameter -Parameter Sets: ServicePrincipalCertificate +Parameter Sets: ServicePrincipal Aliases: -Required: False +Required: True Position: Named Default value: None Accept pipeline input: False @@ -239,7 +268,7 @@ The identifier of the Azure AD tenant. ```yaml Type: String -Parameter Sets: AccessToken, User, ByModule +Parameter Sets: AccessToken, RefreshToken, User, ByModule Aliases: Domain, TenantId Required: False @@ -266,7 +295,7 @@ Use the authorization code flow during authentication. ```yaml Type: SwitchParameter -Parameter Sets: (All) +Parameter Sets: ServicePrincipal, ServicePrincipalCertificate, User, ByModule Aliases: AuthCode Required: False diff --git a/src/PowerShell/Authenticators/AccessTokenAuthenticator.cs b/src/PowerShell/Authenticators/AccessTokenAuthenticator.cs index d4a9615..4278926 100644 --- a/src/PowerShell/Authenticators/AccessTokenAuthenticator.cs +++ b/src/PowerShell/Authenticators/AccessTokenAuthenticator.cs @@ -4,8 +4,6 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Authenticators { using System; - using System.Linq; - using System.Management.Automation; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; @@ -32,16 +30,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Authenticators public override async Task AuthenticateAsync(AuthenticationParameters parameters, CancellationToken cancellationToken = default) { JsonWebToken token; - string value; - - if (parameters.Scopes.Contains($"{parameters.Environment.PartnerCenterEndpoint}/user_impersonation")) - { - value = parameters.Account.GetProperty(PartnerAccountPropertyType.AccessToken); - } - else - { - throw new PSInvalidOperationException("This operation is not supported when you connect using an access token. Please connect interactively or using a refresh token."); - } + string value = parameters.Account.GetProperty(PartnerAccountPropertyType.AccessToken); token = new JsonWebToken(value); diff --git a/src/PowerShell/Commands/AddPartnerCustomerCartLineItem.cs b/src/PowerShell/Commands/AddPartnerCustomerCartLineItem.cs index 3541822..e6e8863 100644 --- a/src/PowerShell/Commands/AddPartnerCustomerCartLineItem.cs +++ b/src/PowerShell/Commands/AddPartnerCustomerCartLineItem.cs @@ -9,6 +9,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using System.Text.RegularExpressions; using Extensions; + using Models.Authentication; using Models.Carts; using PartnerCenter.Models.Carts; using Properties; @@ -16,8 +17,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Adds a cart line item to the specified cart. /// - [Cmdlet(VerbsCommon.Add, "PartnerCustomerCartLineItem", SupportsShouldProcess = true), OutputType(typeof(PSCart))] - public class AddPartnerCustomerCartLineItem : PartnerCmdlet + [Cmdlet(VerbsCommon.Add, "PartnerCustomerCartLineItem", SupportsShouldProcess = true)] + [OutputType(typeof(PSCart))] + public class AddPartnerCustomerCartLineItem : PartnerAsyncCmdlet { /// /// Gets or sets the required cart identifier. @@ -45,24 +47,29 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Cart cart; - CartLineItem cartLineItem; - List lineItems; - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.AddPartnerCustomerCartLineItemWhatIf, CartId))) + Scheduler.RunTask(async () => { - cart = Partner.Customers[CustomerId].Carts[CartId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - lineItems = cart.LineItems.ToList(); + Cart cart; + CartLineItem cartLineItem; + List lineItems; - cartLineItem = new CartLineItem(); - cartLineItem.CopyFrom(LineItem); + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.AddPartnerCustomerCartLineItemWhatIf, CartId))) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - lineItems.Add(cartLineItem); + cart = await partner.Customers[CustomerId].Carts[CartId].GetAsync(CancellationToken).ConfigureAwait(false); + lineItems = cart.LineItems.ToList(); - cart = Partner.Customers[CustomerId].Carts[CartId].PutAsync(cart).GetAwaiter().GetResult(); + cartLineItem = new CartLineItem(); + cartLineItem.CopyFrom(LineItem); - WriteObject(new PSCart(cart)); - } + lineItems.Add(cartLineItem); + + cart = await partner.Customers[CustomerId].Carts[CartId].PutAsync(cart, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCart(cart)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/AddPartnerCustomerUserRoleMember.cs b/src/PowerShell/Commands/AddPartnerCustomerUserRoleMember.cs index da3979c..4fcf8e4 100644 --- a/src/PowerShell/Commands/AddPartnerCustomerUserRoleMember.cs +++ b/src/PowerShell/Commands/AddPartnerCustomerUserRoleMember.cs @@ -5,15 +5,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; using PartnerCenter.Models.Roles; using PartnerCenter.Models.Users; /// /// Gets a list of roles for the specified customer user from Partner Center. /// - [Cmdlet(VerbsCommon.Add, "PartnerCustomerUserRoleMember"), OutputType(typeof(bool))] - public class AddPartnerCustomerUserRoleMember : PartnerCmdlet + [Cmdlet(VerbsCommon.Add, "PartnerCustomerUserRoleMember")] + [OutputType(typeof(bool))] + public class AddPartnerCustomerUserRoleMember : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -41,38 +42,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - UserId.AssertNotEmpty(nameof(UserId)); - RoleId.AssertNotEmpty(nameof(RoleId)); - - CustomerUser user = GetUserById(CustomerId, UserId); - - UserMember newMember = new UserMember() + Scheduler.RunTask(async () => { - UserPrincipalName = user.UserPrincipalName, - DisplayName = user.DisplayName, - Id = user.Id - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + CustomerUser user = await partner.Customers[CustomerId].Users[UserId].GetAsync(CancellationToken).ConfigureAwait(false); - Partner.Customers[CustomerId].DirectoryRoles[RoleId].UserMembers.CreateAsync(newMember).GetAwaiter().GetResult(); - WriteObject(true); + UserMember newMember = new UserMember() + { + UserPrincipalName = user.UserPrincipalName, + DisplayName = user.DisplayName, + Id = user.Id + }; - } - - /// - /// Gets details for a specified user and customer from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user. - /// - /// is empty or null. - /// - private CustomerUser GetUserById(string customerId, string userId) - { - customerId.AssertNotEmpty(nameof(customerId)); - userId.AssertNotEmpty(nameof(userId)); - - return Partner.Customers[customerId].Users[userId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); ; + await partner.Customers[CustomerId].DirectoryRoles[RoleId].UserMembers.CreateAsync(newMember, CancellationToken).ConfigureAwait(false); + WriteObject(true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/ConnectPartnerCenter.cs b/src/PowerShell/Commands/ConnectPartnerCenter.cs index a67870d..0b6f03f 100644 --- a/src/PowerShell/Commands/ConnectPartnerCenter.cs +++ b/src/PowerShell/Commands/ConnectPartnerCenter.cs @@ -211,6 +211,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands else if (ParameterSetName.Equals(ServicePrincipalCertificateParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId); + account.Type = AccountType.Certificate; } else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { @@ -253,7 +254,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands try { - partnerOperations = PartnerSession.Instance.ClientFactory.CreatePartnerOperations(); + partnerOperations = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId).ConfigureAwait(false); profile = await partnerOperations.Profiles.OrganizationProfile.GetAsync().ConfigureAwait(false); PartnerSession.Instance.Context.CountryCode = profile.DefaultAddress.Country; diff --git a/src/PowerShell/Commands/GetPartnerAgreementDetail.cs b/src/PowerShell/Commands/GetPartnerAgreementDetail.cs index 990895c..d42b377 100644 --- a/src/PowerShell/Commands/GetPartnerAgreementDetail.cs +++ b/src/PowerShell/Commands/GetPartnerAgreementDetail.cs @@ -7,14 +7,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using Models.Agreements; + using Models.Authentication; using PartnerCenter.Models; using PartnerCenter.Models.Agreements; /// /// Gets a metadata for the available agreements. /// - [Cmdlet(VerbsCommon.Get, "PartnerAgreementDetail"), OutputType(typeof(PSAgreementMetaData))] - public class GetPartnerAgreementDetail : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerAgreementDetail")] + [OutputType(typeof(PSAgreementMetaData))] + public class GetPartnerAgreementDetail : PartnerAsyncCmdlet { /// /// Gets or sets the agreement type. @@ -28,22 +30,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection agreements; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection agreements; - if (string.IsNullOrEmpty(AgreementType)) - { - agreements = Partner.AgreementDetails.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - else if (AgreementType.Equals("All", StringComparison.InvariantCultureIgnoreCase)) - { - agreements = Partner.AgreementDetails.ByAgreementType("*").GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - else - { - agreements = Partner.AgreementDetails.ByAgreementType(AgreementType).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } + if (string.IsNullOrEmpty(AgreementType)) + { + agreements = await partner.AgreementDetails.GetAsync(CancellationToken).ConfigureAwait(false); + } + else if (AgreementType.Equals("All", StringComparison.InvariantCultureIgnoreCase)) + { + agreements = await partner.AgreementDetails.ByAgreementType("*").GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + agreements = await partner.AgreementDetails.ByAgreementType(AgreementType).GetAsync(CancellationToken).ConfigureAwait(false); + } - WriteObject(agreements.Items.Select(a => new PSAgreementMetaData(a)), true); + WriteObject(agreements.Items.Select(a => new PSAgreementMetaData(a)), true); + + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerAgreementTemplate.cs b/src/PowerShell/Commands/GetPartnerAgreementDocument.cs similarity index 63% rename from src/PowerShell/Commands/GetPartnerAgreementTemplate.cs rename to src/PowerShell/Commands/GetPartnerAgreementDocument.cs index 373716f..e77b90a 100644 --- a/src/PowerShell/Commands/GetPartnerAgreementTemplate.cs +++ b/src/PowerShell/Commands/GetPartnerAgreementDocument.cs @@ -6,10 +6,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using Agreements; using Models.Agreements; + using Models.Authentication; [Cmdlet(VerbsCommon.Get, "PartnerAgreementDocument")] [OutputType(typeof(PSAgreementDocument))] - public class GetPartnerAgreementDocument : PartnerCmdlet + public class GetPartnerAgreementDocument : PartnerAsyncCmdlet { /// /// Gets or sets the country. @@ -37,19 +38,23 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - IAgreementDocument operation = Partner.AgreementTemplates.ById(TemplateId).Document; - - if (!string.IsNullOrEmpty(Country)) + Scheduler.RunTask(async () => { - operation = operation.ByCountry(Country); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + IAgreementDocument operation = partner.AgreementTemplates.ById(TemplateId).Document; - if (!string.IsNullOrEmpty(Language)) - { - operation = operation.ByLanguage(Language); - } + if (!string.IsNullOrEmpty(Country)) + { + operation = operation.ByCountry(Country); + } - WriteObject(new PSAgreementDocument(operation.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + if (!string.IsNullOrEmpty(Language)) + { + operation = operation.ByLanguage(Language); + } + + WriteObject(new PSAgreementDocument(await operation.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerAgreementStatus.cs b/src/PowerShell/Commands/GetPartnerAgreementStatus.cs index 5d210c6..3654c53 100644 --- a/src/PowerShell/Commands/GetPartnerAgreementStatus.cs +++ b/src/PowerShell/Commands/GetPartnerAgreementStatus.cs @@ -5,11 +5,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.Compliance; [Cmdlet(VerbsCommon.Get, "PartnerAgreementStatus", DefaultParameterSetName = "ByTenantId")] [OutputType(typeof(AgreementSignatureStatus))] - public class GetPartnerAgreementStatus : PartnerCmdlet + public class GetPartnerAgreementStatus : PartnerAsyncCmdlet { /// /// Gets or sets the Microsoft Partner Network (MPN) identifier. @@ -29,7 +30,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(Partner.Compliance.AgreementSignatureStatus.GetAsync(MpnId, TenantId, CancellationToken).ConfigureAwait(false).GetAwaiter().GetResult()); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + WriteObject(await partner.Compliance.AgreementSignatureStatus.GetAsync(MpnId, TenantId, CancellationToken).ConfigureAwait(false)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerAuditRecord.cs b/src/PowerShell/Commands/GetPartnerAuditRecord.cs index 45a6d21..bf3bb73 100644 --- a/src/PowerShell/Commands/GetPartnerAuditRecord.cs +++ b/src/PowerShell/Commands/GetPartnerAuditRecord.cs @@ -9,15 +9,18 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using Enumerators; using Models.Auditing; + using Models.Authentication; using PartnerCenter.Models; using PartnerCenter.Models.Auditing; using Properties; + using RequestContext; /// /// Cmdlet that retrieves audit records from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerAuditRecord"), OutputType(typeof(PSAuditRecord))] - public class GetPartnerAuditRecord : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerAuditRecord")] + [OutputType(typeof(PSAuditRecord))] + public class GetPartnerAuditRecord : PartnerAsyncCmdlet { /// /// Gets or sets the end date porition of the query. @@ -36,34 +39,38 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - DateTime endDate; - IResourceCollectionEnumerator> enumerator; - List records; - SeekBasedResourceCollection auditRecords; - - endDate = EndDate ?? DateTime.Now; - - if ((endDate - StartDate).Days >= 90) + Scheduler.RunTask(async () => { - throw new PSInvalidOperationException(Resources.AuditRecordDateError); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - records = new List(); + DateTime endDate; + IResourceCollectionEnumerator> enumerator; + List records; + SeekBasedResourceCollection auditRecords; - foreach (DateTime date in ChunkDate(StartDate, endDate, 30)) - { - auditRecords = Partner.AuditRecords.QueryAsync(date).GetAwaiter().GetResult(); + endDate = EndDate ?? DateTime.Now; - enumerator = Partner.Enumerators.AuditRecords.Create(auditRecords); - - while (enumerator.HasValue) + if ((endDate - StartDate).Days >= 90) { - records.AddRange(enumerator.Current.Items.Select(r => new PSAuditRecord(r))); - enumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + throw new PSInvalidOperationException(Resources.AuditRecordDateError); } - } - WriteObject(records, true); + records = new List(); + + foreach (DateTime date in ChunkDate(StartDate, endDate, 30)) + { + auditRecords = await partner.AuditRecords.QueryAsync(date, null, null, CancellationToken).ConfigureAwait(false); + enumerator = partner.Enumerators.AuditRecords.Create(auditRecords); + + while (enumerator.HasValue) + { + records.AddRange(enumerator.Current.Items.Select(r => new PSAuditRecord(r))); + await enumerator.NextAsync(RequestContextFactory.Create(CorrelationId), CancellationToken).ConfigureAwait(false); + } + } + + WriteObject(records, true); + }, true); } private static IEnumerable ChunkDate(DateTime startDate, DateTime endDate, int size) diff --git a/src/PowerShell/Commands/GetPartnerAzureRateCard.cs b/src/PowerShell/Commands/GetPartnerAzureRateCard.cs index 49a6e06..f54d073 100644 --- a/src/PowerShell/Commands/GetPartnerAzureRateCard.cs +++ b/src/PowerShell/Commands/GetPartnerAzureRateCard.cs @@ -4,14 +4,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.RateCards; using PartnerCenter.Models.RateCards; /// /// Cmdlet that retrieves Azrue Rate Card details. /// - [Cmdlet(VerbsCommon.Get, "PartnerAzureRateCard"), OutputType(typeof(PSAzureRateCard))] - public class GetPartnerAzureRateCard : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerAzureRateCard")] + [OutputType(typeof(PSAzureRateCard))] + public class GetPartnerAzureRateCard : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -36,18 +38,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - AzureRateCard rateCard; - - if (SharedServices.IsPresent && SharedServices.ToBool()) + Scheduler.RunTask(async () => { - rateCard = Partner.RateCards.Azure.GetSharedAsync(Currency, Region).GetAwaiter().GetResult(); - } - else - { - rateCard = Partner.RateCards.Azure.GetAsync(Currency, Region).GetAwaiter().GetResult(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + AzureRateCard rateCard; - WriteObject(new PSAzureRateCard(rateCard)); + if (SharedServices.IsPresent && SharedServices.ToBool()) + { + rateCard = await partner.RateCards.Azure.GetSharedAsync(Currency, Region, CancellationToken).ConfigureAwait(false); + } + else + { + rateCard = await partner.RateCards.Azure.GetAsync(Currency, Region, CancellationToken).ConfigureAwait(false); + } + + WriteObject(new PSAzureRateCard(rateCard)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerBillingProfile.cs b/src/PowerShell/Commands/GetPartnerBillingProfile.cs index cb6804e..74a4990 100644 --- a/src/PowerShell/Commands/GetPartnerBillingProfile.cs +++ b/src/PowerShell/Commands/GetPartnerBillingProfile.cs @@ -4,20 +4,26 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.Partners; /// /// Gets the partner billing profile from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerBillingProfile"), OutputType(typeof(PSBillingProfile))] - public class GetPartnerBillingProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerBillingProfile")] + [OutputType(typeof(PSBillingProfile))] + public class GetPartnerBillingProfile : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - WriteObject(new PSBillingProfile(Partner.Profiles.BillingProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + WriteObject(new PSBillingProfile(await partner.Profiles.BillingProfile.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCountryValidation.cs b/src/PowerShell/Commands/GetPartnerCountryValidation.cs index 77f2956..4b23efa 100644 --- a/src/PowerShell/Commands/GetPartnerCountryValidation.cs +++ b/src/PowerShell/Commands/GetPartnerCountryValidation.cs @@ -4,10 +4,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.CountryValidationRules; - [Cmdlet(VerbsCommon.Get, "PartnerCountryValidation"), OutputType(typeof(PSCountryValidationRules))] - public class GetPartnerCountryValidation : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCountryValidation")] + [OutputType(typeof(PSCountryValidationRules))] + public class GetPartnerCountryValidation : PartnerAsyncCmdlet { /// /// Gets or sets the country code in ISO2 format. @@ -20,7 +22,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(new PSCountryValidationRules(Partner.CountryValidationRules.ByCountry(CountryCode).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + WriteObject(new PSCountryValidationRules(await partner.CountryValidationRules.ByCountry(CountryCode).GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerAgreement.cs b/src/PowerShell/Commands/GetPartnerCustomerAgreement.cs index 613ec2f..5e49739 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerAgreement.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerAgreement.cs @@ -7,12 +7,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using System.Text.RegularExpressions; using Models.Agreements; + using Models.Authentication; + using PartnerCenter.Models; + using PartnerCenter.Models.Agreements; /// /// Gets a list of agreements the customer in place. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerAgreement"), OutputType(typeof(PSAgreement))] - public class GetPartnerCustomerAgreement : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerAgreement")] + [OutputType(typeof(PSAgreement))] + public class GetPartnerCustomerAgreement : PartnerAsyncCmdlet { /// /// Gets or sets the agreement type. @@ -33,14 +37,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(AgreementType)) + Scheduler.RunTask(async () => { - WriteObject(Partner.Customers[CustomerId].Agreements.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(a => new PSAgreement(a)), true); - } - else - { - WriteObject(Partner.Customers[CustomerId].Agreements.ByAgreementType(AgreementType).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(a => new PSAgreement(a)), true); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection agreements; + + if (string.IsNullOrEmpty(AgreementType)) + { + agreements = await partner.Customers[CustomerId].Agreements.GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + agreements = await partner.Customers[CustomerId].Agreements.ByAgreementType(AgreementType).GetAsync(CancellationToken).ConfigureAwait(false); + } + + WriteObject(agreements.Items.Select(a => new PSAgreement(a)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerAzurePlanEntitlement.cs b/src/PowerShell/Commands/GetPartnerCustomerAzurePlanEntitlement.cs index 66e24fb..759dd39 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerAzurePlanEntitlement.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerAzurePlanEntitlement.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using PartnerCenter.Models; using PartnerCenter.Models.Subscriptions; @@ -13,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets a list of Azure Plan entitlements for a customer from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerAzurePlanEntitlement"), OutputType(typeof(PSAzureEntitlement))] - public class GetPartnerCustomerAzurePlanEntitlement : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerAzurePlanEntitlement")] + [OutputType(typeof(PSAzureEntitlement))] + public class GetPartnerCustomerAzurePlanEntitlement : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -35,14 +37,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection entitlements = Partner.Customers[CustomerId] - .Subscriptions[SubscriptionId] - .GetAzurePlanSubscriptionEntitlementsAsync() - .ConfigureAwait(false) - .GetAwaiter() - .GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - WriteObject(entitlements.Items.Select(e => new PSAzureEntitlement(e)), true); + ResourceCollection entitlements = await partner.Customers[CustomerId] + .Subscriptions[SubscriptionId] + .GetAzurePlanSubscriptionEntitlementsAsync(CancellationToken) + .ConfigureAwait(false); + + WriteObject(entitlements.Items.Select(e => new PSAzureEntitlement(e)), true); + }, true); } } } diff --git a/src/PowerShell/Commands/GetPartnerCustomerBillingProfile.cs b/src/PowerShell/Commands/GetPartnerCustomerBillingProfile.cs index ff8a54c..0f2a977 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerBillingProfile.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerBillingProfile.cs @@ -5,10 +5,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Customers; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerBillingProfile"), OutputType(typeof(PSCustomerBillingProfile))] - public class GetPartnerCustomerBillingProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerBillingProfile")] + [OutputType(typeof(PSCustomerBillingProfile))] + public class GetPartnerCustomerBillingProfile : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -22,7 +24,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(new PSCustomerBillingProfile(Partner.Customers[CustomerId].Profiles.Billing.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + WriteObject(new PSCustomerBillingProfile(await partner.Customers[CustomerId].Profiles.Billing.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } diff --git a/src/PowerShell/Commands/GetPartnerCustomerCart.cs b/src/PowerShell/Commands/GetPartnerCustomerCart.cs index aadaeac..a26c454 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerCart.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerCart.cs @@ -5,10 +5,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Carts; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerCart"), OutputType(typeof(PSCart))] - public class GetPartnerCustomerCart : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerCart")] + [OutputType(typeof(PSCart))] + public class GetPartnerCustomerCart : PartnerAsyncCmdlet { /// /// Gets or sets the required cart identifier. @@ -29,7 +31,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(new PSCart(Partner.Customers[CustomerId].Carts[CartId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + WriteObject(new PSCart(await partner.Customers[CustomerId].Carts[CartId].GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerCompanyProfile.cs b/src/PowerShell/Commands/GetPartnerCustomerCompanyProfile.cs index ef58005..0b3ead7 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerCompanyProfile.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerCompanyProfile.cs @@ -5,13 +5,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Customers; /// /// Command to get a customer's company profile. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerCompanyProfile"), OutputType(typeof(PSCustomerCompanyProfile))] - public class GetPartnerCustomerCompanyProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerCompanyProfile")] + [OutputType(typeof(PSCustomerCompanyProfile))] + public class GetPartnerCustomerCompanyProfile : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -25,7 +27,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(new PSCustomerCompanyProfile(Partner.Customers[CustomerId].Profiles.Company.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + WriteObject(new PSCustomerCompanyProfile(await partner.Customers[CustomerId].Profiles.Company.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerConfigurationPolicy.cs b/src/PowerShell/Commands/GetPartnerCustomerConfigurationPolicy.cs index 74aed3d..bc7d667 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerConfigurationPolicy.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerConfigurationPolicy.cs @@ -3,19 +3,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; using Models; + using Models.Authentication; + using PartnerCenter.Models; using PartnerCenter.Models.DevicesDeployment; /// /// Return a list of configuration policies or a specific configration policy for the specified customer identifier. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerConfigurationPolicy"), OutputType(typeof(PSConfigurationPolicy))] - public class GetPartnerCustomerConfigurationPolicy : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerConfigurationPolicy")] + [OutputType(typeof(PSConfigurationPolicy))] + public class GetPartnerCustomerConfigurationPolicy : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -40,51 +41,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(PolicyId)) + + Scheduler.RunTask(async () => { - GetCustomerPolicies(CustomerId); - } - else - { - GetCustomerPolicy(CustomerId, PolicyId); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - /// - /// Gets the configuration policies for the specified customer from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private void GetCustomerPolicies(string customerId) - { - IEnumerable devicePolicy; - customerId.AssertNotEmpty(nameof(customerId)); - - devicePolicy = Partner.Customers[customerId].ConfigurationPolicies.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items; - WriteObject(devicePolicy.Select(d => new PSConfigurationPolicy(d)), true); - } - - /// - /// Gets the specified policy from the specified customer from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the policy. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetCustomerPolicy(string customerId, string policyId) - { - ConfigurationPolicy devicePolicy; - - customerId.AssertNotEmpty(nameof(customerId)); - policyId.AssertNotEmpty(nameof(policyId)); - - devicePolicy = Partner.Customers[customerId].ConfigurationPolicies[policyId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(new PSConfigurationPolicy(devicePolicy), true); + if (string.IsNullOrEmpty(PolicyId)) + { + ResourceCollection policies = await partner.Customers[CustomerId].ConfigurationPolicies.GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(policies.Items.Select(d => new PSConfigurationPolicy(d)), true); + } + else + { + ConfigurationPolicy policy = await partner.Customers[CustomerId].ConfigurationPolicies[PolicyId].GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(policy); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerDevice.cs b/src/PowerShell/Commands/GetPartnerCustomerDevice.cs index 38c1738..e3ee89a 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerDevice.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerDevice.cs @@ -3,18 +3,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.DevicesDeployment; + using PartnerCenter.Models; using PartnerCenter.Models.DevicesDeployment; /// - /// Return a list of devices in the specified device batch for the specified customer. + /// Gets a list of devices in the specified device batch for the specified customer. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerDevice"), OutputType(typeof(PSDevice))] - public class GetPartnerCustomerDevice : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerDevice")] + [OutputType(typeof(PSDevice))] + public class GetPartnerCustomerDevice : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -35,8 +37,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - IEnumerable devices = Partner.Customers[CustomerId].DeviceBatches[BatchId].Devices.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items; - WriteObject(devices.Select(d => new PSDevice(d)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection devices = await partner.Customers[CustomerId].DeviceBatches[BatchId].Devices.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(devices.Items.Select(d => new PSDevice(d)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerDeviceBatch.cs b/src/PowerShell/Commands/GetPartnerCustomerDeviceBatch.cs index cfc5afa..be1d6ab 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerDeviceBatch.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerDeviceBatch.cs @@ -3,18 +3,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.DevicesDeployment; + using PartnerCenter.Models; using PartnerCenter.Models.DevicesDeployment; /// /// Gets a colletion of device batches from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerDeviceBatch"), OutputType(typeof(PSDeviceBatch))] - public class GetPartnerCustomerDeviceBatch : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerDeviceBatch")] + [OutputType(typeof(PSDeviceBatch))] + public class GetPartnerCustomerDeviceBatch : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -28,8 +30,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - IEnumerable deviceBatch = Partner.Customers[CustomerId].DeviceBatches.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items; - WriteObject(deviceBatch.Select(db => new PSDeviceBatch(db)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection deviceBatch = await partner.Customers[CustomerId].DeviceBatches.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(deviceBatch.Items.Select(b => new PSDeviceBatch(b)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerEntitlement.cs b/src/PowerShell/Commands/GetPartnerCustomerEntitlement.cs index 9ef1612..f146089 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerEntitlement.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerEntitlement.cs @@ -3,19 +3,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; using Models.Entitlements; + using PartnerCenter.Models; using PartnerCenter.Models.Entitlements; /// /// Gets a list of entitlements for a customer from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerEntitlement"), OutputType(typeof(PSEntitlement))] - public class GetPartnerCustomerEntitlement : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerEntitlement")] + [OutputType(typeof(PSEntitlement))] + public class GetPartnerCustomerEntitlement : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -41,51 +42,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(OrderId)) + Scheduler.RunTask(async () => { - GetEntitlements(CustomerId); - } - else - { - GetEntitlements(CustomerId, OrderId); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection entitlements = await partner.Customers[CustomerId].Entitlements.GetAsync(ShowExpiry.ToBool(), CancellationToken).ConfigureAwait(false); - /// - /// Gets a list of entitlements from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the order. - /// - /// is empty or null. - /// - private void GetEntitlements(string customerId, string orderId) - { - IEnumerable entitlements; - - customerId.AssertNotEmpty(nameof(customerId)); - - entitlements = Partner.Customers[customerId].Entitlements.GetAsync(ShowExpiry.ToBool()).GetAwaiter().GetResult().Items.Where(e => e.ReferenceOrder.Id == orderId); - - WriteObject(entitlements.Select(e => new PSEntitlement(e)), true); - } - - /// - /// Gets a list of customers from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private void GetEntitlements(string customerId) - { - IEnumerable entitlements; - - customerId.AssertNotEmpty(nameof(customerId)); - - entitlements = Partner.Customers[customerId].Entitlements.GetAsync(ShowExpiry.ToBool()).GetAwaiter().GetResult().Items; - - WriteObject(entitlements.Select(e => new PSEntitlement(e)), true); + if (string.IsNullOrEmpty(OrderId)) + { + WriteObject(entitlements.Items.Select(e => new PSEntitlement(e)), true); + } + else + { + WriteObject(entitlements.Items.Where(e => e.ReferenceOrder.Id == OrderId).Select(e => new PSEntitlement(e)), true); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerLicenseDeploymentInfo.cs b/src/PowerShell/Commands/GetPartnerCustomerLicenseDeploymentInfo.cs index b60037b..57db8df 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerLicenseDeploymentInfo.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerLicenseDeploymentInfo.cs @@ -7,11 +7,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using System.Text.RegularExpressions; using Models.Analytics; + using Models.Authentication; using PartnerCenter.Models; using PartnerCenter.Models.Analytics; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerLicenseDeploymentInfo"), OutputType(typeof(PSCustomerLicensesDeploymentInsights))] - public class GetPartnerCustomerLicenseDeploymentInfo : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerLicenseDeploymentInfo")] + [OutputType(typeof(PSCustomerLicensesDeploymentInsights))] + public class GetPartnerCustomerLicenseDeploymentInfo : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -25,11 +27,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection insights; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection insights = await partner.Customers[CustomerId].Analytics.Licenses.Deployment.GetAsync(CancellationToken).ConfigureAwait(false); - insights = Partner.Customers[CustomerId].Analytics.Licenses.Deployment.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - WriteObject(insights.Items.Select(i => new PSCustomerLicensesDeploymentInsights(i)), true); + WriteObject(insights.Items.Select(i => new PSCustomerLicensesDeploymentInsights(i)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerManagedService.cs b/src/PowerShell/Commands/GetPartnerCustomerManagedService.cs index 7c4bd3c..177af14 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerManagedService.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerManagedService.cs @@ -6,16 +6,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; + using Models.ManagedServices; using PartnerCenter.Models; using PartnerCenter.Models.ManagedServices; - using PartnerCenter.PowerShell.Models.ManagedServices; /// /// Gets the customer's managed services from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerManagedService"), OutputType(typeof(PSManagedService))] - public class GetPartnerCustomerManagedService : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerManagedService")] + [OutputType(typeof(PSManagedService))] + public class GetPartnerCustomerManagedService : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -36,60 +37,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (!string.IsNullOrEmpty(ManagedServiceId)) + Scheduler.RunTask(async () => { - GetManagedService(CustomerId, ManagedServiceId); - } - else - { - GetManagedServices(CustomerId); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection managedServices = await partner.Customers.ById(CustomerId).ManagedServices.GetAsync(CancellationToken).ConfigureAwait(false); - /// - /// Gets the managed services for the customer. - /// - /// Identifier for the customer. - /// - /// is empty or null. - /// - private void GetManagedServices(string customerId) - { - ResourceCollection managedServices; - - customerId.AssertNotEmpty(nameof(customerId)); - - managedServices = Partner.Customers.ById(CustomerId).ManagedServices.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (managedServices.TotalCount > 0) - { - WriteObject(managedServices.Items.Select(s => new PSManagedService(s)), true); - } - } - - /// - /// Gets a specific managed service for a customer. - /// - /// The idnentifier for the customer. - /// The identifier of the managed service. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetManagedService(string customerId, string managedServiceId) - { - ResourceCollection managedServices; - - customerId.AssertNotEmpty(nameof(customerId)); - managedServiceId.AssertNotEmpty(nameof(managedServiceId)); - - managedServices = Partner.Customers.ById(CustomerId).ManagedServices.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (managedServices.TotalCount > 0) - { - WriteObject(managedServices.Items.Where(s => s.Id == managedServiceId).Select(i => new PSManagedService(i)), true); - } + if (string.IsNullOrEmpty(ManagedServiceId)) + { + WriteObject(managedServices.Items.Select(s => new PSManagedService(s)), true); + } + else + { + WriteObject(managedServices.Items.Where(s => s.Id == ManagedServiceId).Select(i => new PSManagedService(i)), true); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerOrder.cs b/src/PowerShell/Commands/GetPartnerCustomerOrder.cs index 249461b..66bccf6 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerOrder.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerOrder.cs @@ -3,20 +3,21 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; + using Models.Orders; + using PartnerCenter.Models; using PartnerCenter.Models.Offers; using PartnerCenter.Models.Orders; - using PartnerCenter.PowerShell.Models.Orders; /// /// Get a customer, or a list of customers, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerOrder"), OutputType(typeof(PSOrder))] - public class GetPartnerCustomerOrder : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerOrder")] + [OutputType(typeof(PSOrder))] + public class GetPartnerCustomerOrder : PartnerAsyncCmdlet { /// /// Gets or sets the optional cilling cycle identifier. @@ -55,64 +56,32 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(OrderId)) + Scheduler.RunTask(async () => { - GetCustomerOrders(CustomerId, BillingCycle); - } - else - { - GetCustomerOrder(CustomerId, OrderId); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - /// - /// Gets the specified customer order from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the order. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetCustomerOrder(string customerId, string orderId) - { - Order order; - bool includePrice = IncludePrice.ToBool(); + if (string.IsNullOrEmpty(OrderId)) + { + ResourceCollection orders; - customerId.AssertNotEmpty(nameof(customerId)); - orderId.AssertNotEmpty(nameof(orderId)); + if (BillingCycle.HasValue) + { + orders = await partner.Customers.ById(CustomerId).Orders.ByBillingCycleType(BillingCycle.Value).GetAsync(IncludePrice.ToBool(), CancellationToken).ConfigureAwait(false); + } + else + { + orders = await partner.Customers.ById(CustomerId).Orders.GetAsync(IncludePrice.ToBool(), CancellationToken).ConfigureAwait(false); + } - order = Partner.Customers.ById(customerId).Orders.ById(orderId).GetAsync(includePrice).GetAwaiter().GetResult(); + WriteObject(orders.Items.Select(o => new PSOrder(o)), true); + } + else + { + Order order = await partner.Customers.ById(CustomerId).Orders.ById(OrderId).GetAsync(IncludePrice.ToBool(), CancellationToken).ConfigureAwait(false); + WriteObject(new PSOrder(order)); + } - WriteObject(new PSOrder(order)); - } - - /// - /// Gets a list of customer orders from Partner Center. - /// - /// Identifier of the customer. - /// BillingCycle identifier. - /// - /// is empty or null. - /// - private void GetCustomerOrders(string customerId, BillingCycleType? billingCycle) - { - IEnumerable orders; - bool includePrice = IncludePrice.ToBool(); - - customerId.AssertNotEmpty(nameof(customerId)); - - if (billingCycle.HasValue) - { - orders = Partner.Customers.ById(customerId).Orders.ByBillingCycleType(billingCycle.Value).GetAsync(includePrice).GetAwaiter().GetResult().Items; - } - else - { - orders = Partner.Customers.ById(customerId).Orders.GetAsync(includePrice).GetAwaiter().GetResult().Items; - } - - WriteObject(orders.Select(o => new PSOrder(o)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerOrderLineItemActivationLink.cs b/src/PowerShell/Commands/GetPartnerCustomerOrderLineItemActivationLink.cs index bb02670..aaf8c16 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerOrderLineItemActivationLink.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerOrderLineItemActivationLink.cs @@ -5,6 +5,8 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; + using PartnerCenter.Models; using PartnerCenter.Models.Orders; /// @@ -12,7 +14,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// [Cmdlet(VerbsCommon.Get, "PartnerCustomerOrderLineItemActivationLink")] [OutputType(typeof(OrderLineItemActivationLink))] - public class GetPartnerCustomerOrderLineItemActivationLink : PartnerCmdlet + public class GetPartnerCustomerOrderLineItemActivationLink : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -40,7 +42,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(Partner.Customers[CustomerId].Orders[OrderId].OrderLineItems[OrderLineItemNumber].ActivationLink.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items, true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection links = await partner.Customers[CustomerId].Orders[OrderId].OrderLineItems[OrderLineItemNumber].ActivationLink.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(links.Items, true); + + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerOrderProvisioningStatus.cs b/src/PowerShell/Commands/GetPartnerCustomerOrderProvisioningStatus.cs index 53c4161..bae0c51 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerOrderProvisioningStatus.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerOrderProvisioningStatus.cs @@ -5,14 +5,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.Orders; + using PartnerCenter.Models; + using PartnerCenter.Models.Orders; /// /// Gets the provisioning status for the specified order. /// [Cmdlet(VerbsCommon.Get, "PartnerCustomerOrderProvisioningStatus")] [OutputType(typeof(PSOrderLineItemProvisioningStatus))] - public class GetPartnerCustomerOrderProvisioningStatus : PartnerCmdlet + public class GetPartnerCustomerOrderProvisioningStatus : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -31,7 +34,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(Partner.Customers[CustomerId].Orders[OrderId].ProvisioningStatus.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(s => new PSOrderLineItemProvisioningStatus(s))); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection status = await partner.Customers[CustomerId].Orders[OrderId].ProvisioningStatus.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(status.Items.Select(s => new PSOrderLineItemProvisioningStatus(s))); + }, true); } } } diff --git a/src/PowerShell/Commands/GetPartnerCustomerQualification.cs b/src/PowerShell/Commands/GetPartnerCustomerQualification.cs index 44d4e7f..00b9602 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerQualification.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerQualification.cs @@ -5,13 +5,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.Customers; /// /// Gets the qualification for a customer from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerQualification"), OutputType(typeof(CustomerQualification))] - public class GetPartnerCustomerQualification : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerQualification")] + [OutputType(typeof(CustomerQualification))] + public class GetPartnerCustomerQualification : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -25,7 +27,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(Partner.Customers[CustomerId].Qualification.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + CustomerQualification qualification = await partner.Customers[CustomerId].Qualification.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(qualification); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerServiceCosts.cs b/src/PowerShell/Commands/GetPartnerCustomerServiceCosts.cs index 6884a42..53c09ec 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerServiceCosts.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerServiceCosts.cs @@ -6,12 +6,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.ServiceCosts; using PartnerCenter.Models; using PartnerCenter.Models.ServiceCosts; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerServiceCosts"), OutputType(typeof(PSServiceCostLineItem))] - public class GetPartnerCustomerServiceCosts : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerServiceCosts")] + [OutputType(typeof(PSServiceCostLineItem))] + public class GetPartnerCustomerServiceCosts : PartnerAsyncCmdlet { /// /// Gets or sets the billing period. @@ -32,11 +34,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection lineItems; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection lineItems = await partner.Customers[CustomerId].ServiceCosts.ByBillingPeriod(BillingPeriod).LineItems.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(lineItems.Items.Select(i => new PSServiceCostLineItem(i)), true); + }, true); - lineItems = Partner.Customers[CustomerId].ServiceCosts.ByBillingPeriod(BillingPeriod).LineItems.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(lineItems.Items.Select(i => new PSServiceCostLineItem(i)), true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerServiceCostsSummary.cs b/src/PowerShell/Commands/GetPartnerCustomerServiceCostsSummary.cs index e378555..670e2e7 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerServiceCostsSummary.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerServiceCostsSummary.cs @@ -5,11 +5,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.ServiceCosts; using PartnerCenter.Models.ServiceCosts; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerServiceCostsSummary"), OutputType(typeof(PSServiceCostsSummary))] - public class GetPartnerCustomerServiceCostsSummary : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerServiceCostsSummary")] + [OutputType(typeof(PSServiceCostsSummary))] + public class GetPartnerCustomerServiceCostsSummary : PartnerAsyncCmdlet { /// /// Gets or sets the billing period. @@ -30,9 +32,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ServiceCostsSummary summary = Partner.Customers[CustomerId].ServiceCosts.ByBillingPeriod(BillingPeriod).Summary.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ServiceCostsSummary summary = await partner.Customers[CustomerId].ServiceCosts.ByBillingPeriod(BillingPeriod).Summary.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(new PSServiceCostsSummary(summary)); + WriteObject(new PSServiceCostsSummary(summary)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscribedSku.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscribedSku.cs index 60377ca..bd4ce1f 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscribedSku.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscribedSku.cs @@ -6,12 +6,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Licenses; using PartnerCenter.Models; using PartnerCenter.Models.Licenses; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscribedSku"), OutputType(typeof(PSSubscribedSku))] - public class GetPartnerCustomerSubscribedSku : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscribedSku")] + [OutputType(typeof(PSSubscribedSku))] + public class GetPartnerCustomerSubscribedSku : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -32,8 +34,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection subscribedSkus = Partner.Customers[CustomerId].SubscribedSkus.GetAsync(LicenseGroup?.Select(item => item).ToList()).GetAwaiter().GetResult(); - WriteObject(subscribedSkus.Items.Select(s => new PSSubscribedSku(s)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection subscribedSkus = await partner.Customers[CustomerId].SubscribedSkus.GetAsync(LicenseGroup?.Select(item => item).ToList(), CancellationToken).ConfigureAwait(false); + + WriteObject(subscribedSkus.Items.Select(s => new PSSubscribedSku(s)), true); + }, true); + } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscription.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscription.cs index 098f4a7..50d2cb8 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscription.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscription.cs @@ -74,22 +74,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands if (!string.IsNullOrWhiteSpace(MpnId)) { - subscriptions = await partner.Customers[customerId].Subscriptions.ByPartner(MpnId).GetAsync().ConfigureAwait(false); + subscriptions = await partner.Customers[customerId].Subscriptions.ByPartner(MpnId).GetAsync(CancellationToken).ConfigureAwait(false); } else if (!string.IsNullOrWhiteSpace(OrderId)) { - subscriptions = await partner.Customers[customerId].Subscriptions.ByOrder(OrderId).GetAsync().ConfigureAwait(false); + subscriptions = await partner.Customers[customerId].Subscriptions.ByOrder(OrderId).GetAsync(CancellationToken).ConfigureAwait(false); } else { - subscriptions = await partner.Customers[customerId].Subscriptions.GetAsync().ConfigureAwait(false); + subscriptions = await partner.Customers[customerId].Subscriptions.GetAsync(CancellationToken).ConfigureAwait(false); } WriteObject(subscriptions.Items.Select(s => new PSSubscription(s)), true); } else { - WriteObject(new PSSubscription(await partner.Customers[customerId].Subscriptions[SubscriptionId].GetAsync().ConfigureAwait(false))); + WriteObject(new PSSubscription(await partner.Customers[customerId].Subscriptions[SubscriptionId].GetAsync(CancellationToken).ConfigureAwait(false))); } }, true); } diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionAddOn.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionAddOn.cs index 215b386..e71d645 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionAddOn.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionAddOn.cs @@ -9,12 +9,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using PartnerCenter.Models; using PartnerCenter.Models.Subscriptions; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionAddOn"), OutputType(typeof(PSSubscription))] - public class GetPartnerCustomerSubscriptionAddOn : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionAddOn")] + [OutputType(typeof(PSSubscription))] + public class GetPartnerCustomerSubscriptionAddOn : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -35,8 +37,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection subscripions = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].AddOns.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(subscripions.Items.Select(s => new PSSubscription(s)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection subscripions = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].AddOns.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(subscripions.Items.Select(s => new PSSubscription(s)), true); + }, true); + } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionMeterUsage.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionMeterUsage.cs index 05c24b1..5c76186 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionMeterUsage.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionMeterUsage.cs @@ -6,12 +6,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Usage; using PartnerCenter.Models; using PartnerCenter.Models.Usage; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionMeterUsage"), OutputType(typeof(PSMeterUsageRecord))] - public class GetPartnerCustomerSubscriptionMeterUsage : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionMeterUsage")] + [OutputType(typeof(PSMeterUsageRecord))] + public class GetPartnerCustomerSubscriptionMeterUsage : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -32,10 +34,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection usageRecords; - - usageRecords = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].UsageRecords.ByMeter.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(usageRecords.Items.Select(r => new PSMeterUsageRecord(r)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection usageRecords = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].UsageRecords.ByMeter.GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(usageRecords.Items.Select(r => new PSMeterUsageRecord(r)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionProvisioningStatus.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionProvisioningStatus.cs index b1f4bf2..b2a7d40 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionProvisioningStatus.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionProvisioningStatus.cs @@ -5,14 +5,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using PartnerCenter.Models.Subscriptions; /// - /// Retrieves the provisioning status for the specified subscription. + /// Gets the provisioning status for the specified subscription. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionProvisioningStatus"), OutputType(typeof(PSSubscriptionProvisioningStatus))] - public class GetPartnerCustomerSubscriptionProvisioningStatus : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionProvisioningStatus")] + [OutputType(typeof(PSSubscriptionProvisioningStatus))] + public class GetPartnerCustomerSubscriptionProvisioningStatus : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -33,9 +35,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - SubscriptionProvisioningStatus status = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].ProvisioningStatus.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SubscriptionProvisioningStatus status = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].ProvisioningStatus.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(new PSSubscriptionProvisioningStatus(status)); + WriteObject(new PSSubscriptionProvisioningStatus(status)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionRegistrationStatus.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionRegistrationStatus.cs index 9db5801..c1f0155 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionRegistrationStatus.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionRegistrationStatus.cs @@ -5,14 +5,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using PartnerCenter.Models.Subscriptions; /// - /// Retrieves the registration status for the specified subscription. + /// Gets the registration status for the specified subscription. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionRegistrationStatus"), OutputType(typeof(PSSubscriptionRegistrationStatus))] - public class GetPartnerCustomerSubscriptionRegistrationStatus : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionRegistrationStatus")] + [OutputType(typeof(PSSubscriptionRegistrationStatus))] + public class GetPartnerCustomerSubscriptionRegistrationStatus : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -33,9 +35,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - SubscriptionRegistrationStatus status = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].RegistrationStatus.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SubscriptionRegistrationStatus status = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].RegistrationStatus.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(new PSSubscriptionRegistrationStatus(status)); + WriteObject(new PSSubscriptionRegistrationStatus(status)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionResourceUsage.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionResourceUsage.cs index 1b6f2a6..2f65caf 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionResourceUsage.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionResourceUsage.cs @@ -6,12 +6,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Usage; using PartnerCenter.Models; using PartnerCenter.Models.Usage; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionResourceUsage"), OutputType(typeof(PSResourceUsageRecord))] - public class GetPartnerCustomerSubscriptionResourceUsage : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionResourceUsage")] + [OutputType(typeof(PSResourceUsageRecord))] + public class GetPartnerCustomerSubscriptionResourceUsage : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -32,10 +34,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection usageRecords; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection usageRecords = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].UsageRecords.ByResource.GetAsync(CancellationToken).ConfigureAwait(false); - usageRecords = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].UsageRecords.ByResource.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(usageRecords.Items.Select(r => new PSResourceUsageRecord(r)), true); + WriteObject(usageRecords.Items.Select(r => new PSResourceUsageRecord(r)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionSupportContact.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionSupportContact.cs index 99cb008..20ceb93 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionSupportContact.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionSupportContact.cs @@ -5,11 +5,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using PartnerCenter.Models.Subscriptions; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionSupportContact"), OutputType(typeof(PSSupportContact))] - public class GetPartnerCustomerSubscriptionSupportContact : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionSupportContact")] + [OutputType(typeof(PSSupportContact))] + public class GetPartnerCustomerSubscriptionSupportContact : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -30,8 +32,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - SupportContact contact = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].SupportContact.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(new PSSupportContact(contact)); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SupportContact contact = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].SupportContact.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(new PSSupportContact(contact)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionUpgrades.cs b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionUpgrades.cs index 7ef3a5e..e35a48f 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerSubscriptionUpgrades.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerSubscriptionUpgrades.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.CustomerSubscriptionUpgrades; using PartnerCenter.Models; using PartnerCenter.Models.Subscriptions; @@ -13,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets the available upgrade offers for the specified subscription. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionUpgrades"), OutputType(typeof(PSCustomerSubscriptionUpgrades))] - public class GetCustomerSubscriptionUpgrades : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerSubscriptionUpgrades")] + [OutputType(typeof(PSCustomerSubscriptionUpgrades))] + public class GetCustomerSubscriptionUpgrades : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -35,10 +37,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection upgrades; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection upgrades = await partner.Customers.ById(CustomerId).Subscriptions.ById(SubscriptionId).Upgrades.GetAsync(CancellationToken).ConfigureAwait(false); - upgrades = Partner.Customers.ById(CustomerId).Subscriptions.ById(SubscriptionId).Upgrades.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(upgrades.Items.Select(c => new PSCustomerSubscriptionUpgrades(c)), true); + WriteObject(upgrades.Items.Select(c => new PSCustomerSubscriptionUpgrades(c)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerTrialConversion.cs b/src/PowerShell/Commands/GetPartnerCustomerTrialConversion.cs index d16d771..97cf142 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerTrialConversion.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerTrialConversion.cs @@ -6,12 +6,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.CustomerTrialConversion; using PartnerCenter.Models; using PartnerCenter.Models.Subscriptions; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerTrialConversion"), OutputType(typeof(PSCustomerTrialConversion))] - public class GetPartnerTrialConversion : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerTrialConversion")] + [OutputType(typeof(PSCustomerTrialConversion))] + public class GetPartnerTrialConversion : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -32,8 +34,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection conversions = Partner.Customers.ById(CustomerId).Subscriptions.ById(SubscriptionId).Conversions.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(conversions.Items.Select(c => new PSCustomerTrialConversion(c)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection conversions = await partner.Customers.ById(CustomerId).Subscriptions.ById(SubscriptionId).Conversions.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(conversions.Items.Select(c => new PSCustomerTrialConversion(c)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerUsageRecord.cs b/src/PowerShell/Commands/GetPartnerCustomerUsageRecord.cs index aa58c1f..471470b 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerUsageRecord.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerUsageRecord.cs @@ -5,21 +5,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.Usage; using PartnerCenter.Models; using PartnerCenter.Models.Usage; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerUsageRecord"), OutputType(typeof(PSCustomerUsageSummary))] - public class GetPartnerCustomerUsageRecord : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerUsageRecord")] + [OutputType(typeof(PSCustomerUsageSummary))] + public class GetPartnerCustomerUsageRecord : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - ResourceCollection usageRecords = Partner.Customers.UsageRecords.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection usageRecords = await partner.Customers.UsageRecords.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(usageRecords.Items.Select(r => new PSCustomerMonthlyUsageRecord(r)), true); + WriteObject(usageRecords.Items.Select(r => new PSCustomerMonthlyUsageRecord(r)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerUsageSummary.cs b/src/PowerShell/Commands/GetPartnerCustomerUsageSummary.cs index 6f6e69b..dd49ba0 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerUsageSummary.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerUsageSummary.cs @@ -5,10 +5,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Usage; + using PartnerCenter.Models.Usage; - [Cmdlet(VerbsCommon.Get, "PartnerCustomerUsageSummary"), OutputType(typeof(PSCustomerUsageSummary))] - public class GetPartnerCustomerUsageSummary : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerUsageSummary")] + [OutputType(typeof(PSCustomerUsageSummary))] + public class GetPartnerCustomerUsageSummary : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -22,7 +25,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(new PSCustomerUsageSummary(Partner.Customers[CustomerId].UsageSummary.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + CustomerUsageSummary usageSummary = await partner.Customers[CustomerId].UsageSummary.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCustomerUsageSummary(usageSummary)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerUser.cs b/src/PowerShell/Commands/GetPartnerCustomerUser.cs index 1ec43dd..250952d 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerUser.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerUser.cs @@ -8,24 +8,29 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Microsoft.Graph; + using Models.Authentication; using Models.Users; + using Network; using PartnerCenter.Enumerators; using PartnerCenter.Models; using PartnerCenter.Models.Query; using PartnerCenter.Models.Users; + using RequestContext; /// /// Gets a list of users for a customer from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerUser", DefaultParameterSetName = "ByCustomerId"), OutputType(typeof(PSCustomerUser))] - public class GetPartnerCustomerUser : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerUser", DefaultParameterSetName = "ByCustomerId")] + [OutputType(typeof(PSCustomerUser))] + public class GetPartnerCustomerUser : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. /// [Parameter(ParameterSetName = "ByCustomerId", Mandatory = true, Position = 0, HelpMessage = "The identifier for the customer.")] [Parameter(ParameterSetName = "ByUserId", Mandatory = true, Position = 0, HelpMessage = "The identifier for the customer.")] + [Parameter(ParameterSetName = "ByUserState", Mandatory = true, Position = 0, HelpMessage = "The identifier for the customer.")] [Parameter(ParameterSetName = "ByUpn", Mandatory = true, Position = 0, HelpMessage = "The identifier for the customer.")] [ValidatePattern(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", Options = RegexOptions.Compiled | RegexOptions.IgnoreCase)] public string CustomerId { get; set; } @@ -47,7 +52,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets or sets the optional user identifier. /// - [Parameter(ParameterSetName = "ByCustomerId", Mandatory = false, HelpMessage = "A flag that indicates whether or not to show deleted users.")] + [Parameter(ParameterSetName = "ByUserState", Mandatory = true, HelpMessage = "A flag that indicates whether or not to get deleted users.")] [ValidateNotNullOrEmpty] public SwitchParameter ReturnDeletedUsers { get; set; } @@ -56,128 +61,66 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - switch (ParameterSetName) + Scheduler.RunTask(async () => { - case "ByCustomerId": - if (ReturnDeletedUsers) + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + if (ParameterSetName.Equals("ByCustomerId", StringComparison.InvariantCultureIgnoreCase)) + { + IResourceCollectionEnumerator> usersEnumerator; + List users; + SeekBasedResourceCollection seekUsers; + + users = new List(); + + seekUsers = await partner.Customers[CustomerId].Users.GetAsync(CancellationToken).ConfigureAwait(false); + usersEnumerator = partner.Enumerators.CustomerUsers.Create(seekUsers); + + while (usersEnumerator.HasValue) { - List users = GetDeletedUsers(CustomerId); - WriteObject(users.Select(u => new PSCustomerUser(u)), true); - } - else - { - List users = GetUsers(CustomerId); - WriteObject(users.Select(u => new PSCustomerUser(u)), true); + users.AddRange(usersEnumerator.Current.Items); + await usersEnumerator.NextAsync(RequestContextFactory.Create(CorrelationId), CancellationToken).ConfigureAwait(false); } - break; - case "ByUpn": - GetUserByUpn(CustomerId, UserPrincipalName); - break; - case "ByUserId": - GetUserById(CustomerId, UserId); - break; - } - } + WriteObject(users.Select(u => new PSCustomerUser(u)), true); + } + else if (ParameterSetName.Equals("ByUserId", StringComparison.InvariantCultureIgnoreCase)) + { + CustomerUser customerUser = await partner.Customers[CustomerId].Users[UserId].GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(new PSCustomerUser(customerUser)); + } + else if (ParameterSetName.Equals("ByUserState", StringComparison.InvariantCultureIgnoreCase)) + { + SimpleFieldFilter filter = new SimpleFieldFilter("UserState", FieldFilterOperation.Equals, "Inactive"); + IQuery simpleQueryWithFilter = QueryFactory.BuildSimpleQuery(filter); + IResourceCollectionEnumerator> usersEnumerator; + List users; + SeekBasedResourceCollection seekUsers; - /// - /// Gets a details for a specified user and customer from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user. - /// - /// is empty or null. - /// - private void GetUserById(string customerId, string userId) - { + users = new List(); - customerId.AssertNotEmpty(nameof(customerId)); - userId.AssertNotEmpty(nameof(userId)); + seekUsers = await partner.Customers[CustomerId].Users.QueryAsync(simpleQueryWithFilter, CancellationToken).ConfigureAwait(false); + usersEnumerator = partner.Enumerators.CustomerUsers.Create(seekUsers); - WriteObject(new PSCustomerUser(Partner.Customers[customerId].Users[userId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); - } + while (usersEnumerator.HasValue) + { + users.AddRange(usersEnumerator.Current.Items); + await usersEnumerator.NextAsync(RequestContextFactory.Create(CorrelationId), CancellationToken).ConfigureAwait(false); + } - /// - /// Gets a list of users from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private List GetUsers(string customerId) - { - IResourceCollectionEnumerator> usersEnumerator; - List users; - SeekBasedResourceCollection seekUsers; + WriteObject(users.Select(u => new PSCustomerUser(u)), true); + } + else if (ParameterSetName.Equals("ByUpn", StringComparison.InvariantCultureIgnoreCase)) + { + GraphServiceClient client = PartnerSession.Instance.ClientFactory.CreateGraphServiceClient() as GraphServiceClient; + client.AuthenticationProvider = new GraphAuthenticationProvider(CustomerId); - customerId.AssertNotEmpty(nameof(customerId)); + Graph.User user = await client.Users[UserPrincipalName].Request().GetAsync(CancellationToken).ConfigureAwait(false); + CustomerUser customerUser = await partner.Customers[CustomerId].Users[user.Id].GetAsync(CancellationToken).ConfigureAwait(false); - users = new List(); - - seekUsers = Partner.Customers[customerId].Users.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - usersEnumerator = Partner.Enumerators.CustomerUsers.Create(seekUsers); - - while (usersEnumerator.HasValue) - { - users.AddRange(usersEnumerator.Current.Items); - usersEnumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - - return users; - } - - /// - /// Gets a list of deleted users from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private List GetDeletedUsers(string customerId) - { - SimpleFieldFilter filter = new SimpleFieldFilter("UserState", FieldFilterOperation.Equals, "Inactive"); - IQuery simpleQueryWithFilter = QueryFactory.BuildSimpleQuery(filter); - IResourceCollectionEnumerator> usersEnumerator; - List users; - SeekBasedResourceCollection seekUsers; - - customerId.AssertNotEmpty(nameof(customerId)); - - users = new List(); - - seekUsers = Partner.Customers[customerId].Users.QueryAsync(simpleQueryWithFilter).GetAwaiter().GetResult(); - usersEnumerator = Partner.Enumerators.CustomerUsers.Create(seekUsers); - - while (usersEnumerator.HasValue) - { - users.AddRange(usersEnumerator.Current.Items); - usersEnumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - - return users; - } - - /// - /// Gets a list of users by searching for the user principal name from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user principal name. - /// - /// is empty or null. - /// - private void GetUserByUpn(string customerId, string userPrincipalName) - { - - customerId.AssertNotEmpty(nameof(customerId)); - customerId.AssertNotEmpty(nameof(userPrincipalName)); - - List gUsers = GetUsers(customerId); - CustomerUser fUser = gUsers.SingleOrDefault(u => string.Equals(u.UserPrincipalName, userPrincipalName, StringComparison.CurrentCultureIgnoreCase)); - - if (fUser != null) - { - WriteObject(new PSCustomerUser(fUser)); - } + WriteObject(customerUser); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerCustomerUserRole.cs b/src/PowerShell/Commands/GetPartnerCustomerUserRole.cs index 237af67..b376c56 100644 --- a/src/PowerShell/Commands/GetPartnerCustomerUserRole.cs +++ b/src/PowerShell/Commands/GetPartnerCustomerUserRole.cs @@ -3,19 +3,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; using Models.Roles; + using PartnerCenter.Models; using PartnerCenter.Models.Roles; /// /// Gets a list of roles for the specified customer user from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerCustomerUserRole"), OutputType(typeof(PSDirectoryRole))] - public class GetPartnerCustomerUserRole : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerCustomerUserRole")] + [OutputType(typeof(PSDirectoryRole))] + public class GetPartnerCustomerUserRole : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -36,52 +37,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(UserId)) + Scheduler.RunTask(async () => { - GetRole(CustomerId); - } - else - { - GetRole(CustomerId, UserId); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection roles; - /// - /// Gets a list of roles from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetRole(string customerId, string userId) - { - IEnumerable roles; + if (string.IsNullOrEmpty(UserId)) + { + roles = await partner.Customers[CustomerId].DirectoryRoles.GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + roles = await partner.Customers[CustomerId].Users[UserId].DirectoryRoles.GetAsync(CancellationToken).ConfigureAwait(false); + } - customerId.AssertNotEmpty(nameof(customerId)); - userId.AssertNotEmpty(nameof(userId)); - - roles = Partner.Customers[customerId].Users[userId].DirectoryRoles.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items; - WriteObject(roles.Select(e => new PSDirectoryRole(e)), true); - } - - /// - /// Gets a list of customers from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private void GetRole(string customerId) - { - IEnumerable roles; - - customerId.AssertNotEmpty(nameof(customerId)); - - roles = Partner.Customers[customerId].DirectoryRoles.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items; - WriteObject(roles.Select(e => new PSDirectoryRole(e)), true); + WriteObject(roles.Items.Select(r => new PSDirectoryRole(r)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerIndirectReseller.cs b/src/PowerShell/Commands/GetPartnerIndirectReseller.cs index c4fa5be..6d18b09 100644 --- a/src/PowerShell/Commands/GetPartnerIndirectReseller.cs +++ b/src/PowerShell/Commands/GetPartnerIndirectReseller.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Relationships; using PartnerCenter.Models; using PartnerCenter.Models.Relationships; @@ -13,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets a list of indirect resellers from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerIndirectReseller"), OutputType(typeof(PSPartnerRelationship))] - public class GetPartnerIndirectReseller : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerIndirectReseller")] + [OutputType(typeof(PSPartnerRelationship))] + public class GetPartnerIndirectReseller : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -28,19 +30,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection resellers; - - if (string.IsNullOrEmpty(CustomerId)) + Scheduler.RunTask(async () => { - resellers = Partner.Relationships.GetAsync(PartnerRelationshipType.IsIndirectCloudSolutionProviderOf).GetAwaiter().GetResult(); - } - else - { - resellers = Partner.Customers[CustomerId].Relationships.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection resellers; - WriteObject(resellers.Items.Select(r => new PSPartnerRelationship(r)), true); + if (string.IsNullOrEmpty(CustomerId)) + { + resellers = await partner.Relationships.GetAsync(PartnerRelationshipType.IsIndirectCloudSolutionProviderOf, CancellationToken).ConfigureAwait(false); + } + else + { + resellers = await partner.Customers[CustomerId].Relationships.GetAsync(CancellationToken).ConfigureAwait(false); + } + WriteObject(resellers.Items.Select(r => new PSPartnerRelationship(r)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerInvoice.cs b/src/PowerShell/Commands/GetPartnerInvoice.cs index 3bf5583..a43ad8e 100644 --- a/src/PowerShell/Commands/GetPartnerInvoice.cs +++ b/src/PowerShell/Commands/GetPartnerInvoice.cs @@ -7,15 +7,18 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using Enumerators; + using Models.Authentication; using Models.Invoices; using PartnerCenter.Models; using PartnerCenter.Models.Invoices; + using RequestContext; /// /// Gets a list of invoices from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerInvoice"), OutputType(typeof(PSInvoice))] - public class GetPartnerInvoice : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerInvoice")] + [OutputType(typeof(PSInvoice))] + public class GetPartnerInvoice : PartnerAsyncCmdlet { /// /// Gets or sets the invoice identifier. @@ -29,34 +32,34 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(InvoiceId)) + Scheduler.RunTask(async () => { - GetInvoices(); - } - else - { - WriteObject(new PSInvoice(Partner.Invoices[InvoiceId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - private void GetInvoices() - { - IResourceCollectionEnumerator> enumerator; - List invoices; - ResourceCollection resources; + if (string.IsNullOrEmpty(InvoiceId)) + { + IResourceCollectionEnumerator> enumerator; + List invoices; + ResourceCollection resources; - resources = Partner.Invoices.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - enumerator = Partner.Enumerators.Invoices.Create(resources); + resources = await partner.Invoices.GetAsync(CancellationToken).ConfigureAwait(false); + enumerator = partner.Enumerators.Invoices.Create(resources); - invoices = new List(); + invoices = new List(); - while (enumerator.HasValue) - { - invoices.AddRange(enumerator.Current.Items.Select(i => new PSInvoice(i))); - enumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } + while (enumerator.HasValue) + { + invoices.AddRange(enumerator.Current.Items.Select(i => new PSInvoice(i))); + await enumerator.NextAsync(RequestContextFactory.Create(CorrelationId), CancellationToken).ConfigureAwait(false); + } - WriteObject(invoices, true); + WriteObject(invoices, true); + } + else + { + WriteObject(new PSInvoice(await partner.Invoices[InvoiceId].GetAsync(CancellationToken).ConfigureAwait(false))); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerInvoiceStatement.cs b/src/PowerShell/Commands/GetPartnerInvoiceStatement.cs index 5e27df5..b6636a4 100644 --- a/src/PowerShell/Commands/GetPartnerInvoiceStatement.cs +++ b/src/PowerShell/Commands/GetPartnerInvoiceStatement.cs @@ -6,12 +6,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.IO; using System.Management.Automation; + using Models.Authentication; /// - /// Get partner licenses usage information aggregated to include all customers from Partner Center. + /// Get partner invoice statement from Partner Center. /// [Cmdlet(VerbsCommon.Get, "PartnerInvoiceStatement")] - public class GetPartnerInvoiceStatement : PartnerCmdlet + public class GetPartnerInvoiceStatement : PartnerAsyncCmdlet { /// /// The invoice id of the statement to retrieve. @@ -39,36 +40,41 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(OutputPath)) + Scheduler.RunTask(async () => { - OutputPath = Directory.GetCurrentDirectory(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - DirectoryInfo dirInfo = Directory.CreateDirectory(OutputPath); - string filePath; + if (string.IsNullOrEmpty(OutputPath)) + { + OutputPath = Directory.GetCurrentDirectory(); + } - if (dirInfo.FullName.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture), System.StringComparison.CurrentCulture)) - { - filePath = $"{dirInfo.FullName}{InvoiceId}.pdf"; - } - else - { - filePath = $"{dirInfo.FullName}{Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture)}{InvoiceId}.pdf"; - } + DirectoryInfo dirInfo = Directory.CreateDirectory(OutputPath); + string filePath; - if (File.Exists(filePath) && !Overwrite.IsPresent) - { - throw new PSInvalidOperationException($"The path already exists: {filePath}. Specify the -Overwrite switch to overwrite the file"); - } + if (dirInfo.FullName.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture), System.StringComparison.CurrentCulture)) + { + filePath = $"{dirInfo.FullName}{InvoiceId}.pdf"; + } + else + { + filePath = $"{dirInfo.FullName}{Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture)}{InvoiceId}.pdf"; + } - using (Stream stream = Partner.Invoices.ById(InvoiceId).Documents.Statement.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult()) - { - FileStream file = File.Create(filePath); - stream.Seek(0, SeekOrigin.Begin); - stream.CopyTo(file); + if (File.Exists(filePath) && !Overwrite.IsPresent) + { + throw new PSInvalidOperationException($"The path already exists: {filePath}. Specify the -Overwrite switch to overwrite the file"); + } - file.Close(); - } + using (Stream stream = await partner.Invoices.ById(InvoiceId).Documents.Statement.GetAsync(CancellationToken).ConfigureAwait(false)) + { + FileStream file = File.Create(filePath); + stream.Seek(0, SeekOrigin.Begin); + stream.CopyTo(file); + + file.Close(); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerInvoiceSummary.cs b/src/PowerShell/Commands/GetPartnerInvoiceSummary.cs index 384d9d9..512c751 100644 --- a/src/PowerShell/Commands/GetPartnerInvoiceSummary.cs +++ b/src/PowerShell/Commands/GetPartnerInvoiceSummary.cs @@ -5,21 +5,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.Invoices; using PartnerCenter.Models; using PartnerCenter.Models.Invoices; - [Cmdlet(VerbsCommon.Get, "PartnerInvoiceSummary"), OutputType(typeof(PSInvoiceSummary))] - public class GetPartnerInvoiceSummary : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerInvoiceSummary")] + [OutputType(typeof(PSInvoiceSummary))] + public class GetPartnerInvoiceSummary : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - ResourceCollection summaries = Partner.Invoices.Summaries.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection summaries = await partner.Invoices.Summaries.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(summaries.Items.Select(s => new PSInvoiceSummary(s)), true); + WriteObject(summaries.Items.Select(s => new PSInvoiceSummary(s)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerInvoiceTaxReceiptStatement.cs b/src/PowerShell/Commands/GetPartnerInvoiceTaxReceiptStatement.cs index d2b895e..c674667 100644 --- a/src/PowerShell/Commands/GetPartnerInvoiceTaxReceiptStatement.cs +++ b/src/PowerShell/Commands/GetPartnerInvoiceTaxReceiptStatement.cs @@ -6,12 +6,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.IO; using System.Management.Automation; + using Models.Authentication; /// /// Get partner licenses usage information aggregated to include all customers from Partner Center. /// [Cmdlet(VerbsCommon.Get, "PartnerInvoiceTaxReceiptStatement")] - public class GetPartnerInvoiceTaxReceiptStatement : PartnerCmdlet + public class GetPartnerInvoiceTaxReceiptStatement : PartnerAsyncCmdlet { /// /// The invoice identifier of the statement to retrieve. @@ -46,43 +47,48 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (string.IsNullOrEmpty(OutputPath)) + Scheduler.RunTask(async () => { - OutputPath = Directory.GetCurrentDirectory(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - DirectoryInfo dirInfo = Directory.CreateDirectory(OutputPath); - string filePath; - - if (dirInfo.FullName.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture), System.StringComparison.CurrentCulture)) - { - filePath = dirInfo.FullName + InvoiceId + ".pdf"; - } - else - { - filePath = dirInfo.FullName + Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture) + InvoiceId + ".pdf"; - } - - if (File.Exists(filePath) && !Overwrite.IsPresent) - { - throw new PSInvalidOperationException("The path already exists: " + filePath + ". Specify the -Overwrite switch to overwrite the file"); - } - - FileStream fileStream = null; - - try - { - using (Stream stream = Partner.Invoices.ById(InvoiceId).Documents.Statement.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult()) + if (string.IsNullOrEmpty(OutputPath)) { - fileStream = File.Create(filePath); - stream.Seek(0, SeekOrigin.Begin); - stream.CopyTo(fileStream); + OutputPath = Directory.GetCurrentDirectory(); } - } - finally - { - fileStream?.Dispose(); - } + + DirectoryInfo dirInfo = Directory.CreateDirectory(OutputPath); + string filePath; + + if (dirInfo.FullName.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture), System.StringComparison.CurrentCulture)) + { + filePath = dirInfo.FullName + InvoiceId + ".pdf"; + } + else + { + filePath = dirInfo.FullName + Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentCulture) + InvoiceId + ".pdf"; + } + + if (File.Exists(filePath) && !Overwrite.IsPresent) + { + throw new PSInvalidOperationException("The path already exists: " + filePath + ". Specify the -Overwrite switch to overwrite the file"); + } + + FileStream fileStream = null; + + try + { + using (Stream stream = await partner.Invoices.ById(InvoiceId).Documents.Statement.GetAsync(CancellationToken).ConfigureAwait(false)) + { + fileStream = File.Create(filePath); + stream.Seek(0, SeekOrigin.Begin); + stream.CopyTo(fileStream); + } + } + finally + { + fileStream?.Dispose(); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerLegalProfile.cs b/src/PowerShell/Commands/GetPartnerLegalProfile.cs index 2bb374e..c92e904 100644 --- a/src/PowerShell/Commands/GetPartnerLegalProfile.cs +++ b/src/PowerShell/Commands/GetPartnerLegalProfile.cs @@ -4,20 +4,28 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.Partners; + using PartnerCenter.Models.Partners; /// /// Gets the partner organization profile from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerLegalProfile"), OutputType(typeof(PSLegalBusinessProfile))] - public class GetPartnerLegalProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerLegalProfile")] + [OutputType(typeof(PSLegalBusinessProfile))] + public class GetPartnerLegalProfile : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - WriteObject(new PSLegalBusinessProfile(Partner.Profiles.LegalBusinessProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSLegalBusinessProfile(await partner.Profiles.LegalBusinessProfile.GetAsync(VettingVersion.Current, CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerLicenseDeploymentInfo.cs b/src/PowerShell/Commands/GetPartnerLicenseDeploymentInfo.cs index 75f53a7..bb07c3e 100644 --- a/src/PowerShell/Commands/GetPartnerLicenseDeploymentInfo.cs +++ b/src/PowerShell/Commands/GetPartnerLicenseDeploymentInfo.cs @@ -6,22 +6,29 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using Models.Analytics; + using Models.Authentication; using PartnerCenter.Models; using PartnerCenter.Models.Analytics; /// /// Get partner licenses deployment information aggregated to include all customers from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerLicenseDeploymentInfo"), OutputType(typeof(PSPartnerLicensesDeploymentInsight))] - public class GetPartnerLicenseDeploymentInfo : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerLicenseDeploymentInfo")] + [OutputType(typeof(PSPartnerLicensesDeploymentInsight))] + public class GetPartnerLicenseDeploymentInfo : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - ResourceCollection insights = Partner.Analytics.Licenses.Deployment.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(insights.Items.Select(l => new PSPartnerLicensesDeploymentInsight(l)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection insights = await partner.Analytics.Licenses.Deployment.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(insights.Items.Select(l => new PSPartnerLicensesDeploymentInsight(l)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerLicenseUsageInfo.cs b/src/PowerShell/Commands/GetPartnerLicenseUsageInfo.cs index bb70c5f..ca1afaa 100644 --- a/src/PowerShell/Commands/GetPartnerLicenseUsageInfo.cs +++ b/src/PowerShell/Commands/GetPartnerLicenseUsageInfo.cs @@ -6,22 +6,29 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using Models.Analytics; + using Models.Authentication; using PartnerCenter.Models; using PartnerCenter.Models.Analytics; /// /// Get partner licenses usage information aggregated to include all customers from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerLicenseUsageInfo"), OutputType(typeof(PSPartnerLicensesUsageInsight))] - public class GetPartnerLicenseUsageInfo : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerLicenseUsageInfo")] + [OutputType(typeof(PSPartnerLicensesUsageInsight))] + public class GetPartnerLicenseUsageInfo : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - ResourceCollection insights = Partner.Analytics.Licenses.Usage.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(insights.Items.Select(l => new PSPartnerLicensesUsageInsight(l)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection insights = await partner.Analytics.Licenses.Usage.GetAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(insights.Items.Select(l => new PSPartnerLicensesUsageInsight(l)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerMpnProfile.cs b/src/PowerShell/Commands/GetPartnerMpnProfile.cs index 94c564d..2d7d787 100644 --- a/src/PowerShell/Commands/GetPartnerMpnProfile.cs +++ b/src/PowerShell/Commands/GetPartnerMpnProfile.cs @@ -4,16 +4,18 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.Partners; using PartnerCenter.Models.Partners; - [Cmdlet(VerbsCommon.Get, "PartnerMpnProfile"), OutputType(typeof(PSMpnProfile))] - public class GetPartnerMpnProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerMpnProfile")] + [OutputType(typeof(PSMpnProfile))] + public class GetPartnerMpnProfile : PartnerAsyncCmdlet { /// /// Gets or sets the MPN identifier. /// - [Parameter(HelpMessage = "The partner's MPN identifier.", Mandatory = false)] + [Parameter(HelpMessage = "The partner's Microsoft Partner Network (MPN) identifier.", Mandatory = false)] [ValidateNotNull] public string MpnId { get; set; } @@ -22,18 +24,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - MpnProfile profile; - - if (string.IsNullOrEmpty(MpnId)) + Scheduler.RunTask(async () => { - profile = Partner.Profiles.MpnProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - else - { - profile = Partner.Profiles.MpnProfile.GetAsync(MpnId).GetAwaiter().GetResult(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + MpnProfile profile; - WriteObject(new PSMpnProfile(profile)); + if (string.IsNullOrEmpty(MpnId)) + { + profile = await partner.Profiles.MpnProfile.GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + profile = await partner.Profiles.MpnProfile.GetAsync(MpnId, CancellationToken).ConfigureAwait(false); + } + + WriteObject(new PSMpnProfile(profile)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerOffer.cs b/src/PowerShell/Commands/GetPartnerOffer.cs index 9e58c40..6bd2b38 100644 --- a/src/PowerShell/Commands/GetPartnerOffer.cs +++ b/src/PowerShell/Commands/GetPartnerOffer.cs @@ -6,7 +6,6 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Collections.Generic; using System.Linq; using System.Management.Automation; - using Extensions; using Models.Authentication; using Models.Offers; using PartnerCenter.Models; @@ -15,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Get an offer, or a list offers, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerOffer"), OutputType(typeof(PSOffer))] - public class GetPartnerOffer : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerOffer")] + [OutputType(typeof(PSOffer))] + public class GetPartnerOffer : PartnerAsyncCmdlet { /// /// Gets or sets the switch indicating whether or not to scope the results to add-ons. @@ -53,74 +53,28 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; - - if (!string.IsNullOrEmpty(Category) && string.IsNullOrEmpty(OfferId)) + Scheduler.RunTask(async () => { - GetOffersByCategory(countryCode, Category); - } - else if (string.IsNullOrEmpty(OfferId)) - { - GetOffers(countryCode); - } - else - { - GetOffer(countryCode, OfferId); - } - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; - /// - /// Gets the specified offer. - /// - /// The country used to obtain the offer. - /// Identifier for the offer. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetOffer(string countryCode, string offerId) - { - Offer offer; + if (!string.IsNullOrEmpty(Category) && string.IsNullOrEmpty(OfferId)) + { + ResourceCollection offers = await partner.Offers.ByCountry(countryCode).ByCategory(Category).GetAsync(CancellationToken).ConfigureAwait(false); + WriteOutput(offers.Items); + } + else if (string.IsNullOrEmpty(OfferId)) + { + ResourceCollection offers = await partner.Offers.ByCountry(countryCode).GetAsync(CancellationToken).ConfigureAwait(false); + WriteOutput(offers.Items); + } + else + { + Offer offer = await partner.Offers.ByCountry(countryCode).ById(OfferId).GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(offer); + } - countryCode.AssertNotEmpty(nameof(countryCode)); - offerId.AssertNotEmpty(nameof(offerId)); - - offer = Partner.Offers.ByCountry(countryCode).ById(offerId).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(new PSOffer(offer)); - } - - /// - /// Gets a list of offers available for the specified country. - /// - /// The country used to obtain the offers. - /// - /// is empty or null. - /// - private void GetOffers(string countryCode) - { - ResourceCollection offers; - - countryCode.AssertNotEmpty(nameof(countryCode)); - - offers = Partner.Offers.ByCountry(countryCode).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteOutput(offers.Items); - } - - /// - /// Gets a list of offers by country and category. - /// - /// The country used to obtain the offers. - /// The category for the offers. - private void GetOffersByCategory(string countryCode, string category) - { - ResourceCollection offers; - - countryCode.AssertNotEmpty(nameof(countryCode)); - category.AssertNotEmpty(nameof(category)); - - offers = Partner.Offers.ByCountry(countryCode).ByCategory(category).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteOutput(offers.Items); + }, true); } /// diff --git a/src/PowerShell/Commands/GetPartnerOfferAddon.cs b/src/PowerShell/Commands/GetPartnerOfferAddon.cs index 190d80a..c191164 100644 --- a/src/PowerShell/Commands/GetPartnerOfferAddon.cs +++ b/src/PowerShell/Commands/GetPartnerOfferAddon.cs @@ -13,8 +13,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using PartnerCenter.Models; using PartnerCenter.Models.Offers; - [Cmdlet(VerbsCommon.Get, "PartnerOfferAddon"), OutputType(typeof(PSOffer))] - public class GetPartnerOfferAddon : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerOfferAddon")] + [OutputType(typeof(PSOffer))] + public class GetPartnerOfferAddon : PartnerAsyncCmdlet { /// /// Gets or sets the country code. @@ -36,12 +37,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection offers; - string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection offers; + string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; - offers = Partner.Offers.ByCountry(countryCode).ById(OfferId).AddOns.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + offers = await partner.Offers.ByCountry(countryCode).ById(OfferId).AddOns.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(offers.Items.Select(o => new PSOffer(o)), true); + WriteObject(offers.Items.Select(o => new PSOffer(o)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerOfferCategory.cs b/src/PowerShell/Commands/GetPartnerOfferCategory.cs index 5a2255a..3da4d62 100644 --- a/src/PowerShell/Commands/GetPartnerOfferCategory.cs +++ b/src/PowerShell/Commands/GetPartnerOfferCategory.cs @@ -5,6 +5,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.Offers; using PartnerCenter.Models; using PartnerCenter.Models.Offers; @@ -12,8 +13,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Get an offer, or a list offers, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerOfferCategory"), OutputType(typeof(PSOfferCategory))] - public class GetPartnerOfferCategory : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerOfferCategory")] + [OutputType(typeof(PSOfferCategory))] + public class GetPartnerOfferCategory : PartnerAsyncCmdlet { /// /// Gets or sets the country code used to obtain offers. @@ -27,9 +29,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection offerCategories = Partner.OfferCategories.ByCountry(CountryCode).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection offerCategories = await partner.OfferCategories.ByCountry(CountryCode).GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(offerCategories.Items.Select(c => new PSOfferCategory(c))); + WriteObject(offerCategories.Items.Select(c => new PSOfferCategory(c))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerOrganizationProfile.cs b/src/PowerShell/Commands/GetPartnerOrganizationProfile.cs index f2e7a99..9cb686f 100644 --- a/src/PowerShell/Commands/GetPartnerOrganizationProfile.cs +++ b/src/PowerShell/Commands/GetPartnerOrganizationProfile.cs @@ -4,20 +4,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.Partners; /// /// Gets the partner organization profile from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerOrganizationProfile"), OutputType(typeof(PSOrganizationProfile))] - public class GetPartnerOrganizationProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerOrganizationProfile")] + [OutputType(typeof(PSOrganizationProfile))] + public class GetPartnerOrganizationProfile : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - WriteObject(new PSOrganizationProfile(Partner.Profiles.OrganizationProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSOrganizationProfile(await partner.Profiles.OrganizationProfile.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerProduct.cs b/src/PowerShell/Commands/GetPartnerProduct.cs index 214573a..9e2b07e 100644 --- a/src/PowerShell/Commands/GetPartnerProduct.cs +++ b/src/PowerShell/Commands/GetPartnerProduct.cs @@ -7,13 +7,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using Models.Authentication; using Models.Products; + using PartnerCenter.Models; + using PartnerCenter.Models.Products; using Products; /// /// Get a product, or a list products, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerProduct", DefaultParameterSetName = ByTargetViewParameterSetName), OutputType(typeof(PSProduct))] - public class GetPartnerProduct : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerProduct", DefaultParameterSetName = ByTargetViewParameterSetName)] + [OutputType(typeof(PSProduct))] + public class GetPartnerProduct : PartnerAsyncCmdlet { /// /// The name of the by product identifier parameter set. @@ -68,33 +71,37 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - IProductCollectionByCountry operations = Partner.Products.ByCountry(string.IsNullOrEmpty(CountryCode) ? PartnerSession.Instance.Context.CountryCode : CountryCode); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + IProductCollectionByCountry operations = partner.Products.ByCountry(string.IsNullOrEmpty(CountryCode) ? PartnerSession.Instance.Context.CountryCode : CountryCode); - if (ParameterSetName == ByProductIdParameterSetName) - { - WriteObject(new PSProduct(operations.ById(ProductId).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); - } - else if (ParameterSetName == ByReservationScopeParameterSetName) - { - WriteObject( - new PSProduct( - operations.ById(ProductId).ByReservationScope(ReservationScope).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); - } - else if (ParameterSetName == ByTargetViewParameterSetName) - { - if (string.IsNullOrEmpty(Segment)) + if (ParameterSetName == ByProductIdParameterSetName) + { + WriteObject(new PSProduct(await operations.ById(ProductId).GetAsync(CancellationToken).ConfigureAwait(false))); + } + else if (ParameterSetName == ByReservationScopeParameterSetName) { WriteObject( - operations.ByTargetView(Catalog).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult() - .Items.Select(p => new PSProduct(p)), true); + new PSProduct( + await operations.ById(ProductId).ByReservationScope(ReservationScope).GetAsync(CancellationToken).ConfigureAwait(false))); } - else + else if (ParameterSetName == ByTargetViewParameterSetName) { - WriteObject( - operations.ByTargetView(Catalog).ByTargetSegment(Segment).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult() - .Items.Select(p => new PSProduct(p)), true); + ResourceCollection products; + + if (string.IsNullOrEmpty(Segment)) + { + products = await operations.ByTargetView(Catalog).GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + products = await operations.ByTargetView(Catalog).ByTargetSegment(Segment).GetAsync(CancellationToken).ConfigureAwait(false); + } + + WriteObject(products.Items.Select(p => new PSProduct(p)), true); } - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerProductAvailability.cs b/src/PowerShell/Commands/GetPartnerProductAvailability.cs index aacab85..6511755 100644 --- a/src/PowerShell/Commands/GetPartnerProductAvailability.cs +++ b/src/PowerShell/Commands/GetPartnerProductAvailability.cs @@ -13,8 +13,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Get a product, or a list products, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerProductAvailability", DefaultParameterSetName = "BySku"), OutputType(typeof(PSProductAvailability))] - public class GetPartnerProductAvailability : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerProductAvailability", DefaultParameterSetName = "BySku")] + [OutputType(typeof(PSProductAvailability))] + public class GetPartnerProductAvailability : PartnerAsyncCmdlet { /// /// Gets or sets the product identifier. @@ -55,76 +56,44 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; - - if (string.IsNullOrEmpty(AvailabilityId)) + Scheduler.RunTask(async () => { - if (!string.IsNullOrEmpty(Segment)) + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; + + if (string.IsNullOrEmpty(AvailabilityId)) { - GetProductAvailabilityBySku(countryCode, ProductId, SkuId); + ResourceCollection productAvailability; + + if (!string.IsNullOrEmpty(Segment)) + { + productAvailability = await partner.Products.ByCountry(countryCode).ById(ProductId).Skus.ById(SkuId).Availabilities.ByTargetSegment(Segment).GetAsync(CancellationToken).ConfigureAwait(false); + + if (productAvailability.TotalCount > 0) + { + WriteObject(productAvailability.Items.Select(pa => new PSProductAvailability(pa)), true); + } + } + else + { + productAvailability = await partner.Products.ByCountry(countryCode).ById(ProductId).Skus.ById(SkuId).Availabilities.GetAsync(CancellationToken).ConfigureAwait(false); + + if (productAvailability.TotalCount > 0) + { + WriteObject(productAvailability.Items.Select(pa => new PSProductAvailability(pa)), true); + } + } + } + else if (!string.IsNullOrEmpty(AvailabilityId)) + { + Availability availability = await partner.Products.ByCountry(countryCode).ById(ProductId).Skus.ById(SkuId).Availabilities.ById(AvailabilityId).GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(availability); } else { - GetProductAvailabilityBySku(countryCode, ProductId, SkuId, Segment); + throw new PSInvalidOperationException("You must specify a ProductId or Catalog."); } - } - else if (!string.IsNullOrEmpty(AvailabilityId)) - { - GetProductAvailabilityById(countryCode, ProductId, SkuId, AvailabilityId); - } - else - { - throw new PSInvalidOperationException("You must specify a ProductId or Catalog."); - } - } - - /// - /// Gets the specified product availability. - /// - /// The country used to obtain the offer. - /// Identifier for the product. - /// Identifier for the product Sku. - /// Identifier for the target segment. - private void GetProductAvailabilityBySku(string countryCode, string productId, string skuId, string segment = null) - { - ResourceCollection productAvailability; - - // If segment is specified, get the information using the segment. Otherwise don't - if (!string.IsNullOrEmpty(segment)) - { - productAvailability = Partner.Products.ByCountry(countryCode).ById(productId).Skus.ById(skuId).Availabilities.ByTargetSegment(segment).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (productAvailability.TotalCount > 0) - { - WriteObject(productAvailability.Items.Select(pa => new PSProductAvailability(pa)), true); - } - } - else - { - productAvailability = Partner.Products.ByCountry(countryCode).ById(productId).Skus.ById(skuId).Availabilities.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (productAvailability.TotalCount > 0) - { - WriteObject(productAvailability.Items.Select(pa => new PSProductAvailability(pa)), true); - } - } - } - - /// - /// Gets the specified product availability. - /// - /// The country used to obtain the offer. - /// Identifier for the product. - /// Identifier for the product Sku. - /// Identifier for the product availability. - private void GetProductAvailabilityById(string countryCode, string productId, string skuId, string availabilityId) - { - Availability productAvailability = Partner.Products.ByCountry(countryCode).ById(productId).Skus.ById(skuId).Availabilities.ById(availabilityId).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (productAvailability != null) - { - WriteObject(new PSProductAvailability(productAvailability)); - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerProductInventory.cs b/src/PowerShell/Commands/GetPartnerProductInventory.cs index 0ed3443..a405866 100644 --- a/src/PowerShell/Commands/GetPartnerProductInventory.cs +++ b/src/PowerShell/Commands/GetPartnerProductInventory.cs @@ -7,7 +7,6 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Collections.Generic; using System.Linq; using System.Management.Automation; - using Extensions; using Models.Authentication; using Models.Products; using PartnerCenter.Models.Products; @@ -15,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Get a product, or a list products, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerProductInventory"), OutputType(typeof(PSInventoryItem))] - public class GetPartnerProductInventory : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerProductInventory")] + [OutputType(typeof(PSInventoryItem))] + public class GetPartnerProductInventory : PartnerAsyncCmdlet { /// /// Gets or sets the country code used to obtain product skus. @@ -28,6 +28,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Gets or sets the product identifier. /// [Parameter(Mandatory = true, HelpMessage = "A string that identifies the product.")] + [ValidateNotNull] public string ProductId { get; set; } /// @@ -52,52 +53,33 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ProductId.AssertNotEmpty(nameof(ProductId)); - - string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; - - if (Variables == null) + Scheduler.RunTask(async () => { - Variables = new Hashtable(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + string countryCode = (string.IsNullOrEmpty(CountryCode)) ? PartnerSession.Instance.Context.CountryCode : CountryCode; - GetProductInventory(countryCode, ProductId, SkuId, Variables); - } + if (Variables == null) + { + Variables = new Hashtable(); + } - /// - /// Gets the specified product SKU. - /// - /// The country used to obtain the offer. - /// Identifier for the product. - /// The list of variables needed to execute an inventory check on this item. - /// - /// is empty or null. - /// or - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetProductInventory(string countryCode, string productId, string skuId, Hashtable context) - { - IEnumerable item; - InventoryCheckRequest request; + IEnumerable item; + InventoryCheckRequest request; - countryCode.AssertNotEmpty(nameof(countryCode)); - productId.AssertNotEmpty(nameof(productId)); + request = new InventoryCheckRequest() + { + TargetItems = string.IsNullOrEmpty(SkuId) ? new InventoryItem[] { new InventoryItem { ProductId = ProductId } } : new InventoryItem[] { new InventoryItem { ProductId = ProductId, SkuId = SkuId } }, + }; - request = new InventoryCheckRequest() - { - TargetItems = string.IsNullOrEmpty(skuId) ? new InventoryItem[] { new InventoryItem { ProductId = productId } } : new InventoryItem[] { new InventoryItem { ProductId = productId, SkuId = skuId } }, - }; + foreach (KeyValuePair kvp in Variables.Cast().ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value)) + { + request.InventoryContext.Add(kvp.Key, kvp.Value); + } - foreach (KeyValuePair kvp in context.Cast().ToDictionary(kvp => (string)kvp.Key, kvp => (string)kvp.Value)) - { - request.InventoryContext.Add(kvp.Key, kvp.Value); - } + item = await partner.Extensions.Product.ByCountry(countryCode).CheckInventoryAsync(request, CancellationToken).ConfigureAwait(false); - item = Partner.Extensions.Product.ByCountry(countryCode).CheckInventoryAsync(request).GetAwaiter().GetResult(); - - WriteObject(item.Select(i => new PSInventoryItem(i)), true); + WriteObject(item.Select(i => new PSInventoryItem(i)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerProductSku.cs b/src/PowerShell/Commands/GetPartnerProductSku.cs index 2897fed..6b3f8ff 100644 --- a/src/PowerShell/Commands/GetPartnerProductSku.cs +++ b/src/PowerShell/Commands/GetPartnerProductSku.cs @@ -7,13 +7,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using Models.Authentication; using Models.Products; + using PartnerCenter.Models; + using PartnerCenter.Models.Products; using Products; /// /// Get a product SKU, or a list product SKUs, from Partner Center. /// [Cmdlet(VerbsCommon.Get, "PartnerProductSku", DefaultParameterSetName = ByProductIdParameterSetName), OutputType(typeof(PSSku))] - public class GetPartnerProductSku : PartnerCmdlet + public class GetPartnerProductSku : PartnerAsyncCmdlet { /// /// The name of the by product identifier parameter set. @@ -68,41 +70,58 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - IProductCollectionByCountry operations = Partner.Products.ByCountry(string.IsNullOrEmpty(CountryCode) ? PartnerSession.Instance.Context.CountryCode : CountryCode); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + IProductCollectionByCountry operations = partner.Products.ByCountry(string.IsNullOrEmpty(CountryCode) ? PartnerSession.Instance.Context.CountryCode : CountryCode); - if (ParameterSetName == ByProductIdParameterSetName) - { - if (string.IsNullOrEmpty(ReservationScope)) + if (ParameterSetName == ByProductIdParameterSetName) { - WriteObject(operations.ById(ProductId).Skus.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(s => new PSSku(s)), true); + ResourceCollection skus; + + if (string.IsNullOrEmpty(ReservationScope)) + { + skus = await operations.ById(ProductId).Skus.GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + skus = await operations.ById(ProductId).Skus.ByReservationScope(ReservationScope).GetAsync(CancellationToken).ConfigureAwait(false); + } + + WriteObject(skus.Items.Select(s => new PSSku(s)), true); } - else + else if (ParameterSetName == BySkuIdParameterSetName) { - WriteObject(operations.ById(ProductId).Skus.ByReservationScope(ReservationScope).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(s => new PSSku(s)), true); + Sku sku; + + if (string.IsNullOrEmpty(ReservationScope)) + { + sku = await operations.ById(ProductId).Skus.ById(SkuId).GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + sku = await operations.ById(ProductId).Skus.ById(SkuId).ByReservationScope(ReservationScope).GetAsync(CancellationToken).ConfigureAwait(false); + } + + WriteObject(new PSSku(sku)); + } - } - else if (ParameterSetName == BySkuIdParameterSetName) - { - if (string.IsNullOrEmpty(ReservationScope)) + else if (ParameterSetName == BySegmentParameterSetName) { - WriteObject(new PSSku(operations.ById(ProductId).Skus.ById(SkuId).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + ResourceCollection skus; + + if (string.IsNullOrEmpty(ReservationScope)) + { + skus = await operations.ById(ProductId).Skus.ByTargetSegment(Segment).GetAsync(CancellationToken).ConfigureAwait(false); + } + else + { + skus = await operations.ById(ProductId).Skus.ByTargetSegment(Segment).ByReservationScope(ReservationScope).GetAsync(CancellationToken).ConfigureAwait(false); + } + + WriteObject(skus.Items.Select(s => new PSSku(s)), true); } - else - { - WriteObject(new PSSku(operations.ById(ProductId).Skus.ById(SkuId).ByReservationScope(ReservationScope).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); - } - } - else if (ParameterSetName == BySegmentParameterSetName) - { - if (string.IsNullOrEmpty(ReservationScope)) - { - WriteObject(operations.ById(ProductId).Skus.ByTargetSegment(Segment).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(s => new PSSku(s)), true); - } - else - { - WriteObject(operations.ById(ProductId).Skus.ByTargetSegment(Segment).ByReservationScope(ReservationScope).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(s => new PSSku(s)), true); - } - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerProductUpgrade.cs b/src/PowerShell/Commands/GetPartnerProductUpgrade.cs index 8843bbe..67336e8 100644 --- a/src/PowerShell/Commands/GetPartnerProductUpgrade.cs +++ b/src/PowerShell/Commands/GetPartnerProductUpgrade.cs @@ -5,10 +5,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.ProductUpgrades; - [Cmdlet(VerbsCommon.Get, "PartnerProductUpgradeStatus"), OutputType(typeof(ProductUpgradeStatus))] - public class GetPartnerProductUpgradeStatus : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerProductUpgradeStatus")] + [OutputType(typeof(ProductUpgradeStatus))] + public class GetPartnerProductUpgradeStatus : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -36,11 +38,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Partner.ProductUpgrades.ById(UpgradeId).CheckStatusAsync(new ProductUpgradeRequest + Scheduler.RunTask(async () => { - CustomerId = CustomerId, - ProductFamily = ProductFamily - }).ConfigureAwait(false).GetAwaiter().GetResult(); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + await partner.ProductUpgrades.ById(UpgradeId).CheckStatusAsync(new ProductUpgradeRequest + { + CustomerId = CustomerId, + ProductFamily = ProductFamily + }, CancellationToken).ConfigureAwait(false); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerProductUpgradeEligibility.cs b/src/PowerShell/Commands/GetPartnerProductUpgradeEligibility.cs index c95ff7e..3a9d227 100644 --- a/src/PowerShell/Commands/GetPartnerProductUpgradeEligibility.cs +++ b/src/PowerShell/Commands/GetPartnerProductUpgradeEligibility.cs @@ -5,10 +5,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.ProductUpgrades; - [Cmdlet(VerbsCommon.Get, "PartnerProductUpgradeEligibility"), OutputType(typeof(ProductUpgradeEligibility))] - public class GetPartnerProductUpgradeEligibility : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerProductUpgradeEligibility")] + [OutputType(typeof(ProductUpgradeEligibility))] + public class GetPartnerProductUpgradeEligibility : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -29,11 +31,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Partner.ProductUpgrades.CheckEligibilityAsync(new ProductUpgradeRequest + Scheduler.RunTask(async () => { - CustomerId = CustomerId, - ProductFamily = ProductFamily - }).ConfigureAwait(false).GetAwaiter().GetResult(); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(await partner.ProductUpgrades.CheckEligibilityAsync(new ProductUpgradeRequest + { + CustomerId = CustomerId, + ProductFamily = ProductFamily + }, CancellationToken).ConfigureAwait(false)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerResellerRequestLink.cs b/src/PowerShell/Commands/GetPartnerResellerRequestLink.cs index 0fd8106..898012f 100644 --- a/src/PowerShell/Commands/GetPartnerResellerRequestLink.cs +++ b/src/PowerShell/Commands/GetPartnerResellerRequestLink.cs @@ -4,20 +4,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.CustomerRelationshipRequests; /// /// Get the resller relationship request link. /// - [Cmdlet(VerbsCommon.Get, "PartnerResellerRequestLink"), OutputType(typeof(PSCustomerRelationshipRequest))] - public class GetPartnerResellerRequestLink : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerResellerRequestLink")] + [OutputType(typeof(PSCustomerRelationshipRequest))] + public class GetPartnerResellerRequestLink : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - WriteObject(new PSCustomerRelationshipRequest(Partner.Customers.RelationshipRequest.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCustomerRelationshipRequest(await partner.Customers.RelationshipRequest.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerRole.cs b/src/PowerShell/Commands/GetPartnerRole.cs index c9eb1f0..5e40aa1 100644 --- a/src/PowerShell/Commands/GetPartnerRole.cs +++ b/src/PowerShell/Commands/GetPartnerRole.cs @@ -5,6 +5,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.Roles; using PartnerCenter.Models; using PartnerCenter.Models.Roles; @@ -12,17 +13,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Get a list of partner roles. /// - [Cmdlet(VerbsCommon.Get, "PartnerRole"), OutputType(typeof(PSRole))] - public class GetPartnerRole : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerRole")] + [OutputType(typeof(PSRole))] + public class GetPartnerRole : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - SeekBasedResourceCollection roles = Partner.Roles.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SeekBasedResourceCollection roles = await partner.Roles.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(roles.Items.Select(r => new PSRole(r)), true); + WriteObject(roles.Items.Select(r => new PSRole(r)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerRoleMember.cs b/src/PowerShell/Commands/GetPartnerRoleMember.cs index b127129..f3d797f 100644 --- a/src/PowerShell/Commands/GetPartnerRoleMember.cs +++ b/src/PowerShell/Commands/GetPartnerRoleMember.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Roles; using PartnerCenter.Models; using PartnerCenter.Models.Roles; @@ -13,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets the members for the specified partner roles. /// - [Cmdlet(VerbsCommon.Get, "PartnerRoleMember"), OutputType(typeof(PSUserMember))] - public class GetPartnerRoleMember : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerRoleMember")] + [OutputType(typeof(PSUserMember))] + public class GetPartnerRoleMember : PartnerAsyncCmdlet { /// /// Gets or sets the role identifier. @@ -28,9 +30,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - SeekBasedResourceCollection members = Partner.Roles[RoleId].Members.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SeekBasedResourceCollection members = await partner.Roles[RoleId].Members.GetAsync(CancellationToken).ConfigureAwait(false); - WriteObject(members.Items.Select(m => new PSUserMember(m)), true); + WriteObject(members.Items.Select(m => new PSUserMember(m)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerServiceIncident.cs b/src/PowerShell/Commands/GetPartnerServiceIncident.cs index 494b816..bb9bddd 100644 --- a/src/PowerShell/Commands/GetPartnerServiceIncident.cs +++ b/src/PowerShell/Commands/GetPartnerServiceIncident.cs @@ -6,14 +6,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Collections.Generic; using System.Linq; using System.Management.Automation; + using Models.Authentication; using PartnerCenter.Models; using PartnerCenter.Models.Incidents; /// /// Gets a list of service incidents from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerServiceIncident"), OutputType(typeof(ServiceIncidentDetail))] - public class GetPartnerServiceIncident : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerServiceIncident")] + [OutputType(typeof(ServiceIncidentDetail))] + public class GetPartnerServiceIncident : PartnerAsyncCmdlet { /// /// Gets or sets the optional status type. @@ -33,27 +35,32 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection incidents; - IEnumerable results; - - incidents = Partner.ServiceIncidents.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (incidents.TotalCount > 0) + Scheduler.RunTask(async () => { - results = incidents.Items.SelectMany(i => i.Incidents); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection incidents; + IEnumerable results; - if (Status.HasValue) + incidents = await partner.ServiceIncidents.GetAsync(CancellationToken).ConfigureAwait(false); + + if (incidents.TotalCount > 0) { - results = results.Where(i => i.Status == Status); + results = incidents.Items.SelectMany(i => i.Incidents); + + if (Status.HasValue) + { + results = results.Where(i => i.Status == Status); + } + + if (!Resolved) + { + results = results.Where(i => !i.Resolved); + } + + WriteObject(results, true); } - if (!Resolved) - { - results = results.Where(i => !i.Resolved); - } - - WriteObject(results, true); - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerServiceRequest.cs b/src/PowerShell/Commands/GetPartnerServiceRequest.cs index e568bf2..f346350 100644 --- a/src/PowerShell/Commands/GetPartnerServiceRequest.cs +++ b/src/PowerShell/Commands/GetPartnerServiceRequest.cs @@ -3,22 +3,24 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using System.Threading.Tasks; + using Models.Authentication; using Models.ServiceRequests; using PartnerCenter.Enumerators; using PartnerCenter.Models; using PartnerCenter.Models.ServiceRequests; + using RequestContext; /// /// Get a service request, or a list of service requests, from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerServiceRequest", DefaultParameterSetName = "ByStatus"), OutputType(typeof(PSServiceRequest))] - public class GetPartnerServiceRequest : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerServiceRequest", DefaultParameterSetName = "ByStatus")] + [OutputType(typeof(PSServiceRequest))] + public class GetPartnerServiceRequest : PartnerAsyncCmdlet { /// /// Gets or sets the request status @@ -57,131 +59,51 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (!string.IsNullOrEmpty(CustomerId)) + Scheduler.RunTask(async () => { - if (!string.IsNullOrEmpty(RequestId)) + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + if (!string.IsNullOrEmpty(CustomerId)) { - GetCustomerServiceRequest(CustomerId, RequestId); + if (!string.IsNullOrEmpty(RequestId)) + { + ServiceRequest request = await partner.Customers.ById(CustomerId).ServiceRequests.ById(RequestId).GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(request); + } + else + { + ResourceCollection requests = await partner.Customers.ById(CustomerId).ServiceRequests.GetAsync(CancellationToken).ConfigureAwait(false); + await HandleOutputAsync(partner, requests, Severity, Status).ConfigureAwait(false); + } } else { - GetCustomerServiceRequests(CustomerId, Status, Severity); + if (!string.IsNullOrEmpty(RequestId)) + { + ServiceRequest request = await partner.ServiceRequests.ById(RequestId).GetAsync(CancellationToken).ConfigureAwait(false); + WriteObject(request); + } + else + { + ResourceCollection requests = await partner.ServiceRequests.GetAsync(CancellationToken).ConfigureAwait(false); + await HandleOutputAsync(partner, requests, Severity, Status).ConfigureAwait(false); + } } - } - else - { - if (!string.IsNullOrEmpty(RequestId)) - { - GetServiceRequest(RequestId); - } - else - { - GetServiceRequests(Status, Severity); - } - } + }, true); } - /// - /// Gets the specified service request for a customer. - /// - /// The identifier for the customer. - /// The identifier for the service request. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private void GetCustomerServiceRequest(string customerId, string requestId) - { - ServiceRequest request; - - customerId.AssertNotEmpty(nameof(customerId)); - requestId.AssertNotEmpty(nameof(requestId)); - - - request = Partner.Customers.ById(customerId).ServiceRequests.ById(requestId).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (request != null) - { - WriteObject(new PSServiceRequest(request)); - } - - } - - /// - /// Gets a list of service requests for a customer. - /// - /// The identifier of the customer. - /// The status of the service request. - /// The severity of the service request. - /// - /// is empty or null. - /// - private void GetCustomerServiceRequests(string customerId, ServiceRequestStatus? status, ServiceRequestSeverity? severity) - { - ResourceCollection requests; - - customerId.AssertNotEmpty(nameof(customerId)); - - requests = Partner.Customers.ById(customerId).ServiceRequests.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (requests.TotalCount > 0) - { - HandleOutput(requests, severity, status); - } - } - - /// - /// Gets the specified service request for a partner. - /// - /// Identifier for the service request. - /// - /// is empty or null. - /// - private void GetServiceRequest(string requestId) - { - ServiceRequest request; - - requestId.AssertNotEmpty(nameof(requestId)); - - request = Partner.ServiceRequests.ById(requestId).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (request != null) - { - WriteObject(new PSServiceRequest(request)); - } - - } - - /// - /// Gets a list of service requests for a partner. - /// - /// Identifier for the service request. - /// Identifier for the service request. - private void GetServiceRequests(ServiceRequestStatus? status, ServiceRequestSeverity? severity) - { - ResourceCollection requests; - - requests = Partner.ServiceRequests.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (requests.TotalCount > 0) - { - HandleOutput(requests, severity, status); - } - } - - private void HandleOutput(ResourceCollection requests, ServiceRequestSeverity? severity, ServiceRequestStatus? status) + private async Task HandleOutputAsync(IPartner partner, ResourceCollection requests, ServiceRequestSeverity? severity, ServiceRequestStatus? status) { IResourceCollectionEnumerator> enumerator; List serviceRequests; - enumerator = Partner.Enumerators.ServiceRequests.Create(requests); + enumerator = partner.Enumerators.ServiceRequests.Create(requests); serviceRequests = new List(); while (enumerator.HasValue) { serviceRequests.AddRange(enumerator.Current.Items); - enumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + await enumerator.NextAsync(RequestContextFactory.Create(CorrelationId), CancellationToken).ConfigureAwait(false); } if (severity.HasValue && status.HasValue) diff --git a/src/PowerShell/Commands/GetPartnerServiceRequestTopic.cs b/src/PowerShell/Commands/GetPartnerServiceRequestTopic.cs index 85838cd..74d4316 100644 --- a/src/PowerShell/Commands/GetPartnerServiceRequestTopic.cs +++ b/src/PowerShell/Commands/GetPartnerServiceRequestTopic.cs @@ -3,10 +3,10 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { - using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.ServiceRequests; using PartnerCenter.Models; using PartnerCenter.Models.ServiceRequests; @@ -15,7 +15,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Get a service request, or a list of service requests, from Partner Center. /// [Cmdlet(VerbsCommon.Get, "PartnerServiceRequestTopic"), OutputType(typeof(PSSupportTopic))] - public class GetPartnerServiceRequestTopic : PartnerCmdlet + public class GetPartnerServiceRequestTopic : PartnerAsyncCmdlet { /// /// Gets or sets the support topic identifier @@ -28,22 +28,23 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ResourceCollection topics; - IEnumerable results; - - topics = Partner.ServiceRequests.SupportTopics.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (topics.TotalCount > 0) + Scheduler.RunTask(async () => { - results = topics.Items; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ResourceCollection topics; + + topics = await partner.ServiceRequests.SupportTopics.GetAsync(CancellationToken).ConfigureAwait(false); + if (!string.IsNullOrEmpty(SupportTopicId)) { - results = results.Where(t => t.Id.ToString(CultureInfo.CurrentCulture) == SupportTopicId); + WriteObject(topics.Items.Where(t => t.Id.ToString(CultureInfo.CurrentCulture) == SupportTopicId)); } - - WriteObject(results.Select(t => new PSSupportTopic(t)), true); - } + else + { + WriteObject(topics.Items.Select(t => new PSSupportTopic(t)), true); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerSupportProfile.cs b/src/PowerShell/Commands/GetPartnerSupportProfile.cs index 7db5bdc..795e79a 100644 --- a/src/PowerShell/Commands/GetPartnerSupportProfile.cs +++ b/src/PowerShell/Commands/GetPartnerSupportProfile.cs @@ -4,20 +4,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using Models.Partners; /// /// Gets the partner support profile from Partner Center. /// - [Cmdlet(VerbsCommon.Get, "PartnerSupportProfile"), OutputType(typeof(PSSupportProfile))] - public class GetPartnerSupportProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Get, "PartnerSupportProfile")] + [OutputType(typeof(PSSupportProfile))] + public class GetPartnerSupportProfile : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - WriteObject(new PSSupportProfile(Partner.Profiles.SupportProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult())); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSSupportProfile(await partner.Profiles.SupportProfile.GetAsync(CancellationToken).ConfigureAwait(false))); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/GetPartnerValidationCode.cs b/src/PowerShell/Commands/GetPartnerValidationCode.cs index 76a2fb8..2d79ef8 100644 --- a/src/PowerShell/Commands/GetPartnerValidationCode.cs +++ b/src/PowerShell/Commands/GetPartnerValidationCode.cs @@ -3,23 +3,32 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { + using System.Collections.Generic; using System.Linq; using System.Management.Automation; + using Models.Authentication; using Models.ValidationCodes; + using PartnerCenter.Models.ValidationCodes; /// /// Gets validation code which is used for Government Community Cloud customers qualification. /// [Cmdlet(VerbsCommon.Get, "PartnerValidationCode")] [OutputType(typeof(PSValidationCode))] - public class GetPartnerValidationCode : PartnerCmdlet + public class GetPartnerValidationCode : PartnerAsyncCmdlet { /// /// Executes the operations associated with the cmdlet. /// public override void ExecuteCmdlet() { - WriteObject(Partner.Validations.GetValidationCodesAsync().ConfigureAwait(false).GetAwaiter().GetResult().Select(c => new PSValidationCode(c)), true); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + IEnumerable codes = await partner.Validations.GetValidationCodesAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(codes.Select(c => new PSValidationCode(c)), true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerAccessToken.cs b/src/PowerShell/Commands/NewPartnerAccessToken.cs index 01f2047..4955a54 100644 --- a/src/PowerShell/Commands/NewPartnerAccessToken.cs +++ b/src/PowerShell/Commands/NewPartnerAccessToken.cs @@ -33,6 +33,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// private const string Message = "We have launched a browser for you to login. For the old experience with device code flow, please run 'New-PartnerAccessToken -UseDeviceAuthentication'."; + /// + /// The name of the refresh token parameter set. + /// + private const string RefreshTokenParameterSet = "RefreshToken"; + /// /// The name of the service principal parameter set. /// @@ -59,6 +64,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Gets or sets the application identifier. /// [Parameter(HelpMessage = "The application identifier to be used during authentication.", Mandatory = true, ParameterSetName = AccessTokenParameterSet)] + [Parameter(HelpMessage = "The application identifier to be used during authentication.", Mandatory = false, ParameterSetName = RefreshTokenParameterSet)] [Parameter(HelpMessage = "The application identifier to be used during authentication.", Mandatory = true, ParameterSetName = ServicePrincipalParameterSet)] [Parameter(HelpMessage = "The application identifier to be used during authentication.", Mandatory = true, ParameterSetName = ServicePrincipalCertificateParameterSet)] [Parameter(HelpMessage = "The application identifier to be used during authentication.", Mandatory = true, ParameterSetName = UserParameterSet)] @@ -69,6 +75,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets or sets the certificate thumbprint. /// + [Parameter(HelpMessage = "Certificate Hash (Thumbprint)", Mandatory = false, ParameterSetName = RefreshTokenParameterSet)] [Parameter(HelpMessage = "Certificate Hash (Thumbprint)", Mandatory = true, ParameterSetName = ServicePrincipalCertificateParameterSet)] public string CertificateThumbprint { get; set; } @@ -76,6 +83,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Gets or sets the service principal credential. /// [Parameter(HelpMessage = "Credentials that represents the service principal.", Mandatory = false, ParameterSetName = AccessTokenParameterSet)] + [Parameter(HelpMessage = "Credentials that represents the service principal.", Mandatory = false, ParameterSetName = RefreshTokenParameterSet)] [Parameter(HelpMessage = "Credentials that represents the service principal.", Mandatory = true, ParameterSetName = ServicePrincipalParameterSet)] [ValidateNotNull] public PSCredential Credential { get; set; } @@ -92,6 +100,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Gets or sets the module that an access token is being generated. /// [Parameter(HelpMessage = "The module that an access token is being generated.", Mandatory = true, ParameterSetName = ByModuleParameterSet)] + [Parameter(HelpMessage = "The module that an access token is being generated.", Mandatory = false, ParameterSetName = RefreshTokenParameterSet)] [Alias("ModuleName")] [ValidateSet(nameof(ModuleName.ExchangeOnline))] public ModuleName Module { get; set; } @@ -99,22 +108,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Gets or sets the refresh token to use during authentication. /// - [Parameter(HelpMessage = "The refresh token to use during authentication.", Mandatory = false)] + [Parameter(HelpMessage = "The refresh token to use during authentication.", Mandatory = true, ParameterSetName = RefreshTokenParameterSet)] [ValidateNotNullOrEmpty] public string RefreshToken { get; set; } /// /// Gets or sets the scopes used for authentication. /// - [Parameter(HelpMessage = "Scopes requested to access a protected API.", Mandatory = true, ParameterSetName = AccessTokenParameterSet)] - [Parameter(HelpMessage = "Scopes requested to access a protected API.", Mandatory = true, ParameterSetName = ServicePrincipalParameterSet)] - [Parameter(HelpMessage = "Scopes requested to access a protected API.", Mandatory = true, ParameterSetName = ServicePrincipalCertificateParameterSet)] - [Parameter(HelpMessage = "Scopes requested to access a protected API.", Mandatory = true, ParameterSetName = UserParameterSet)] + [Parameter(HelpMessage = "Scopes requested to access a protected API.", Mandatory = true)] public string[] Scopes { get; set; } /// /// Gets or sets a flag indicating that a service principal is being used. /// + [Parameter(HelpMessage = "Indicates that this account authenticates by providing service principal credentials.", Mandatory = false, ParameterSetName = RefreshTokenParameterSet)] [Parameter(HelpMessage = "Indicates that this account authenticates by providing service principal credentials.", Mandatory = true, ParameterSetName = ServicePrincipalParameterSet)] [Parameter(HelpMessage = "Indicates that this account authenticates by providing service principal credentials.", Mandatory = false, ParameterSetName = ServicePrincipalCertificateParameterSet)] public SwitchParameter ServicePrincipal { get; set; } @@ -125,6 +132,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands [Alias("Domain", "TenantId")] [Parameter(HelpMessage = "Identifier or name for the tenant.", Mandatory = false, ParameterSetName = AccessTokenParameterSet)] [Parameter(HelpMessage = "Identifier or name for the tenant.", Mandatory = false, ParameterSetName = ByModuleParameterSet)] + [Parameter(HelpMessage = "Identifier or name for the tenant.", Mandatory = false, ParameterSetName = RefreshTokenParameterSet)] [Parameter(HelpMessage = "Identifier or name for the tenant.", Mandatory = true, ParameterSetName = ServicePrincipalCertificateParameterSet)] [Parameter(HelpMessage = "Identifier or name for the tenant.", Mandatory = true, ParameterSetName = ServicePrincipalParameterSet)] [Parameter(HelpMessage = "Identifier or name for the tenant.", Mandatory = false, ParameterSetName = UserParameterSet)] @@ -135,14 +143,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Gets or sets a flag indicating if the authorization code flow should be used. /// [Alias("AuthCode")] - [Parameter(HelpMessage = "Use the authorization code flow during authentication.", Mandatory = false)] + [Parameter(HelpMessage = "Use the authorization code flow during authentication.", Mandatory = false, ParameterSetName = ByModuleParameterSet)] + [Parameter(HelpMessage = "Use the authorization code flow during authentication.", Mandatory = false, ParameterSetName = ServicePrincipalCertificateParameterSet)] + [Parameter(HelpMessage = "Use the authorization code flow during authentication.", Mandatory = false, ParameterSetName = ServicePrincipalParameterSet)] + [Parameter(HelpMessage = "Use the authorization code flow during authentication.", Mandatory = false, ParameterSetName = UserParameterSet)] public SwitchParameter UseAuthorizationCode { get; set; } /// /// Gets or sets a flag indicating if the device code flow should be used. /// [Alias("DeviceCode", "DeviceAuth", "Device")] - [Parameter(ParameterSetName = UserParameterSet, Mandatory = false, HelpMessage = "Use device code authentication instead of a browser control.")] + [Parameter(HelpMessage = "Use device code authentication instead of a browser control.", Mandatory = false, ParameterSetName = UserParameterSet)] public SwitchParameter UseDeviceAuthentication { get; set; } /// @@ -155,6 +166,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands PartnerAccount account = new PartnerAccount(); string applicationId; + if (!string.IsNullOrEmpty(CertificateThumbprint)) + { + account.SetProperty(PartnerAccountPropertyType.CertificateThumbprint, CertificateThumbprint); + } + if (ParameterSetName.Equals(AccessTokenParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.SetProperty(PartnerAccountPropertyType.AccessToken, AccessToken); @@ -169,6 +185,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands Scopes = PowerShellModule.KnownModules[Module].Scopes.ToArray(); } + else if (ParameterSetName.Equals(ServicePrincipalCertificateParameterSet, StringComparison.InvariantCultureIgnoreCase)) + { + account.SetProperty(PartnerAccountPropertyType.ApplicationId, ApplicationId); + account.Type = AccountType.Certificate; + applicationId = ApplicationId; + } else if (ParameterSetName.Equals(ServicePrincipalParameterSet, StringComparison.InvariantCultureIgnoreCase)) { account.ObjectId = Credential.UserName; diff --git a/src/PowerShell/Commands/NewPartnerCustomer.cs b/src/PowerShell/Commands/NewPartnerCustomer.cs index a69c87e..d362086 100644 --- a/src/PowerShell/Commands/NewPartnerCustomer.cs +++ b/src/PowerShell/Commands/NewPartnerCustomer.cs @@ -15,7 +15,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using Validations; [Cmdlet(VerbsCommon.New, "PartnerCustomer", SupportsShouldProcess = true), OutputType(typeof(PSCustomer))] - public class NewPartnerCustomer : PartnerCmdlet + public class NewPartnerCustomer : PartnerAsyncCmdlet { /// /// The country code for the United States. @@ -145,80 +145,80 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - PartnerCenter.Models.Customers.Customer customer; - IValidator
validator; - string country; - string culture; - string region; - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerWhatIf, Name))) + Scheduler.RunTask(async () => { - - country = (string.IsNullOrEmpty(BillingAddressCountry)) ? PartnerSession.Instance.Context.CountryCode : BillingAddressCountry; - culture = (string.IsNullOrEmpty(Culture)) ? PartnerSession.Instance.Context.Locale : Culture; - - if (string.IsNullOrEmpty(BillingAddressRegion)) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerWhatIf, Name))) { - region = null; - } - else - { - region = BillingAddressRegion.Equals(UnitedStatesCountryCode, StringComparison.InvariantCultureIgnoreCase) ? string.Empty : BillingAddressRegion; - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - customer = new PartnerCenter.Models.Customers.Customer - { - AssociatedPartnerId = AssociatedPartnerId, - BillingProfile = new PartnerCenter.Models.Customers.CustomerBillingProfile + PartnerCenter.Models.Customers.Customer customer; + string country = (string.IsNullOrEmpty(BillingAddressCountry)) ? PartnerSession.Instance.Context.CountryCode : BillingAddressCountry; + string culture = (string.IsNullOrEmpty(Culture)) ? PartnerSession.Instance.Context.Locale : Culture; + string region; + + if (string.IsNullOrEmpty(BillingAddressRegion)) { - CompanyName = Name, - Culture = culture, - DefaultAddress = new Address + region = null; + } + else + { + region = BillingAddressRegion.Equals(UnitedStatesCountryCode, StringComparison.InvariantCultureIgnoreCase) ? string.Empty : BillingAddressRegion; + } + + customer = new PartnerCenter.Models.Customers.Customer + { + AssociatedPartnerId = AssociatedPartnerId, + BillingProfile = new PartnerCenter.Models.Customers.CustomerBillingProfile { - AddressLine1 = BillingAddressLine1, - AddressLine2 = BillingAddressLine2, - City = BillingAddressCity, - Country = country, + CompanyName = Name, + Culture = culture, + DefaultAddress = new Address + { + AddressLine1 = BillingAddressLine1, + AddressLine2 = BillingAddressLine2, + City = BillingAddressCity, + Country = country, + FirstName = ContactFirstName, + LastName = ContactLastName, + PhoneNumber = ContactPhoneNumber, + PostalCode = BillingAddressPostalCode, + Region = region, + State = BillingAddressState + }, + Email = ContactEmail, FirstName = ContactFirstName, - LastName = ContactLastName, - PhoneNumber = ContactPhoneNumber, - PostalCode = BillingAddressPostalCode, - Region = region, - State = BillingAddressState + Language = Language, + LastName = ContactLastName }, - Email = ContactEmail, - FirstName = ContactFirstName, - Language = Language, - LastName = ContactLastName - }, - CompanyProfile = new PartnerCenter.Models.Customers.CustomerCompanyProfile - { - CompanyName = Name, - Domain = Domain - } - }; + CompanyProfile = new PartnerCenter.Models.Customers.CustomerCompanyProfile + { + CompanyName = Name, + Domain = Domain + } + }; - if (!DisableValidation.ToBool()) - { - if (Partner.Domains.ByDomain(Domain).ExistsAsync().ConfigureAwait(false).GetAwaiter().GetResult()) + if (!DisableValidation.ToBool()) { - throw new PSInvalidOperationException( - string.Format( - CultureInfo.CurrentCulture, - Resources.DomainExistsError, - Domain)); + if (await partner.Domains.ByDomain(Domain).ExistsAsync(CancellationToken).ConfigureAwait(false)) + { + throw new PSInvalidOperationException( + string.Format( + CultureInfo.CurrentCulture, + Resources.DomainExistsError, + Domain)); + } + + IValidator
validator = new AddressValidator(partner); + + if (!await validator.IsValidAsync(customer.BillingProfile.DefaultAddress, CancellationToken).ConfigureAwait(false)) + { + throw new PartnerException("The address for the customer is not valid."); + } } - validator = new AddressValidator(Partner); - - if (!validator.IsValid(customer.BillingProfile.DefaultAddress, d => WriteDebug(d))) - { - throw new PartnerException("The address for the customer is not valid."); - } + WriteObject(await partner.Customers.CreateAsync(customer).ConfigureAwait(false)); } - - WriteObject(Partner.Customers.CreateAsync(customer).GetAwaiter().GetResult()); - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerAgreement.cs b/src/PowerShell/Commands/NewPartnerCustomerAgreement.cs index 5e7a1c7..943fdce 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerAgreement.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerAgreement.cs @@ -7,14 +7,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using System.Text.RegularExpressions; using Models.Agreements; + using Models.Authentication; using PartnerCenter.Models.Agreements; using Properties; /// /// Create a new agreement for the specified customer. /// - [Cmdlet(VerbsCommon.New, "PartnerCustomerAgreement"), OutputType(typeof(PSAgreement))] - public class NewPartnerCustomerAgreement : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerCustomerAgreement")] + [OutputType(typeof(PSAgreement))] + public class NewPartnerCustomerAgreement : PartnerAsyncCmdlet { /// /// Gets or sets the agreement type. @@ -76,31 +78,34 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Agreement agreement; - DateTime dateAgreed = DateAgreed ?? DateTime.Now; - - if (ShouldProcess(Resources.NewPartnerCustomerAgreementWhatIf)) + Scheduler.RunTask(async () => { - agreement = new Agreement + if (ShouldProcess(Resources.NewPartnerCustomerAgreementWhatIf)) { - DateAgreed = dateAgreed, - PrimaryContact = new Contact + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + Agreement agreement; + DateTime dateAgreed = DateAgreed ?? DateTime.Now; + + agreement = new Agreement { - Email = ContactEmail, - FirstName = ContactFirstName, - LastName = ContactLastName, - PhoneNumber = ContactPhoneNumber + DateAgreed = dateAgreed, + PrimaryContact = new Contact + { + Email = ContactEmail, + FirstName = ContactFirstName, + LastName = ContactLastName, + PhoneNumber = ContactPhoneNumber - }, - TemplateId = TemplateId, - Type = AgreementType, - }; + }, + TemplateId = TemplateId, + Type = AgreementType, + }; - agreement = Partner.Customers[CustomerId].Agreements.CreateAsync(agreement).GetAwaiter().GetResult(); - - WriteObject(agreement); - } + agreement = await partner.Customers[CustomerId].Agreements.CreateAsync(agreement, CancellationToken).ConfigureAwait(false); + WriteObject(agreement); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerApplicationConsent.cs b/src/PowerShell/Commands/NewPartnerCustomerApplicationConsent.cs index 60886f5..71f13b1 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerApplicationConsent.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerApplicationConsent.cs @@ -5,13 +5,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.ApplicationConsents; /// /// Create a new application consent for the specified customer. /// - [Cmdlet(VerbsCommon.New, "PartnerCustomerApplicationConsent"), OutputType(typeof(ApplicationConsent))] - public class NewPartnerCustomerApplicationConsent : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerCustomerApplicationConsent")] + [OutputType(typeof(ApplicationConsent))] + public class NewPartnerCustomerApplicationConsent : PartnerAsyncCmdlet { /// /// Gets or sets the application grants. @@ -45,17 +47,22 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ApplicationConsent consent = new ApplicationConsent + Scheduler.RunTask(async () => { - ApplicationId = ApplicationId, - DisplayName = DisplayName - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - consent.ApplicationGrants.AddRange(ApplicationGrants); + ApplicationConsent consent = new ApplicationConsent + { + ApplicationId = ApplicationId, + DisplayName = DisplayName + }; - consent = Partner.Customers[CustomerId].ApplicationConsents.CreateAsync(consent).GetAwaiter().GetResult(); + consent.ApplicationGrants.AddRange(ApplicationGrants); - WriteObject(consent); + consent = await partner.Customers[CustomerId].ApplicationConsents.CreateAsync(consent, CancellationToken).ConfigureAwait(false); + + WriteObject(consent); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerCart.cs b/src/PowerShell/Commands/NewPartnerCustomerCart.cs index 338c2a7..60bcdb7 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerCart.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerCart.cs @@ -9,12 +9,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Carts; using PartnerCenter.Models.Carts; using Properties; - [Cmdlet(VerbsCommon.New, "PartnerCustomerCart", SupportsShouldProcess = true), OutputType(typeof(PSCart))] - public class NewPartnerCustomerCart : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerCustomerCart", SupportsShouldProcess = true)] + [OutputType(typeof(PSCart))] + public class NewPartnerCustomerCart : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -34,48 +36,49 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Cart cart; - CartLineItem lineItem; - List lineItems; - - if (!ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewCartWhatIf, CustomerId))) + Scheduler.RunTask(async () => { - return; - } - - lineItems = new List(); - - foreach (PSCartLineItem item in LineItems) - { - lineItem = new CartLineItem + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewCartWhatIf, CustomerId))) { - BillingCycle = item.BillingCycle, - CatalogItemId = item.CatalogItemId, - CurrencyCode = item.CurrencyCode, - Error = item.Error, - FriendlyName = item.FriendlyName, - Id = item.Id, - OrderGroup = item.OrderGroup, - Participants = item.Participants, - Quantity = item.Quantity - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - foreach (KeyValuePair kvp in item.ProvisioningContext?.Cast().ToDictionary(entry => (string)entry.Key, entry => (string)entry.Value)) - { - lineItem.ProvisioningContext.Add(kvp.Key, kvp.Value); + Cart cart; + CartLineItem lineItem; + List lineItems = new List(); + + foreach (PSCartLineItem item in LineItems) + { + lineItem = new CartLineItem + { + BillingCycle = item.BillingCycle, + CatalogItemId = item.CatalogItemId, + CurrencyCode = item.CurrencyCode, + Error = item.Error, + FriendlyName = item.FriendlyName, + Id = item.Id, + OrderGroup = item.OrderGroup, + Participants = item.Participants, + Quantity = item.Quantity + }; + + foreach (KeyValuePair kvp in item.ProvisioningContext?.Cast().ToDictionary(entry => (string)entry.Key, entry => (string)entry.Value)) + { + lineItem.ProvisioningContext.Add(kvp.Key, kvp.Value); + } + + lineItems.Add(lineItem); + } + + cart = new Cart + { + LineItems = lineItems + }; + + cart = await partner.Customers[CustomerId].Carts.CreateAsync(cart, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCart(cart)); } - - lineItems.Add(lineItem); - } - - cart = new Cart - { - LineItems = lineItems - }; - - cart = Partner.Customers[CustomerId].Carts.CreateAsync(cart).GetAwaiter().GetResult(); - - WriteObject(new PSCart(cart)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerConfigurationPolicy.cs b/src/PowerShell/Commands/NewPartnerCustomerConfigurationPolicy.cs index 799a2fc..27407a5 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerConfigurationPolicy.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerConfigurationPolicy.cs @@ -7,6 +7,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using System.Text.RegularExpressions; using Models; + using Models.Authentication; using PartnerCenter.Models.DevicesDeployment; using PartnerCenter.PowerShell.Properties; @@ -15,7 +16,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands ///
[Cmdlet(VerbsCommon.New, "PartnerCustomerConfigurationPolicy", SupportsShouldProcess = true)] [OutputType(typeof(PSConfigurationPolicy))] - public class NewPartnerCustomerConfigurationPolicy : PartnerCmdlet + public class NewPartnerCustomerConfigurationPolicy : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -73,49 +74,51 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ConfigurationPolicy devicePolicy; - List policySettings = new List(); - - if (!ShouldProcess(Resources.NewPartnerCustomerConfigurationPolicyWhatIf)) + Scheduler.RunTask(async () => { - return; - } + if (ShouldProcess(Resources.NewPartnerCustomerConfigurationPolicyWhatIf)) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ConfigurationPolicy devicePolicy; + List policySettings = new List(); - if (OobeUserNotLocalAdmin) - { - policySettings.Add(PolicySettingsTypes.OobeUserNotLocalAdmin); - } + if (OobeUserNotLocalAdmin) + { + policySettings.Add(PolicySettingsTypes.OobeUserNotLocalAdmin); + } - if (SkipEula) - { - policySettings.Add(PolicySettingsTypes.SkipEula); - } + if (SkipEula) + { + policySettings.Add(PolicySettingsTypes.SkipEula); + } - if (SkipExpressSettings) - { - policySettings.Add(PolicySettingsTypes.SkipExpressSettings); - } + if (SkipExpressSettings) + { + policySettings.Add(PolicySettingsTypes.SkipExpressSettings); + } - if (RemoveOemPreinstalls) - { - policySettings.Add(PolicySettingsTypes.RemoveOemPreinstalls); - } + if (RemoveOemPreinstalls) + { + policySettings.Add(PolicySettingsTypes.RemoveOemPreinstalls); + } - if (SkipOemRegistration) - { - policySettings.Add(PolicySettingsTypes.SkipOemRegistration); - } + if (SkipOemRegistration) + { + policySettings.Add(PolicySettingsTypes.SkipOemRegistration); + } - ConfigurationPolicy configurationPolicy = new ConfigurationPolicy - { - Name = Name, - Description = Description, - PolicySettings = policySettings - }; + ConfigurationPolicy configurationPolicy = new ConfigurationPolicy + { + Name = Name, + Description = Description, + PolicySettings = policySettings + }; - devicePolicy = Partner.Customers[CustomerId].ConfigurationPolicies.CreateAsync(configurationPolicy).GetAwaiter().GetResult(); - WriteObject(new PSConfigurationPolicy(devicePolicy)); + devicePolicy = await partner.Customers[CustomerId].ConfigurationPolicies.CreateAsync(configurationPolicy, CancellationToken).ConfigureAwait(false); + WriteObject(new PSConfigurationPolicy(devicePolicy)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerDeviceBatch.cs b/src/PowerShell/Commands/NewPartnerCustomerDeviceBatch.cs index d9cd92d..6ac874c 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerDeviceBatch.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerDeviceBatch.cs @@ -9,14 +9,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using System.Threading; + using System.Threading.Tasks; + using Models.Authentication; using Models.DevicesDeployment; using PartnerCenter.Models; using PartnerCenter.Models.DevicesDeployment; using Properties; - [Cmdlet(VerbsCommon.New, "PartnerCustomerDeviceBatch", SupportsShouldProcess = true), OutputType(typeof(PSBatchUploadDetails))] - public class NewPartnerCustomerDeviceBatch : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerCustomerDeviceBatch", SupportsShouldProcess = true)] + [OutputType(typeof(PSBatchUploadDetails))] + public class NewPartnerCustomerDeviceBatch : PartnerAsyncCmdlet { /// /// Gets or sets the identifier for the device batch. @@ -44,62 +46,64 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - DeviceBatchCreationRequest request; - ResourceCollection batches; - IEnumerable devices; - BatchUploadDetails status; - string location; - - if (!ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerDeviceBatchWhatIf, BatchId))) + Scheduler.RunTask(async () => { - return; - } - - batches = Partner.Customers[CustomerId].DeviceBatches.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - devices = Devices.Select(d => new Device - { - HardwareHash = d.HardwareHash, - ModelName = d.ModelName, - OemManufacturerName = d.OemManufacturerName, - Policies = d.Policies, - ProductKey = d.ProductKey, - SerialNumber = d.SerialNumber - }); - - if (batches.Items.SingleOrDefault(b => b.Id.Equals(BatchId, StringComparison.InvariantCultureIgnoreCase)) != null) - { - location = Partner.Customers[CustomerId].DeviceBatches[BatchId].Devices.CreateAsync(Devices.Select(d => new Device + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerDeviceBatchWhatIf, BatchId))) { - HardwareHash = d.HardwareHash, - ModelName = d.ModelName, - OemManufacturerName = d.OemManufacturerName, - Policies = d.Policies, - ProductKey = d.ProductKey, - SerialNumber = d.SerialNumber - })).GetAwaiter().GetResult(); - } - else - { - request = new DeviceBatchCreationRequest - { - BatchId = BatchId, - Devices = devices - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + DeviceBatchCreationRequest request; + ResourceCollection batches; + IEnumerable devices; + BatchUploadDetails status; + string location; - location = Partner.Customers[CustomerId].DeviceBatches.CreateAsync(request).GetAwaiter().GetResult(); - } + batches = await partner.Customers[CustomerId].DeviceBatches.GetAsync(CancellationToken).ConfigureAwait(false); - status = Partner.Customers[CustomerId].BatchUploadStatus.ById(location.Split('/')[4]).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + devices = Devices.Select(d => new Device + { + HardwareHash = d.HardwareHash, + ModelName = d.ModelName, + OemManufacturerName = d.OemManufacturerName, + Policies = d.Policies, + ProductKey = d.ProductKey, + SerialNumber = d.SerialNumber + }); - while (status.Status == DeviceUploadStatusType.Processing || status.Status == DeviceUploadStatusType.Queued) - { - Thread.Sleep(5000); + if (batches.Items.SingleOrDefault(b => b.Id.Equals(BatchId, StringComparison.InvariantCultureIgnoreCase)) != null) + { + location = await partner.Customers[CustomerId].DeviceBatches[BatchId].Devices.CreateAsync(Devices.Select(d => new Device + { + HardwareHash = d.HardwareHash, + ModelName = d.ModelName, + OemManufacturerName = d.OemManufacturerName, + Policies = d.Policies, + ProductKey = d.ProductKey, + SerialNumber = d.SerialNumber + }), CancellationToken).ConfigureAwait(false); + } + else + { + request = new DeviceBatchCreationRequest + { + BatchId = BatchId, + Devices = devices + }; - status = Partner.Customers[CustomerId].BatchUploadStatus.ById(location.Split('/')[4]).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } + location = await partner.Customers[CustomerId].DeviceBatches.CreateAsync(request, CancellationToken).ConfigureAwait(false); + } - WriteObject(new PSBatchUploadDetails(status)); + status = await partner.Customers[CustomerId].BatchUploadStatus.ById(location.Split('/')[4]).GetAsync(CancellationToken).ConfigureAwait(false); + + while (status.Status == DeviceUploadStatusType.Processing || status.Status == DeviceUploadStatusType.Queued) + { + await Task.Delay(5000, CancellationToken).ConfigureAwait(false); + + status = await partner.Customers[CustomerId].BatchUploadStatus.ById(location.Split('/')[4]).GetAsync(CancellationToken).ConfigureAwait(false); + } + + WriteObject(new PSBatchUploadDetails(status)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerOrder.cs b/src/PowerShell/Commands/NewPartnerCustomerOrder.cs index 716b9a2..0efc284 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerOrder.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerOrder.cs @@ -8,13 +8,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.Offers; using PartnerCenter.Models.Orders; using PartnerCenter.PowerShell.Models.Orders; [Cmdlet(VerbsCommon.New, "PartnerCustomerOrder", DefaultParameterSetName = SubscriptionParameterSet, SupportsShouldProcess = true)] [OutputType(typeof(PSOrder))] - public class NewPartnerCustomerOrder : PartnerCmdlet + public class NewPartnerCustomerOrder : PartnerAsyncCmdlet { /// /// The name for the add-on parameter set. @@ -59,50 +60,54 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - List lineItems = new List(); - Order newOrder; - - foreach (PSOrderLineItem item in LineItems) + Scheduler.RunTask(async () => { - OrderLineItem lineItem = new OrderLineItem - { - FriendlyName = item.FriendlyName, - LineItemNumber = item.LineItemNumber, - OfferId = item.OfferId, - ParentSubscriptionId = item.ParentSubscriptionId, - PartnerIdOnRecord = item.PartnerIdOnRecord, - Quantity = item.Quantity, - SubscriptionId = item.SubscriptionId - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + List lineItems = new List(); + Order newOrder; - if (item.ProvisioningContext != null && item.ProvisioningContext.Count > 0) + foreach (PSOrderLineItem item in LineItems) { - foreach (KeyValuePair kvp in item.ProvisioningContext.Cast().ToDictionary(entry => (string)entry.Key, kvp => (string)kvp.Value)) + OrderLineItem lineItem = new OrderLineItem { - lineItem.ProvisioningContext.Add(kvp.Key, kvp.Value); + FriendlyName = item.FriendlyName, + LineItemNumber = item.LineItemNumber, + OfferId = item.OfferId, + ParentSubscriptionId = item.ParentSubscriptionId, + PartnerIdOnRecord = item.PartnerIdOnRecord, + Quantity = item.Quantity, + SubscriptionId = item.SubscriptionId + }; + + if (item.ProvisioningContext != null && item.ProvisioningContext.Count > 0) + { + foreach (KeyValuePair kvp in item.ProvisioningContext.Cast().ToDictionary(entry => (string)entry.Key, kvp => (string)kvp.Value)) + { + lineItem.ProvisioningContext.Add(kvp.Key, kvp.Value); + } } + + lineItems.Add(lineItem); } - lineItems.Add(lineItem); - } + newOrder = new Order + { + BillingCycle = BillingCycle, + LineItems = lineItems, + ReferenceCustomerId = CustomerId + }; - newOrder = new Order - { - BillingCycle = BillingCycle, - LineItems = lineItems, - ReferenceCustomerId = CustomerId - }; + if (string.IsNullOrEmpty(OrderId)) + { + newOrder = await partner.Customers[CustomerId].Orders.CreateAsync(newOrder, CancellationToken).ConfigureAwait(false); + } + else + { + newOrder = await partner.Customers[CustomerId].Orders.ById(OrderId).PatchAsync(newOrder, CancellationToken).ConfigureAwait(false); + } - if (string.IsNullOrEmpty(OrderId)) - { - newOrder = Partner.Customers[CustomerId].Orders.CreateAsync(newOrder).GetAwaiter().GetResult(); - } - else - { - newOrder = Partner.Customers[CustomerId].Orders.ById(OrderId).PatchAsync(newOrder).GetAwaiter().GetResult(); - } - - WriteObject(new PSOrder(newOrder)); + WriteObject(new PSOrder(newOrder)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerSubscriptionActivation.cs b/src/PowerShell/Commands/NewPartnerCustomerSubscriptionActivation.cs index 25ca6a8..f18cb06 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerSubscriptionActivation.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerSubscriptionActivation.cs @@ -6,14 +6,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using Properties; /// /// Activates a third-party subscription in the integration sandbox. /// - [Cmdlet(VerbsCommon.New, "PartnerCustomerSubscriptionActivation", SupportsShouldProcess = true), OutputType(typeof(PSSubscriptionActivationResult))] - public class NewPartnerCustomerSubscriptionActivation : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerCustomerSubscriptionActivation", SupportsShouldProcess = true)] + [OutputType(typeof(PSSubscriptionActivationResult))] + public class NewPartnerCustomerSubscriptionActivation : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -34,14 +36,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (ShouldProcess(string.Format( - CultureInfo.CurrentCulture, - Resources.SubscriptionActivationWhatIf, - SubscriptionId, - CustomerId))) + Scheduler.RunTask(async () => { - WriteObject(Partner.Customers[CustomerId].Subscriptions[SubscriptionId].ActivateAsync().ConfigureAwait(false).GetAwaiter().GetResult()); - } + if (ShouldProcess(string.Format( + CultureInfo.CurrentCulture, + Resources.SubscriptionActivationWhatIf, + SubscriptionId, + CustomerId))) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(await partner.Customers[CustomerId].Subscriptions[SubscriptionId].ActivateAsync(CancellationToken).ConfigureAwait(false)); + } + }, true); + } } } diff --git a/src/PowerShell/Commands/NewPartnerCustomerSubscriptionRegistration.cs b/src/PowerShell/Commands/NewPartnerCustomerSubscriptionRegistration.cs index 5687862..99af443 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerSubscriptionRegistration.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerSubscriptionRegistration.cs @@ -6,13 +6,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Properties; /// /// Registers an existing Subscription so that it is enabled for ordering Azure Reserved VM Instances. /// - [Cmdlet(VerbsCommon.New, "PartnerCustomerSubscriptionRegistration", SupportsShouldProcess = true), OutputType(typeof(string))] - public class NewPartnerCustomerSubscriptionRegistration : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerCustomerSubscriptionRegistration", SupportsShouldProcess = true)] + [OutputType(typeof(string))] + public class NewPartnerCustomerSubscriptionRegistration : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -33,14 +35,19 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (ShouldProcess(string.Format( - CultureInfo.CurrentCulture, - Resources.SubscriptionRegistrationWhatIf, - SubscriptionId, - CustomerId))) + Scheduler.RunTask(async () => { - WriteObject(Partner.Customers[CustomerId].Subscriptions[SubscriptionId].Registration.RegisterAsync().ConfigureAwait(false).GetAwaiter().GetResult()); - } + if (ShouldProcess(string.Format( + CultureInfo.CurrentCulture, + Resources.SubscriptionRegistrationWhatIf, + SubscriptionId, + CustomerId))) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(await partner.Customers[CustomerId].Subscriptions[SubscriptionId].Registration.RegisterAsync(CancellationToken).ConfigureAwait(false)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerCustomerUser.cs b/src/PowerShell/Commands/NewPartnerCustomerUser.cs index b63a824..1f981e9 100644 --- a/src/PowerShell/Commands/NewPartnerCustomerUser.cs +++ b/src/PowerShell/Commands/NewPartnerCustomerUser.cs @@ -14,7 +14,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using Properties; [Cmdlet(VerbsCommon.New, "PartnerCustomerUser", SupportsShouldProcess = true), OutputType(typeof(PSCustomerUser))] - public class NewPartnerCustomerUser : PartnerCmdlet + public class NewPartnerCustomerUser : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -76,31 +76,35 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - CustomerUser newUser; - string country; - CustomerId.AssertNotEmpty(nameof(CustomerId)); - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerUserWhatIf, UserPrincipalName))) + Scheduler.RunTask(async () => { - country = (string.IsNullOrEmpty(UsageLocation)) ? PartnerSession.Instance.Context.CountryCode : UsageLocation; - string stringPassword = SecureStringExtensions.ConvertToString(Password); - - newUser = new CustomerUser + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.NewPartnerCustomerUserWhatIf, UserPrincipalName))) { - PasswordProfile = new PasswordProfile() + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + CustomerUser newUser; + string country; + + country = (string.IsNullOrEmpty(UsageLocation)) ? PartnerSession.Instance.Context.CountryCode : UsageLocation; + string stringPassword = SecureStringExtensions.ConvertToString(Password); + + newUser = new CustomerUser { - ForceChangePassword = ForceChangePassword.IsPresent, - Password = stringPassword - }, - DisplayName = DisplayName, - FirstName = FirstName, - LastName = LastName, - UsageLocation = country, - UserPrincipalName = UserPrincipalName - }; - CustomerUser createdUser = Partner.Customers[CustomerId].Users.CreateAsync(newUser).GetAwaiter().GetResult(); - WriteObject(new PSCustomerUser(createdUser)); - } + PasswordProfile = new PasswordProfile() + { + ForceChangePassword = ForceChangePassword.IsPresent, + Password = stringPassword + }, + DisplayName = DisplayName, + FirstName = FirstName, + LastName = LastName, + UsageLocation = country, + UserPrincipalName = UserPrincipalName + }; + CustomerUser createdUser = await partner.Customers[CustomerId].Users.CreateAsync(newUser, CancellationToken).ConfigureAwait(false); + WriteObject(new PSCustomerUser(createdUser)); + } + }, true); + } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerProductUpgrade.cs b/src/PowerShell/Commands/NewPartnerProductUpgrade.cs index e8f51c8..71c4f5c 100644 --- a/src/PowerShell/Commands/NewPartnerProductUpgrade.cs +++ b/src/PowerShell/Commands/NewPartnerProductUpgrade.cs @@ -5,10 +5,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using PartnerCenter.Models.ProductUpgrades; - [Cmdlet(VerbsCommon.New, "PartnerProductUpgrade"), OutputType(typeof(ProductUpgradeRequest))] - public class NewPartnerProductUpgrade : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerProductUpgrade")] + [OutputType(typeof(ProductUpgradeRequest))] + public class NewPartnerProductUpgrade : PartnerAsyncCmdlet { /// /// Gets or sets the identifier of the customer. @@ -29,11 +31,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(Partner.ProductUpgrades.CreateAsync(new ProductUpgradeRequest + Scheduler.RunTask(async () => { - CustomerId = CustomerId, - ProductFamily = ProductFamily - }).ConfigureAwait(false).GetAwaiter().GetResult()); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + WriteObject(await partner.ProductUpgrades.CreateAsync(new ProductUpgradeRequest + { + CustomerId = CustomerId, + ProductFamily = ProductFamily + }, CancellationToken).ConfigureAwait(false)); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/NewPartnerServiceRequest.cs b/src/PowerShell/Commands/NewPartnerServiceRequest.cs index 740abb4..e6fe8db 100644 --- a/src/PowerShell/Commands/NewPartnerServiceRequest.cs +++ b/src/PowerShell/Commands/NewPartnerServiceRequest.cs @@ -9,8 +9,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using PartnerCenter.Models.ServiceRequests; using Properties; - [Cmdlet(VerbsCommon.New, "PartnerServiceRequest", SupportsShouldProcess = true), OutputType(typeof(PSServiceRequest))] - public class NewPartnerServiceRequest : PartnerCmdlet + [Cmdlet(VerbsCommon.New, "PartnerServiceRequest", SupportsShouldProcess = true)] + [OutputType(typeof(PSServiceRequest))] + public class NewPartnerServiceRequest : PartnerAsyncCmdlet { /// /// Gets or sets the locale of the organization creating the service request. @@ -51,25 +52,30 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ServiceRequest request; - string agentLocale; - - if (ShouldProcess(Resources.NewPartnerServiceRequestWhatIf)) + Scheduler.RunTask(async () => { - agentLocale = string.IsNullOrEmpty(AgentLocale) ? PartnerSession.Instance.Context.Locale : AgentLocale; - - request = new ServiceRequest + if (ShouldProcess(Resources.NewPartnerServiceRequestWhatIf)) { - Description = Description, - Severity = Severity, - SupportTopicId = SupportTopicId, - Title = Title - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ServiceRequest request; + string agentLocale; - request = Partner.ServiceRequests.CreateAsync(request, agentLocale).GetAwaiter().GetResult(); + agentLocale = string.IsNullOrEmpty(AgentLocale) ? PartnerSession.Instance.Context.Locale : AgentLocale; - WriteObject(new PSServiceRequest(request)); - } + request = new ServiceRequest + { + Description = Description, + Severity = Severity, + SupportTopicId = SupportTopicId, + Title = Title + }; + + request = await partner.ServiceRequests.CreateAsync(request, agentLocale, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSServiceRequest(request)); + } + + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/PartnerCmdlet.cs b/src/PowerShell/Commands/PartnerCmdlet.cs deleted file mode 100644 index 3d911df..0000000 --- a/src/PowerShell/Commands/PartnerCmdlet.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace Microsoft.Store.PartnerCenter.PowerShell.Commands -{ - using System.Management.Automation; - using Models.Authentication; - using Properties; - - /// - /// The base class for the partner cmdlets. - /// - public abstract class PartnerCmdlet : PartnerPSCmdlet - { - /// - /// Gets the available Partner Center operations. - /// - internal IPartner Partner { get; private set; } - - /// - /// Operations that happen before the cmdlet is executed. - /// - protected override void BeginProcessing() - { - if (PartnerSession.Instance.Context == null) - { - throw new PSInvalidOperationException(Resources.RunConnectPartnerCenter); - } - - Partner = PartnerSession.Instance.ClientFactory.CreatePartnerOperations(); - - base.BeginProcessing(); - } - } -} \ No newline at end of file diff --git a/src/PowerShell/Commands/PartnerPSCmdlet.cs b/src/PowerShell/Commands/PartnerPSCmdlet.cs index 8b3db62..964530b 100644 --- a/src/PowerShell/Commands/PartnerPSCmdlet.cs +++ b/src/PowerShell/Commands/PartnerPSCmdlet.cs @@ -17,6 +17,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using ApplicationInsights.DataContracts; using ApplicationInsights.Extensibility; using Exceptions; + using Microsoft.Identity.Client; using Models; using Models.Authentication; using Network; @@ -38,6 +39,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// private const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/partnercenterps-changewarnings"; + /// + /// The identifier for the session. + /// + private static readonly Guid sessionId = Guid.NewGuid(); + /// /// Client that provides the ability to interact with the Application Insights service. /// @@ -56,6 +62,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// private CancellationTokenSource cancellationSource; + /// + /// The correlation identifier used to correlate events. + /// + private Guid correlationId; + /// /// A flag indicating if the object has already been disposed. /// @@ -81,6 +92,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// protected CancellationToken CancellationToken => cancellationSource.Token; + /// + /// Gets the correlation identifier used for correlating events. + /// + protected Guid CorrelationId => correlationId; + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// @@ -154,6 +170,11 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands cancellationSource = new CancellationTokenSource(); } + if (correlationId == default) + { + correlationId = Guid.NewGuid(); + } + httpTracingInterceptor ??= new RecordingTracingInterceptor(PartnerSession.Instance.DebugMessages); ServiceClientTracing.IsEnabled = true; @@ -169,9 +190,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands CommandName = commandAlias, IsSuccess = true, ModuleVersion = GetType().Assembly.GetName().Version.ToString(), - ParameterSetName = ParameterSetName + ParameterSetName = ParameterSetName, + SessionId = sessionId.ToString(), }; + if (!string.IsNullOrEmpty(PartnerSession.Instance?.Context?.Account?.Identifier)) + { + qosEvent.UserId = GenerateSha256HashString(PartnerSession.Instance.Context.Account.Identifier); + } + if (MyInvocation != null && MyInvocation.BoundParameters != null && MyInvocation.BoundParameters.Keys != null) { qosEvent.Parameters = string.Join(" ", MyInvocation.BoundParameters.Keys.Select( @@ -322,7 +349,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands } /// - /// Generate a SHA 256 hash string from the originInput. + /// Generate a SHA 256 hash string from the input. /// /// The input value to be hashed. /// The SHA 256 hash, or empty if the input is only whtespace. @@ -441,6 +468,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands Message = "The message has been removed due to PII" }; + + if (qosEvent.Exception is MsalServiceException) + { + MsalServiceException ex = qosEvent.Exception as MsalServiceException; + + exceptionTelemetry.Properties.Add("CorrelationId", ex.CorrelationId); + exceptionTelemetry.Properties.Add("ErrorCode", ex.ErrorCode); + exceptionTelemetry.Properties.Add("StatusCode", ex.StatusCode.ToString()); + } if (qosEvent.Exception is PartnerException) { PartnerException ex = qosEvent.Exception as PartnerException; @@ -489,14 +525,18 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands PageViewTelemetry pageViewTelemetry = new PageViewTelemetry { - Name = EventName, Duration = qosEvent.Duration, + Name = EventName, Timestamp = qosEvent.StartTime }; pageViewTelemetry.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); + pageViewTelemetry.Context.Session.Id = qosEvent.SessionId; + pageViewTelemetry.Context.User.Id = qosEvent.UserId; + PopulatePropertiesFromQos(pageViewTelemetry.Properties); +#if !DEBUG try { telemetryClient.TrackPageView(pageViewTelemetry); @@ -510,6 +550,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { LogExceptionEvent(); } +#endif } /// @@ -531,6 +572,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands eventProperties.Add("IsSuccess", qosEvent.IsSuccess.ToString(CultureInfo.InvariantCulture)); eventProperties.Add("ModuleVersion", qosEvent.ModuleVersion); eventProperties.Add("PowerShellVersion", Host.Version.ToString()); + eventProperties.Add("SessionId", qosEvent.SessionId); if (!string.IsNullOrEmpty(PartnerSession.Instance.Context?.Account?.Tenant)) { diff --git a/src/PowerShell/Commands/RegisterPartnerTokenCache.cs b/src/PowerShell/Commands/RegisterPartnerTokenCache.cs index 4758f56..ddb9ac2 100644 --- a/src/PowerShell/Commands/RegisterPartnerTokenCache.cs +++ b/src/PowerShell/Commands/RegisterPartnerTokenCache.cs @@ -40,10 +40,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { string inMemoryControlFilePath = Path.Combine(SharedUtilities.GetUserRootDirectory(), ".PartnerCenter", "InMemoryTokenCache"); + // TODO - Need to clone the cache if already connected; otherwise, the user will need to connect. + if (InMemory.IsPresent && InMemory.ToBool()) { if (!File.Exists(inMemoryControlFilePath)) { + Directory.CreateDirectory(Path.GetDirectoryName(inMemoryControlFilePath)); File.Create(inMemoryControlFilePath).Dispose(); } diff --git a/src/PowerShell/Commands/RemovePartnerCustomerConfigurationPolicy.cs b/src/PowerShell/Commands/RemovePartnerCustomerConfigurationPolicy.cs index 33c5d2e..19256f0 100644 --- a/src/PowerShell/Commands/RemovePartnerCustomerConfigurationPolicy.cs +++ b/src/PowerShell/Commands/RemovePartnerCustomerConfigurationPolicy.cs @@ -5,13 +5,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Properties; /// /// Return a list of configuration policies or a specific configration policy for the specified customer identifier. /// - [Cmdlet(VerbsCommon.Remove, "PartnerCustomerConfigurationPolicy"), OutputType(typeof(bool))] - public class RemovePartnerCustomerConfigurationPolicy : PartnerCmdlet + [Cmdlet(VerbsCommon.Remove, "PartnerCustomerConfigurationPolicy")] + [OutputType(typeof(bool))] + public class RemovePartnerCustomerConfigurationPolicy : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -36,13 +38,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (!ShouldProcess(Resources.RemovePartnerCustomerConfigurationPolicyWhatIf, PolicyId)) + Scheduler.RunTask(async () => { - return; - } + if (ShouldProcess(Resources.RemovePartnerCustomerConfigurationPolicyWhatIf, PolicyId)) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - Partner.Customers[CustomerId].ConfigurationPolicies[PolicyId].DeleteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(true); + await partner.Customers[CustomerId].ConfigurationPolicies[PolicyId].DeleteAsync(CancellationToken).ConfigureAwait(false); + WriteObject(true); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/RemovePartnerCustomerUser.cs b/src/PowerShell/Commands/RemovePartnerCustomerUser.cs index 652c51a..cbabd29 100644 --- a/src/PowerShell/Commands/RemovePartnerCustomerUser.cs +++ b/src/PowerShell/Commands/RemovePartnerCustomerUser.cs @@ -4,22 +4,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System; - using System.Collections.Generic; using System.Globalization; - using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; - using PartnerCenter.Enumerators; - using PartnerCenter.Models; - using PartnerCenter.Models.Users; + using Graph; + using Models.Authentication; + using Network; using Properties; /// /// Gets a list of users for a customer from Partner Center. /// - [Cmdlet(VerbsCommon.Remove, "PartnerCustomerUser", DefaultParameterSetName = "ByUserId", SupportsShouldProcess = true), OutputType(typeof(bool))] - public class RemovePartnerCustomerUser : PartnerCmdlet + [Cmdlet(VerbsCommon.Remove, "PartnerCustomerUser", DefaultParameterSetName = "ByUserId", SupportsShouldProcess = true)] + [OutputType(typeof(bool))] + public class RemovePartnerCustomerUser : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -48,100 +46,32 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RemovePartnerCustomerUserWhatIf, UserId))) + string value = string.IsNullOrEmpty(UserId) ? UserPrincipalName : UserId; + + Scheduler.RunTask(async () => { - switch (ParameterSetName) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RemovePartnerCustomerUserWhatIf, value))) { - case "ByUpn": - RemoveUserByUpn(CustomerId, UserPrincipalName); - break; - case "ByUserId": - RemoveUserById(CustomerId, UserId); - break; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + string userId; + + if (ParameterSetName.Equals("ByUpn", StringComparison.InvariantCultureIgnoreCase)) + { + GraphServiceClient client = PartnerSession.Instance.ClientFactory.CreateGraphServiceClient() as GraphServiceClient; + client.AuthenticationProvider = new GraphAuthenticationProvider(CustomerId); + + Graph.User user = await client.Users[UserPrincipalName].Request().GetAsync(CancellationToken).ConfigureAwait(false); + userId = user.Id; + } + else + { + userId = UserId; + } + + await partner.Customers.ById(CustomerId).Users.ById(UserId).DeleteAsync(CancellationToken).ConfigureAwait(false); + WriteObject(true); } - } - } - - /// - /// Gets a details for a specified user and customer from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user. - /// - /// is empty or null. - /// - private void RemoveUserById(string customerId, string userId) - { - customerId.AssertNotEmpty(nameof(customerId)); - userId.AssertNotEmpty(nameof(userId)); - - Partner.Customers.ById(customerId).Users.ById(userId).DeleteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(true); - } - - /// - /// Removes the customer user from Partner Center based on the specified user principal name. - /// - /// Identifier of the customer. - /// Identifier of the user principal name. - /// - /// is empty or null. - /// - private void RemoveUserByUpn(string customerId, string userPrincipalName) - { - customerId.AssertNotEmpty(nameof(customerId)); - customerId.AssertNotEmpty(nameof(userPrincipalName)); - - string userIdToDelete = GetUserIdByUpn(customerId, userPrincipalName); - - RemoveUserById(customerId, userIdToDelete); - } - - /// - /// Gets a user id by searching for the user principal name from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user principal name. - /// - /// is empty or null. - /// - private string GetUserIdByUpn(string customerId, string userPrincipalName) - { - customerId.AssertNotEmpty(nameof(customerId)); - customerId.AssertNotEmpty(nameof(userPrincipalName)); - - List gUsers = GetUsers(customerId); - - return gUsers.SingleOrDefault(u => string.Equals(u.UserPrincipalName, userPrincipalName, StringComparison.CurrentCultureIgnoreCase)).Id; - } - - /// - /// Gets a list of users from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private List GetUsers(string customerId) - { - IResourceCollectionEnumerator> usersEnumerator; - List users; - SeekBasedResourceCollection seekUsers; - - customerId.AssertNotEmpty(nameof(customerId)); - - users = new List(); - - seekUsers = Partner.Customers[customerId].Users.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - usersEnumerator = Partner.Enumerators.CustomerUsers.Create(seekUsers); - - while (usersEnumerator.HasValue) - { - users.AddRange(usersEnumerator.Current.Items); - usersEnumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - - return users; + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/RemovePartnerCustomerUserRoleMember.cs b/src/PowerShell/Commands/RemovePartnerCustomerUserRoleMember.cs index 77d75ac..6d4b79c 100644 --- a/src/PowerShell/Commands/RemovePartnerCustomerUserRoleMember.cs +++ b/src/PowerShell/Commands/RemovePartnerCustomerUserRoleMember.cs @@ -5,13 +5,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; /// /// Removes the user from the specified role. /// - [Cmdlet(VerbsCommon.Remove, "PartnerCustomerUserRoleMember"), OutputType(typeof(bool))] - public class RemovePartnerCustomerUserRoleMember : PartnerCmdlet + [Cmdlet(VerbsCommon.Remove, "PartnerCustomerUserRoleMember")] + [OutputType(typeof(bool))] + public class RemovePartnerCustomerUserRoleMember : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -31,6 +32,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// Gets or sets the role identifier. /// [Parameter(Mandatory = false, HelpMessage = "Identifier for the role.")] + [ValidateNotNull] public string RoleId { get; set; } /// @@ -38,12 +40,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - CustomerId.AssertNotEmpty(nameof(CustomerId)); - UserId.AssertNotEmpty(nameof(UserId)); - RoleId.AssertNotEmpty(nameof(RoleId)); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - Partner.Customers[CustomerId].DirectoryRoles[RoleId].UserMembers[UserId].DeleteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(true); + await partner.Customers[CustomerId].DirectoryRoles[RoleId].UserMembers[UserId].DeleteAsync(CancellationToken).ConfigureAwait(false); + WriteObject(true); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/RemovePartnerResellerRelationship.cs b/src/PowerShell/Commands/RemovePartnerResellerRelationship.cs index 95834e1..24b7d1a 100644 --- a/src/PowerShell/Commands/RemovePartnerResellerRelationship.cs +++ b/src/PowerShell/Commands/RemovePartnerResellerRelationship.cs @@ -7,6 +7,8 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; + using Microsoft.Store.PartnerCenter.Models.Customers; + using Models.Authentication; using Models.Customers; using PartnerCenter.Models; using PartnerCenter.Models.Subscriptions; @@ -15,8 +17,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Removes the relationship between the specified customer and the partner. /// - [Cmdlet(VerbsCommon.Remove, "PartnerResellerRelationship", ConfirmImpact = ConfirmImpact.High, SupportsShouldProcess = true), OutputType(typeof(PSCustomer))] - public class RemovePartnerResellerRelationship : PartnerCmdlet + [Cmdlet(VerbsCommon.Remove, "PartnerResellerRelationship", ConfirmImpact = ConfirmImpact.High, SupportsShouldProcess = true)] + [OutputType(typeof(PSCustomer))] + public class RemovePartnerResellerRelationship : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -30,27 +33,30 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - PartnerCenter.Models.Customers.Customer customer; - ResourceCollection subscriptions; - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RemovePartnerResellerRelationshipWhatIf, CustomerId))) + Scheduler.RunTask(async () => { - subscriptions = Partner.Customers[CustomerId].Subscriptions.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - foreach (Subscription subscription in subscriptions.Items.Where(s => s.Status == SubscriptionStatus.Active)) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RemovePartnerResellerRelationshipWhatIf, CustomerId))) { - subscription.Status = SubscriptionStatus.Suspended; - Partner.Customers[CustomerId].Subscriptions[subscription.Id].PatchAsync(subscription).GetAwaiter().GetResult(); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - customer = Partner.Customers[CustomerId].PatchAsync( - new PartnerCenter.Models.Customers.Customer + Customer customer; + ResourceCollection subscriptions = await partner.Customers[CustomerId].Subscriptions.GetAsync(CancellationToken).ConfigureAwait(false); + + foreach (Subscription subscription in subscriptions.Items.Where(s => s.Status == SubscriptionStatus.Active)) { - RelationshipToPartner = PartnerCenter.Models.Customers.CustomerPartnerRelationship.None - }).GetAwaiter().GetResult(); + subscription.Status = SubscriptionStatus.Suspended; + await partner.Customers[CustomerId].Subscriptions[subscription.Id].PatchAsync(subscription, CancellationToken).ConfigureAwait(false); + } - WriteObject(new PSCustomer(customer)); - } + customer = await partner.Customers[CustomerId].PatchAsync( + new Customer + { + RelationshipToPartner = CustomerPartnerRelationship.None + }, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCustomer(customer)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/RemovePartnerSandboxCustomer.cs b/src/PowerShell/Commands/RemovePartnerSandboxCustomer.cs index 24ae217..75ac19e 100644 --- a/src/PowerShell/Commands/RemovePartnerSandboxCustomer.cs +++ b/src/PowerShell/Commands/RemovePartnerSandboxCustomer.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Properties; /// @@ -13,7 +14,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// [Cmdlet(VerbsCommon.Remove, "PartnerSandboxCustomer", ConfirmImpact = ConfirmImpact.High, SupportsShouldProcess = true)] [OutputType(typeof(bool))] - public class RemovePartnerSandboxCustomer : PartnerCmdlet + public class RemovePartnerSandboxCustomer : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -27,11 +28,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RemovePartnerSandboxCustomerWhatIf, CustomerId))) + Scheduler.RunTask(async () => { - Partner.Customers[CustomerId].DeleteAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(true); - } + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RemovePartnerSandboxCustomerWhatIf, CustomerId))) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + await partner.Customers[CustomerId].DeleteAsync(CancellationToken).ConfigureAwait(false); + WriteObject(true); + } + + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/RestorePartnerCustomerUser.cs b/src/PowerShell/Commands/RestorePartnerCustomerUser.cs index 1c7555b..193816d 100644 --- a/src/PowerShell/Commands/RestorePartnerCustomerUser.cs +++ b/src/PowerShell/Commands/RestorePartnerCustomerUser.cs @@ -9,18 +9,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Linq; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; + using Models.Authentication; using PartnerCenter.Enumerators; using PartnerCenter.Models; using PartnerCenter.Models.Query; using PartnerCenter.Models.Users; using Properties; + using RequestContext; /// /// Gets a list of users for a customer from Partner Center. /// - [Cmdlet(VerbsData.Restore, "PartnerCustomerUser", DefaultParameterSetName = "ByUserId", SupportsShouldProcess = true), OutputType(typeof(bool))] - public class RestorePartnerCustomerUser : PartnerCmdlet + [Cmdlet(VerbsData.Restore, "PartnerCustomerUser", DefaultParameterSetName = "ByUserId", SupportsShouldProcess = true)] + [OutputType(typeof(bool))] + public class RestorePartnerCustomerUser : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -49,104 +51,54 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RestorePartnerCustomerUserWhatIf, UserId))) + Scheduler.RunTask(async () => { - switch (ParameterSetName) + string value = string.IsNullOrEmpty(UserId) ? UserPrincipalName : UserId; + + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.RestorePartnerCustomerUserWhatIf, value))) { - case "ByUpn": - RestoreUserByUpn(CustomerId, UserPrincipalName); - break; - case "ByUserId": - RestoreUserById(CustomerId, UserId); - break; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + string userId; + + if (ParameterSetName.Equals("ByUpn", StringComparison.InvariantCultureIgnoreCase)) + { + SimpleFieldFilter filter = new SimpleFieldFilter("UserState", FieldFilterOperation.Equals, "Inactive"); + IQuery simpleQueryWithFilter = QueryFactory.BuildSimpleQuery(filter); + IResourceCollectionEnumerator> usersEnumerator; + List users = new List(); + SeekBasedResourceCollection seekUsers; + + seekUsers = await partner.Customers[CustomerId].Users.QueryAsync(simpleQueryWithFilter, CancellationToken).ConfigureAwait(false); + usersEnumerator = partner.Enumerators.CustomerUsers.Create(seekUsers); + + while (usersEnumerator.HasValue) + { + users.AddRange(usersEnumerator.Current.Items); + await usersEnumerator.NextAsync(RequestContextFactory.Create(CorrelationId), CancellationToken).ConfigureAwait(false); + } + + CustomerUser user = users.SingleOrDefault(u => string.Equals(u.UserPrincipalName, UserPrincipalName, StringComparison.CurrentCultureIgnoreCase)); + + if (user == null) + { + throw new PSInvalidOperationException($"Unable to locate {UserPrincipalName}"); + } + + userId = user.Id; + } + else + { + userId = UserId; + } + + CustomerUser updatedCustomerUser = new CustomerUser + { + State = UserState.Active + }; + + await partner.Customers.ById(CustomerId).Users.ById(userId).PatchAsync(updatedCustomerUser, CancellationToken).ConfigureAwait(false); } - } - } - - /// - /// Restores the specified customer user id. - /// - /// Identifier of the customer. - /// Identifier of the user. - /// - /// is empty or null. - /// - private void RestoreUserById(string customerId, string userId) - { - customerId.AssertNotEmpty(nameof(customerId)); - userId.AssertNotEmpty(nameof(userId)); - - CustomerUser updatedCustomerUser = new CustomerUser - { - State = UserState.Active - }; - - Partner.Customers.ById(customerId).Users.ById(userId).PatchAsync(updatedCustomerUser).GetAwaiter().GetResult(); - WriteObject(true); - } - - /// - /// Restores the customer user from Partner Center based on the specified user principal name. - /// - /// Identifier of the customer. - /// Identifier of the user principal name. - /// - /// is empty or null. - /// - private void RestoreUserByUpn(string customerId, string userPrincipalName) - { - customerId.AssertNotEmpty(nameof(customerId)); - userPrincipalName.AssertNotEmpty(nameof(userPrincipalName)); - - RestoreUserById(customerId, GetUserIdByUpn(customerId, userPrincipalName)); - } - - /// - /// Gets a user id by searching for the user principal name from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the user principal name. - /// - /// is empty or null. - /// - private string GetUserIdByUpn(string customerId, string userPrincipalName) - { - customerId.AssertNotEmpty(nameof(customerId)); - customerId.AssertNotEmpty(nameof(userPrincipalName)); - - List gUsers = GetDeletedUsers(customerId); - - return gUsers.SingleOrDefault(u => string.Equals(u.UserPrincipalName, userPrincipalName, StringComparison.CurrentCultureIgnoreCase)).Id; - } - - /// - /// Gets a list of deleted users from Partner Center. - /// - /// Identifier of the customer. - /// - /// is empty or null. - /// - private List GetDeletedUsers(string customerId) - { - SimpleFieldFilter filter = new SimpleFieldFilter("UserState", FieldFilterOperation.Equals, "Inactive"); - IQuery simpleQueryWithFilter = QueryFactory.BuildSimpleQuery(filter); - IResourceCollectionEnumerator> usersEnumerator; - List users; - SeekBasedResourceCollection seekUsers; - - customerId.AssertNotEmpty(nameof(customerId)); - - users = new List(); - - seekUsers = Partner.Customers[customerId].Users.QueryAsync(simpleQueryWithFilter).GetAwaiter().GetResult(); - usersEnumerator = Partner.Enumerators.CustomerUsers.Create(seekUsers); - while (usersEnumerator.HasValue) - { - users.AddRange(usersEnumerator.Current.Items); - usersEnumerator.NextAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - - return users; + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerBillingProfile.cs b/src/PowerShell/Commands/SetPartnerBillingProfile.cs index 6fbaff8..e41144c 100644 --- a/src/PowerShell/Commands/SetPartnerBillingProfile.cs +++ b/src/PowerShell/Commands/SetPartnerBillingProfile.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Partners; using PartnerCenter.Models; using PartnerCenter.Models.Partners; @@ -14,8 +15,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Sets the partner billing profile in Partner Center. /// - [Cmdlet(VerbsCommon.Set, "PartnerBillingProfile", SupportsShouldProcess = true), OutputType(typeof(PSBillingProfile))] - public class SetPartnerBillingProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerBillingProfile", SupportsShouldProcess = true)] + [OutputType(typeof(PSBillingProfile))] + public class SetPartnerBillingProfile : PartnerAsyncCmdlet { /// /// Gets or sets the first line of the address. @@ -112,43 +114,48 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - BillingProfile profile; - IValidator
validator; - - if (ShouldProcess("Updates the partner's billing profile")) + Scheduler.RunTask(async () => { - profile = Partner.Profiles.BillingProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - profile.Address.AddressLine1 = UpdateValue(AddressLine1, profile.Address.AddressLine1); - profile.Address.AddressLine2 = UpdateValue(AddressLine2, profile.Address.AddressLine2); - profile.Address.City = UpdateValue(City, profile.Address.City); - profile.Address.PostalCode = UpdateValue(PostalCode, profile.Address.PostalCode); - profile.Address.Region = UpdateValue(Region, profile.Address.Region); - profile.Address.State = UpdateValue(State, profile.Address.State); + BillingProfile profile; + IValidator
validator; - profile.PrimaryContact.Email = UpdateValue(EmailAddress, profile.PrimaryContact.Email); - profile.PrimaryContact.FirstName = UpdateValue(FirstName, profile.PrimaryContact.FirstName); - profile.PrimaryContact.LastName = UpdateValue(LastName, profile.PrimaryContact.LastName); - profile.PrimaryContact.PhoneNumber = UpdateValue(PhoneNumber, profile.PrimaryContact.PhoneNumber); - - profile.PurchaseOrderNumber = UpdateValue(PurchaseOrderNumber, profile.PurchaseOrderNumber); - profile.TaxId = UpdateValue(TaxId, profile.TaxId); - - - if (!DisableValidation.ToBool()) + if (ShouldProcess("Updates the partner's billing profile")) { - validator = new AddressValidator(Partner); + profile = await partner.Profiles.BillingProfile.GetAsync(CancellationToken).ConfigureAwait(false); - if (!validator.IsValid(profile.Address, d => WriteDebug(d))) + profile.Address.AddressLine1 = UpdateValue(AddressLine1, profile.Address.AddressLine1); + profile.Address.AddressLine2 = UpdateValue(AddressLine2, profile.Address.AddressLine2); + profile.Address.City = UpdateValue(City, profile.Address.City); + profile.Address.PostalCode = UpdateValue(PostalCode, profile.Address.PostalCode); + profile.Address.Region = UpdateValue(Region, profile.Address.Region); + profile.Address.State = UpdateValue(State, profile.Address.State); + + profile.PrimaryContact.Email = UpdateValue(EmailAddress, profile.PrimaryContact.Email); + profile.PrimaryContact.FirstName = UpdateValue(FirstName, profile.PrimaryContact.FirstName); + profile.PrimaryContact.LastName = UpdateValue(LastName, profile.PrimaryContact.LastName); + profile.PrimaryContact.PhoneNumber = UpdateValue(PhoneNumber, profile.PrimaryContact.PhoneNumber); + + profile.PurchaseOrderNumber = UpdateValue(PurchaseOrderNumber, profile.PurchaseOrderNumber); + profile.TaxId = UpdateValue(TaxId, profile.TaxId); + + + if (!DisableValidation.ToBool()) { - throw new PSInvalidOperationException("The specified address is invalid. Please verify the address and try again."); + validator = new AddressValidator(partner); + + if (!await validator.IsValidAsync(profile.Address, CancellationToken)) + { + throw new PSInvalidOperationException("The specified address is invalid. Please verify the address and try again."); + } } + + await partner.Profiles.BillingProfile.UpdateAsync(profile, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSBillingProfile(profile)); } - - Partner.Profiles.BillingProfile.UpdateAsync(profile).GetAwaiter().GetResult(); - - WriteObject(new PSBillingProfile(profile)); - } + }, true); } private static string UpdateValue(string input, string output) diff --git a/src/PowerShell/Commands/SetPartnerCustomer.cs b/src/PowerShell/Commands/SetPartnerCustomer.cs index 7921292..25e8612 100644 --- a/src/PowerShell/Commands/SetPartnerCustomer.cs +++ b/src/PowerShell/Commands/SetPartnerCustomer.cs @@ -7,6 +7,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Customers; using PartnerCenter.Exceptions; using PartnerCenter.Models; @@ -16,7 +17,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands [Cmdlet(VerbsCommon.Set, "PartnerCustomer", DefaultParameterSetName = "Customer", SupportsShouldProcess = true)] [OutputType(typeof(PSCustomer))] - public class SetPartnerCustomer : PartnerCmdlet + public class SetPartnerCustomer : PartnerAsyncCmdlet { /// /// Gets or sets the customer being modified. @@ -127,47 +128,45 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Customer customer; - IValidator
validator; - string customerId; + string customerId = (InputObject == null) ? CustomerId : InputObject.CustomerId; - customerId = (InputObject == null) ? CustomerId : InputObject.CustomerId; - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerWhatIf, customerId))) + Scheduler.RunTask(async () => { - if (InputObject == null && string.IsNullOrEmpty(CustomerId)) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerWhatIf, customerId))) { - throw new PSInvalidOperationException(Resources.InvalidSetCustomerIdentifierException); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + Customer customer; + IValidator
validator; - customer = Partner.Customers[customerId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + customer = await partner.Customers[customerId].GetAsync(CancellationToken).ConfigureAwait(false); - customer.BillingProfile.DefaultAddress.AddressLine1 = UpdateValue(BillingAddressLine1, customer.BillingProfile.DefaultAddress.AddressLine1); - customer.BillingProfile.DefaultAddress.AddressLine2 = UpdateValue(BillingAddressLine2, customer.BillingProfile.DefaultAddress.AddressLine2); - customer.BillingProfile.DefaultAddress.City = UpdateValue(BillingAddressCity, customer.BillingProfile.DefaultAddress.City); - customer.BillingProfile.DefaultAddress.Country = UpdateValue(BillingAddressCountry, customer.BillingProfile.DefaultAddress.Country); - customer.BillingProfile.DefaultAddress.PhoneNumber = UpdateValue(BillingAddressPhoneNumber, customer.BillingProfile.DefaultAddress.PhoneNumber); - customer.BillingProfile.DefaultAddress.PostalCode = UpdateValue(BillingAddressPostalCode, customer.BillingProfile.DefaultAddress.PostalCode); - customer.BillingProfile.DefaultAddress.Region = UpdateValue(BillingAddressRegion, customer.BillingProfile.DefaultAddress.Region); - customer.BillingProfile.DefaultAddress.State = UpdateValue(BillingAddressState, customer.BillingProfile.DefaultAddress.State); - customer.BillingProfile.CompanyName = UpdateValue(Name, customer.BillingProfile.CompanyName); - customer.BillingProfile.Email = UpdateValue(Email, customer.BillingProfile.Email); + customer.BillingProfile.DefaultAddress.AddressLine1 = UpdateValue(BillingAddressLine1, customer.BillingProfile.DefaultAddress.AddressLine1); + customer.BillingProfile.DefaultAddress.AddressLine2 = UpdateValue(BillingAddressLine2, customer.BillingProfile.DefaultAddress.AddressLine2); + customer.BillingProfile.DefaultAddress.City = UpdateValue(BillingAddressCity, customer.BillingProfile.DefaultAddress.City); + customer.BillingProfile.DefaultAddress.Country = UpdateValue(BillingAddressCountry, customer.BillingProfile.DefaultAddress.Country); + customer.BillingProfile.DefaultAddress.PhoneNumber = UpdateValue(BillingAddressPhoneNumber, customer.BillingProfile.DefaultAddress.PhoneNumber); + customer.BillingProfile.DefaultAddress.PostalCode = UpdateValue(BillingAddressPostalCode, customer.BillingProfile.DefaultAddress.PostalCode); + customer.BillingProfile.DefaultAddress.Region = UpdateValue(BillingAddressRegion, customer.BillingProfile.DefaultAddress.Region); + customer.BillingProfile.DefaultAddress.State = UpdateValue(BillingAddressState, customer.BillingProfile.DefaultAddress.State); + customer.BillingProfile.CompanyName = UpdateValue(Name, customer.BillingProfile.CompanyName); + customer.BillingProfile.Email = UpdateValue(Email, customer.BillingProfile.Email); - if (!DisableValidation.ToBool()) - { - validator = new AddressValidator(Partner); - - if (!validator.IsValid(customer.BillingProfile.DefaultAddress, d => WriteDebug(d))) + if (!DisableValidation.ToBool()) { - throw new PartnerException("The address for the customer is not valid."); + validator = new AddressValidator(partner); + + if (!await validator.IsValidAsync(customer.BillingProfile.DefaultAddress, CancellationToken)) + { + throw new PartnerException("The address for the customer is not valid."); + } } + + await partner.Customers[customerId].Profiles.Billing.UpdateAsync(customer.BillingProfile, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCustomer(customer)); } - - Partner.Customers[customerId].Profiles.Billing.UpdateAsync(customer.BillingProfile).GetAwaiter().GetResult(); - - WriteObject(new PSCustomer(customer)); - } + }, true); } private static string UpdateValue(string input, string output) diff --git a/src/PowerShell/Commands/SetPartnerCustomerCart.cs b/src/PowerShell/Commands/SetPartnerCustomerCart.cs index 663c7e4..b826829 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerCart.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerCart.cs @@ -8,6 +8,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Management.Automation; using System.Text.RegularExpressions; using Extensions; + using Models.Authentication; using Models.Carts; using PartnerCenter.Models.Carts; using Properties; @@ -15,8 +16,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Updates the specified cart. /// - [Cmdlet(VerbsCommon.Set, "PartnerCustomerCart", SupportsShouldProcess = true), OutputType(typeof(PSCart))] - public class SetPartnerCustomerCart : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerCustomerCart", SupportsShouldProcess = true)] + [OutputType(typeof(PSCart))] + public class SetPartnerCustomerCart : PartnerAsyncCmdlet { /// /// Gets or sets the required cart identifier. @@ -44,33 +46,33 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Cart cart; - CartLineItem cartLineItem; - List cartLineItems; - - if (!ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerCartWhatIf, CartId))) + Scheduler.RunTask(async () => { - return; - } + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerCartWhatIf, CartId))) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + Cart cart; + CartLineItem cartLineItem; + List cartLineItems; - cart = Partner.Customers[CustomerId].Carts[CartId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + cart = await partner.Customers[CustomerId].Carts[CartId].GetAsync(CancellationToken).ConfigureAwait(false); - cartLineItems = new List(); + cartLineItems = new List(); - foreach (PSCartLineItem item in LineItems) - { - cartLineItem = new CartLineItem(); - cartLineItem.CopyFrom(item); + foreach (PSCartLineItem item in LineItems) + { + cartLineItem = new CartLineItem(); + cartLineItem.CopyFrom(item); - cartLineItems.Add(cartLineItem); - } + cartLineItems.Add(cartLineItem); + } - cart.LineItems = cartLineItems; - - cart = Partner.Customers[CustomerId].Carts[CartId].PutAsync(cart).GetAwaiter().GetResult(); - - WriteObject(new PSCart(cart)); + cart.LineItems = cartLineItems; + cart = await partner.Customers[CustomerId].Carts[CartId].PutAsync(cart, CancellationToken).ConfigureAwait(false); + WriteObject(new PSCart(cart)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerCustomerConfigurationPolicy.cs b/src/PowerShell/Commands/SetPartnerCustomerConfigurationPolicy.cs index 84e369c..b1d1696 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerConfigurationPolicy.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerConfigurationPolicy.cs @@ -6,16 +6,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Collections.Generic; using System.Management.Automation; using System.Text.RegularExpressions; - using Extensions; using Models; + using Models.Authentication; using PartnerCenter.Models.DevicesDeployment; using Properties; /// /// Creates a new configuration policies for the specified customer identifier. /// - [Cmdlet(VerbsCommon.Set, "PartnerCustomerConfigurationPolicy", SupportsShouldProcess = true), OutputType(typeof(PSConfigurationPolicy))] - public class SetPartnerCustomerConfigurationPolicy : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerCustomerConfigurationPolicy", SupportsShouldProcess = true)] + [OutputType(typeof(PSConfigurationPolicy))] + public class SetPartnerCustomerConfigurationPolicy : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -78,71 +79,56 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ConfigurationPolicy configurationPolicy = GetCustomerPolicy(CustomerId, PolicyId); - List policySettings = new List(); - - if (!ShouldProcess(Resources.SetPartnerCustomerConfigurationPolicyWhatIf, PolicyId)) + Scheduler.RunTask(async () => { - return; - } + if (ShouldProcess(Resources.SetPartnerCustomerConfigurationPolicyWhatIf, PolicyId)) + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + ConfigurationPolicy configurationPolicy = await partner.Customers[CustomerId].ConfigurationPolicies[PolicyId].GetAsync(CancellationToken).ConfigureAwait(false); + List policySettings = new List(); - if (OobeUserNotLocalAdmin) - { - policySettings.Add(PolicySettingsTypes.OobeUserNotLocalAdmin); - } + if (OobeUserNotLocalAdmin) + { + policySettings.Add(PolicySettingsTypes.OobeUserNotLocalAdmin); + } - if (SkipEula) - { - policySettings.Add(PolicySettingsTypes.SkipEula); - } + if (SkipEula) + { + policySettings.Add(PolicySettingsTypes.SkipEula); + } - if (SkipExpressSettings) - { - policySettings.Add(PolicySettingsTypes.SkipExpressSettings); - } + if (SkipExpressSettings) + { + policySettings.Add(PolicySettingsTypes.SkipExpressSettings); + } - if (RemoveOemPreinstalls) - { - policySettings.Add(PolicySettingsTypes.RemoveOemPreinstalls); - } + if (RemoveOemPreinstalls) + { + policySettings.Add(PolicySettingsTypes.RemoveOemPreinstalls); + } - if (SkipOemRegistration) - { - policySettings.Add(PolicySettingsTypes.SkipOemRegistration); - } + if (SkipOemRegistration) + { + policySettings.Add(PolicySettingsTypes.SkipOemRegistration); + } - if (!string.IsNullOrEmpty(Name)) - { - configurationPolicy.Name = Name; - } + if (!string.IsNullOrEmpty(Name)) + { + configurationPolicy.Name = Name; + } - if (!string.IsNullOrEmpty(Description)) - { - configurationPolicy.Description = Description; - } + if (!string.IsNullOrEmpty(Description)) + { + configurationPolicy.Description = Description; + } - configurationPolicy.PolicySettings = policySettings; + configurationPolicy.PolicySettings = policySettings; - ConfigurationPolicy devicePolicy = Partner.Customers[CustomerId].ConfigurationPolicies[PolicyId].PatchAsync(configurationPolicy).GetAwaiter().GetResult(); - WriteObject(new PSConfigurationPolicy(devicePolicy)); - } + ConfigurationPolicy devicePolicy = await partner.Customers[CustomerId].ConfigurationPolicies[PolicyId].PatchAsync(configurationPolicy, CancellationToken).ConfigureAwait(false); + WriteObject(new PSConfigurationPolicy(devicePolicy)); - /// - /// Gets the specified policy from the specified customer from Partner Center. - /// - /// Identifier of the customer. - /// Identifier of the policy. - /// - /// is empty or null. - /// or - /// is empty or null. - /// - private ConfigurationPolicy GetCustomerPolicy(string customerId, string policyId) - { - customerId.AssertNotEmpty(nameof(customerId)); - policyId.AssertNotEmpty(nameof(policyId)); - - return Partner.Customers[customerId].ConfigurationPolicies[policyId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerCustomerQualification.cs b/src/PowerShell/Commands/SetPartnerCustomerQualification.cs index feed8e2..a0c168b 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerQualification.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerQualification.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Customers; using PartnerCenter.Models.Customers; using PartnerCenter.Models.ValidationCodes; @@ -16,7 +17,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands ///
[Cmdlet(VerbsCommon.Set, "PartnerCustomerQualification", DefaultParameterSetName = "Customer", SupportsShouldProcess = true)] [OutputType(typeof(CustomerQualification))] - public class SetPartnerCustomerQualification : PartnerCmdlet + public class SetPartnerCustomerQualification : PartnerAsyncCmdlet { /// /// Gets or sets the customer being modified. @@ -56,27 +57,27 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { string customerId = (InputObject == null) ? CustomerId : InputObject.CustomerId; - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerWhatIf, customerId))) + Scheduler.RunTask(async () => { - if (InputObject == null && string.IsNullOrEmpty(CustomerId)) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerWhatIf, customerId))) { - throw new PSInvalidOperationException(Resources.InvalidSetCustomerIdentifierException); - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - if (Qualification == CustomerQualification.GovernmentCommunityCloud) - { - if (ValidationCode == null) + if (Qualification == CustomerQualification.GovernmentCommunityCloud) { - throw new PSInvalidOperationException("The validation code must be set when assigning the Government Community Cloud qualification. Use the Get-PartnerValidation command to get the validation code."); - } + if (ValidationCode == null) + { + throw new PSInvalidOperationException("The validation code must be set when assigning the Government Community Cloud qualification. Use the Get-PartnerValidation command to get the validation code."); + } - WriteObject(Partner.Customers[customerId].Qualification.UpdateAsync(Qualification, ValidationCode).GetAwaiter().GetResult()); + WriteObject(await partner.Customers[customerId].Qualification.UpdateAsync(Qualification, ValidationCode, CancellationToken).ConfigureAwait(false)); + } + else + { + WriteObject(await partner.Customers[customerId].Qualification.UpdateAsync(Qualification).ConfigureAwait(false)); + } } - else - { - WriteObject(Partner.Customers[customerId].Qualification.UpdateAsync(Qualification).GetAwaiter().GetResult()); - } - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerCustomerSubscription.cs b/src/PowerShell/Commands/SetPartnerCustomerSubscription.cs index cff865e..465ad64 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerSubscription.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerSubscription.cs @@ -90,23 +90,19 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands customerId = (InputObject == null) ? CustomerId : InputObject.CustomerId; - if (!ShouldProcess( + if (ShouldProcess( string.Format( CultureInfo.CurrentCulture, Resources.SetPartnerCustomerSubscriptionWhatIf, SubscriptionId, customerId))) { - return; - } + subscription = await partner.Customers[customerId].Subscriptions[SubscriptionId].GetAsync().ConfigureAwait(false); - subscription = await partner.Customers[customerId].Subscriptions[SubscriptionId].GetAsync().ConfigureAwait(false); - - - if (BillingCycle.HasValue) - { - await partner.Customers[customerId].Orders[subscription.OrderId].PatchAsync(new Order + if (BillingCycle.HasValue) { - BillingCycle = BillingCycle.Value, - LineItems = new List + await partner.Customers[customerId].Orders[subscription.OrderId].PatchAsync(new Order + { + BillingCycle = BillingCycle.Value, + LineItems = new List { new OrderLineItem { @@ -117,35 +113,36 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands Quantity = subscription.Quantity } }, - ReferenceCustomerId = customerId - }).ConfigureAwait(false); + ReferenceCustomerId = customerId + }).ConfigureAwait(false); - subscription.BillingCycle = BillingCycle.Value; + subscription.BillingCycle = BillingCycle.Value; + } + + if (!string.IsNullOrEmpty(FriendlyName)) + { + subscription.FriendlyName = FriendlyName; + } + + if (!string.IsNullOrEmpty(PartnerId)) + { + subscription.PartnerId = PartnerId; + } + + if (Quantity.HasValue) + { + subscription.Quantity = Quantity.Value; + } + + if (Status.HasValue) + { + subscription.Status = Status.Value; + } + + subscription = await partner.Customers[customerId].Subscriptions[SubscriptionId].PatchAsync(subscription).ConfigureAwait(false); + + WriteObject(new PSSubscription(subscription)); } - - if (!string.IsNullOrEmpty(FriendlyName)) - { - subscription.FriendlyName = FriendlyName; - } - - if (!string.IsNullOrEmpty(PartnerId)) - { - subscription.PartnerId = PartnerId; - } - - if (Quantity.HasValue) - { - subscription.Quantity = Quantity.Value; - } - - if (Status.HasValue) - { - subscription.Status = Status.Value; - } - - subscription = await partner.Customers[customerId].Subscriptions[SubscriptionId].PatchAsync(subscription).ConfigureAwait(false); - - WriteObject(new PSSubscription(subscription)); }); } } diff --git a/src/PowerShell/Commands/SetPartnerCustomerSubscriptionSupportContact.cs b/src/PowerShell/Commands/SetPartnerCustomerSubscriptionSupportContact.cs index 31bcb35..9e476b5 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerSubscriptionSupportContact.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerSubscriptionSupportContact.cs @@ -6,12 +6,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Subscriptions; using PartnerCenter.Models.Subscriptions; using Properties; - [Cmdlet(VerbsCommon.Set, "PartnerCustomerSubscriptionSupportContact", SupportsShouldProcess = true), OutputType(typeof(PSSupportContact))] - public class SetPartnerCustomerSubscriptionSupportContact : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerCustomerSubscriptionSupportContact", SupportsShouldProcess = true)] + [OutputType(typeof(PSSupportContact))] + public class SetPartnerCustomerSubscriptionSupportContact : PartnerAsyncCmdlet { /// /// Gets or sets the required customer identifier. @@ -53,23 +55,25 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - SupportContact contact; - - if (ShouldProcess(string.Format( - CultureInfo.CurrentCulture, - Resources.SetPartnerCustomerSubscriptionSupportContactWhatIf, - SubscriptionId))) + Scheduler.RunTask(async () => { - contact = new SupportContact + if (ShouldProcess(string.Format( + CultureInfo.CurrentCulture, + Resources.SetPartnerCustomerSubscriptionSupportContactWhatIf, + SubscriptionId))) { - Name = Name, - SupportMpnId = SupportMpnId, - SupportTenantId = SupportTenantId - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SupportContact contact = new SupportContact + { + Name = Name, + SupportMpnId = SupportMpnId, + SupportTenantId = SupportTenantId + }; - contact = Partner.Customers[CustomerId].Subscriptions[SubscriptionId].SupportContact.UpdateAsync(contact).GetAwaiter().GetResult(); - WriteObject(new PSSupportContact(contact)); - } + contact = await partner.Customers[CustomerId].Subscriptions[SubscriptionId].SupportContact.UpdateAsync(contact, CancellationToken).ConfigureAwait(false); + WriteObject(new PSSupportContact(contact)); + } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerCustomerUser.cs b/src/PowerShell/Commands/SetPartnerCustomerUser.cs index a7e5837..f7299c9 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerUser.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerUser.cs @@ -8,6 +8,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Security; using System.Text.RegularExpressions; using Extensions; + using Models.Authentication; using Models.Users; using PartnerCenter.Models.Users; using Properties; @@ -15,8 +16,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Sets user information for a customer from Partner Center. /// - [Cmdlet(VerbsCommon.Set, "PartnerCustomerUser", DefaultParameterSetName = "UserId", SupportsShouldProcess = true), OutputType(typeof(PSCustomerUser))] - public class SetPartnerCustomerUser : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerCustomerUser", DefaultParameterSetName = "UserId", SupportsShouldProcess = true)] + [OutputType(typeof(PSCustomerUser))] + public class SetPartnerCustomerUser : PartnerAsyncCmdlet { /// /// Gets or sets the display name for the user. @@ -90,74 +92,69 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - CustomerUser user; - PasswordProfile profile; + string userId = InputObject == null ? UserId : InputObject.UserId; - UserId = (InputObject == null) ? UserId : InputObject.UserId; - - user = Partner.Customers[CustomerId].Users[UserId].GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - if (user.Id == UserId) + Scheduler.RunTask(async () => { - if (UserPrincipalName != null) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerUserWhatIf, userId))) { - user.UserPrincipalName = UserPrincipalName; - } + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + PasswordProfile profile; - if (!string.IsNullOrEmpty(FirstName)) - { - user.FirstName = FirstName; - } + CustomerUser user = await partner.Customers[CustomerId].Users[userId].GetAsync(CancellationToken).ConfigureAwait(false); - if (!string.IsNullOrEmpty(LastName)) - { - user.LastName = LastName; - } - - if (!string.IsNullOrEmpty(DisplayName)) - { - user.DisplayName = DisplayName; - } - - if (!string.IsNullOrEmpty(UsageLocation)) - { - user.UsageLocation = UsageLocation; - } - - if (Password != null && Password.Length > 0) - { - string stringPassword = SecureStringExtensions.ConvertToString(Password); - - profile = new PasswordProfile + if (UserPrincipalName != null) { - Password = stringPassword, - ForceChangePassword = ForceChangePasswordNextLogin.IsPresent - }; - - user.PasswordProfile = profile; - } - else if (ForceChangePasswordNextLogin.IsPresent) - { - profile = new PasswordProfile - { - ForceChangePassword = ForceChangePasswordNextLogin.IsPresent - }; - - user.PasswordProfile = profile; - } - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerCustomerUserWhatIf, UserId))) - { - if (InputObject == null && string.IsNullOrEmpty(UserId)) - { - throw new PSInvalidOperationException(Resources.InvalidSetCustomerUserIdentifierException); + user.UserPrincipalName = UserPrincipalName; } - user = Partner.Customers[CustomerId].Users[UserId].PatchAsync(user).GetAwaiter().GetResult(); + if (!string.IsNullOrEmpty(FirstName)) + { + user.FirstName = FirstName; + } + + if (!string.IsNullOrEmpty(LastName)) + { + user.LastName = LastName; + } + + if (!string.IsNullOrEmpty(DisplayName)) + { + user.DisplayName = DisplayName; + } + + if (!string.IsNullOrEmpty(UsageLocation)) + { + user.UsageLocation = UsageLocation; + } + + if (Password != null && Password.Length > 0) + { + string stringPassword = SecureStringExtensions.ConvertToString(Password); + + profile = new PasswordProfile + { + Password = stringPassword, + ForceChangePassword = ForceChangePasswordNextLogin.IsPresent + }; + + user.PasswordProfile = profile; + } + else if (ForceChangePasswordNextLogin.IsPresent) + { + profile = new PasswordProfile + { + ForceChangePassword = ForceChangePasswordNextLogin.IsPresent + }; + + user.PasswordProfile = profile; + } + + user = await partner.Customers[CustomerId].Users[userId].PatchAsync(user, CancellationToken).ConfigureAwait(false); WriteObject(new PSCustomerUser(user), true); } - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerCustomerUserLicense.cs b/src/PowerShell/Commands/SetPartnerCustomerUserLicense.cs index 2c59aa2..91644cb 100644 --- a/src/PowerShell/Commands/SetPartnerCustomerUserLicense.cs +++ b/src/PowerShell/Commands/SetPartnerCustomerUserLicense.cs @@ -7,12 +7,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Licenses; using PartnerCenter.Models.Licenses; using Properties; - [Cmdlet(VerbsCommon.Set, "PartnerCustomerUserLicense", SupportsShouldProcess = true), OutputType(typeof(PSLicenseUpdate))] - public class SetPartnerCustomerUserLicense : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerCustomerUserLicense", SupportsShouldProcess = true)] + [OutputType(typeof(PSLicenseUpdate))] + public class SetPartnerCustomerUserLicense : PartnerAsyncCmdlet { /// /// Gets or sets the customer identifier. @@ -40,35 +42,36 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - LicenseUpdate update; - List licensesToAssign; - - if (ShouldProcess(string.Format( - CultureInfo.CurrentCulture, - Resources.SetPartnerCustomerUserLicenseWhatIf, - UserId))) + Scheduler.RunTask(async () => { - licensesToAssign = new List(); - - foreach (PSLicenseAssignment licenseAssignment in LicenseUpdate.LicensesToAssign) + if (ShouldProcess(string.Format( + CultureInfo.CurrentCulture, + Resources.SetPartnerCustomerUserLicenseWhatIf, + UserId))) { - licensesToAssign.Add(new LicenseAssignment + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + List licensesToAssign = new List(); + + foreach (PSLicenseAssignment licenseAssignment in LicenseUpdate.LicensesToAssign) { - ExcludedPlans = licenseAssignment.ExcludedPlans, - SkuId = licenseAssignment.SkuId - }); + licensesToAssign.Add(new LicenseAssignment + { + ExcludedPlans = licenseAssignment.ExcludedPlans, + SkuId = licenseAssignment.SkuId + }); + } + + LicenseUpdate update = new LicenseUpdate + { + LicensesToAssign = licensesToAssign, + LicensesToRemove = LicenseUpdate.LicensesToRemove + }; + + update = await partner.Customers[CustomerId].Users[UserId].LicenseUpdates.CreateAsync(update, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSLicenseUpdate(update)); } - - update = new LicenseUpdate - { - LicensesToAssign = licensesToAssign, - LicensesToRemove = LicenseUpdate.LicensesToRemove - }; - - update = Partner.Customers[CustomerId].Users[UserId].LicenseUpdates.CreateAsync(update).GetAwaiter().GetResult(); - - WriteObject(new PSLicenseUpdate(update)); - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerLegalProfile.cs b/src/PowerShell/Commands/SetPartnerLegalProfile.cs index 8b6a8ce..d8b532c 100644 --- a/src/PowerShell/Commands/SetPartnerLegalProfile.cs +++ b/src/PowerShell/Commands/SetPartnerLegalProfile.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Partners; using PartnerCenter.Models; using PartnerCenter.Models.Partners; @@ -15,8 +16,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Sets the partner legal profile in Partner Center. /// - [Cmdlet(VerbsCommon.Set, "PartnerLegalProfile", SupportsShouldProcess = true), OutputType(typeof(PSLegalBusinessProfile))] - public class SetPartnerLegalProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerLegalProfile", SupportsShouldProcess = true)] + [OutputType(typeof(PSLegalBusinessProfile))] + public class SetPartnerLegalProfile : PartnerAsyncCmdlet { /// /// Gets or sets the first line of the address. @@ -106,37 +108,38 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - IValidator
validator; - LegalBusinessProfile profile; - - if (ShouldProcess(Resources.SetPartnerLegalProfileWhatIf)) + Scheduler.RunTask(async () => { - profile = Partner.Profiles.LegalBusinessProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - profile.Address.AddressLine1 = UpdateValue(AddressLine1, profile.Address.AddressLine1); - profile.Address.AddressLine2 = UpdateValue(AddressLine2, profile.Address.AddressLine2); - profile.Address.City = UpdateValue(City, profile.Address.City); - profile.Address.Country = UpdateValue(Country, profile.Address.Country); - profile.Address.PostalCode = UpdateValue(PostalCode, profile.Address.PostalCode); - profile.Address.Region = UpdateValue(Region, profile.Address.Region); - profile.Address.State = UpdateValue(State, profile.Address.State); - profile.CompanyApproverAddress = profile.Address; - profile.CompanyApproverEmail = UpdateValue(EmailAddress, profile.CompanyApproverEmail); - - if (!DisableValidation.ToBool()) + if (ShouldProcess(Resources.SetPartnerLegalProfileWhatIf)) { - validator = new AddressValidator(Partner); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + LegalBusinessProfile profile = await partner.Profiles.LegalBusinessProfile.GetAsync(VettingVersion.Current, CancellationToken).ConfigureAwait(false); - if (!validator.IsValid(profile.Address, d => WriteDebug(d))) + profile.Address.AddressLine1 = UpdateValue(AddressLine1, profile.Address.AddressLine1); + profile.Address.AddressLine2 = UpdateValue(AddressLine2, profile.Address.AddressLine2); + profile.Address.City = UpdateValue(City, profile.Address.City); + profile.Address.Country = UpdateValue(Country, profile.Address.Country); + profile.Address.PostalCode = UpdateValue(PostalCode, profile.Address.PostalCode); + profile.Address.Region = UpdateValue(Region, profile.Address.Region); + profile.Address.State = UpdateValue(State, profile.Address.State); + profile.CompanyApproverAddress = profile.Address; + profile.CompanyApproverEmail = UpdateValue(EmailAddress, profile.CompanyApproverEmail); + + if (!DisableValidation.ToBool()) { - throw new PSInvalidOperationException("The specified address is invalid. Please verify the address and try again."); + IValidator
validator = new AddressValidator(partner); + + if (!await validator.IsValidAsync(profile.Address, CancellationToken).ConfigureAwait(false)) + { + throw new PSInvalidOperationException("The specified address is invalid. Please verify the address and try again."); + } } + + profile = await partner.Profiles.LegalBusinessProfile.UpdateAsync(profile, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSLegalBusinessProfile(profile)); } - - profile = Partner.Profiles.LegalBusinessProfile.UpdateAsync(profile).GetAwaiter().GetResult(); - - WriteObject(new PSLegalBusinessProfile(profile)); - } + }, true); } private static string UpdateValue(string input, string output) diff --git a/src/PowerShell/Commands/SetPartnerOrganizationProfile.cs b/src/PowerShell/Commands/SetPartnerOrganizationProfile.cs index d9af562..afe405b 100644 --- a/src/PowerShell/Commands/SetPartnerOrganizationProfile.cs +++ b/src/PowerShell/Commands/SetPartnerOrganizationProfile.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Partners; using PartnerCenter.Models; using PartnerCenter.Models.Partners; @@ -14,8 +15,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Sets the partner organization profile in Partner Center. /// - [Cmdlet(VerbsCommon.Set, "PartnerOrganizationProfile", SupportsShouldProcess = true), OutputType(typeof(PSOrganizationProfile))] - public class SetPartnerOrganizationProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerOrganizationProfile", SupportsShouldProcess = true)] + [OutputType(typeof(PSOrganizationProfile))] + public class SetPartnerOrganizationProfile : PartnerAsyncCmdlet { /// /// Gets or sets the company name. @@ -119,41 +121,43 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - OrganizationProfile profile; - IValidator
validator; - - if (ShouldProcess("Updates the partner's organization profile")) + Scheduler.RunTask(async () => { - profile = Partner.Profiles.OrganizationProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - - profile.CompanyName = UpdateValue(CompanyName, profile.CompanyName); - profile.Email = UpdateValue(Email, profile.Email); - profile.Language = UpdateValue(Language, profile.Language); - profile.Culture = UpdateValue(Culture, profile.Culture); - - profile.DefaultAddress.AddressLine1 = UpdateValue(AddressLine1, profile.DefaultAddress.AddressLine1); - profile.DefaultAddress.AddressLine2 = UpdateValue(AddressLine2, profile.DefaultAddress.AddressLine2); - profile.DefaultAddress.City = UpdateValue(City, profile.DefaultAddress.City); - profile.DefaultAddress.Country = UpdateValue(Country, profile.DefaultAddress.Country); - profile.DefaultAddress.PostalCode = UpdateValue(PostalCode, profile.DefaultAddress.PostalCode); - profile.DefaultAddress.State = UpdateValue(State, profile.DefaultAddress.State); - profile.DefaultAddress.FirstName = UpdateValue(FirstName, profile.DefaultAddress.FirstName); - profile.DefaultAddress.LastName = UpdateValue(LastName, profile.DefaultAddress.LastName); - profile.DefaultAddress.PhoneNumber = UpdateValue(PhoneNumber, profile.DefaultAddress.PhoneNumber); - - if (!DisableValidation.ToBool()) + if (ShouldProcess("Updates the partner's organization profile")) { - validator = new AddressValidator(Partner); + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - if (!validator.IsValid(profile.DefaultAddress, d => WriteDebug(d))) + OrganizationProfile profile = await partner.Profiles.OrganizationProfile.GetAsync(CancellationToken).ConfigureAwait(false); + + profile.CompanyName = UpdateValue(CompanyName, profile.CompanyName); + profile.Email = UpdateValue(Email, profile.Email); + profile.Language = UpdateValue(Language, profile.Language); + profile.Culture = UpdateValue(Culture, profile.Culture); + + profile.DefaultAddress.AddressLine1 = UpdateValue(AddressLine1, profile.DefaultAddress.AddressLine1); + profile.DefaultAddress.AddressLine2 = UpdateValue(AddressLine2, profile.DefaultAddress.AddressLine2); + profile.DefaultAddress.City = UpdateValue(City, profile.DefaultAddress.City); + profile.DefaultAddress.Country = UpdateValue(Country, profile.DefaultAddress.Country); + profile.DefaultAddress.PostalCode = UpdateValue(PostalCode, profile.DefaultAddress.PostalCode); + profile.DefaultAddress.State = UpdateValue(State, profile.DefaultAddress.State); + profile.DefaultAddress.FirstName = UpdateValue(FirstName, profile.DefaultAddress.FirstName); + profile.DefaultAddress.LastName = UpdateValue(LastName, profile.DefaultAddress.LastName); + profile.DefaultAddress.PhoneNumber = UpdateValue(PhoneNumber, profile.DefaultAddress.PhoneNumber); + + if (!DisableValidation.ToBool()) { - throw new PSInvalidOperationException("The specified address is invalid. Please verify the address and try again."); - } - } + IValidator
validator = new AddressValidator(partner); - profile = Partner.Profiles.OrganizationProfile.UpdateAsync(profile).GetAwaiter().GetResult(); - WriteObject(new PSOrganizationProfile(profile)); - } + if (!await validator.IsValidAsync(profile.DefaultAddress, CancellationToken)) + { + throw new PSInvalidOperationException("The specified address is invalid. Please verify the address and try again."); + } + } + + profile = await partner.Profiles.OrganizationProfile.UpdateAsync(profile, CancellationToken).ConfigureAwait(false); + WriteObject(new PSOrganizationProfile(profile)); + } + }, true); } private static string UpdateValue(string input, string output) diff --git a/src/PowerShell/Commands/SetPartnerServiceRequest.cs b/src/PowerShell/Commands/SetPartnerServiceRequest.cs index a049699..9e90bf0 100644 --- a/src/PowerShell/Commands/SetPartnerServiceRequest.cs +++ b/src/PowerShell/Commands/SetPartnerServiceRequest.cs @@ -11,8 +11,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using PartnerCenter.Models.ServiceRequests; using Properties; - [Cmdlet(VerbsCommon.Set, "PartnerServiceRequest", SupportsShouldProcess = true), OutputType(typeof(PSServiceRequest))] - public class SetPartnerServiceRequest : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerServiceRequest", SupportsShouldProcess = true)] + [OutputType(typeof(PSServiceRequest))] + public class SetPartnerServiceRequest : PartnerAsyncCmdlet { /// /// Gets or set the text of the new note that will be added to the service request. @@ -40,31 +41,34 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - ServiceRequest request; - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerServiceRequestWhatIf, ServiceRequestId))) + Scheduler.RunTask(async () => { - request = new ServiceRequest(); - - if (!string.IsNullOrEmpty(NewNote)) + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.SetPartnerServiceRequestWhatIf, ServiceRequestId))) { - request.NewNote = new ServiceRequestNote + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + + ServiceRequest request = new ServiceRequest(); + + if (!string.IsNullOrEmpty(NewNote)) { - CreatedByName = PartnerSession.Instance.Context.Account.ObjectId, - CreatedDate = DateTime.UtcNow, - Text = NewNote - }; + request.NewNote = new ServiceRequestNote + { + CreatedByName = PartnerSession.Instance.Context.Account.ObjectId, + CreatedDate = DateTime.UtcNow, + Text = NewNote + }; + } + + if (Status.HasValue) + { + request.Status = Status.Value; + } + + request = await partner.ServiceRequests[ServiceRequestId].PatchAsync(request, CancellationToken).ConfigureAwait(false); + + WriteObject(new PSServiceRequest(request)); } - - if (Status.HasValue) - { - request.Status = Status.Value; - } - - request = Partner.ServiceRequests[ServiceRequestId].PatchAsync(request).GetAwaiter().GetResult(); - - WriteObject(new PSServiceRequest(request)); - } + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/SetPartnerSupportProfile.cs b/src/PowerShell/Commands/SetPartnerSupportProfile.cs index 0a213d3..8e1bc38 100644 --- a/src/PowerShell/Commands/SetPartnerSupportProfile.cs +++ b/src/PowerShell/Commands/SetPartnerSupportProfile.cs @@ -6,14 +6,16 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Partners; using PartnerCenter.Models.Partners; /// /// Sets the partner support profile in Partner Center. /// - [Cmdlet(VerbsCommon.Set, "PartnerSupportProfile", SupportsShouldProcess = true), OutputType(typeof(PSSupportProfile))] - public class SetPartnerSupportProfile : PartnerCmdlet + [Cmdlet(VerbsCommon.Set, "PartnerSupportProfile", SupportsShouldProcess = true)] + [OutputType(typeof(PSSupportProfile))] + public class SetPartnerSupportProfile : PartnerAsyncCmdlet { /// /// Gets or sets the email address of the support contact. @@ -41,17 +43,19 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - SupportProfile profile; + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + SupportProfile profile = await partner.Profiles.SupportProfile.GetAsync(CancellationToken).ConfigureAwait(false); - profile = Partner.Profiles.SupportProfile.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + profile.Email = UpdateValue(SupportEmail, profile.Email); + profile.Telephone = UpdateValue(SupportPhoneNumber, profile.Telephone); + profile.Website = UpdateValue(SupportWebsite, profile.Website); - profile.Email = UpdateValue(SupportEmail, profile.Email); - profile.Telephone = UpdateValue(SupportPhoneNumber, profile.Telephone); - profile.Website = UpdateValue(SupportWebsite, profile.Website); + profile = await partner.Profiles.SupportProfile.UpdateAsync(profile, CancellationToken).ConfigureAwait(false); - profile = Partner.Profiles.SupportProfile.UpdateAsync(profile).GetAwaiter().GetResult(); - - WriteObject(new PSSupportProfile(profile)); + WriteObject(new PSSupportProfile(profile)); + }, true); } private static string UpdateValue(string input, string output) diff --git a/src/PowerShell/Commands/SubmitPartnerCustomerCart.cs b/src/PowerShell/Commands/SubmitPartnerCustomerCart.cs index 736d1bc..77692b3 100644 --- a/src/PowerShell/Commands/SubmitPartnerCustomerCart.cs +++ b/src/PowerShell/Commands/SubmitPartnerCustomerCart.cs @@ -6,6 +6,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands using System.Globalization; using System.Management.Automation; using System.Text.RegularExpressions; + using Models.Authentication; using Models.Carts; using PartnerCenter.Models.Carts; using Properties; @@ -13,8 +14,9 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// /// Checks out the specified cart. /// - [Cmdlet(VerbsLifecycle.Submit, "PartnerCustomerCart", SupportsShouldProcess = true), OutputType(typeof(PSCartCheckoutResult))] - public class SubmitPartnerCustomerCart : PartnerCmdlet + [Cmdlet(VerbsLifecycle.Submit, "PartnerCustomerCart", SupportsShouldProcess = true)] + [OutputType(typeof(PSCartCheckoutResult))] + public class SubmitPartnerCustomerCart : PartnerAsyncCmdlet { /// /// Gets or sets the required cart identifier. @@ -35,13 +37,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - CartCheckoutResult checkoutResult; - - if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.CheckoutPartnerCustomerCartWhatIf, CartId))) + Scheduler.RunTask(async () => { - checkoutResult = Partner.Customers[CustomerId].Carts[CartId].CheckoutAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - WriteObject(new PSCartCheckoutResult(checkoutResult)); - } + if (ShouldProcess(string.Format(CultureInfo.CurrentCulture, Resources.CheckoutPartnerCustomerCartWhatIf, CartId))) + { + + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + CartCheckoutResult checkoutResult = await partner.Customers[CustomerId].Carts[CartId].CheckoutAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(new PSCartCheckoutResult(checkoutResult)); + } + }, true); } } } diff --git a/src/PowerShell/Commands/TestPartnerAddress.cs b/src/PowerShell/Commands/TestPartnerAddress.cs index ee10172..92798ed 100644 --- a/src/PowerShell/Commands/TestPartnerAddress.cs +++ b/src/PowerShell/Commands/TestPartnerAddress.cs @@ -4,6 +4,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; using PartnerCenter.Models; using Validations; @@ -12,7 +13,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands ///
[Cmdlet(VerbsDiagnostic.Test, "PartnerAddress")] [OutputType(typeof(bool))] - public class TestPartnerAddress : PartnerCmdlet + public class TestPartnerAddress : PartnerAsyncCmdlet { /// /// Gets or sets the first line of the address. @@ -68,23 +69,26 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - Address address; - IValidator
validator; - - address = new Address + Scheduler.RunTask(async () => { - AddressLine1 = AddressLine1, - AddressLine2 = AddressLine2, - City = City, - Country = Country, - PostalCode = PostalCode, - Region = Region, - State = State - }; + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); - validator = new AddressValidator(Partner); + Address address = new Address + { + AddressLine1 = AddressLine1, + AddressLine2 = AddressLine2, + City = City, + Country = Country, + PostalCode = PostalCode, + Region = Region, + State = State + }; - WriteObject(validator.IsValid(address, d => WriteDebug(d))); + IValidator
validator = new AddressValidator(partner); + bool isValid = await validator.IsValidAsync(address); + + WriteObject(isValid); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Commands/TestPartnerDomainAvailability.cs b/src/PowerShell/Commands/TestPartnerDomainAvailability.cs index 64422af..1220ef2 100644 --- a/src/PowerShell/Commands/TestPartnerDomainAvailability.cs +++ b/src/PowerShell/Commands/TestPartnerDomainAvailability.cs @@ -4,12 +4,14 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands { using System.Management.Automation; + using Models.Authentication; /// /// Check to see if the specified domain name is available. /// - [Cmdlet(VerbsDiagnostic.Test, "PartnerDomainAvailability"), OutputType(typeof(bool))] - public class TestPartnerDomainAvailability : PartnerCmdlet + [Cmdlet(VerbsDiagnostic.Test, "PartnerDomainAvailability")] + [OutputType(typeof(bool))] + public class TestPartnerDomainAvailability : PartnerAsyncCmdlet { /// /// The domain name to be checked. @@ -24,7 +26,13 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Commands /// public override void ExecuteCmdlet() { - WriteObject(!Partner.Domains.ByDomain(Domain).ExistsAsync().ConfigureAwait(false).GetAwaiter().GetResult()); + Scheduler.RunTask(async () => + { + IPartner partner = await PartnerSession.Instance.ClientFactory.CreatePartnerOperationsAsync(CorrelationId, CancellationToken).ConfigureAwait(false); + bool exists = await partner.Domains.ByDomain(Domain).ExistsAsync(CancellationToken).ConfigureAwait(false); + + WriteObject(!exists); + }, true); } } } \ No newline at end of file diff --git a/src/PowerShell/Factories/AuthenticationFactory.cs b/src/PowerShell/Factories/AuthenticationFactory.cs index b741c75..f86eb9a 100644 --- a/src/PowerShell/Factories/AuthenticationFactory.cs +++ b/src/PowerShell/Factories/AuthenticationFactory.cs @@ -77,7 +77,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Factories return new InteractiveParameters(account, environment, scopes, message); } - else if (account.Type == AccountType.ServicePrincipal || account.Type == AccountType.Certificate) + else if (account.Type == AccountType.Certificate || account.Type == AccountType.ServicePrincipal) { return new ServicePrincipalParameters(account, environment, scopes); } diff --git a/src/PowerShell/Factories/ClientFactory.cs b/src/PowerShell/Factories/ClientFactory.cs index 7bb3d72..8a639d8 100644 --- a/src/PowerShell/Factories/ClientFactory.cs +++ b/src/PowerShell/Factories/ClientFactory.cs @@ -8,10 +8,12 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Factories using System.Net; using System.Net.Http; using System.Reflection; + using System.Threading; using System.Threading.Tasks; using Extensions; using Graph; using Identity.Client; + using Microsoft.Store.PartnerCenter.RequestContext; using Models.Authentication; using Network; using Rest; @@ -54,24 +56,21 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Factories /// /// Creates a new instance of the object used to interface with Partner Center. /// + /// The correlation identifier for the request context. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// An instance of the class. - public virtual IPartner CreatePartnerOperations() - { - return CreatePartnerOperationsAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - - /// - /// Creates a new instance of the object used to interface with Partner Center. - /// - /// An instance of the class. - public virtual async Task CreatePartnerOperationsAsync() + public virtual async Task CreatePartnerOperationsAsync(Guid correlationId = default, CancellationToken cancellationToken = default) { PartnerService.Instance.ApiRootUrl = new Uri(PartnerSession.Instance.Context.Environment.PartnerCenterEndpoint); + RequestContext requestContext = new RequestContext(correlationId); + AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync( PartnerSession.Instance.Context.Account, PartnerSession.Instance.Context.Environment, - new[] { PartnerSession.Instance.Context.Account.GetProperty(PartnerAccountPropertyType.Scope) }).ConfigureAwait(false); + new[] { PartnerSession.Instance.Context.Account.GetProperty(PartnerAccountPropertyType.Scope) }, + null, + cancellationToken).ConfigureAwait(false); return PartnerService.Instance.CreatePartnerOperations( new PowerShellCredentials(new AuthenticationToken(authResult.AccessToken, authResult.ExpiresOn)), diff --git a/src/PowerShell/Factories/IClientFactory.cs b/src/PowerShell/Factories/IClientFactory.cs index b6f1dbb..8bf6668 100644 --- a/src/PowerShell/Factories/IClientFactory.cs +++ b/src/PowerShell/Factories/IClientFactory.cs @@ -3,6 +3,8 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Factories { + using System; + using System.Threading; using System.Threading.Tasks; using Graph; using Rest; @@ -21,14 +23,10 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Factories /// /// Creates a new instance of the object used to interface with Partner Center. /// + /// The correlation identifier for the request context. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// An instance of the class. - IPartner CreatePartnerOperations(); - - /// - /// Creates a new instance of the object used to interface with Partner Center. - /// - /// An instance of the class. - Task CreatePartnerOperationsAsync(); + Task CreatePartnerOperationsAsync(Guid correlationId = default, CancellationToken cancellationToken = default); /// /// Creates a new service client used interact with a specific service. diff --git a/src/PowerShell/Models/PartnerQosEvent.cs b/src/PowerShell/Models/PartnerQosEvent.cs index cc9a174..af9721b 100644 --- a/src/PowerShell/Models/PartnerQosEvent.cs +++ b/src/PowerShell/Models/PartnerQosEvent.cs @@ -67,11 +67,21 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Models /// public string Parameters { get; set; } + /// + /// Gets or sets the session identifier. + /// + public string SessionId { get; set; } + /// /// Gets or sets the start time of the event. /// public DateTimeOffset StartTime { get; set; } + /// + /// Gets or sets the user identifier. + /// + public string UserId { get; set; } + /// /// Finishes the quality of service event. /// diff --git a/src/PowerShell/Network/GraphAuthenticationProvider.cs b/src/PowerShell/Network/GraphAuthenticationProvider.cs index e89a27e..b741e02 100644 --- a/src/PowerShell/Network/GraphAuthenticationProvider.cs +++ b/src/PowerShell/Network/GraphAuthenticationProvider.cs @@ -15,6 +15,20 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Network /// public class GraphAuthenticationProvider : IAuthenticationProvider { + /// + /// The identifier of the tenant that owns the resources being accessed. + /// + private readonly string tenantId; + + /// + /// Initializes a new instance of the class. + /// + /// The identifier of the tenant that owns the resources being accessed. + public GraphAuthenticationProvider(string tenantId = null) + { + this.tenantId = tenantId; + } + /// /// Authenticates the specified request message. /// @@ -24,8 +38,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Network { request.AssertNotNull(nameof(request)); + PartnerAccount account = PartnerSession.Instance.Context.Account.Clone(); + + if (!string.IsNullOrEmpty(tenantId)) + { + account.Tenant = tenantId; + } + AuthenticationResult authResult = await PartnerSession.Instance.AuthenticationFactory.AuthenticateAsync( - PartnerSession.Instance.Context.Account, + account, PartnerSession.Instance.Context.Environment, new[] { $"{PartnerSession.Instance.Context.Environment.GraphEndpoint}/.default" }).ConfigureAwait(false); diff --git a/src/PowerShell/Validations/AddressValidator.cs b/src/PowerShell/Validations/AddressValidator.cs index bd9d36d..0ab0ca2 100644 --- a/src/PowerShell/Validations/AddressValidator.cs +++ b/src/PowerShell/Validations/AddressValidator.cs @@ -7,6 +7,8 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Validations using System.Globalization; using System.Linq; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using Extensions; using PartnerCenter.Models; using PartnerCenter.Models.ValidationRules; @@ -36,15 +38,15 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Validations /// Determines if the resource is valid. /// /// The resource to be validate. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// true if the resource is valid; otherwise false. - public bool IsValid(Address resource, Action debugAction) + public async Task IsValidAsync(Address resource, CancellationToken cancellationToken = default) { CountryValidationRules validationRules; resource.AssertNotNull(nameof(resource)); - debugAction("Requesting country validation services from the partner service."); - validationRules = partner.CountryValidationRules.ByCountry(resource.Country).GetAsync().ConfigureAwait(false).GetAwaiter().GetResult(); + validationRules = await partner.CountryValidationRules.ByCountry(resource.Country).GetAsync(cancellationToken).ConfigureAwait(false); if (validationRules.IsCityRequired && string.IsNullOrEmpty(resource.City)) { @@ -87,8 +89,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Validations resource.PhoneNumber)); } - debugAction("Checking if the address is valid using the partner service."); - return partner.Validations.IsAddressValidAsync(resource).ConfigureAwait(false).GetAwaiter().GetResult(); + return await partner.Validations.IsAddressValidAsync(resource, cancellationToken).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/src/PowerShell/Validations/IValidator.cs b/src/PowerShell/Validations/IValidator.cs index 3e61a4a..fbecb94 100644 --- a/src/PowerShell/Validations/IValidator.cs +++ b/src/PowerShell/Validations/IValidator.cs @@ -3,10 +3,17 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.Validations { - using System; + using System.Threading; + using System.Threading.Tasks; public interface IValidator { - bool IsValid(T resource, Action debugAction); + /// + /// Determines if the resource is valid. + /// + /// The resource to be validate. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// true if the resource is valid; otherwise false. + Task IsValidAsync(T resource, CancellationToken cancellationToken = default); } } \ No newline at end of file diff --git a/test/PowerShell.UnitTests/Factories/MockClientFactory.cs b/test/PowerShell.UnitTests/Factories/MockClientFactory.cs index 7db039a..893ede8 100644 --- a/test/PowerShell.UnitTests/Factories/MockClientFactory.cs +++ b/test/PowerShell.UnitTests/Factories/MockClientFactory.cs @@ -4,6 +4,7 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.UnitTests.Factories { using System; + using System.Threading; using System.Threading.Tasks; using Graph; using Network; @@ -66,17 +67,10 @@ namespace Microsoft.Store.PartnerCenter.PowerShell.UnitTests.Factories /// /// Creates a new instance of the object used to interface with Partner Center. /// + /// The correlation identifier for the request context. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// An instance of the class. - public virtual IPartner CreatePartnerOperations() - { - return CreatePartnerOperationsAsync().ConfigureAwait(false).GetAwaiter().GetResult(); - } - - /// - /// Creates a new instance of the object used to interface with Partner Center. - /// - /// An instance of the class. - public virtual async Task CreatePartnerOperationsAsync() + public virtual async Task CreatePartnerOperationsAsync(Guid correlationId = default, CancellationToken cancellationToken = default) { if (partnerOperations == null) {