This commit is contained in:
Ali Khudhair 2018-08-31 08:13:52 -07:00 коммит произвёл Isaiah Williams
Родитель ed1254ab88
Коммит e7d40f5839
172 изменённых файлов: 10575 добавлений и 0 удалений

0
.gitattributes поставляемый Normal file
Просмотреть файл

Просмотреть файл

@ -0,0 +1,27 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Partner Center SDK Samples", "Source\Partner Center SDK Samples\Partner Center SDK Samples.csproj", "{AC93E5CC-549C-4F13-9675-A86860918C2B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9445B986-021F-44FE-BA08-92C43301F8AF}"
ProjectSection(SolutionItems) = preProject
nuget.config = nuget.config
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{AC93E5CC-549C-4F13-9675-A86860918C2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AC93E5CC-549C-4F13-9675-A86860918C2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AC93E5CC-549C-4F13-9675-A86860918C2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AC93E5CC-549C-4F13-9675-A86860918C2B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,44 @@
// -----------------------------------------------------------------------
// <copyright file="AggregatePartnerScenario.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples
{
using System;
using System.Collections.Generic;
using System.Globalization;
using ScenarioExecution;
/// <summary>
/// A scenarios that is composed of one or more sub-scenarios.
/// </summary>
public class AggregatePartnerScenario : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="AggregatePartnerScenario"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="childScenarios">A list of child scenarios.</param>
/// <param name="context">The scenario context.</param>
public AggregatePartnerScenario(
string title,
IEnumerable<IPartnerScenario> childScenarios,
IScenarioContext context) : base(title, context, new AggregateScenarioExecutionStrategy(), new List<IPartnerScenario>(childScenarios))
{
}
/// <summary>
/// Runs the aggregate scenario.
/// </summary>
protected override void RunScenario()
{
// display the child scenarios
for (int i = 0; i < this.Children.Count; ++i)
{
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", i + 1, this.Children[i].Title));
}
}
}
}

Просмотреть файл

@ -0,0 +1,75 @@
// -----------------------------------------------------------------------
// <copyright file="CreateCustomerAgreement.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Agreements
{
using System;
using System.Collections.Generic;
using Models.Agreements;
/// <summary>
/// Showcases creation of a customer agreement.
/// </summary>
public class CreateCustomerAgreement : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateCustomerAgreement"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateCustomerAgreement(IScenarioContext context) : base("Create a new customer agreement", context)
{
}
/// <summary>
/// executes the create customer agreement scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to create the agreement for");
string selectedUserId =
this.ObtainUserMemberId("Enter the user ID of the partner to create customer's agreement");
string agreementTemplateId = this.Context.Configuration.Scenario.DefaultAgreementTemplateId;
// Currently, the only supported value is “998b88de-aa99-4388-a42c-1b3517d49490”, which is the unique identifier for the Microsoft Cloud Agreement.
if (string.IsNullOrWhiteSpace(agreementTemplateId))
{
// The value was not set in the configuration, prompt the user the enter value
agreementTemplateId = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the agreement template ID", "The agreement template ID can't be empty");
}
else
{
Console.WriteLine("Found {0}: {1} in configuration.", "Agreement template Id", agreementTemplateId);
}
var partnerOperations = this.Context.UserPartnerOperations;
var agreement = new Agreement
{
UserId = selectedUserId,
DateAgreed = DateTime.UtcNow,
Type = AgreementType.MicrosoftCloudAgreement,
TemplateId = agreementTemplateId,
PrimaryContact = new Contact
{
FirstName = "First",
LastName = "Last",
Email = "first.last@outlook.com",
PhoneNumber = "4123456789"
}
};
this.Context.ConsoleHelper.WriteObject(agreement, "New Agreement");
this.Context.ConsoleHelper.StartProgress("Creating Agreement");
var newlyCreatedagreement = partnerOperations.Customers.ById(selectedCustomerId).Agreements.Create(agreement);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Create new agreement successfully!");
this.Context.ConsoleHelper.WriteObject(newlyCreatedagreement, "Newly created agreement Information");
}
}
}

Просмотреть файл

@ -0,0 +1,39 @@
// -----------------------------------------------------------------------
// <copyright file="GetAgreementDetails.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Agreements
{
using Models;
using Models.Agreements;
/// <summary>
/// Showcases getting the list of agreement details.
/// </summary>
public class GetAgreementDetails : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAgreementDetails"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetAgreementDetails(IScenarioContext context) : base("Get agreement details.", context)
{
}
/// <summary>
/// Executes the get agreement details scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving agreement details");
ResourceCollection<AgreementMetaData> agreementDetails = partnerOperations.AgreementDetails.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(agreementDetails, "Agreement details:");
}
}
}

Просмотреть файл

@ -0,0 +1,51 @@
// <copyright file="GetCustomerAgreements.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Agreements
{
using System;
using System.Linq;
using Models;
using Models.Agreements;
/// <summary>
/// Showcases the retrieval of customer agreements.
/// </summary>
public class GetCustomerAgreements : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerAgreements"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerAgreements(IScenarioContext context) : base("Get all customer agreements.", context)
{
}
/// <summary>
/// Executes the get customer agreements scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to create the agreement for");
this.Context.ConsoleHelper.StartProgress("Retrieving customer's agreements");
ResourceCollection<Agreement> customerAgreements = partnerOperations.Customers.ById(selectedCustomerId)
.Agreements.Get();
this.Context.ConsoleHelper.StopProgress();
if (!customerAgreements.Items.Any())
{
Console.WriteLine("No Service requests found for the given customer.");
}
else
{
this.Context.ConsoleHelper.WriteObject(customerAgreements, "Customer agreements:");
}
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerLicensesDeploymentAnalytics.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Analytics
{
/// <summary>
/// Gets a single customer's licenses deployment analytics.
/// </summary>
public class GetCustomerLicensesDeploymentAnalytics : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerLicensesDeploymentAnalytics"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerLicensesDeploymentAnalytics(IScenarioContext context) : base("Get customer licenses deployment analytics", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToRetrieve = this.ObtainCustomerId("Enter the ID of the customer to retrieve");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving customer licenses deployment analytics");
var customerLicensesDeploymentAnalytics = partnerOperations.Customers.ById(customerIdToRetrieve).Analytics.Licenses.Deployment.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerLicensesDeploymentAnalytics, "Customer licenses deployment analytics");
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerLicensesUsageAnalytics.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Analytics
{
/// <summary>
/// Gets a single customer's licenses usage analytics.
/// </summary>
public class GetCustomerLicensesUsageAnalytics : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerLicensesUsageAnalytics"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerLicensesUsageAnalytics(IScenarioContext context) : base("Get customer licenses usage analytics", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToRetrieve = this.ObtainCustomerId("Enter the ID of the customer to retrieve");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving customer licenses usage analytics");
var customerLicensesDeploymentAnalytics = partnerOperations.Customers.ById(customerIdToRetrieve).Analytics.Licenses.Usage.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerLicensesDeploymentAnalytics, "Customer licenses usage analytics");
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
// -----------------------------------------------------------------------
// <copyright file="GetPartnerLicensesDeploymentAnalytics.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Analytics
{
/// <summary>
/// Gets partner's licenses deployment analytics.
/// </summary>
public class GetPartnerLicensesDeploymentAnalytics : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPartnerLicensesDeploymentAnalytics"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetPartnerLicensesDeploymentAnalytics(IScenarioContext context) : base("Get partner licenses deployment analytics", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving partner licenses deployment analytics");
var partnerLicensesDeploymentAnalytics = partnerOperations.Analytics.Licenses.Deployment.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(partnerLicensesDeploymentAnalytics, "Partner licenses deployment analytics");
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
// -----------------------------------------------------------------------
// <copyright file="GetPartnerLicensesUsageAnalytics.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Analytics
{
/// <summary>
/// Gets partner's licenses usage analytics.
/// </summary>
public class GetPartnerLicensesUsageAnalytics : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPartnerLicensesUsageAnalytics"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetPartnerLicensesUsageAnalytics(IScenarioContext context) : base("Get partner licenses usage analytics", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving partner licenses usage analytics");
var partnerLicensesUsageAnalytics = partnerOperations.Analytics.Licenses.Usage.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(partnerLicensesUsageAnalytics, "Partner licenses usage analytics");
}
}
}

Просмотреть файл

@ -0,0 +1,134 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="PartnerServiceSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="UserAuthentication" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="AppAuthentication" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="ScenarioSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<!-- Groups settings related to remote endpoints needed to access the partner API service -->
<PartnerServiceSettings>
<add key="PartnerServiceApiEndpoint" value="https://api.partnercenter.microsoft.com" />
<add key="AuthenticationAuthorityEndpoint" value="https://login.windows.net" />
<add key="GraphEndpoint" value="https://graph.windows.net" />
<add key="CommonDomain" value="common" />
</PartnerServiceSettings>
<UserAuthentication>
<!-- The active directory application ID used by the user login, paste your application ID here. -->
<add key="ApplicationId" value="" />
<!-- The resource the application is attempting to access i.e. the partner API service. -->
<!-- This value must NOT end with a trailing '/'. -->
<add key="ResourceUrl" value="https://api.partnercenter.microsoft.com" />
<add key="RedirectUrl" value="http://localhost" />
<!-- The active directory user credentials, paste your credentials here. -->
<add key="UserName" value="" />
<add key="Password" value="" />
</UserAuthentication>
<AppAuthentication>
<!-- The active directory application ID used by the application login, paste your application ID here. -->
<add key="ApplicationId" value="" />
<!-- The active directory application secret used by the application login, paste your application secret here. -->
<add key="ApplicationSecret" value="" />
<!-- The active directory domain on which the application is hosted. Paste your domain here. -->
<add key="Domain" value="" />
</AppAuthentication>
<!-- Holds samples settings -->
<ScenarioSettings>
<!-- The domain suffix to use when creating a new customer -->
<add key="CustomerDomainSuffix" value="onmicrosoft.com" />
<!-- The ID of the customer to delete from the TIP account, leave empty to prompt user to enter it -->
<add key="CustomerIdToDelete" value="" />
<!-- The ID of the customer user to delete, leave empty to prompt user to enter it -->
<add key="CustomerUserIdToDelete" value="" />
<!-- The ID of the default directory role, leave empty to prompt user to enter it -->
<add key="DefaultDirectoryRoleId" value="" />
<!-- The ID of the default user member of default directory role, leave empty to prompt user to enter it -->
<add key="DefaultUserMemberId" value="" />
<!-- The ID of the default customer to use for customer related samples, leave empty to prompt user to enter it -->
<add key="DefaultCustomerId" value="" />
<!-- The ID of the defautl partner's user ID to use for agreement related samples, leave empty to prompt the user to enter it-->
<add key="DefaultPartnerUserId" value="" />
<!-- The ID of the default configuration policy to use for device related samples, leave empty to prompt user to enter it -->
<add key="DefaultConfigurationPolicyId" value="" />
<!-- The ID of the default agreement template ID to user for agreements related samples, leave empty to prompt user to enter it -->
<add key="DefaultAgreementTemplateId" value="" />
<!-- The ID of the default device batch to use for device related samples, leave empty to prompt user to enter it -->
<add key="DefaultDeviceBatchId" value="" />
<!-- The ID of the default device to use for device related samples, leave empty to prompt user to enter it -->
<add key="DefaultDeviceId" value="" />
<!-- The ID of the default batch upload status tracking to use for device related samples, leave empty to prompt user to enter it -->
<add key="DefaultBatchUploadStatusTrackingId" value="" />
<!-- The ID of the default customer user to use for customer user related samples, leave empty to prompt user to enter it -->
<add key="DefaultCustomerUserId" value="" />
<!-- The number of customers to retrieve per page -->
<add key="CustomerPageSize" value="100" />
<!-- The number of customer users to retrieve per page -->
<add key="CustomerUserPageSize" value="10" />
<!-- The number of invoices to retrieve per page -->
<add key="InvoicePageSize" value="100" />
<!-- The default Invoice ID of partner, leave empty to prompt user to enter it -->
<add key="DefaultInvoiceId" value="" />
<!-- The partner MPN ID to use in indirect partner samples, leave empty to prompt user to enter it -->
<add key="PartnerMpnId" value="" />
<!-- The service request ID to use in service request samples, leave empty to prompt user to enter it -->
<add key="DefaultServiceRequestId" value="" />
<!-- The number of service requests to retrieve per page -->
<add key="ServiceRequestPageSize" value="100" />
<!-- The support topic ID to use in service request samples, leave empty to prompt user to enter it -->
<add key="DefaultSupportTopicId" value="" />
<!-- The partner MPN ID to use in indirect partner samples, leave empty to prompt user to enter it -->
<add key="PartnerMpnId" value="" />
<!-- The number of offers to return per page -->
<add key="DefaultOfferPageSize" value="20" />
<!-- The offer ID to use in offer scenarios, leave empty to prompt user to enter it -->
<add key="DefaultOfferId" value="" />
<!-- The product ID to use in product scenarios, leave empty to prompt user to enter it -->
<add key="DefaultProductId" value="" />
<!-- The sku ID to use in sku scenarios, leave empty to prompt user to enter it -->
<add key="DefaultSkuId" value="" />
<!-- The availability ID to use in availability scenarios, leave empty to prompt user to enter it -->
<add key="DefaultAvailabilityId" value="" />
<!-- The order ID to use in order scenarios, leave empty to prompt user to enter it -->
<add key="DefaultOrderId" value="" />
<!-- The subscription ID to use in subscription scenarios, leave empty to prompt user to enter it -->
<add key="DefaultSubscriptionId" value="" />
<!-- The number of subscriptions to retrieve per page -->
<add key="SubscriptionPageSize" value="20" />
<!-- The ID of the default indirect reseller to use for indirect model related samples, leave empty to prompt user to enter it -->
<add key="DefaultIndirectResellerId" value="" />
<!-- The default quantity change to be made during update, leave empty to prompt user to enter it -->
<add key="DefaultQuantity" value="" />
<!-- The Default Availability Catalog Id, leave empty to prompt user to enter it -->
<add key="DefaultAvailabilityCatalogId" value="" />
<!-- The Default Cart Id, leave empty to prompt user to enter it -->
<add key="DefaultCartId" value="" />
<!-- The Default CatalogItemId, leave empty to prompt user to enter it -->
<add key="DefaultCatalogItemId" value="" />
<!-- The Default Scope for provision status, leave empty to prompt user to enter it -->
<add key="DefaultScope" value="" />
<!-- The Default Azure Subscription Id for provision status, leave empty to prompt user to enter it -->
<add key="DefaultAzureSubscriptionId" value="" />
<!-- The Default Billing Cycle for creating a cart, leave empty to prompt user to enter it -->
<add key="DefaultBillingCycle" value="" />
</ScenarioSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.IdentityModel.Clients.ActiveDirectory" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.29.0.1078" newVersion="2.29.0.1078" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,65 @@
// -----------------------------------------------------------------------
// <copyright file="QueryAuditRecords.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Orders
{
using System;
using System.Globalization;
using Models.Query;
/// <summary>
/// A scenario that retrieves a partner's audit records.
/// </summary>
public class QueryAuditRecords : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="QueryAuditRecords"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public QueryAuditRecords(IScenarioContext context) : base("Query for the partner's audit records.", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
const int PageSize = 10;
var startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01);
this.Context.ConsoleHelper.StartProgress(
string.Format(CultureInfo.InvariantCulture, "Retrieving the partner's audit records - start date: {0} | page size: {1}", startDate, PageSize));
var auditRecordsPage = partnerOperations.AuditRecords.Query(startDate.Date, query: QueryFactory.Instance.BuildIndexedQuery(PageSize));
this.Context.ConsoleHelper.StopProgress();
// create a customer enumerator which will aid us in traversing the customer pages
var auditRecordEnumerator = partnerOperations.Enumerators.AuditRecords.Create(auditRecordsPage);
int pageNumber = 1;
while (auditRecordEnumerator.HasValue)
{
// print the current audit record results page
this.Context.ConsoleHelper.WriteObject(auditRecordEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Audit Record Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next set of audit records");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next audit records page");
// get the next page of audit records
auditRecordEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,78 @@
// -----------------------------------------------------------------------
// <copyright file="SearchAuditRecords.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Orders
{
using System;
using System.Globalization;
using Microsoft.Store.PartnerCenter.Models.Auditing;
using Models.Query;
/// <summary>
/// A scenario that retrieves a partner's audit records and filter by customer company name.
/// </summary>
public class SearchAuditRecords : BasePartnerScenario
{
/// <summary>
/// The search field.
/// </summary>
private readonly AuditRecordSearchField auditRecordSearchField;
/// <summary>
/// Initializes a new instance of the <see cref="SearchAuditRecords"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="auditRecordSearchField">The search field.</param>
/// <param name="context">The scenario context.</param>
public SearchAuditRecords(string title, AuditRecordSearchField auditRecordSearchField, IScenarioContext context) : base(title, context)
{
this.auditRecordSearchField = auditRecordSearchField;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string searchPrefix = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the prefix to search for", "The entered prefix is empty");
var startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01);
this.Context.ConsoleHelper.StartProgress(
string.Format(CultureInfo.InvariantCulture, "Retrieving the partner's audit records - start date: {0}", startDate));
var filter = new SimpleFieldFilter(AuditRecordSearchField.CompanyName.ToString(), FieldFilterOperation.Substring, searchPrefix);
var auditRecordsPage = partnerOperations.AuditRecords.Query(startDate.Date, query: QueryFactory.Instance.BuildSimpleQuery(filter));
this.Context.ConsoleHelper.StopProgress();
// create a customer enumerator which will aid us in traversing the customer pages
var auditRecordEnumerator = partnerOperations.Enumerators.AuditRecords.Create(auditRecordsPage);
int pageNumber = 1;
while (auditRecordEnumerator.HasValue)
{
// print the current audit record results page
this.Context.ConsoleHelper.WriteObject(auditRecordEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Audit Record Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next set of audit records");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next audit records page");
// get the next page of audit records
auditRecordEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,78 @@
// -----------------------------------------------------------------------
// <copyright file="SearchAuditRecordsByCustomerId.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Orders
{
using System;
using System.Globalization;
using Microsoft.Store.PartnerCenter.Models.Auditing;
using Models.Query;
/// <summary>
/// A scenario that retrieves a partner's audit records and filter by customer company name.
/// </summary>
public class SearchAuditRecordsByCustomerId : BasePartnerScenario
{
/// <summary>
/// The search field.
/// </summary>
private readonly AuditRecordSearchField auditRecordSearchField;
/// <summary>
/// Initializes a new instance of the <see cref="SearchAuditRecordsByCustomerId"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="auditRecordSearchField">The search field.</param>
/// <param name="context">The scenario context.</param>
public SearchAuditRecordsByCustomerId(string title, AuditRecordSearchField auditRecordSearchField, IScenarioContext context) : base(title, context)
{
this.auditRecordSearchField = auditRecordSearchField;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string customerId = this.Context.ConsoleHelper.ReadNonEmptyString("Enter a Customer Id to search for", "No Customer Id entered");
var startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01);
this.Context.ConsoleHelper.StartProgress(
string.Format(CultureInfo.InvariantCulture, "Retrieving the partner's audit records - start date: {0}", startDate));
var filter = new SimpleFieldFilter(AuditRecordSearchField.CustomerId.ToString(), FieldFilterOperation.Equals, customerId);
var auditRecordsPage = partnerOperations.AuditRecords.Query(startDate.Date, query: QueryFactory.Instance.BuildSimpleQuery(filter));
this.Context.ConsoleHelper.StopProgress();
// create a customer enumerator which will aid us in traversing the customer pages
var auditRecordEnumerator = partnerOperations.Enumerators.AuditRecords.Create(auditRecordsPage);
int pageNumber = 1;
while (auditRecordEnumerator.HasValue)
{
// print the current audit record results page
this.Context.ConsoleHelper.WriteObject(auditRecordEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Audit Record Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next set of audit records");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next audit records page");
// get the next page of audit records
auditRecordEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,121 @@
// -----------------------------------------------------------------------
// <copyright file="SearchAuditRecordsByResourceType.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Orders
{
using System;
using System.Globalization;
using Microsoft.Store.PartnerCenter.Models.Auditing;
using Models.Query;
/// <summary>
/// A scenario that retrieves a partner's audit records and filter by customer company name.
/// </summary>
public class SearchAuditRecordsByResourceType : BasePartnerScenario
{
/// <summary>
/// The search field.
/// </summary>
private readonly AuditRecordSearchField auditRecordSearchField;
/// <summary>
/// Initializes a new instance of the <see cref="SearchAuditRecordsByResourceType"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="auditRecordSearchField">The search field.</param>
/// <param name="context">The scenario context.</param>
public SearchAuditRecordsByResourceType(string title, AuditRecordSearchField auditRecordSearchField, IScenarioContext context) : base(title, context)
{
this.auditRecordSearchField = auditRecordSearchField;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string[] resourceTypes = Enum.GetNames(typeof(ResourceType));
int resourceTypesMaxIndex;
for (resourceTypesMaxIndex = 0; resourceTypesMaxIndex < resourceTypes.Length; resourceTypesMaxIndex++)
{
Console.WriteLine(resourceTypesMaxIndex.ToString() + ": " + resourceTypes[resourceTypesMaxIndex]);
}
// decrement max index by 1 to account for zero-based start
resourceTypesMaxIndex--;
Console.WriteLine();
while (true)
{
string resourceType = this.Context.ConsoleHelper.ReadNonEmptyString(
"Enter the number corresponding to the Resource Type to search for",
string.Format(CultureInfo.InvariantCulture, "Please enter a number between 0 and {0}", resourceTypesMaxIndex));
int resourceTypeInt = -1;
if (int.TryParse(resourceType, out resourceTypeInt))
{
if (resourceTypeInt < 0 || resourceTypeInt > resourceTypesMaxIndex)
{
this.Context.ConsoleHelper.Error(
string.Format(CultureInfo.InvariantCulture, "The number must be between 0 and {0}", resourceTypesMaxIndex));
break;
}
}
else
{
this.Context.ConsoleHelper.Error(
string.Format(CultureInfo.InvariantCulture, "The number must be a valid integer between 0 and {0}", resourceTypesMaxIndex));
break;
}
var startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01);
this.Context.ConsoleHelper.StartProgress(
string.Format(CultureInfo.InvariantCulture, "Retrieving the partner's audit records - start date: {0}", startDate));
string searchField = Enum.GetName(typeof(ResourceType), resourceTypeInt);
var filter = new SimpleFieldFilter(AuditRecordSearchField.ResourceType.ToString(), FieldFilterOperation.Equals, searchField);
var auditRecordsPage = partnerOperations.AuditRecords.Query(startDate.Date, query: QueryFactory.Instance.BuildSimpleQuery(filter));
this.Context.ConsoleHelper.StopProgress();
// create a customer enumerator which will aid us in traversing the customer pages
var auditRecordEnumerator = partnerOperations.Enumerators.AuditRecords.Create(auditRecordsPage);
int pageNumber = 1;
while (auditRecordEnumerator.HasValue)
{
// print the current audit record results page
this.Context.ConsoleHelper.WriteObject(auditRecordEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Audit Record Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next set of audit records");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next audit records page");
// get the next page of audit records
auditRecordEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
break;
}
}
}
}

Просмотреть файл

@ -0,0 +1,519 @@
// -----------------------------------------------------------------------
// <copyright file="BasePartnerScenario.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples
{
using System;
using System.Collections.Generic;
using ScenarioExecution;
/// <summary>
/// The base class for partner scenarios. Provides common behavior for all partner scenarios.
/// </summary>
public abstract class BasePartnerScenario : IPartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="BasePartnerScenario"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="context">The scenario context.</param>
/// <param name="executionStrategy">The scenario execution strategy.</param>
/// <param name="childScenarios">The child scenarios attached to the current scenario.</param>
public BasePartnerScenario(string title, IScenarioContext context, IScenarioExecutionStrategy executionStrategy = null, IReadOnlyList<IPartnerScenario> childScenarios = null)
{
if (string.IsNullOrWhiteSpace(title))
{
throw new ArgumentException("title has to be set");
}
if (context == null)
{
throw new ArgumentNullException("context");
}
this.Title = title;
this.Context = context;
this.ExecutionStrategy = executionStrategy ?? new PromptExecutionStrategy();
this.Children = childScenarios;
}
/// <summary>
/// Gets the scenario title.
/// </summary>
public string Title { get; private set; }
/// <summary>
/// Gets the children scenarios of the current scenario.
/// </summary>
public IReadOnlyList<IPartnerScenario> Children { get; private set; }
/// <summary>
/// Gets the scenario context.
/// </summary>
public IScenarioContext Context { get; private set; }
/// <summary>
/// Gets or sets the scenario execution behavior.
/// </summary>
private IScenarioExecutionStrategy ExecutionStrategy { get; set; }
/// <summary>
/// Runs the scenario.
/// </summary>
public void Run()
{
do
{
Console.Clear();
this.Context.ConsoleHelper.WriteColored(this.Title, ConsoleColor.DarkCyan);
this.Context.ConsoleHelper.WriteColored(new string('-', 80), ConsoleColor.DarkCyan);
Console.WriteLine();
try
{
this.RunScenario();
}
catch (Exception exception)
{
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Error(exception.ToString());
}
Console.WriteLine();
}
while (!this.ExecutionStrategy.IsScenarioComplete(this));
}
/// <summary>
/// Obtains a customer ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A customer ID.</returns>
protected string ObtainCustomerId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultCustomerId,
"Customer Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the customer ID" : promptMessage,
"The customer ID can't be empty");
}
/// <summary>
/// Obtains a configuration policy ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A configuration policy ID.</returns>
protected string ObtainConfigurationPolicyId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultConfigurationPolicyId,
"Configuration Policy Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the configuration policy ID" : promptMessage,
"The configuration policy ID can't be empty");
}
/// <summary>
/// Obtains a device batch ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A device batch ID.</returns>
protected string ObtainDeviceBatchId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultDeviceBatchId,
"Device Batch Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the device batch ID" : promptMessage,
"The device batch ID can't be empty");
}
/// <summary>
/// Obtains a device ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A device ID.</returns>
protected string ObtainDeviceId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultDeviceId,
"Device Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the device ID" : promptMessage,
"The device ID can't be empty");
}
/// <summary>
/// Obtains a tracking ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A batch upload status tracking ID.</returns>
protected string ObtainBatchUploadStatusTrackingId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultBatchUploadStatusTrackingId,
"Batch Upload Status Tracking Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the Batch Upload Status Tracking ID" : promptMessage,
"The Batch Upload Status Tracking ID can't be empty");
}
/// <summary>
/// Obtains an indirect reseller ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>An indirect reseller ID.</returns>
protected string ObtainIndirectResellerId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultIndirectResellerId,
"Indirect Reseller Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the indirect reseller ID" : promptMessage,
"The indirect reseller ID can't be empty");
}
/// <summary>
/// Obtains a directory role ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A directory role ID.</returns>
protected string ObtainDirectoryRoleId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultDirectoryRoleId,
"Directory Role Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the Directory Role ID" : promptMessage,
"The Directory Role ID can't be empty");
}
/// <summary>
/// Obtains a customer user ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A customer user ID.</returns>
protected string ObtainCustomerUserId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultCustomerUserId,
"Customer User Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the customer user ID" : promptMessage,
"The customer user ID can't be empty");
}
/// <summary>
/// Obtains a user member ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A user member ID.</returns>
protected string ObtainUserMemberId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultUserMemberId,
"User Member Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the User Member ID" : promptMessage,
"The User Member ID can't be empty");
}
/// <summary>
/// Obtains a customer user ID to delete from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A customer user ID.</returns>
protected string ObtainCustomerUserIdDelete(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.CustomerUserIdToDelete,
"Customer User Id To Delete",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the customer user ID to delete" : promptMessage,
"The customer user ID can't be empty");
}
/// <summary>
/// Obtains a customer user page size to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>A customer user page size.</returns>
protected string ObtainCustomerUserPageSize(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.CustomerUserPageSize,
"Customer user page size",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the customer user page size" : promptMessage,
"The customer user page size can't be empty");
}
/// <summary>
/// Obtains an MPN ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The MPN ID.</returns>
protected string ObtainMpnId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.PartnerMpnId,
"MPN Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the MPN ID" : promptMessage,
"The MPN ID can't be empty");
}
/// <summary>
/// Obtains an offer ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The offer ID.</returns>
protected string ObtainOfferId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultOfferId,
"Offer Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the offer ID" : promptMessage,
"The Offer ID can't be empty");
}
/// <summary>
/// Obtains a product ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The product ID.</returns>
protected string ObtainProductId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultProductId,
"Product Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the product ID" : promptMessage,
"The Product ID can't be empty");
}
/// <summary>
/// Obtains a SKU ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The SKU ID.</returns>
protected string ObtainSkuId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultSkuId,
"Sku Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the sku ID" : promptMessage,
"The Sku ID can't be empty");
}
/// <summary>
/// Obtains the availability ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The availability ID.</returns>
protected string ObtainAvailabilityId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultAvailabilityId,
"Availability Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the availability ID" : promptMessage,
"The Availability ID can't be empty");
}
/// <summary>
/// Obtains a catalogItemId to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The catalog Item ID.</returns>
protected string ObtainCatalogItemId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultCatalogItemId,
"Catalog Item Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the catalog item ID" : promptMessage,
"The catalog item ID can't be empty");
}
/// <summary>
/// Obtains a scope for provisioning status to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The scope.</returns>
protected string ObtainScope(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultScope,
"Scope",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the Scope" : promptMessage,
"The Scope can't be empty");
}
/// <summary>
/// Obtain an order ID to work with the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message</param>
/// <returns>The order ID</returns>
protected string ObtainOrderID(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultOrderId,
"Order Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the order ID" : promptMessage,
"The Order ID can't be empty");
}
/// <summary>
/// Obtain an cart ID to work with the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message</param>
/// <returns>The cart ID</returns>
protected string ObtainCartID(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultCartId,
"Cart Id",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the cart ID" : promptMessage,
"The cart ID can't be empty");
}
/// <summary>
/// Obtain a quantity to update order with the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message</param>
/// <returns>The quantity to update</returns>
protected string ObtainQuantity(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultQuantity,
"Quantity",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the Quantity" : promptMessage,
"The Quantity can't be empty");
}
/// <summary>
/// Obtain billing cycle type to create the order with the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message</param>
/// <returns>The quantity to update</returns>
protected string ObtainBillingCycle(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultBillingCycle,
"Billing Cycle",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the Billing Cycle" : promptMessage,
"The Billing Cycle can't be empty");
}
/// <summary>
/// Obtain an Azure Subscription Id for provision status with the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message</param>
/// <returns>Azure subscription Id</returns>
protected string ObtainAzureSubscriptionId(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultAzureSubscriptionId,
"Quantity",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the Azure Subscription Id" : promptMessage,
"The Azure Subscription Id can't be empty");
}
/// <summary>
/// Obtains a subscription ID to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="customerId">The customer ID who owns the subscription.</param>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The subscription ID.</returns>
protected string ObtainSubscriptionId(string customerId, string promptMessage = default(string))
{
var partnerOperations = this.Context.UserPartnerOperations;
var subscriptionId = this.Context.Configuration.Scenario.DefaultSubscriptionId;
if (string.IsNullOrWhiteSpace(subscriptionId))
{
// get the customer subscriptions and let the user enter the subscription Id afterwards
this.Context.ConsoleHelper.StartProgress("Retrieving customer subscriptions");
var subscriptions = partnerOperations.Customers.ById(customerId).Subscriptions.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(subscriptions, "Customer subscriptions");
Console.WriteLine();
subscriptionId = this.Context.ConsoleHelper.ReadNonEmptyString(
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the subscription ID" : promptMessage, "Subscription ID can't be empty");
}
else
{
Console.WriteLine("Found subscription ID: {0} in configuration.", subscriptionId);
}
return subscriptionId.Trim();
}
/// <summary>
/// Obtains the product SKU ID by asking the user to enter it after displaying customer subscribed SKUs.
/// </summary>
/// <param name="customerId">The customer identifier of the customer that has the subscribed SKUs.</param>
/// <param name="promptMessage">An optional custom prompt message.</param>
/// <returns>The product SKU identifier.</returns>
protected string ObtainProductSkuId(string customerId, string promptMessage = default(string))
{
var partnerOperations = this.Context.UserPartnerOperations;
string productSkuId = string.Empty;
if (string.IsNullOrWhiteSpace(productSkuId))
{
// get the customer subscribed Skus and let the user enter the productSku Id afterwards
this.Context.ConsoleHelper.StartProgress("Retrieving customer subscribed SKUs");
var customerSubscribedSkus = partnerOperations.Customers.ById(customerId).SubscribedSkus.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerSubscribedSkus, "Customer Subscribed SKUs");
Console.WriteLine();
productSkuId = this.Context.ConsoleHelper.ReadNonEmptyString(
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the product SKU ID" : promptMessage, "Product SKU ID can't be empty");
}
else
{
Console.WriteLine("Found product SKU ID: {0} in configuration.", productSkuId);
}
return productSkuId.Trim();
}
/// <summary>
/// Runs the scenario logic. This is delegated to the implementing sub class.
/// </summary>
protected abstract void RunScenario();
/// <summary>
/// Obtain billing cycle type to work with the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="promptMessage">An optional custom prompt message</param>
/// <returns>Billing cycle type</returns>
protected string ObtainBillingCycleType(string promptMessage = default(string))
{
return this.ObtainValue(
this.Context.Configuration.Scenario.DefaultBillingCycle,
"Billing cycle type",
string.IsNullOrWhiteSpace(promptMessage) ? "Enter the billing cycle type" : promptMessage,
"The billing cycle type can't be empty");
}
/// <summary>
/// Obtains a value to work with from the configuration if set there or prompts the user to enter it.
/// </summary>
/// <param name="configuredValue">The value read from the configuration.</param>
/// <param name="title">The title of the value.</param>
/// <param name="promptMessage">The prompt message to use if the value was not set in the configuration.</param>
/// <param name="errorMessage">The error message to use if the user did not enter a value.</param>
/// <returns>A string value.</returns>
private string ObtainValue(string configuredValue, string title, string promptMessage, string errorMessage)
{
string value = configuredValue;
if (string.IsNullOrWhiteSpace(value))
{
// The value was not set in the configuration, prompt the user the enter value
value = this.Context.ConsoleHelper.ReadNonEmptyString(promptMessage, errorMessage);
}
else
{
Console.WriteLine("Found {0}: {1} in configuration.", title, value);
}
return value.Trim();
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="CheckoutCart.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Carts
{
/// <summary>
/// A scenario that checkout a cart for a customer.
/// </summary>
public class CheckoutCart : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckoutCart"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CheckoutCart(IScenarioContext context) : base("Checkout a Cart", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string customerId = this.ObtainCustomerId("Enter the ID of the customer making the purchase");
string cartId = this.ObtainCartID("Enter the ID of cart to checkout");
var existingCart = partnerOperations.Customers.ById(customerId).Carts.ById(cartId).Get();
this.Context.ConsoleHelper.WriteObject(existingCart, "Cart to be checked out");
this.Context.ConsoleHelper.StartProgress("Checking out cart");
var checkoutResult = partnerOperations.Customers.ById(customerId).Carts.ById(cartId).Checkout();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(checkoutResult, "Final Cart: ");
}
}
}

Просмотреть файл

@ -0,0 +1,78 @@
// -----------------------------------------------------------------------
// <copyright file="CreateCart.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Carts
{
using System.Collections.Generic;
using System.Linq;
using Models.Carts;
/// <summary>
/// A scenario that creates a new cart for a customer.
/// </summary>
public class CreateCart : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateCart"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateCart(IScenarioContext context) : base("Create a Cart", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string customerId = this.ObtainCustomerId("Enter the ID of the customer making the purchase");
string catalogItemId = this.ObtainCatalogItemId("Enter the catalog Item Id");
string productId = catalogItemId.Split(':')[0];
string skuId = catalogItemId.Split(':')[1];
string scope = string.Empty;
string subscriptionId = string.Empty;
string duration = string.Empty;
var sku = partnerOperations.Products.ByCountry("US").ById(productId).Skus.ById(skuId).Get();
if (sku.ProvisioningVariables != null)
{
scope = this.ObtainScope("Enter the Scope for the Provisioning status");
subscriptionId = this.ObtainAzureSubscriptionId("Enter the Subscription Id");
duration = (string)sku.DynamicAttributes["duration"];
}
var cart = new Cart()
{
LineItems = new List<CartLineItem>()
{
new CartLineItem()
{
CatalogItemId = catalogItemId,
FriendlyName = "Myofferpurchase",
Quantity = 1,
BillingCycle = sku.SupportedBillingCycles.ToArray().First(),
ProvisioningContext = (sku.ProvisioningVariables == null) ? null : new Dictionary<string, string>
{
{ "subscriptionId", subscriptionId },
{ "scope", scope },
{ "duration", duration }
}
}
}
};
this.Context.ConsoleHelper.WriteObject(cart, "Cart to be created");
this.Context.ConsoleHelper.StartProgress("Creating cart");
var createdCart = partnerOperations.Customers.ById(customerId).Carts.Create(cart);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(createdCart, "Created cart");
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// -----------------------------------------------------------------------
// <copyright file="UpdateCart.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Carts
{
using System.Linq;
using Store.PartnerCenter.Models.Carts;
/// <summary>
/// A scenario that updates a new cart for a customer.
/// </summary>
public class UpdateCart : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateCart"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public UpdateCart(IScenarioContext context) : base("Update a Cart", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string customerId = this.ObtainCustomerId("Enter the ID of the customer making the purchase");
string cartId = this.ObtainCartID("Enter the ID of cart for which changes are to be made");
int quantityChange = int.Parse(this.ObtainQuantity("Enter the amount the quantity has to be changed"));
Cart existingCart = partnerOperations.Customers.ById(customerId).Carts.ById(cartId).Get();
this.Context.ConsoleHelper.WriteObject(existingCart, "Cart to be updated");
this.Context.ConsoleHelper.StartProgress("Updating cart");
existingCart.LineItems.ToArray()[0].Quantity += quantityChange;
var updatedCart = partnerOperations.Customers.ById(customerId).Carts.ById(cartId).Put(existingCart);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(updatedCart, "Updated cart");
}
}
}

Просмотреть файл

@ -0,0 +1,55 @@
// -----------------------------------------------------------------------
// <copyright file="ApplicationAuthenticationSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Configuration
{
/// <summary>
/// Holds an application authentication section settings.
/// </summary>
public class ApplicationAuthenticationSection : Section
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationAuthenticationSection"/> class.
/// </summary>
/// <param name="sectionName">The application authentication section name.</param>
public ApplicationAuthenticationSection(string sectionName) : base(sectionName)
{
}
/// <summary>
/// Gets the AAD application ID.
/// </summary>
public string ApplicationId
{
get
{
return this.ConfigurationSection["ApplicationId"];
}
}
/// <summary>
/// Gets AAD application secret.
/// </summary>
public string ApplicationSecret
{
get
{
return this.ConfigurationSection["ApplicationSecret"];
}
}
/// <summary>
/// Gets AAD Domain which hosts the application.
/// </summary>
public string Domain
{
get
{
return this.ConfigurationSection["Domain"];
}
}
}
}

Просмотреть файл

@ -0,0 +1,103 @@
// -----------------------------------------------------------------------
// <copyright file="ConfigurationManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Configuration
{
using System;
/// <summary>
/// Encapsulates the sample application configuration read from app.config.
/// </summary>
public class ConfigurationManager
{
/// <summary>
/// A lazy reference to a <see cref="ConfigurationManager"/> instance.
/// </summary>
private static Lazy<ConfigurationManager> instance = new Lazy<ConfigurationManager>(() => new ConfigurationManager());
/// <summary>
/// A reference to the partner service settings.
/// </summary>
private Lazy<PartnerServiceSettingsSection> partnerServiceSettings = new Lazy<PartnerServiceSettingsSection>(() => new PartnerServiceSettingsSection());
/// <summary>
/// A reference to the user authentication configuration.
/// </summary>
private Lazy<UserAuthenticationSection> userAuthentication = new Lazy<UserAuthenticationSection>(() => new UserAuthenticationSection("UserAuthentication"));
/// <summary>
/// A reference to the application authentication configuration.
/// </summary>
private Lazy<ApplicationAuthenticationSection> appAuthentication = new Lazy<ApplicationAuthenticationSection>(() => new ApplicationAuthenticationSection("AppAuthentication"));
/// <summary>
/// A reference to the scenario settings.
/// </summary>
private Lazy<ScenarioSettingsSection> scenarioSettings = new Lazy<ScenarioSettingsSection>(() => new ScenarioSettingsSection());
/// <summary>
/// Prevents a default instance of the <see cref="ConfigurationManager"/> class from being created.
/// </summary>
private ConfigurationManager()
{
}
/// <summary>
/// Gets the singleton instance of the <see cref="ConfigurationManager"/> class.
/// </summary>
public static ConfigurationManager Instance
{
get
{
return ConfigurationManager.instance.Value;
}
}
/// <summary>
/// Gets the partner service settings section.
/// </summary>
public PartnerServiceSettingsSection PartnerService
{
get
{
return this.partnerServiceSettings.Value;
}
}
/// <summary>
/// Gets the user authentication section.
/// </summary>
public UserAuthenticationSection UserAuthentication
{
get
{
return this.userAuthentication.Value;
}
}
/// <summary>
/// Gets the application authentication section.
/// </summary>
public ApplicationAuthenticationSection ApplicationAuthentication
{
get
{
return this.appAuthentication.Value;
}
}
/// <summary>
/// Gets the scenario settings section.
/// </summary>
public ScenarioSettingsSection Scenario
{
get
{
return this.scenarioSettings.Value;
}
}
}
}

Просмотреть файл

@ -0,0 +1,67 @@
// -----------------------------------------------------------------------
// <copyright file="PartnerServiceSettingsSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Configuration
{
using System;
/// <summary>
/// Holds the partner service settings section.
/// </summary>
public class PartnerServiceSettingsSection : Section
{
/// <summary>
/// Initializes a new instance of the <see cref="PartnerServiceSettingsSection"/> class.
/// </summary>
public PartnerServiceSettingsSection() : base("PartnerServiceSettings")
{
}
/// <summary>
/// Gets the partner service API endpoint.
/// </summary>
public Uri PartnerServiceApiEndpoint
{
get
{
return new Uri(this.ConfigurationSection["PartnerServiceApiEndpoint"]);
}
}
/// <summary>
/// Gets the authentication authority (AAD) endpoint.
/// </summary>
public Uri AuthenticationAuthorityEndpoint
{
get
{
return new Uri(this.ConfigurationSection["AuthenticationAuthorityEndpoint"]);
}
}
/// <summary>
/// Gets the graph API end point.
/// </summary>
public Uri GraphEndpoint
{
get
{
return new Uri(this.ConfigurationSection["GraphEndpoint"]);
}
}
/// <summary>
/// Gets the AAD common domain.
/// </summary>
public string CommonDomain
{
get
{
return this.ConfigurationSection["CommonDomain"];
}
}
}
}

Просмотреть файл

@ -0,0 +1,403 @@
// -----------------------------------------------------------------------
// <copyright file="ScenarioSettingsSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Configuration
{
/// <summary>
/// Holds the scenario specific settings section.
/// </summary>
public class ScenarioSettingsSection : Section
{
/// <summary>
/// Initializes a new instance of the <see cref="ScenarioSettingsSection"/> class.
/// </summary>
public ScenarioSettingsSection() : base("ScenarioSettings")
{
}
/// <summary>
/// Gets the customer domain suffix.
/// </summary>
public string CustomerDomainSuffix
{
get
{
return this.ConfigurationSection["CustomerDomainSuffix"];
}
}
/// <summary>
/// Gets the ID of the customer to delete from the TIP account.
/// </summary>
public string CustomerIdToDelete
{
get
{
return this.ConfigurationSection["CustomerIdToDelete"];
}
}
/// <summary>
/// Gets the ID of the customer user to delete.
/// </summary>
public string CustomerUserIdToDelete
{
get
{
return this.ConfigurationSection["CustomerUserIdToDelete"];
}
}
/// <summary>
/// Gets the ID of the directory role whose details should be read.
/// </summary>
public string DefaultDirectoryRoleId
{
get
{
return this.ConfigurationSection["DefaultDirectoryRoleId"];
}
}
/// <summary>
/// Gets the ID of the user member whose details should be read.
/// </summary>
public string DefaultUserMemberId
{
get
{
return this.ConfigurationSection["DefaultUserMemberId"];
}
}
/// <summary>
/// Gets the ID of the customer whose details should be read.
/// </summary>
public string DefaultCustomerId
{
get
{
return this.ConfigurationSection["DefaultCustomerId"];
}
}
/// <summary>
/// Gets the configured ID of the configuration policy.
/// </summary>
public string DefaultConfigurationPolicyId
{
get
{
return this.ConfigurationSection["DefaultConfigurationPolicyId"];
}
}
/// <summary>
/// Gets the configured ID of the Devices Batch.
/// </summary>
public string DefaultDeviceBatchId
{
get
{
return this.ConfigurationSection["DefaultDeviceBatchId"];
}
}
/// <summary>
/// Gets the configured ID of the Device.
/// </summary>
public string DefaultDeviceId
{
get
{
return this.ConfigurationSection["DefaultDeviceId"];
}
}
/// <summary>
/// Gets the configured ID of the Batch Upload Status Tracking.
/// </summary>
public string DefaultBatchUploadStatusTrackingId
{
get
{
return this.ConfigurationSection["DefaultBatchUploadStatusTrackingId"];
}
}
/// <summary>
/// Gets the ID of the indirect reseller id whose details should be read.
/// </summary>
public string DefaultIndirectResellerId
{
get
{
return this.ConfigurationSection["DefaultIndirectResellerId"];
}
}
/// <summary>
/// Gets the ID of the default customer user.
/// </summary>
public string DefaultCustomerUserId
{
get
{
return this.ConfigurationSection["DefaultCustomerUserId"];
}
}
/// <summary>
/// Gets the number of customers to return in each customer page.
/// </summary>
public int CustomerPageSize
{
get
{
return int.Parse(this.ConfigurationSection["CustomerPageSize"]);
}
}
/// <summary>
/// Gets the number of customer users to return in each customer user page.
/// </summary>
public string CustomerUserPageSize
{
get
{
return this.ConfigurationSection["CustomerUserPageSize"];
}
}
/// <summary>
/// Gets the number of offers to return in each offer page.
/// </summary>
public int DefaultOfferPageSize
{
get
{
return int.Parse(this.ConfigurationSection["DefaultOfferPageSize"]);
}
}
/// <summary>
/// Gets the number of invoices to return in each invoice page.
/// </summary>
public int InvoicePageSize
{
get
{
return int.Parse(this.ConfigurationSection["InvoicePageSize"]);
}
}
/// <summary>
/// Gets the configured Invoice ID.
/// </summary>
public string DefaultInvoiceId
{
get
{
return this.ConfigurationSection["DefaultInvoiceId"];
}
}
/// <summary>
/// Gets the configured partner MPD ID.
/// </summary>
public string PartnerMpnId
{
get
{
return this.ConfigurationSection["PartnerMpnId"];
}
}
/// <summary>
/// Gets the configured offer ID.
/// </summary>
public string DefaultOfferId
{
get
{
return this.ConfigurationSection["DefaultOfferId"];
}
}
/// <summary>
/// Gets the configured product ID.
/// </summary>
public string DefaultProductId
{
get
{
return this.ConfigurationSection["DefaultProductId"];
}
}
/// <summary>
/// Gets the configured SKU ID.
/// </summary>
public string DefaultSkuId
{
get
{
return this.ConfigurationSection["DefaultSkuId"];
}
}
/// <summary>
/// Gets the configured availability ID.
/// </summary>
public string DefaultAvailabilityId
{
get
{
return this.ConfigurationSection["DefaultAvailabilityId"];
}
}
/// <summary>
/// Gets the configured order ID.
/// </summary>
public string DefaultOrderId
{
get
{
return this.ConfigurationSection["DefaultOrderId"];
}
}
/// <summary>
/// Gets the configured subscription ID.
/// </summary>
public string DefaultSubscriptionId
{
get
{
return this.ConfigurationSection["DefaultSubscriptionId"];
}
}
/// <summary>
/// Gets the service request ID.
/// </summary>
public string DefaultServiceRequestId
{
get
{
return this.ConfigurationSection["DefaultServiceRequestId"];
}
}
/// <summary>
/// Gets the number of service requests to return in each service request page.
/// </summary>
public int ServiceRequestPageSize
{
get
{
return int.Parse(this.ConfigurationSection["ServiceRequestPageSize"]);
}
}
/// <summary>
/// Gets the configured support topic ID for creating new service request.
/// </summary>
public string DefaultSupportTopicId
{
get
{
return this.ConfigurationSection["DefaultSupportTopicId"];
}
}
/// <summary>
/// Gets the configured agreement template ID for create new customer agreements.
/// </summary>
public string DefaultAgreementTemplateId
{
get { return this.ConfigurationSection["DefaultAgreementTemplateId"]; }
}
/// <summary>
/// Gets the partner's user ID for creating new customer agreement.
/// </summary>
public string DefaultPartnerUserId
{
get
{
return this.ConfigurationSection["DefaultPartnerUserId"];
}
}
/// <summary>
/// Gets the cart Id for an existing cart
/// </summary>
public string DefaultCartId
{
get
{
return this.ConfigurationSection["DefaultCartId"];
}
}
/// <summary>
/// Gets the Quantity for updating an existing cart
/// </summary>
public string DefaultQuantity
{
get
{
return this.ConfigurationSection["DefaultQuantity"];
}
}
/// <summary>
/// Gets the Catalog Item Id for an item from catalog
/// </summary>
public string DefaultCatalogItemId
{
get
{
return this.ConfigurationSection["DefaultCatalogItemId"];
}
}
/// <summary>
/// Gets the scope for provisioning status
/// </summary>
public string DefaultScope
{
get
{
return this.ConfigurationSection["DefaultScope"];
}
}
/// <summary>
/// Gets the Azure Subscription Id for provision status
/// </summary>
public string DefaultAzureSubscriptionId
{
get
{
return this.ConfigurationSection["DefaultAzureSubscriptionId"];
}
}
/// <summary>
/// Gets the BillingCycle for creating a cart
/// </summary>
public string DefaultBillingCycle
{
get
{
return this.ConfigurationSection["DefaultBillingCycle"];
}
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// -----------------------------------------------------------------------
// <copyright file="Section.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Configuration
{
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
/// <summary>
/// Encapsulates a configuration section read from app.config.
/// </summary>
public abstract class Section
{
/// <summary>
/// Initializes a new instance of the <see cref="Section"/> class.
/// </summary>
/// <param name="sectionName">The configuration section name.</param>
protected Section(string sectionName)
{
if (string.IsNullOrWhiteSpace(sectionName))
{
throw new ArgumentException("sectionName must be set");
}
this.ConfigurationSection = System.Configuration.ConfigurationManager.GetSection(sectionName) as NameValueCollection;
if (this.ConfigurationSection == null)
{
throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "Could not read section: {0} from configuration", sectionName));
}
}
/// <summary>
/// Gets the configuration section.
/// </summary>
protected NameValueCollection ConfigurationSection { get; private set; }
}
}

Просмотреть файл

@ -0,0 +1,79 @@
// -----------------------------------------------------------------------
// <copyright file="UserAuthenticationSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Configuration
{
using System;
/// <summary>
/// Holds a user authentication section settings.
/// </summary>
public class UserAuthenticationSection : Section
{
/// <summary>
/// Initializes a new instance of the <see cref="UserAuthenticationSection"/> class.
/// </summary>
/// <param name="sectionName">The application authentication section name.</param>
public UserAuthenticationSection(string sectionName) : base(sectionName)
{
}
/// <summary>
/// Gets the AAD application ID.
/// </summary>
public string ApplicationId
{
get
{
return this.ConfigurationSection["ApplicationId"];
}
}
/// <summary>
/// Gets the resource the application is attempting to access, i.e. the partner API service.
/// </summary>
public Uri ResourceUrl
{
get
{
return new Uri(this.ConfigurationSection["ResourceUrl"]);
}
}
/// <summary>
/// Gets the application redirect URL.
/// </summary>
public Uri RedirectUrl
{
get
{
return new Uri(this.ConfigurationSection["RedirectUrl"]);
}
}
/// <summary>
/// Gets AAD user name.
/// </summary>
public string UserName
{
get
{
return this.ConfigurationSection["UserName"];
}
}
/// <summary>
/// Gets AAD password.
/// </summary>
public string Password
{
get
{
return this.ConfigurationSection["Password"];
}
}
}
}

Просмотреть файл

@ -0,0 +1,153 @@
// -----------------------------------------------------------------------
// <copyright file="ScenarioContext.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Context
{
using System;
using System.Threading.Tasks;
using Configuration;
using Helpers;
using IdentityModel.Clients.ActiveDirectory;
using Store.PartnerCenter;
using Store.PartnerCenter.Extensions;
/// <summary>
/// Scenario context implementation class.
/// </summary>
public class ScenarioContext : IScenarioContext
{
/// <summary>
/// A lazy reference to an user based partner operations.
/// </summary>
private IAggregatePartner userPartnerOperations = null;
/// <summary>
/// A lazy reference to an application based partner operations.
/// </summary>
private IAggregatePartner appPartnerOperations = null;
/// <summary>
/// Initializes a new instance of the <see cref="ScenarioContext"/> class.
/// </summary>
public ScenarioContext()
{
PartnerService.Instance.ApiRootUrl = this.Configuration.PartnerService.PartnerServiceApiEndpoint.ToString();
PartnerService.Instance.ApplicationName = "Partner Center .NET SDK Samples";
}
/// <summary>
/// Gets a partner operations instance which is application based authenticated.
/// </summary>
public IAggregatePartner AppPartnerOperations
{
get
{
if (this.appPartnerOperations == null)
{
this.ConsoleHelper.StartProgress("Authenticating application");
IPartnerCredentials appCredentials = PartnerCredentials.Instance.GenerateByApplicationCredentials(
this.Configuration.ApplicationAuthentication.ApplicationId,
this.Configuration.ApplicationAuthentication.ApplicationSecret,
this.Configuration.ApplicationAuthentication.Domain,
this.Configuration.PartnerService.AuthenticationAuthorityEndpoint.OriginalString,
this.Configuration.PartnerService.GraphEndpoint.OriginalString);
this.ConsoleHelper.StopProgress();
this.ConsoleHelper.Success("Authenticated!");
this.appPartnerOperations = PartnerService.Instance.CreatePartnerOperations(appCredentials);
}
return this.appPartnerOperations;
}
}
/// <summary>
/// Gets a configuration instance.
/// </summary>
public ConfigurationManager Configuration
{
get
{
return ConfigurationManager.Instance;
}
}
/// <summary>
/// Gets a console helper instance.
/// </summary>
public ConsoleHelper ConsoleHelper
{
get
{
return ConsoleHelper.Instance;
}
}
/// <summary>
/// Gets a partner operations instance which is user based authenticated.
/// </summary>
public IAggregatePartner UserPartnerOperations
{
get
{
if (this.userPartnerOperations == null)
{
this.ConsoleHelper.StartProgress("Authenticating user");
var aadAuthenticationResult = this.LoginUserToAad();
// Authenticate by user context with the partner service
IPartnerCredentials userCredentials = PartnerCredentials.Instance.GenerateByUserCredentials(
this.Configuration.UserAuthentication.ApplicationId,
new AuthenticationToken(
aadAuthenticationResult.AccessToken,
aadAuthenticationResult.ExpiresOn),
delegate
{
// token has expired, re-Login to Azure Active Directory
this.ConsoleHelper.StartProgress("Token expired. Re-authenticating user");
var aadToken = this.LoginUserToAad();
this.ConsoleHelper.StopProgress();
// give the partner SDK the new add token information
return Task.FromResult(new AuthenticationToken(aadToken.AccessToken, aadToken.ExpiresOn));
});
this.ConsoleHelper.StopProgress();
this.ConsoleHelper.Success("Authenticated!");
this.userPartnerOperations = PartnerService.Instance.CreatePartnerOperations(userCredentials);
}
return this.userPartnerOperations;
}
}
/// <summary>
/// Logs in to AAD as a user and obtains the user authentication token.
/// </summary>
/// <returns>The user authentication result.</returns>
private AuthenticationResult LoginUserToAad()
{
var addAuthority = new UriBuilder(this.Configuration.PartnerService.AuthenticationAuthorityEndpoint)
{
Path = this.Configuration.PartnerService.CommonDomain
};
UserCredential userCredentials = new UserCredential(
this.Configuration.UserAuthentication.UserName,
this.Configuration.UserAuthentication.Password);
AuthenticationContext authContext = new AuthenticationContext(addAuthority.Uri.AbsoluteUri);
return authContext.AcquireToken(
this.Configuration.UserAuthentication.ResourceUrl.OriginalString,
this.Configuration.UserAuthentication.ApplicationId,
userCredentials);
}
}
}

Просмотреть файл

@ -0,0 +1,61 @@
// -----------------------------------------------------------------------
// <copyright file="AddUserMemberToDirectoryRole.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerDirectoryRoles
{
using System;
using Models.Roles;
/// <summary>
/// Adds user member to a directory role.
/// </summary>
public class AddUserMemberToDirectoryRole : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="AddUserMemberToDirectoryRole"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public AddUserMemberToDirectoryRole(IScenarioContext context) : base("Add user member to a directory role", context)
{
}
/// <summary>
/// Executes the add user member to a directory role scenario.
/// </summary>
protected override void RunScenario()
{
// get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get details for creating user member");
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer whose customer user details should be used for user member");
// get directory role Id.
string selectedDirectoryRoleId = this.ObtainDirectoryRoleId("Enter the ID of the directory role");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting Customer User Details");
// getting customer user details
var selectedCustomer = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Get();
this.Context.ConsoleHelper.StopProgress();
UserMember userMemberToAdd = new UserMember()
{
UserPrincipalName = selectedCustomer.UserPrincipalName,
DisplayName = selectedCustomer.DisplayName,
Id = selectedCustomer.Id
};
this.Context.ConsoleHelper.StartProgress("Adding user member to directory roles");
// Add this customer user to the selected directory role.
var userMemberAdded = partnerOperations.Customers.ById(selectedCustomerId).DirectoryRoles.ById(selectedDirectoryRoleId).UserMembers.Create(userMemberToAdd);
this.Context.ConsoleHelper.StopProgress();
Console.WriteLine("Below Customer user was added to directory role with id: {0}", selectedDirectoryRoleId);
this.Context.ConsoleHelper.WriteObject(userMemberAdded, "Added Customer User Member to Directory Role Details");
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerDirectoryRoleUserMembers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerDirectoryRoles
{
/// <summary>
/// Showcases get customer users by directory role service.
/// </summary>
public class GetCustomerDirectoryRoleUserMembers : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerDirectoryRoleUserMembers"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerDirectoryRoleUserMembers(IScenarioContext context) : base("Get customer user by directory role", context)
{
}
/// <summary>
/// Executes the get customer users by directory role service scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id to get directory role user members.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get directory role user members");
// get directory role Id.
string selectedDirectoryRoleId = this.ObtainDirectoryRoleId("Enter the ID of the directory role");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting user members by directory roles");
// Get all user members having the selected directory role.
var userMembers = partnerOperations.Customers.ById(selectedCustomerId).DirectoryRoles.ById(selectedDirectoryRoleId).UserMembers.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(userMembers, "User Members who are having the selected directory role");
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerDirectoryRoles.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerDirectoryRoles
{
/// <summary>
/// Gets customer directory roles details.
/// </summary>
public class GetCustomerDirectoryRoles : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerDirectoryRoles"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerDirectoryRoles(IScenarioContext context) : base("Get customer directory roles", context)
{
}
/// <summary>
/// Executes the get customer directory roles scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get directory roles");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer directory roles");
// get directory roles of customer.
var directoryRoles = partnerOperations.Customers.ById(selectedCustomerId).DirectoryRoles.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(directoryRoles, "Customer Directory Role Details");
}
}
}

Просмотреть файл

@ -0,0 +1,47 @@
// -----------------------------------------------------------------------
// <copyright file="RemoveCustomerUserMemberFromDirectoryRole.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerDirectoryRoles
{
using System;
/// <summary>
/// Showcases remove customer user from directory role service.
/// </summary>
public class RemoveCustomerUserMemberFromDirectoryRole : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoveCustomerUserMemberFromDirectoryRole"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public RemoveCustomerUserMemberFromDirectoryRole(IScenarioContext context) : base("Remove customer user from a directory role", context)
{
}
/// <summary>
/// Executes the remove customer user from a directory role scenario.
/// </summary>
protected override void RunScenario()
{
// get user member Id.
string selectedUserMemberId = this.ObtainUserMemberId("Enter the ID of the user member of directory role user to remove");
// get directory role Id of the entered user member.
string selectedDirectoryRoleId = this.ObtainDirectoryRoleId("Enter the ID of the directory role to remove customer user");
// get customer Id of the entered directory roles.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer whose customer user to remove from a directory role");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Removing user member from directory role");
// Remove user member from selected directory role.
partnerOperations.Customers.ById(selectedCustomerId).DirectoryRoles.ById(selectedDirectoryRoleId).UserMembers.ById(selectedUserMemberId).Delete();
this.Context.ConsoleHelper.StopProgress();
Console.WriteLine("The user member with Id: {0} is removed from directory role Id: {1}", selectedUserMemberId, selectedDirectoryRoleId);
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerAvailabilities.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves the availabilities of a product's SKU for a customer.
/// </summary>
public class GetCustomerAvailabilities : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerAvailabilities"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerAvailabilities(IScenarioContext context) : base("Get availabilities for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
var skuId = this.ObtainSkuId("Enter the ID of the corresponding sku");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting availabilities for product {0} and sku {1} for customer {2}", productId, skuId, customerId));
var skuAvailabilities = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.ById(skuId).Availabilities.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(skuAvailabilities, "Availabilities for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerAvailabilitiesByTargetSegment.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves the availabilities of a product's SKU for a customer that target a specific segment.
/// </summary>
public class GetCustomerAvailabilitiesByTargetSegment : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerAvailabilitiesByTargetSegment"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerAvailabilitiesByTargetSegment(IScenarioContext context) : base("Get availabilities for customer by segment", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
var skuId = this.ObtainSkuId("Enter the ID of the corresponding sku");
string segment = this.Context.ConsoleHelper.ReadNonEmptyString("The segment to filter the availabilities on", "The segment can't be empty");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting sku availabilities for product {0} and sku {1} by segment {2} for customer {3}", productId, skuId, segment, customerId));
var skuAvailabilities = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.ById(skuId).Availabilities.ByTargetSegment(segment).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(skuAvailabilities, "Availabilities for customer by segment");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerAvailability.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves the availability of a product's SKU for a customer.
/// </summary>
public class GetCustomerAvailability : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerAvailability"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerAvailability(IScenarioContext context) : base("Get availability for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
var skuId = this.ObtainSkuId("Enter the ID of the corresponding sku");
var availabilityId = this.ObtainAvailabilityId("Enter the ID of the availability");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting availability {0} for product {1} and sku {2} for customer {3}", availabilityId, productId, skuId, customerId));
var skuAvailability = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.ById(skuId).Availabilities.ById(availabilityId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(skuAvailability, "Availability for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerProduct.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves product details for a customer.
/// </summary>
public class GetCustomerProduct : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerProduct"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerProduct(IScenarioContext context) : base("Get product for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the product");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting product {0} details for customer {1}", productId, customerId));
var product = partnerOperations.Customers.ById(customerId).Products.ById(productId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(product, "Product details for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerProducts.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves all the products in a catalog view that apply to a costumer.
/// </summary>
public class GetCustomerProducts : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerProducts"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerProducts(IScenarioContext context) : base("Get products for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
string targetView = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the target view to get its supported products", "The target view can't be empty");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting products in catalog view {0} for customer {1}", targetView, customerId));
var products = partnerOperations.Customers.ById(customerId).Products.ByTargetView(targetView).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(products, "Products for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerProductsByTargetSegment.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves all the products in a catalog view that apply to a customer and that target a specific segment.
/// </summary>
public class GetCustomerProductsByTargetSegment : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerProductsByTargetSegment"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerProductsByTargetSegment(IScenarioContext context) : base("Get products for customer by segment", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
string targetView = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the target view to get its supported products", "The target view can't be empty");
string segment = this.Context.ConsoleHelper.ReadNonEmptyString("The segment to filter the products on", "The segment can't be empty");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting products in catalog view {0} by segment {1} for customer {2}", targetView, segment, customerId));
var products = partnerOperations.Customers.ById(customerId).Products.ByTargetView(targetView).ByTargetSegment(segment).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(products, "Products for customer by segment");
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerSku.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves details of a product's SKU for a customer.
/// </summary>
public class GetCustomerSku : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerSku"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerSku(IScenarioContext context) : base("Get sku for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
var skuId = this.ObtainSkuId("Enter the ID of the sku");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting sku details for sku {0} from product {1} for customer {2}", skuId, productId, customerId));
var sku = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.ById(skuId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(sku, "Sku details for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerSkuDownloadOptions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves the download options of a product's SKU for a customer.
/// </summary>
public class GetCustomerSkuDownloadOptions : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerSkuDownloadOptions"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerSkuDownloadOptions(IScenarioContext context) : base("Get sku download options for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
var skuId = this.ObtainSkuId("Enter the ID of the corresponding sku");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting sku download options for sku {0} from product {1} for customer {2}", skuId, productId, customerId));
var sku = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.ById(skuId).DownloadOptions.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(sku, "Sku download options for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerSkus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves all the SKUs related to a product that apply to a customer.
/// </summary>
public class GetCustomerSkus : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerSkus"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerSkus(IScenarioContext context) : base("Get skus for customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting skus from product {0} for customer {1}", productId, customerId));
var skus = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(skus, "Skus for customer");
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerSkusByTargetSegment.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerProducts
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves all the SKUs related to a product that apply to a customer and that target a specific segment.
/// </summary>
public class GetCustomerSkusByTargetSegment : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerSkusByTargetSegment"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerSkusByTargetSegment(IScenarioContext context) : base("Get skus for customer by segment", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerId = this.ObtainCustomerId("Enter the ID of the corresponding customer");
var productId = this.ObtainProductId("Enter the ID of the corresponding product");
string segment = this.Context.ConsoleHelper.ReadNonEmptyString("The segment to filter the skus on", "The segment can't be empty");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting skus from product {0} by segment {1} for customer {2}", productId, segment, customerId));
var skus = partnerOperations.Customers.ById(customerId).Products.ById(productId).Skus.ByTargetSegment(segment).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(skus, string.Format(CultureInfo.InvariantCulture, "Skus for customer {0} by segment {1}", productId, segment));
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerServiceCostsLineItems.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerServiceCosts
{
using Models.ServiceCosts;
/// <summary>
/// Gets Customer Service Costs Line Items.
/// </summary>
public class GetCustomerServiceCostsLineItems : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerServiceCostsLineItems"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerServiceCostsLineItems(IScenarioContext context) : base("Get customer service costs line items", context)
{
}
/// <summary>
/// Executes the get Customer Service Costs Line Items.
/// </summary>
protected override void RunScenario()
{
// get a customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get service costs line items");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer service costs line items");
// get the customer's Service Costs Line Items.
var customerServiceCostsLineItems = partnerOperations.Customers.ById(selectedCustomerId).ServiceCosts.ByBillingPeriod(ServiceCostsBillingPeriod.MostRecent).LineItems.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerServiceCostsLineItems, "Customer Service Costs Line Items");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerServiceCostsSummary.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerServiceCosts
{
using Models.ServiceCosts;
/// <summary>
/// Gets Customer Service Costs Summary.
/// </summary>
public class GetCustomerServiceCostsSummary : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerServiceCostsSummary"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerServiceCostsSummary(IScenarioContext context) : base("Get customer service costs summary", context)
{
}
/// <summary>
/// Executes the get Customer Service Costs scenario.
/// </summary>
protected override void RunScenario()
{
// get a customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get service costs summary");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer service costs summary");
// get the customer's Service Costs Summary.
var customerServiceCostsSummary = partnerOperations.Customers.ById(selectedCustomerId).ServiceCosts.ByBillingPeriod(ServiceCostsBillingPeriod.MostRecent).Summary.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerServiceCostsSummary, "Customer Service Costs Summary");
}
}
}

Просмотреть файл

@ -0,0 +1,44 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerSubscribedSkus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerSubscribedSkus
{
using System;
/// <summary>
/// Gets Customer Subscribed SKUs details.
/// </summary>
public class GetCustomerSubscribedSkus : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerSubscribedSkus"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerSubscribedSkus(IScenarioContext context) : base("Get customer subscribed SKUs", context)
{
}
/// <summary>
/// Executes the get Customer Subscribed SKUs scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get subscribed skus");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer subscribed SKUs");
// get Customer Subscribed SKUs information.
var customerSubscribedSkus = partnerOperations.Customers.ById(selectedCustomerId).SubscribedSkus.Get();
this.Context.ConsoleHelper.StopProgress();
Console.Out.WriteLine("Customer Subscribed Skus Count: " + customerSubscribedSkus.TotalCount);
this.Context.ConsoleHelper.WriteObject(customerSubscribedSkus, "Customer Subscribed Sku");
}
}
}

Просмотреть файл

@ -0,0 +1,61 @@
// -----------------------------------------------------------------------
// <copyright file="CreateCustomerUser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using Models.Users;
/// <summary>
/// Creates a new customer user.
/// </summary>
public class CreateCustomerUser : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateCustomerUser"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateCustomerUser(IScenarioContext context) : base("Create a new customer user", context)
{
}
/// <summary>
/// Executes the create customer user scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to create customer user");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer of selected customer Id");
// get customer.
var selectedCustomer = partnerOperations.Customers.ById(selectedCustomerId).Get();
this.Context.ConsoleHelper.StopProgress();
var customerUserToCreate = new CustomerUser()
{
PasswordProfile = new PasswordProfile() { ForceChangePassword = true, Password = "Password!1" },
DisplayName = "Kate",
FirstName = "Kate",
LastName = "Nichols",
UsageLocation = "US",
UserPrincipalName = Guid.NewGuid().ToString("N") + "@" + selectedCustomer.CompanyProfile.Domain
};
this.Context.ConsoleHelper.WriteObject(customerUserToCreate, "New customer user Information");
this.Context.ConsoleHelper.StartProgress("Creating customer user");
// Create a customer user.
var createdUser = partnerOperations.Customers.ById(selectedCustomerId).Users.Create(customerUserToCreate);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Success!");
this.Context.ConsoleHelper.WriteObject(createdUser, "Created User Information");
}
}
}

Просмотреть файл

@ -0,0 +1,82 @@
// -----------------------------------------------------------------------
// <copyright file="CustomerUserAssignGroup1Licenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using System.Collections.Generic;
using System.Linq;
using Models.Licenses;
/// <summary>
/// Assign customer user a group1 license.
/// </summary>
public class CustomerUserAssignGroup1Licenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignGroup1Licenses"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CustomerUserAssignGroup1Licenses(IScenarioContext context) : base("Assign customer user a group1 license", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// Get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
// Get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to assign license");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting Subscribed Skus");
// A list of the groupids
// Group1 – This group has all products whose license can be managed in the Azure Active Directory (AAD).
List<LicenseGroupId> groupIds = new List<LicenseGroupId>() { LicenseGroupId.Group1 };
// Get customer's group1 subscribed skus information.
var customerGroup1SubscribedSkus = partnerOperations.Customers.ById(selectedCustomerId).SubscribedSkus.Get(groupIds);
this.Context.ConsoleHelper.StopProgress();
// Prepare license request.
LicenseUpdate updateLicense = new LicenseUpdate();
LicenseAssignment license = new LicenseAssignment();
// Select the first subscribed sku.
SubscribedSku sku = customerGroup1SubscribedSkus.Items.First();
// Assigning first subscribed sku as the license
license.SkuId = sku.ProductSku.Id;
license.ExcludedPlans = null;
List<LicenseAssignment> licenseList = new List<LicenseAssignment>();
licenseList.Add(license);
updateLicense.LicensesToAssign = licenseList;
this.Context.ConsoleHelper.StartProgress("Assigning License");
// Assign licenses to the user.
var assignLicense = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).LicenseUpdates.Create(updateLicense);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.StartProgress("Getting Assigned License");
// Get customer user assigned licenses information after assigning the license.
var customerUserAssignedLicenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get(groupIds);
this.Context.ConsoleHelper.StopProgress();
License userLicense = customerUserAssignedLicenses.Items.First(licenseItem => licenseItem.ProductSku.Id == license.SkuId);
Console.WriteLine("License was successfully assigned to the user.");
this.Context.ConsoleHelper.WriteObject(userLicense, "Assigned License");
}
}
}

Просмотреть файл

@ -0,0 +1,104 @@
// -----------------------------------------------------------------------
// <copyright file="CustomerUserAssignGroup2Licenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using System.Collections.Generic;
using System.Linq;
using Models.Licenses;
/// <summary>
/// Assign customer user a Group2 license
/// </summary>
public class CustomerUserAssignGroup2Licenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignGroup2Licenses"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CustomerUserAssignGroup2Licenses(IScenarioContext context) : base("Assign customer user a Group2 license", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// A sample License Group2 Id - Minecraft product id.
string minecraftProductSkuId = "984df360-9a74-4647-8cf8-696749f6247a";
// Subscribed Sku for minecraft;
SubscribedSku minecraftSubscribedSku = null;
// Get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
// Get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to assign license");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting Subscribed Skus");
// Group2 – This group contains products that cant be managed in Azure Active Directory
List<LicenseGroupId> groupIds = new List<LicenseGroupId>() { LicenseGroupId.Group2 };
// Get customer's subscribed skus information.
var customerSubscribedSkus = partnerOperations.Customers.ById(selectedCustomerId).SubscribedSkus.Get(groupIds);
// Check if a minecraft exists for a given user
foreach (var customerSubscribedSku in customerSubscribedSkus.Items)
{
if (customerSubscribedSku.ProductSku.Id.ToString() == minecraftProductSkuId)
{
minecraftSubscribedSku = customerSubscribedSku;
}
}
if (minecraftSubscribedSku == null)
{
Console.WriteLine("Customer user doesnt have subscribed sku");
this.Context.ConsoleHelper.StopProgress();
return;
}
this.Context.ConsoleHelper.StopProgress();
// Prepare license request.
LicenseUpdate updateLicense = new LicenseUpdate();
// Select the license
SubscribedSku sku = minecraftSubscribedSku;
LicenseAssignment license = new LicenseAssignment();
// Assigning subscribed sku as the license
license.SkuId = sku.ProductSku.Id;
license.ExcludedPlans = null;
List<LicenseAssignment> licenseList = new List<LicenseAssignment>();
licenseList.Add(license);
updateLicense.LicensesToAssign = licenseList;
this.Context.ConsoleHelper.StartProgress("Assigning License");
// Assign licenses to the user.
var assignLicense = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).LicenseUpdates.Create(updateLicense);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.StartProgress("Getting Assigned License");
// Get customer user assigned licenses information after assigning the license.
var customerUserAssignedLicenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get(groupIds);
this.Context.ConsoleHelper.StopProgress();
Console.WriteLine("License was successfully assigned to the user.");
License userLicense = customerUserAssignedLicenses.Items.First(licenseItem => licenseItem.ProductSku.Id == license.SkuId);
this.Context.ConsoleHelper.WriteObject(userLicense, "Assigned License");
}
}
}

Просмотреть файл

@ -0,0 +1,72 @@
// -----------------------------------------------------------------------
// <copyright file="CustomerUserAssignLicenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using System.Collections.Generic;
using System.Linq;
using Models.Licenses;
/// <summary>
/// Assign customer user a license.
/// </summary>
public class CustomerUserAssignLicenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignLicenses"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CustomerUserAssignLicenses(IScenarioContext context) : base("Assign customer user a license", context)
{
}
/// <summary>
/// Executes the assign customer user a license scenario.
/// </summary>
protected override void RunScenario()
{
// Get the customer user ID.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to assign license");
// Get the customer ID for the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
// Get the product SKU for the license.
string selectedProductSkuId = this.ObtainProductSkuId(selectedCustomerId, "Enter the ID of the product SKU for the license");
var partnerOperations = this.Context.UserPartnerOperations;
// Prepare license request.
LicenseUpdate updateLicense = new LicenseUpdate();
LicenseAssignment license = new LicenseAssignment();
license.SkuId = selectedProductSkuId;
license.ExcludedPlans = null;
List<LicenseAssignment> licenseList = new List<LicenseAssignment>();
licenseList.Add(license);
updateLicense.LicensesToAssign = licenseList;
this.Context.ConsoleHelper.StartProgress("Assigning License");
// Assign licenses to the user.
var assignLicense = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).LicenseUpdates.Create(updateLicense);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.StartProgress("Getting Assigned License");
// Get customer user assigned licenses information after assigning the license.
var customerUserAssignedLicenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get();
this.Context.ConsoleHelper.StopProgress();
Console.WriteLine("License was successfully assigned to the user.");
License userLicense = customerUserAssignedLicenses.Items.First();
this.Context.ConsoleHelper.WriteObject(userLicense, "Assigned License");
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// -----------------------------------------------------------------------
// <copyright file="CustomerUserAssignedGroup1AndGroup2Licenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System.Collections.Generic;
using Models.Licenses;
/// <summary>
/// Get customer user assigned group1 and group2 licenses
/// </summary>
public class CustomerUserAssignedGroup1AndGroup2Licenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignedGroup1AndGroup2Licenses"/> class
/// </summary>
/// <param name="context">The scenario context</param>
public CustomerUserAssignedGroup1AndGroup2Licenses(IScenarioContext context) : base("Get customer user assigned group1 and group2 licenses", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// Get the customer user Id
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get assigned licenses");
// Get the customer Id of the entered customer user
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer user assigned licenses");
// Get the customer user assigned group1 and group2 licenses information
// Group1 – This group has all products whose license can be managed in the Azure Active Directory (AAD).
// Group2 – This group contains products that cant be managed in Azure Active Directory
List<LicenseGroupId> groupIds = new List<LicenseGroupId>() { LicenseGroupId.Group1, LicenseGroupId.Group2 };
var customerUserAssignedGroup1Group2Licenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get(groupIds);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerUserAssignedGroup1Group2Licenses, "Customer User Assigned Group1 and Group2 Licenses");
}
}
}

Просмотреть файл

@ -0,0 +1,47 @@
// -------------------------------------------------------------------------------------
// <copyright file="CustomerUserAssignedGroup1Licenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System.Collections.Generic;
using Models.Licenses;
/// <summary>
/// Get customer user assigned group1 licenses
/// </summary>
public class CustomerUserAssignedGroup1Licenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignedGroup1Licenses"/> class
/// </summary>
/// <param name="context">The scenario context</param>
public CustomerUserAssignedGroup1Licenses(IScenarioContext context) : base("Get customer user assigned group1 licenses", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// Get the customer Id of the entered customer user
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
// Get the customer user Id
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get assigned licenses");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer user assigned licenses");
// Get the customer user assigned group1 licenses information
// Group1 – This group has all products whose license can be managed in the Azure Active Directory (AAD).
List<LicenseGroupId> groupIds = new List<LicenseGroupId>() { LicenseGroupId.Group1 };
var customerUserAssignedGroup1Licenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get(groupIds);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerUserAssignedGroup1Licenses, "Customer User Assigned Group1 Licenses");
}
}
}

Просмотреть файл

@ -0,0 +1,47 @@
// -------------------------------------------------------------------------------------
// <copyright file="CustomerUserAssignedGroup2Licenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System.Collections.Generic;
using Models.Licenses;
/// <summary>
/// Get customer user assigned group2 licenses
/// </summary>
public class CustomerUserAssignedGroup2Licenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignedGroup2Licenses"/> class
/// </summary>
/// <param name="context">The scenario context</param>
public CustomerUserAssignedGroup2Licenses(IScenarioContext context) : base("Get customer user assinged group2 licenses", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// Get the customer Id of the entered customer user
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
// Get the customer user Id
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get assigned licenses");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer user assigned licenses");
// Get the customer user assigned group2 licenses information
// Group2 – This group contains products that cant be managed in Azure Active Directory
List<LicenseGroupId> groupIds = new List<LicenseGroupId>() { LicenseGroupId.Group2 };
var customerUserAssignedGroup2Licenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get(groupIds);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerUserAssignedGroup2Licenses, "Customer User Assigned Group2 Licenses");
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// -----------------------------------------------------------------------
// <copyright file="CustomerUserAssignedLicenses.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
/// <summary>
/// Gets customer user assigned licenses.
/// </summary>
public class CustomerUserAssignedLicenses : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserAssignedLicenses"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CustomerUserAssignedLicenses(IScenarioContext context) : base("Get customer user assigned licenses", context)
{
}
/// <summary>
/// Executes the get customer user assigned licenses scenario.
/// </summary>
protected override void RunScenario()
{
// get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get assigned licenses");
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer user assigned licenses");
// get customer user assigned licenses information.
var customerUserAssignedLicenses = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Licenses.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerUserAssignedLicenses, "Customer User Assigned Licenses");
}
}
}

Просмотреть файл

@ -0,0 +1,50 @@
// -----------------------------------------------------------------------
// <copyright file="CustomerUserRestore.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using Models.Users;
/// <summary>
/// Showcases customer user restore API.
/// </summary>
public class CustomerUserRestore : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomerUserRestore"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CustomerUserRestore(IScenarioContext context) : base("Restore a deleted customer user", context)
{
}
/// <summary>
/// Executes the restore customer user scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the corresponding customer to restore customer user details");
// get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to restore");
var partnerOperations = this.Context.UserPartnerOperations;
var updatedCustomerUser = new CustomerUser()
{
State = UserState.Active
};
this.Context.ConsoleHelper.StartProgress("Restoring the customer user");
// restore customer user information using older upn.
var restoredCustomerUserInfo = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Patch(updatedCustomerUser);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(restoredCustomerUserInfo, "Restored customer user.");
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// -----------------------------------------------------------------------
// <copyright file="DeleteCustomerUser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
/// <summary>
/// Deletes a customer user.
/// </summary>
public class DeleteCustomerUser : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteCustomerUser"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public DeleteCustomerUser(IScenarioContext context) : base("Delete customer user", context)
{
}
/// <summary>
/// Executes the delete customer user scenario.
/// </summary>
protected override void RunScenario()
{
// get customer user to delete.
string customerUserIdToDelete = this.ObtainCustomerUserIdDelete("Enter the ID of the customer user to delete");
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the corresponding customer whose customer user to delete");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Deleting customer user");
// delete customer user
partnerOperations.Customers.ById(selectedCustomerId).Users.ById(customerUserIdToDelete).Delete();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Customer User successfully deleted");
}
}
}

Просмотреть файл

@ -0,0 +1,75 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerInactiveUsers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using Models.Query;
/// <summary>
/// Gets inactive customer users in pages.
/// </summary>
public class GetCustomerInactiveUsers : BasePartnerScenario
{
/// <summary>
/// The customer user page size.
/// </summary>
private int customerUserPageSize;
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerInactiveUsers"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
/// <param name="customeruserPageSize">The number of inactive customer users to return per page.</param>
public GetCustomerInactiveUsers(IScenarioContext context, int customeruserPageSize = 0) : base("Get Paged inactive customer users", context)
{
this.customerUserPageSize = customeruserPageSize;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get all inactive customer users in pages");
var partnerOperations = this.Context.UserPartnerOperations;
// get customer user page size
string customerUserPageSize = this.ObtainCustomerUserPageSize();
this.customerUserPageSize = int.Parse(customerUserPageSize);
var filter = new SimpleFieldFilter("UserStatus", FieldFilterOperation.Equals, "Inactive");
// Read inactive customer users in a batch
this.Context.ConsoleHelper.StartProgress("Querying first page of inactive customer users");
var simpleQueryWithFilter = QueryFactory.Instance.BuildIndexedQuery(this.customerUserPageSize, 0, filter);
var customerUsers = partnerOperations.Customers.ById(selectedCustomerId).Users.Query(simpleQueryWithFilter);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.StartProgress("Creating customer user Enumerator");
var customerUsersEnumerator = partnerOperations.Enumerators.CustomerUsers.Create(customerUsers);
this.Context.ConsoleHelper.StopProgress();
while (customerUsersEnumerator.HasValue)
{
// print the current customer user results
this.Context.ConsoleHelper.WriteObject(customerUsersEnumerator.Current);
Console.WriteLine();
Console.Write("Press any key to retrieve the next customer users page");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Getting Next Page");
// get the next page of customer users
customerUsersEnumerator.Next();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerUserCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
/// <summary>
/// Gets customer user collection.
/// </summary>
public class GetCustomerUserCollection : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerUserCollection"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerUserCollection(IScenarioContext context) : base("Get a customer user collection", context)
{
}
/// <summary>
/// Executes the get customer user collection scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get customer user collection");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer users collection");
// get customer users collection
var customerUsers = partnerOperations.Customers.ById(selectedCustomerId).Users.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerUsers, "Customer Users collection");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerUserDetails.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
/// <summary>
/// Gets a single customer user details.
/// </summary>
public class GetCustomerUserDetails : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerUserDetails"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerUserDetails(IScenarioContext context) : base("Get a customer user details", context)
{
}
/// <summary>
/// Executes the get customer user details scenario.
/// </summary>
protected override void RunScenario()
{
// get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get details");
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the corresponding customer to get customer user details");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer user detail");
// Get customer user detail
var selectedCustomerUser = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(selectedCustomerUser, "Customer User detail");
}
}
}

Просмотреть файл

@ -0,0 +1,50 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerUserDirectoryRoles.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
/// <summary>
/// Gets customer user directory roles details.
/// </summary>
public class GetCustomerUserDirectoryRoles : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerUserDirectoryRoles"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerUserDirectoryRoles(IScenarioContext context) : base("Get customer user directory roles", context)
{
}
/// <summary>
/// Executes the get customer user directory roles scenario.
/// </summary>
protected override void RunScenario()
{
// get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to get directory roles");
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the corresponding customer to get directory roles of customer user");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting selected customer user");
// get customer user.
var selectedCustomerUser = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(selectedCustomerUser, "Selected Customer User");
this.Context.ConsoleHelper.StartProgress("Getting customer user directory roles");
// get customer user directory roles.
var userMemberships = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).DirectoryRoles.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(userMemberships, "Customer User directory roles");
}
}
}

Просмотреть файл

@ -0,0 +1,75 @@
// -----------------------------------------------------------------------
// <copyright file="GetPagedCustomerUsers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using System.Globalization;
using Models.Query;
/// <summary>
/// Gets customer users in pages.
/// </summary>
public class GetPagedCustomerUsers : BasePartnerScenario
{
/// <summary>
/// The customer user page size.
/// </summary>
private int customerUserPageSize;
/// <summary>
/// Initializes a new instance of the <see cref="GetPagedCustomerUsers"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
/// <param name="customeruserPageSize">The number of customer users to return per page.</param>
public GetPagedCustomerUsers(IScenarioContext context, int customeruserPageSize = 0) : base("Get Paged customer users", context)
{
this.customerUserPageSize = customeruserPageSize;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get all customer users in pages");
var partnerOperations = this.Context.UserPartnerOperations;
// get customer user page size
string customerUserPageSize = this.ObtainCustomerUserPageSize();
this.customerUserPageSize = int.Parse(customerUserPageSize);
this.Context.ConsoleHelper.StartProgress("Querying first page of customer users");
// query the customers, get the first page if a page size was set, otherwise get all customers
var customerUsersPage = (this.customerUserPageSize <= 0) ? partnerOperations.Customers.ById(selectedCustomerId).Users.Get() : partnerOperations.Customers.ById(selectedCustomerId).Users.Query(QueryFactory.Instance.BuildIndexedQuery(this.customerUserPageSize));
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.StartProgress("Creating customer user Enumerator");
// create a customer user enumerator which will aid us in traversing the customer user pages
var customerUsersEnumerator = partnerOperations.Enumerators.CustomerUsers.Create(customerUsersPage);
this.Context.ConsoleHelper.StopProgress();
int pageNumber = 1;
while (customerUsersEnumerator.HasValue)
{
// print the current customer user result page
this.Context.ConsoleHelper.WriteObject(customerUsersEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Customer User Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next customer users page");
Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Getting Next Page");
// get the next page of customer users
customerUsersEnumerator.Next();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
// -----------------------------------------------------------------------
// <copyright file="SortCustomerUsers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System.Globalization;
using Models.Query;
/// <summary>
/// Sorts the customer users.
/// </summary>
public class SortCustomerUsers : BasePartnerScenario
{
/// <summary>
/// The sort direction.
/// </summary>
private readonly SortDirection sortDirection;
/// <summary>
/// Initializes a new instance of the <see cref="SortCustomerUsers"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="sortDirection">The sort direction.</param>
/// <param name="context">The scenario context.</param>
public SortCustomerUsers(string title, SortDirection sortDirection, IScenarioContext context) : base(title, context)
{
this.sortDirection = sortDirection;
}
/// <summary>
/// Executes the sort customer users scenario.
/// </summary>
protected override void RunScenario()
{
// get customer Id.
string selectedCustomerId = this.ObtainCustomerId("Enter the customer ID");
var partnerOperations = this.Context.UserPartnerOperations;
// get sort field.
string sortField = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the sort field (DisplayName,UserPrincipalName)", "The entered sort field is empty");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting customer users sorted by {0} in {1} order", sortField, this.sortDirection.ToString()));
// get sorted customer users.
var customerUsers = partnerOperations.Customers
.ById(selectedCustomerId)
.Users
.Query(QueryFactory.Instance.BuildIndexedQuery(20, sortOption: new Sort(sortField, this.sortDirection)));
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerUsers, string.Format(CultureInfo.InvariantCulture, "Sorted Customer Users by {0} in {1} order", sortField, this.sortDirection.ToString()));
}
}
}

Просмотреть файл

@ -0,0 +1,69 @@
// -----------------------------------------------------------------------
// <copyright file="UpdateCustomerUser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.CustomerUser
{
using System;
using Models.Users;
/// <summary>
/// A scenario that updates a customer user.
/// </summary>
public class UpdateCustomerUser : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateCustomerUser"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public UpdateCustomerUser(IScenarioContext context) : base("Update customer user", context)
{
}
/// <summary>
/// Executes the update customer user scenario.
/// </summary>
protected override void RunScenario()
{
// get customer user Id.
string selectedCustomerUserId = this.ObtainCustomerUserId("Enter the ID of the customer user to update details");
// get customer Id of the entered customer user.
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the corresponding customer to update customer user");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer user");
// get customer user.
var selectedCustomerUser = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(selectedCustomerUser, "Selected customer User");
this.Context.ConsoleHelper.StartProgress("Getting customer");
// get customer.
var selectedCustomer = partnerOperations.Customers.ById(selectedCustomerId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(selectedCustomer, "Selected Customer");
var updatedCustomerUser = new CustomerUser()
{
PasswordProfile = new PasswordProfile() { ForceChangePassword = true, Password = "Password!1" },
DisplayName = "Shubham Bharti",
FirstName = "Shubham",
LastName = "Bharti",
UsageLocation = "US",
UserPrincipalName = Guid.NewGuid().ToString("N") + "@" + selectedCustomer.CompanyProfile.Domain
};
this.Context.ConsoleHelper.StartProgress("Updating the customer user");
// update customer user information
var updatedCustomerUserInfo = partnerOperations.Customers.ById(selectedCustomerId).Users.ById(selectedCustomerUserId).Patch(updatedCustomerUser);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(updatedCustomerUserInfo, "Updated customer user information");
}
}
}

Просмотреть файл

@ -0,0 +1,44 @@
// -----------------------------------------------------------------------
// <copyright file="CheckDomainAvailability.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// A scenario that checks if a domain is still available for a customer or not.
/// </summary>
public class CheckDomainAvailability : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckDomainAvailability"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CheckDomainAvailability(IScenarioContext context) : base("Check domain availability", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string domainPrefix = this.Context.ConsoleHelper.ReadNonEmptyString("Enter a domain prefix to check its availability", "The entered domain is empty");
this.Context.ConsoleHelper.StartProgress("Checking");
bool isDomainAvailable = !partnerOperations.Domains.ByDomain(domainPrefix).Exists();
this.Context.ConsoleHelper.StopProgress();
if (isDomainAvailable)
{
this.Context.ConsoleHelper.Success("This domain prefix is available!");
}
else
{
this.Context.ConsoleHelper.Warning("This domain prefix is unavailable.");
}
}
}
}

Просмотреть файл

@ -0,0 +1,70 @@
// -----------------------------------------------------------------------
// <copyright file="CreateCustomer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using System;
using System.Globalization;
using Store.PartnerCenter.Models;
using Store.PartnerCenter.Models.Customers;
/// <summary>
/// Creates a new customer for a partner.
/// </summary>
public class CreateCustomer : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateCustomer"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateCustomer(IScenarioContext context) : base("Create a new customer", context)
{
}
/// <summary>
/// Executes the create customer scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
var customerToCreate = new Customer()
{
CompanyProfile = new CustomerCompanyProfile()
{
Domain = string.Format(CultureInfo.InvariantCulture, "SampleApplication{0}.{1}", new Random().Next(), this.Context.Configuration.Scenario.CustomerDomainSuffix)
},
BillingProfile = new CustomerBillingProfile()
{
Culture = "en-US",
Email = "gena@relecloud2.com",
Language = "en",
CompanyName = "Relecloud" + new Random().Next(),
DefaultAddress = new Address()
{
FirstName = "Gena",
LastName = "Soto",
AddressLine1 = "4567 Main Street",
City = "Redmond",
State = "WA",
Country = "US",
PhoneNumber = "4255550101",
PostalCode = "98052"
}
}
};
this.Context.ConsoleHelper.WriteObject(customerToCreate, "New user Information");
this.Context.ConsoleHelper.StartProgress("Creating user");
var newCustomer = partnerOperations.Customers.Create(customerToCreate);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Success!");
this.Context.ConsoleHelper.WriteObject(newCustomer, "Created user Information");
}
}
}

Просмотреть файл

@ -0,0 +1,50 @@
// -----------------------------------------------------------------------
// <copyright file="DeleteCustomerFromTipAccount.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using System;
/// <summary>
/// Deletes a customer from a testing in production account.
/// </summary>
public class DeleteCustomerFromTipAccount : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteCustomerFromTipAccount"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public DeleteCustomerFromTipAccount(IScenarioContext context) : base("Delete customer from TIP account", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToDelete = this.Context.Configuration.Scenario.CustomerIdToDelete;
if (string.IsNullOrWhiteSpace(customerIdToDelete))
{
// prompt the user the enter the customer ID
customerIdToDelete = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the ID of the customer to delete", "The customer ID can't be empty");
}
else
{
Console.WriteLine("Found customer ID: {0} in configuration.", customerIdToDelete);
}
var partnerOperations = this.Context.AppPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Deleting customer");
partnerOperations.Customers.ById(customerIdToDelete).Delete();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Customer successfully deleted");
}
}
}

Просмотреть файл

@ -0,0 +1,70 @@
// -----------------------------------------------------------------------
// <copyright file="DeletePartnerCustomerRelationship.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using System.Collections.Generic;
using Models;
using Models.Customers;
using Models.Subscriptions;
/// <summary>
/// Deletes a partner customer Relationship production account.
/// </summary>
public class DeletePartnerCustomerRelationship : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="DeletePartnerCustomerRelationship"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public DeletePartnerCustomerRelationship(IScenarioContext context) : base("Delete Partner Relationship", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
// prompt the user the enter the customer ID
var customerIdToDeleteRelationshipOf = this.Context.ConsoleHelper.ReadNonEmptyString("Please enter the ID of the customer you want to delete the relationship with", "The customer ID can't be empty");
// Verify that there are no active subscriptions
ResourceCollection<Subscription> customerSubscriptions = partnerOperations.Customers.ById(customerIdToDeleteRelationshipOf).Subscriptions.Get();
IList<Subscription> subscriptions = new List<Subscription>(customerSubscriptions.Items);
foreach (Subscription customerSubscription in subscriptions)
{
if (customerSubscription.Status == SubscriptionStatus.Active)
{
this.Context.ConsoleHelper.Warning(string.Format("Subscription with ID :{0} OfferName: {1} cannot be in active state, ", customerSubscription.Id, customerSubscription.OfferName));
this.Context.ConsoleHelper.Warning("Please Suspend all the Subscriptions and try again. Aborting the delete customer relationship operation");
this.Context.ConsoleHelper.StopProgress();
return;
}
}
// Delete the customer relationship to partner
this.Context.ConsoleHelper.StartProgress("Deleting customer Partner Relationship");
Customer customer = new Customer
{
RelationshipToPartner = CustomerPartnerRelationship.None
};
customer = partnerOperations.Customers.ById(customerIdToDeleteRelationshipOf).Patch(customer);
if (customer.RelationshipToPartner == CustomerPartnerRelationship.None)
{
this.Context.ConsoleHelper.Success("Customer Partner Relationship successfully deleted");
}
this.Context.ConsoleHelper.StopProgress();
}
}
}

Просмотреть файл

@ -0,0 +1,56 @@
// -----------------------------------------------------------------------
// <copyright file="FilterCustomers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using Store.PartnerCenter.Models.Customers;
using Store.PartnerCenter.Models.Query;
/// <summary>
/// Returns customers according to a provided filter.
/// </summary>
public class FilterCustomers : BasePartnerScenario
{
/// <summary>
/// The search field.
/// </summary>
private readonly CustomerSearchField customerSearchField;
/// <summary>
/// Initializes a new instance of the <see cref="FilterCustomers"/> class.
/// </summary>
/// <param name="title">The scenario title.</param>
/// <param name="customerSearchField">The search field.</param>
/// <param name="context">The scenario context.</param>
public FilterCustomers(string title, CustomerSearchField customerSearchField, IScenarioContext context) : base(title, context)
{
this.customerSearchField = customerSearchField;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string searchPrefix = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the prefix to search for", "The entered prefix is empty");
this.Context.ConsoleHelper.StartProgress("Filtering");
var fieldFilter = new SimpleFieldFilter(
this.customerSearchField.ToString(),
FieldFilterOperation.StartsWith,
searchPrefix);
var myQuery = QueryFactory.Instance.BuildSimpleQuery(fieldFilter);
var customers = partnerOperations.Customers.Query(myQuery);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customers, "Customer matches");
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerDetails.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// Gets a single customer details.
/// </summary>
public class GetCustomerDetails : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerDetails"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerDetails(IScenarioContext context) : base("Get a customer details", context)
{
}
/// <summary>
/// Executes the get customer details scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToRetrieve = this.ObtainCustomerId("Enter the ID of the customer to retrieve");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving customer");
var customerDetails = partnerOperations.Customers.ById(customerIdToRetrieve).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerDetails, "Customer details");
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerManagedServices.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// Gets a customer list of managed services.
/// </summary>
public class GetCustomerManagedServices : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerManagedServices"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerManagedServices(IScenarioContext context) : base("Get customer managed services", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerId = this.ObtainCustomerId();
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting the customer's managed services");
var managedServices = partnerOperations.Customers.ById(customerId).ManagedServices.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(managedServices, "Customer managed services");
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerQualification.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// Gets a single customer qualification.
/// </summary>
public class GetCustomerQualification : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerQualification"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerQualification(IScenarioContext context) : base("Get customer qualification", context)
{
}
/// <summary>
/// Executes the get customer qualification scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToRetrieve = this.ObtainCustomerId("Enter the ID of the customer to retrieve qualification for");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving customer qualification");
var customerQualification = partnerOperations.Customers.ById(customerIdToRetrieve).Qualification.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerQualification, "Customer Qualification");
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomerRelationshipRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// Gets the request which establishes a relationship between the partner and their customers.
/// </summary>
public class GetCustomerRelationshipRequest : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomerRelationshipRequest"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomerRelationshipRequest(IScenarioContext context) : base("Get customer relationship request", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving customer relationship request");
var customerRelationshipRequest = partnerOperations.Customers.RelationshipRequest.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerRelationshipRequest, "Customer relationship request");
}
}
}

Просмотреть файл

@ -0,0 +1,68 @@
// -----------------------------------------------------------------------
// <copyright file="GetPagedCustomers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using System;
using System.Globalization;
using Store.PartnerCenter.Models.Query;
/// <summary>
/// Gets a partner customers in pages.
/// </summary>
public class GetPagedCustomers : BasePartnerScenario
{
/// <summary>
/// The customer page size.
/// </summary>
private readonly int customerPageSize;
/// <summary>
/// Initializes a new instance of the <see cref="GetPagedCustomers"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
/// <param name="customerPageSize">The number of customers to return per page.</param>
public GetPagedCustomers(IScenarioContext context, int customerPageSize = 0) : base("Get Paged customers", context)
{
this.customerPageSize = customerPageSize;
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Querying customers");
// query the customers, get the first page if a page size was set, otherwise get all customers
var customersPage = (this.customerPageSize <= 0) ? partnerOperations.Customers.Get() : partnerOperations.Customers.Query(QueryFactory.Instance.BuildIndexedQuery(this.customerPageSize));
this.Context.ConsoleHelper.StopProgress();
// create a customer enumerator which will aid us in traversing the customer pages
var customersEnumerator = partnerOperations.Enumerators.Customers.Create(customersPage);
int pageNumber = 1;
while (customersEnumerator.HasValue)
{
// print the current customer results page
this.Context.ConsoleHelper.WriteObject(customersEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Customer Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next customers page");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next customers page");
// get the next page of customers
customersEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,51 @@
// -----------------------------------------------------------------------
// <copyright file="UpdateCustomerBillingProfile.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// A scenario that updates a customer's billing profile.
/// </summary>
public class UpdateCustomerBillingProfile : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateCustomerBillingProfile"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public UpdateCustomerBillingProfile(IScenarioContext context) : base("Update customer billing profile", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerId = this.ObtainCustomerId();
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customer billing profile");
var billingProfile = partnerOperations.Customers.ById(customerId).Profiles.Billing.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(billingProfile, "Customer billing profile");
this.Context.ConsoleHelper.StartProgress("Updating the customer billing profile");
// append some A's to some of the customer's billing profile properties
billingProfile.FirstName = billingProfile.FirstName + "A";
billingProfile.LastName = billingProfile.LastName + "A";
billingProfile.CompanyName = billingProfile.CompanyName + "A";
// update the billing profile
var updatedBillingProfile = partnerOperations.Customers.ById(customerId).Profiles.Billing.Update(billingProfile);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(updatedBillingProfile, "Updated customer billing profile");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="UpdateCustomerQualification.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using Microsoft.Store.PartnerCenter.Models.Customers;
/// <summary>
/// Updates a single customer qualification.
/// </summary>
public class UpdateCustomerQualification : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateCustomerQualification"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public UpdateCustomerQualification(IScenarioContext context) : base("Update customer qualification", context)
{
}
/// <summary>
/// Executes the update customer qualification scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToRetrieve = this.ObtainCustomerId($"Enter the ID of the customer to update qualification to {CustomerQualification.Education}");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Updating customer qualification");
var customerQualification =
partnerOperations.Customers.ById(customerIdToRetrieve)
.Qualification.Update(CustomerQualification.Education);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(customerQualification, "Customer Qualification");
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
// -----------------------------------------------------------------------
// <copyright file="ValidateCustomerAddress.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
/// <summary>
/// A scenario that showcases country validation rules.
/// </summary>
public class ValidateCustomerAddress : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidateCustomerAddress"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public ValidateCustomerAddress(IScenarioContext context) : base("Validate customer address.", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string countryCode = this.Context.ConsoleHelper.ReadNonEmptyString("Enter the 2 digit country code to get its validation rules", "The country code can't be empty");
this.Context.ConsoleHelper.StartProgress("Retrieving country validation rules");
var countryValidationRules = partnerOperations.CountryValidationRules.ByCountry(countryCode).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(countryValidationRules, " Country validation rules");
}
}
}

Просмотреть файл

@ -0,0 +1,50 @@
// -----------------------------------------------------------------------
// <copyright file="CreateConfigurationPolicy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
using System.Collections.Generic;
using Microsoft.Store.PartnerCenter.Models.DevicesDeployment;
/// <summary>
/// Creates a new configuration policy for devices.
/// </summary>
public class CreateConfigurationPolicy : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateConfigurationPolicy"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateConfigurationPolicy(IScenarioContext context) : base("Create a new configuration policy", context)
{
}
/// <summary>
/// Executes the create configuration policy scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to create the configuration policy for");
var configurationPolicyToCreate = new ConfigurationPolicy
{
Name = "Test Config Policy",
Description = "This configuration policy is created by the SDK samples",
PolicySettings = new List<PolicySettingsType>() { PolicySettingsType.OobeUserNotLocalAdmin, PolicySettingsType.SkipEula }
};
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.WriteObject(configurationPolicyToCreate, "New configuration policy Information");
this.Context.ConsoleHelper.StartProgress("Creating Configuration Policy");
var createdConfigurationPolicy = partnerOperations.Customers.ById(selectedCustomerId).ConfigurationPolicies.Create(configurationPolicyToCreate);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Success!");
this.Context.ConsoleHelper.WriteObject(createdConfigurationPolicy, "Created configuration policy Information");
}
}
}

Просмотреть файл

@ -0,0 +1,60 @@
// -----------------------------------------------------------------------
// <copyright file="CreateDeviceBatch.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
using System.Collections.Generic;
using Microsoft.Store.PartnerCenter.Models.DevicesDeployment;
/// <summary>
/// Creates a new device batch with devices.
/// </summary>
public class CreateDeviceBatch : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateDeviceBatch"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateDeviceBatch(IScenarioContext context) : base("Create a new Device Batch", context)
{
}
/// <summary>
/// Executes the create device batch scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to create the device batch for");
List<Device> devicesToBeUploaded = new List<Device>
{
new Device
{
HardwareHash = "DummyHash123",
ProductKey = "00329-00000-0003-AA606",
SerialNumber = "1R9-ZNP67"
}
};
DeviceBatchCreationRequest newDeviceBatch = new DeviceBatchCreationRequest
{
BatchId = "SDKTestDeviceBatch",
Devices = devicesToBeUploaded
};
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.WriteObject(newDeviceBatch, "New Device Batch");
this.Context.ConsoleHelper.StartProgress("Creating Device Batch");
var trackingLocation = partnerOperations.Customers.ById(selectedCustomerId).DeviceBatches.Create(newDeviceBatch);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(trackingLocation, "Tracking Location to track the status");
this.Context.ConsoleHelper.Success("Create Device Batch Request submitted successfully!");
}
}
}

Просмотреть файл

@ -0,0 +1,63 @@
// -----------------------------------------------------------------------
// <copyright file="CreateDevices.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
using System.Collections.Generic;
using Microsoft.Store.PartnerCenter.Models.DevicesDeployment;
/// <summary>
/// Creates new devices under an existing device batch.
/// </summary>
public class CreateDevices : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateDevices"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateDevices(IScenarioContext context) : base("Create new Devices", context)
{
}
/// <summary>
/// Executes the create device batch scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to create the devices for");
string selectedDeviceBatchId = this.ObtainDeviceBatchId("Enter the ID of the Device batch to add the devices to");
var partnerOperations = this.Context.UserPartnerOperations;
List<Device> devicesToBeUploaded = new List<Device>
{
new Device
{
HardwareHash = "DummyHash1234",
ProductKey = "00329-00000-0003-AA606",
SerialNumber = "2R9-ZNP67"
},
new Device
{
HardwareHash = "DummyHash12345",
ProductKey = "00329-00000-0003-AA606",
SerialNumber = "2R9-ZNP67"
}
};
this.Context.ConsoleHelper.WriteObject(devicesToBeUploaded, "New Devices");
this.Context.ConsoleHelper.StartProgress("Creating Devices");
var trackingLocation = partnerOperations.Customers.ById(selectedCustomerId).DeviceBatches.ById(selectedDeviceBatchId).Devices.Create(devicesToBeUploaded);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(trackingLocation, "Tracking Location to track the status");
this.Context.ConsoleHelper.Success("Create Devices Request submitted successfully!");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="DeleteConfigurationPolicy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Deletes a configuration policy.
/// </summary>
public class DeleteConfigurationPolicy : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConfigurationPolicy"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public DeleteConfigurationPolicy(IScenarioContext context) : base("Delete a configuration policy", context)
{
}
/// <summary>
/// Executes the create device batch scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to delete a configuration policy");
string selectedPolicyId = this.ObtainConfigurationPolicyId("Enter the ID of the configuration policy to delete");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.WriteObject(selectedPolicyId, "Configuration policy to be deleted");
this.Context.ConsoleHelper.StartProgress("Deleting Configuration policy");
partnerOperations.Customers.ById(selectedCustomerId).ConfigurationPolicies.ById(selectedPolicyId).Delete();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Delete Configuration policy request submitted successfully!");
}
}
}

Просмотреть файл

@ -0,0 +1,44 @@
// -----------------------------------------------------------------------
// <copyright file="DeleteDevice.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Deletes a device.
/// </summary>
public class DeleteDevice : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteDevice"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public DeleteDevice(IScenarioContext context) : base("Deletes a device", context)
{
}
/// <summary>
/// Executes the delete device scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to delete a device");
string selectedDeviceBatchId = this.ObtainDeviceBatchId("Enter the ID of the Device batch to retrieve the devices of");
string selectedDeviceId = this.ObtainDeviceId("Enter the ID of the device to delete");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.WriteObject(selectedDeviceId, "Device to be deleted");
this.Context.ConsoleHelper.StartProgress("Deleting device");
partnerOperations.Customers.ById(selectedCustomerId).DeviceBatches.ById(selectedDeviceBatchId).Devices.ById(selectedDeviceId).Delete();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Deleted the device successfully!");
}
}
}

Просмотреть файл

@ -0,0 +1,39 @@
// -----------------------------------------------------------------------
// <copyright file="GetAllConfigurationPolicies.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Gets all configuration policies of a customer.
/// </summary>
public class GetAllConfigurationPolicies : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAllConfigurationPolicies"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetAllConfigurationPolicies(IScenarioContext context) : base("Get all configuration policies", context)
{
}
/// <summary>
/// Executes get all configuration policies scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the ID of the customer to get the configuration policies");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Querying Configuration policies");
var configPolicies = partnerOperations.Customers.ById(selectedCustomerId).ConfigurationPolicies.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(configPolicies, "Configuration Policies");
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetBatchUploadStatus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Gets batch upload status.
/// </summary>
public class GetBatchUploadStatus : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBatchUploadStatus"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetBatchUploadStatus(IScenarioContext context) : base("Get Batch Upload Status", context)
{
}
/// <summary>
/// Executes the create device batch scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the Customer Id to get the status for");
string selectedTrackingId = this.ObtainBatchUploadStatusTrackingId("Enter the batch upload status tracking Id to get the status of");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Querying the status");
var status = partnerOperations.Customers.ById(selectedCustomerId).BatchUploadStatus.ById(selectedTrackingId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(status, "Tracking Status");
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
// -----------------------------------------------------------------------
// <copyright file="GetDevices.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Gets devices of a device batch.
/// </summary>
public class GetDevices : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDevices"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetDevices(IScenarioContext context) : base("Get Devices", context)
{
}
/// <summary>
/// Executes the create device batch scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the Customer Id to get the devices for");
string selectedDeviceBatchId = this.ObtainDeviceBatchId("Enter the ID of the Device batch to retrieve the devices of");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Querying for the devices");
var devices = partnerOperations.Customers.ById(selectedCustomerId).DeviceBatches.ById(selectedDeviceBatchId).Devices.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(devices, "Devices");
}
}
}

Просмотреть файл

@ -0,0 +1,39 @@
// -----------------------------------------------------------------------
// <copyright file="GetDevicesBatches.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
/// <summary>
/// Gets devices batches.
/// </summary>
public class GetDevicesBatches : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDevicesBatches"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetDevicesBatches(IScenarioContext context) : base("Get Devices Batches", context)
{
}
/// <summary>
/// Executes the create device batch scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the Customer Id to get the devices batches for");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Querying for the devices batches");
var devicesBatches = partnerOperations.Customers.ById(selectedCustomerId).DeviceBatches.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(devicesBatches, "Device Batches");
}
}
}

Просмотреть файл

@ -0,0 +1,51 @@
// -----------------------------------------------------------------------
// <copyright file="UpdateConfigurationPolicy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
using System.Collections.Generic;
using Microsoft.Store.PartnerCenter.Models.DevicesDeployment;
/// <summary>
/// Updates configuration policy.
/// </summary>
public class UpdateConfigurationPolicy : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateConfigurationPolicy"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public UpdateConfigurationPolicy(IScenarioContext context) : base("Update configuration policy", context)
{
}
/// <summary>
/// Executes the update configuration policy scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the Customer Id to update the configuration policy for");
string selectedConfigurationPolicyId = this.ObtainConfigurationPolicyId("Enter the ID of the Configuration Policy to update");
ConfigurationPolicy configPolicyToBeUpdated = new ConfigurationPolicy()
{
Name = "Test Config Policy",
Id = selectedConfigurationPolicyId,
PolicySettings = new List<PolicySettingsType>() { PolicySettingsType.OobeUserNotLocalAdmin, PolicySettingsType.RemoveOemPreinstalls }
};
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Updating Configuration Policy");
ConfigurationPolicy updatedConfigurationPolicy = partnerOperations.Customers.ById(selectedCustomerId).ConfigurationPolicies.ById(selectedConfigurationPolicyId).Patch(configPolicyToBeUpdated);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(updatedConfigurationPolicy, "Updated Configuration Policy");
}
}
}

Просмотреть файл

@ -0,0 +1,66 @@
// -----------------------------------------------------------------------
// <copyright file="UpdateDevicesPolicy.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.DevicesDeployment
{
using System.Collections.Generic;
using Microsoft.Store.PartnerCenter.Models.DevicesDeployment;
/// <summary>
/// Updates devices with configuration policy.
/// </summary>
public class UpdateDevicesPolicy : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateDevicesPolicy"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public UpdateDevicesPolicy(IScenarioContext context) : base("Update configuration policy of devices", context)
{
}
/// <summary>
/// Executes the update devices scenario.
/// </summary>
protected override void RunScenario()
{
string selectedCustomerId = this.ObtainCustomerId("Enter the Customer Id to update the devices for");
string selectedConfigurationPolicyId = this.ObtainConfigurationPolicyId("Enter the ID of the Configuration Policy to update the device with");
string selectedDeviceId = this.ObtainDeviceId("Enter the Device Id to update");
List<KeyValuePair<PolicyCategory, string>> policyToBeAdded = new List<KeyValuePair<PolicyCategory, string>>
{
new KeyValuePair<PolicyCategory, string>(PolicyCategory.OOBE, selectedConfigurationPolicyId)
};
List<Device> devices = new List<Device>
{
new Device
{
Id = selectedDeviceId,
Policies = policyToBeAdded
}
};
DevicePolicyUpdateRequest devicePolicyUpdateRequest = new DevicePolicyUpdateRequest
{
Devices = devices
};
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Updating Devices with Configuration Policy");
var trackingLocation = partnerOperations.Customers.ById(selectedCustomerId).DevicePolicy.Update(devicePolicyUpdateRequest);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(trackingLocation, "Tracking Location to track the status");
this.Context.ConsoleHelper.Success("Update Devices Request submitted successfully!");
}
}
}

Просмотреть файл

@ -0,0 +1,70 @@
// -----------------------------------------------------------------------
// <copyright file="GetEntitlements.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Entitlements
{
using System;
using System.Linq;
using Models.Entitlements;
/// <summary>
/// Get customer entitlements.
/// </summary>
public class GetEntitlements : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetEntitlements"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetEntitlements(IScenarioContext context) : base("Get entitlements", context)
{
}
/// <summary>
/// Executes the get customer entitlements scenario.
/// </summary>
protected override void RunScenario()
{
string customerIdToRetrieve = this.ObtainCustomerId("Enter the ID of the customer to retrieve entitlements for");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Retrieving customer entitlements");
var entitlements = partnerOperations.Customers.ById(customerIdToRetrieve).Entitlements.Get();
this.Context.ConsoleHelper.StopProgress();
foreach (var entitlement in entitlements.Items)
{
this.Context.ConsoleHelper.WriteObject(entitlement, "Entitlement details");
try
{
switch (entitlement.EntitlementType.ToLowerInvariant())
{
case "reservedinstance":
var reservedInstanceArtifactDetailsLink =
((ReservedInstanceArtifact)entitlement.EntitledArtifacts.FirstOrDefault(x => string.Equals(x.ArtifactType, "ReservedInstance", StringComparison.OrdinalIgnoreCase)))?.Link;
if (reservedInstanceArtifactDetailsLink != null)
{
var reservedInstanceArtifactDetails =
reservedInstanceArtifactDetailsLink
.InvokeAsync<ReservedInstanceArtifactDetails>(partnerOperations)
.Result;
this.Context.ConsoleHelper.WriteObject(reservedInstanceArtifactDetails);
}
break;
}
}
catch (Exception ex)
{
this.Context.ConsoleHelper.WriteObject(ex.Message, "Artifact Details");
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,311 @@
// -----------------------------------------------------------------------
// <copyright file="ConsoleHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Helpers
{
using System;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Store.PartnerCenter.Models;
/// <summary>
/// Provides useful helpers that aid in writing to the console.
/// </summary>
public class ConsoleHelper : IDisposable
{
/// <summary>
/// A lazy reference to the singleton console helper instance.
/// </summary>
private static Lazy<ConsoleHelper> instance = new Lazy<ConsoleHelper>(() => new ConsoleHelper());
/// <summary>
/// A task that displays progress indicator on the console.
/// </summary>
private Task progressBackgroundTask;
/// <summary>
/// A token source which controls cancelling the progress indicator.
/// </summary>
private CancellationTokenSource progressCancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// Prevents a default instance of the <see cref="ConsoleHelper"/> class from being created.
/// </summary>
private ConsoleHelper()
{
}
/// <summary>
/// Gets the single instance of the <see cref="ConsoleHelper"/>.
/// </summary>
public static ConsoleHelper Instance
{
get
{
return ConsoleHelper.instance.Value;
}
}
/// <summary>
/// Writes a success message to the console.
/// </summary>
/// <param name="message">The message to write.</param>
/// <param name="newLine">Whether or not to write a new line after the message.</param>
public void Success(string message, bool newLine = true)
{
this.WriteColored(message, ConsoleColor.Green, newLine);
}
/// <summary>
/// Writes a progress message to the console and starts a progress animation.
/// </summary>
/// <param name="message">The progress message to write.</param>
public void StartProgress(string message)
{
if (this.progressBackgroundTask == null || this.progressBackgroundTask.Status != TaskStatus.Running)
{
this.progressBackgroundTask = new Task(() =>
{
int dotCounter = 0;
while (!this.progressCancellationTokenSource.Token.IsCancellationRequested)
{
var initialCursorPositionX = Console.CursorLeft;
var initialCursorPositionY = Console.CursorTop;
for (dotCounter = 0; dotCounter < 5; dotCounter++)
{
this.WriteColored(".", ConsoleColor.DarkCyan, false);
Thread.Sleep(200);
if (this.progressCancellationTokenSource.Token.IsCancellationRequested)
{
return;
}
}
// Erase dots.
Console.SetCursorPosition(initialCursorPositionX, initialCursorPositionY);
for (int i = 0; i < dotCounter; ++i)
{
Console.Write(" ");
}
Console.SetCursorPosition(initialCursorPositionX, initialCursorPositionY);
}
});
Console.WriteLine();
this.WriteColored(message, ConsoleColor.DarkCyan, false);
this.progressBackgroundTask.Start();
}
}
/// <summary>
/// Stops the progress animation.
/// </summary>
public void StopProgress()
{
if (this.progressBackgroundTask != null && this.progressBackgroundTask.Status == TaskStatus.Running)
{
this.progressCancellationTokenSource.Cancel();
this.progressBackgroundTask.Wait();
this.progressBackgroundTask.Dispose();
this.progressBackgroundTask = null;
this.progressCancellationTokenSource.Dispose();
this.progressCancellationTokenSource = new CancellationTokenSource();
Console.WriteLine();
Console.WriteLine();
}
}
/// <summary>
/// Writes a warning message to the console.
/// </summary>
/// <param name="message">The message to write.</param>
/// <param name="newLine">Whether or not to write a new line after the message.</param>
public void Warning(string message, bool newLine = true)
{
this.WriteColored(message, ConsoleColor.Yellow, newLine);
}
/// <summary>
/// Writes an error message to the console.
/// </summary>
/// <param name="message">The message to write.</param>
/// <param name="newLine">Whether or not to write a new line after the message.</param>
public void Error(string message, bool newLine = true)
{
this.WriteColored(message, ConsoleColor.Red, newLine);
}
/// <summary>
/// Writes a message with the requested color to the console.
/// </summary>
/// <param name="message">The message to write.</param>
/// <param name="color">The console color to use.</param>
/// <param name="newLine">Whether or not to write a new line after the message.</param>
public void WriteColored(string message, ConsoleColor color, bool newLine = true)
{
Console.ForegroundColor = color;
Console.Write(message + (newLine ? "\n" : string.Empty));
Console.ResetColor();
}
/// <summary>
/// Reads a non empty string from the console.
/// </summary>
/// <param name="promptMessage">The prompt message to display.</param>
/// <param name="validationMessage">The error message to show in case of user input error.</param>
/// <returns>The string input from the console.</returns>
public string ReadNonEmptyString(string promptMessage, string validationMessage = default(string))
{
string input = string.Empty;
validationMessage = validationMessage ?? "Enter a non-empty value";
while (true)
{
Console.Write("{0}: ", promptMessage);
input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
this.Error(validationMessage);
}
else
{
break;
}
}
return input;
}
/// <summary>
/// Reads a string from the console (it can be empty as it is intended to be used with optional values).
/// </summary>
/// <param name="promptMessage">The prompt message to display.</param>
/// <returns>The string input from the console.</returns>
public string ReadOptionalString(string promptMessage)
{
string input = string.Empty;
Console.Write("{0}: ", promptMessage);
input = Console.ReadLine();
return input;
}
/// <summary>
/// Writes an object and its properties recursively to the console. Properties are automatically indented.
/// </summary>
/// <param name="object">The object to print to the console.</param>
/// <param name="title">An optional title to display.</param>
/// <param name="indent">The starting indentation.</param>
public void WriteObject(object @object, string title = default(string), int indent = 0)
{
if (@object == null)
{
return;
}
const int TabSize = 4;
bool isTitlePresent = !string.IsNullOrWhiteSpace(title);
string indentString = new string(' ', indent * TabSize);
Type objectType = @object.GetType();
var collection = @object as ICollection;
if (objectType.Assembly.FullName == typeof(ResourceBase).Assembly.FullName && objectType.IsClass)
{
// this is a partner SDK model class, iterate over it's properties recursively
if (indent == 0 && !string.IsNullOrWhiteSpace(title))
{
Console.WriteLine(title);
Console.WriteLine(new string('-', 90));
}
else if (isTitlePresent)
{
this.WriteColored(string.Format(CultureInfo.InvariantCulture, "{0}{1}: ", indentString, title), ConsoleColor.Yellow);
}
else
{
// since the current element does not have a title, we do not want to shift it's children causing a double shift appearance
// to the user
indent--;
}
PropertyInfo[] properties = objectType.GetProperties();
foreach (PropertyInfo property in properties)
{
this.WriteObject(property.GetValue(@object), property.Name, indent + 1);
}
if (indent == 0 && !string.IsNullOrWhiteSpace(title))
{
Console.WriteLine(new string('-', 90));
}
}
else if (collection != null)
{
// this is a collection, loop through its element and print them recursively
this.WriteColored(string.Format(CultureInfo.InvariantCulture, isTitlePresent ? "{0}{1}: " : string.Empty, indentString, title), ConsoleColor.Yellow);
foreach (var element in collection)
{
this.WriteObject(element, indent: indent + 1);
var elementType = element.GetType();
if (indent == 1)
{
Console.WriteLine(new string('-', 80));
}
}
}
else
{
// print the object as is
this.WriteColored(string.Format(CultureInfo.InvariantCulture, isTitlePresent ? "{0}{1}: " : "{0}", indentString, title), ConsoleColor.DarkYellow, false);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}", @object));
}
}
/// <summary>
/// Disposes of the console helper instance.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes of the console helper instance.
/// </summary>
/// <param name="shouldDispose">Whether to dispose the object or not.</param>
private void Dispose(bool shouldDispose)
{
if (shouldDispose)
{
this.StopProgress();
if (this.progressBackgroundTask != null)
{
this.progressBackgroundTask.Dispose();
}
if (this.progressCancellationTokenSource != null)
{
this.progressCancellationTokenSource.Dispose();
this.progressCancellationTokenSource = null;
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
// -----------------------------------------------------------------------
// <copyright file="IPartnerScenario.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples
{
using System.Collections.Generic;
/// <summary>
/// Represents a partner scenario that demos one or more related partner center APIs.
/// </summary>
public interface IPartnerScenario
{
/// <summary>
/// Gets the scenario title.
/// </summary>
string Title { get; }
/// <summary>
/// Gets the children scenarios of the current scenario.
/// </summary>
IReadOnlyList<IPartnerScenario> Children { get; }
/// <summary>
/// Gets the scenario context.
/// </summary>
IScenarioContext Context { get; }
/// <summary>
/// Runs the scenario.
/// </summary>
void Run();
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="IScenarioContext.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples
{
using Configuration;
using Helpers;
using Store.PartnerCenter;
/// <summary>
/// Holds context properties useful to the scenarios.
/// </summary>
public interface IScenarioContext
{
/// <summary>
/// Gets a partner operations instance which is user based authenticated.
/// </summary>
IAggregatePartner UserPartnerOperations { get; }
/// <summary>
/// Gets a partner operations instance which is application based authenticated.
/// </summary>
IAggregatePartner AppPartnerOperations { get; }
/// <summary>
/// Gets a configuration instance.
/// </summary>
ConfigurationManager Configuration { get; }
/// <summary>
/// Gets a console helper instance.
/// </summary>
ConsoleHelper ConsoleHelper { get; }
}
}

Просмотреть файл

@ -0,0 +1,77 @@
// -----------------------------------------------------------------------
// <copyright file="CreateCustomerForIndirectReseller.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Customers
{
using System;
using System.Globalization;
using Models;
using Models.Customers;
/// <summary>
/// Creates a new customer for an indirect reseller.
/// </summary>
public class CreateCustomerForIndirectReseller : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateCustomerForIndirectReseller"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public CreateCustomerForIndirectReseller(IScenarioContext context) : base("Create a new customer for an indirect reseller", context)
{
}
/// <summary>
/// executes the create customer scenario.
/// </summary>
protected override void RunScenario()
{
var indirectResellerId = this.ObtainIndirectResellerId("Enter the ID of the indirect reseller: ");
var partnerOperations = this.Context.UserPartnerOperations;
var customerToCreate = new Customer()
{
CompanyProfile = new CustomerCompanyProfile()
{
Domain = string.Format(
CultureInfo.InvariantCulture,
"WingtipToys{0}.{1}",
new Random().Next(),
this.Context.Configuration.Scenario.CustomerDomainSuffix)
},
BillingProfile = new CustomerBillingProfile()
{
Culture = "EN-US",
Email = "Gena@wingtiptoys.com",
Language = "En",
CompanyName = "Wingtip Toys" + new Random().Next(),
DefaultAddress = new Address()
{
FirstName = "Gena",
LastName = "Soto",
AddressLine1 = "One Microsoft Way",
City = "Redmond",
State = "WA",
Country = "US",
PostalCode = "98052",
PhoneNumber = "4255550101"
}
},
AssociatedPartnerId = indirectResellerId
};
this.Context.ConsoleHelper.WriteObject(customerToCreate, "New user Information");
this.Context.ConsoleHelper.StartProgress("Creating user");
var newCustomer = partnerOperations.Customers.Create(customerToCreate);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.Success("Success!");
this.Context.ConsoleHelper.WriteObject(newCustomer, "Created user Information");
}
}
}

Просмотреть файл

@ -0,0 +1,76 @@
// -----------------------------------------------------------------------
// <copyright file="GetCustomersOfIndirectReseller.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectModel
{
using System;
using System.Globalization;
using Models.Customers;
using Models.Query;
/// <summary>
/// A scenario that retrieves the list of customers associated to an indirect reseller.
/// </summary>
public class GetCustomersOfIndirectReseller : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetCustomersOfIndirectReseller"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetCustomersOfIndirectReseller(IScenarioContext context) : base("Get customers of indirect reseller", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var indirectResellerId = this.ObtainIndirectResellerId("Enter the ID of the indirect reseller: ");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting customers of the indirect reseller");
// Create a simple field filter.
var filter = new SimpleFieldFilter(
CustomerSearchField.IndirectReseller.ToString(),
FieldFilterOperation.StartsWith,
indirectResellerId);
// Create an iQuery object to pass to the Query method.
var myQuery = QueryFactory.Instance.BuildSimpleQuery(filter);
// Get the collection of matching customers.
var customersPage = partnerOperations.Customers.Query(myQuery);
this.Context.ConsoleHelper.StopProgress();
// Create a customer enumerator which will aid us in traversing the customer pages.
var customersEnumerator = partnerOperations.Enumerators.Customers.Create(customersPage);
int pageNumber = 1;
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Customers of indirect reseller: {0}", indirectResellerId));
while (customersEnumerator.HasValue)
{
// Print the current customer results page.
this.Context.ConsoleHelper.WriteObject(customersEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Customer Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next customers page");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next customers page");
// Get the next page of customers.
customersEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
// -----------------------------------------------------------------------
// <copyright file="GetIndirectResellers.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectModel
{
using Models.Relationships;
/// <summary>
/// A scenario that retrieves the list of indirect resellers associated to the indirect CSP partner
/// </summary>
public class GetIndirectResellers : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetIndirectResellers"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetIndirectResellers(IScenarioContext context) : base("Get indirect resellers", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting indirect resellers");
var indirectResellers = partnerOperations.Relationships.Get(PartnerRelationshipType.IsIndirectCloudSolutionProviderOf);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(indirectResellers, "Indirect Resellers");
}
}
}

Просмотреть файл

@ -0,0 +1,42 @@
// -----------------------------------------------------------------------
// <copyright file="GetIndirectResellersOfCustomer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectModel
{
using System.Globalization;
/// <summary>
/// A scenario that retrieves the list of indirect resellers associated to the indirect CSP partner of a customer.
/// </summary>
public class GetIndirectResellersOfCustomer : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetIndirectResellersOfCustomer"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetIndirectResellersOfCustomer(IScenarioContext context) : base("Get indirect resellers of a customer", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var customerId = this.ObtainCustomerId("Enter the ID of the customer: ");
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting indirect resellers of a customer");
var indirectResellers = partnerOperations.Customers[customerId].Relationships.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(
indirectResellers,
string.Format(CultureInfo.InvariantCulture, "Indirect Resellers of customer: {0}", customerId));
}
}
}

Просмотреть файл

@ -0,0 +1,43 @@
// -----------------------------------------------------------------------
// <copyright file="GetSubscriptionsByMpnId.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectModel
{
using System.Globalization;
/// <summary>
/// A scenario that gets a customer's subscriptions which belong to a partner MPN ID.
/// </summary>
public class GetSubscriptionsByMpnId : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetSubscriptionsByMpnId"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetSubscriptionsByMpnId(IScenarioContext context) : base("Get customer subscriptions by partner MPN ID", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerId = this.ObtainCustomerId();
string partnerMpnId = this.ObtainMpnId();
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting subscriptions");
var customerSubscriptionsByMpnId = partnerOperations.Customers.ById(customerId).Subscriptions.ByPartner(partnerMpnId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(
customerSubscriptionsByMpnId,
string.Format(CultureInfo.InvariantCulture, "Customer subscriptions by MPN ID: {0}", partnerMpnId));
}
}
}

Просмотреть файл

@ -0,0 +1,71 @@
// -----------------------------------------------------------------------
// <copyright file="PlaceOrderForCustomer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Orders
{
using System;
using System.Collections.Generic;
using System.Linq;
using Models.Orders;
using Models.Relationships;
/// <summary>
/// A scenario that creates a new order for a customer with an indirect reseller.
/// </summary>
public class PlaceOrderForCustomer : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="PlaceOrderForCustomer"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public PlaceOrderForCustomer(IScenarioContext context) : base("Create an order for a customer of an indirect reseller", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string customerId = this.ObtainCustomerId("Enter the ID of the customer making the purchase");
string offerId = this.ObtainOfferId("Enter the ID of the offer to purchase");
string indirectResellerId = this.ObtainIndirectResellerId("Enter the ID of the indirect reseller: ");
this.Context.ConsoleHelper.StartProgress("Getting list of indirect resellers");
var indirectResellers = partnerOperations.Relationships.Get(PartnerRelationshipType.IsIndirectCloudSolutionProviderOf);
this.Context.ConsoleHelper.StopProgress();
var selectedIndirectReseller = (indirectResellers != null && indirectResellers.Items.Any()) ?
indirectResellers.Items.FirstOrDefault(reseller => reseller.Id.Equals(indirectResellerId, StringComparison.OrdinalIgnoreCase)) :
null;
var order = new Order()
{
ReferenceCustomerId = customerId,
LineItems = new List<OrderLineItem>()
{
new OrderLineItem()
{
OfferId = offerId,
FriendlyName = "new offer purchase",
Quantity = 5,
PartnerIdOnRecord = selectedIndirectReseller != null ? selectedIndirectReseller.MpnId : null
}
}
};
this.Context.ConsoleHelper.WriteObject(order, "Order to be placed");
this.Context.ConsoleHelper.StartProgress("Placing order");
var createdOrder = partnerOperations.Customers.ById(customerId).Orders.Create(order);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(createdOrder, "Created order");
}
}
}

Просмотреть файл

@ -0,0 +1,47 @@
// -----------------------------------------------------------------------
// <copyright file="VerifyPartnerMpnId.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectModel
{
using System.Globalization;
/// <summary>
/// A scenario that verifies a partner MPN ID.
/// </summary>
public class VerifyPartnerMpnId : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="VerifyPartnerMpnId"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public VerifyPartnerMpnId(IScenarioContext context) : base("Verify partner MPN ID", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting the logged in partner's profile");
var currentPartnerProfile = partnerOperations.Profiles.MpnProfile.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(currentPartnerProfile, "Logged in partner profile");
string partnerMpnId = this.ObtainMpnId("Enter the MPN ID to verify");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting the partner profile for MPN ID: {0}", partnerMpnId));
var partnerProfile = partnerOperations.Profiles.MpnProfile.Get(partnerMpnId);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(partnerProfile, "Partner profile");
}
}
}

Просмотреть файл

@ -0,0 +1,44 @@
// -----------------------------------------------------------------------
// <copyright file="GetSubscriptionsByMpnId.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectPartners
{
using System;
using System.Globalization;
/// <summary>
/// A scenario that gets a customer's subscriptions which belong to a partner MPN ID.
/// </summary>
public class GetSubscriptionsByMpnId : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetSubscriptionsByMpnId"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetSubscriptionsByMpnId(IScenarioContext context) : base("Get customer subscriptions by partner MPN ID", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
string customerId = this.ObtainCustomerId();
string partnerMpnId = this.ObtainMpnId();
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting subscriptions");
var customerSubscriptionsByMpnId = partnerOperations.Customers.ById(customerId).Subscriptions.ByPartner(partnerMpnId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(
customerSubscriptionsByMpnId,
string.Format(CultureInfo.InvariantCulture, "Customer subscriptions by MPN ID: {0}", partnerMpnId));
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
// -----------------------------------------------------------------------
// <copyright file="VerifyPartnerMpnId.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.IndirectPartners
{
using System;
using System.Globalization;
/// <summary>
/// A scenario that verifies a partner MPN ID.
/// </summary>
public class VerifyPartnerMpnId : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="VerifyPartnerMpnId"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public VerifyPartnerMpnId(IScenarioContext context) : base("Verify partner MPN ID", context)
{
}
/// <summary>
/// Executes the scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting the logged in partner's profile");
var currentPartnerProfile = partnerOperations.Profiles.MpnProfile.Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(currentPartnerProfile, "Logged in partner profile");
string partnerMpnId = this.ObtainMpnId("Enter the MPN ID to verify");
this.Context.ConsoleHelper.StartProgress(string.Format(CultureInfo.InvariantCulture, "Getting the partner profile for MPN ID: {0}", partnerMpnId));
var partnerProfile = partnerOperations.Profiles.MpnProfile.Get(partnerMpnId);
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(partnerProfile, "Partner profile");
}
}
}

Просмотреть файл

@ -0,0 +1,37 @@
// -----------------------------------------------------------------------
// <copyright file="GetAccountBalance.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Invoice
{
/// <summary>
/// Gets the account balance for a partner.
/// </summary>
public class GetAccountBalance : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAccountBalance"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetAccountBalance(IScenarioContext context) : base("Get account balance", context)
{
}
/// <summary>
/// executes the get account balance scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
this.Context.ConsoleHelper.StartProgress("Getting account balance");
// Getting the account balance
var accountBalance = partnerOperations.Invoices.Summary.Get().BalanceAmount;
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(accountBalance, "Account Balance");
}
}
}

Просмотреть файл

@ -0,0 +1,60 @@
// -----------------------------------------------------------------------
// <copyright file="GetInvoice.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Invoice
{
using System;
/// <summary>
/// Gets a single partner invoice.
/// </summary>
public class GetInvoice : BasePartnerScenario
{
/// <summary>
/// Initializes a new instance of the <see cref="GetInvoice"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
public GetInvoice(IScenarioContext context) : base("Get partner's invoice details", context)
{
}
/// <summary>
/// executes the get invoice scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string invoiceId = this.Context.Configuration.Scenario.DefaultInvoiceId;
if (string.IsNullOrWhiteSpace(invoiceId))
{
// prompt the user the enter the invoice ID
invoiceId = this.Context.ConsoleHelper.ReadNonEmptyString("Please enter the invoice ID to retrieve ", "The invoice ID can't be empty");
}
else
{
Console.WriteLine("Found Invoice ID: {0} in configuration.", invoiceId);
}
this.Context.ConsoleHelper.StartProgress("Retrieving invoice");
// Retrieving invoice
var invoice = partnerOperations.Invoices.ById(invoiceId).Get();
this.Context.ConsoleHelper.StopProgress();
this.Context.ConsoleHelper.WriteObject(invoice, "Invoice details");
// Retrieving invoice line items
if (invoice.InvoiceDetails != null)
{
foreach (var invoiceDetail in invoice.InvoiceDetails)
{
this.Context.ConsoleHelper.WriteObject(invoiceDetail, "Invoice Line Items");
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,95 @@
// -----------------------------------------------------------------------
// <copyright file="GetInvoiceLineItems.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Store.PartnerCenter.Samples.Invoice
{
using System;
using System.Globalization;
using System.Linq;
/// <summary>
/// Gets an invoice's line items.
/// </summary>
public class GetInvoiceLineItems : BasePartnerScenario
{
/// <summary>
/// The invoice page size.
/// </summary>
private readonly int invoicePageSize;
/// <summary>
/// Initializes a new instance of the <see cref="GetInvoiceLineItems"/> class.
/// </summary>
/// <param name="context">The scenario context.</param>
/// <param name="invoicePageSize">The number of invoice line items to return per page.</param>
public GetInvoiceLineItems(IScenarioContext context, int invoicePageSize = 0) : base("Get an invoice's line items", context)
{
this.invoicePageSize = invoicePageSize;
}
/// <summary>
/// executes the get invoice line items scenario.
/// </summary>
protected override void RunScenario()
{
var partnerOperations = this.Context.UserPartnerOperations;
string invoiceId = this.Context.Configuration.Scenario.DefaultInvoiceId;
if (string.IsNullOrWhiteSpace(invoiceId))
{
// prompt the user the enter the invoice ID
invoiceId = this.Context.ConsoleHelper.ReadNonEmptyString("Please enter the ID of the invoice to retrieve ", "The ID can't be empty");
}
else
{
Console.WriteLine("Found Invoice ID: {0} in configuration.", invoiceId);
}
this.Context.ConsoleHelper.StartProgress("Retrieving Invoice Line Items");
// Retrieve the invoice
var invoiceOperations = partnerOperations.Invoices.ById(invoiceId);
var invoice = invoiceOperations.Get();
this.Context.ConsoleHelper.StopProgress();
if ((invoice.InvoiceDetails == null) || (invoice.InvoiceDetails.Count() <= 0))
{
this.Context.ConsoleHelper.Warning(string.Format(CultureInfo.InvariantCulture, "Invoice {0} does not have any invoice line items", invoice.Id));
}
else
{
foreach (var invoiceDetail in invoice.InvoiceDetails)
{
this.Context.ConsoleHelper.StartProgress(string.Format("Getting invoice line item for product {0} and line item type {1}", invoiceDetail.BillingProvider, invoiceDetail.InvoiceLineItemType));
// Get the invoice line items
var invoiceLineItemsCollection = (this.invoicePageSize <= 0) ? invoiceOperations.By(invoiceDetail.BillingProvider, invoiceDetail.InvoiceLineItemType).Get() : invoiceOperations.By(invoiceDetail.BillingProvider, invoiceDetail.InvoiceLineItemType).Get(this.invoicePageSize, 0);
var invoiceLineItemEnumerator = partnerOperations.Enumerators.InvoiceLineItems.Create(invoiceLineItemsCollection);
this.Context.ConsoleHelper.StopProgress();
int pageNumber = 1;
while (invoiceLineItemEnumerator.HasValue)
{
this.Context.ConsoleHelper.WriteObject(invoiceLineItemEnumerator.Current, string.Format(CultureInfo.InvariantCulture, "Invoice Line Item Page: {0}", pageNumber++));
Console.WriteLine();
Console.Write("Press any key to retrieve the next invoice line items page");
Console.ReadKey();
this.Context.ConsoleHelper.StartProgress("Getting next invoice line items page");
// Get the next list of invoice line items
invoiceLineItemEnumerator.Next();
this.Context.ConsoleHelper.StopProgress();
Console.Clear();
}
}
}
}
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше