diff --git a/build/.gitignore b/build/.gitignore new file mode 100644 index 00000000000..ee956f580c1 --- /dev/null +++ b/build/.gitignore @@ -0,0 +1 @@ +*.snk \ No newline at end of file diff --git a/global.json b/global.json index b8836b5a241..b3578936b91 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "Microsoft.Quantum.Sdk": "0.16.2105140327-beta" + "Microsoft.Quantum.Sdk": "0.17.2106147878-beta" } } diff --git a/src/Azure/Azure.Quantum.Client.Test/CredentialFactoryTests.cs b/src/Azure/Azure.Quantum.Client.Test/CredentialFactoryTests.cs new file mode 100644 index 00000000000..51414d5334f --- /dev/null +++ b/src/Azure/Azure.Quantum.Client.Test/CredentialFactoryTests.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; + +using Azure.Identity; + +using Microsoft.Azure.Quantum.Authentication; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Microsoft.Azure.Quantum.Test +{ + [TestClass] + public class CredentialFactoryTests + { + private const string SUBSCRIPTION = "916dfd6d-030c-4bd9-b579-7bb6d1926e97"; + + [DataTestMethod] + [DataRow(CredentialType.Default, typeof(DefaultAzureCredential))] + [DataRow(CredentialType.Environment, typeof(EnvironmentCredential))] + [DataRow(CredentialType.ManagedIdentity, typeof(ManagedIdentityCredential))] + [DataRow(CredentialType.CLI, typeof(AzureCliCredential))] + [DataRow(CredentialType.SharedToken, typeof(SharedTokenCacheCredential))] + [DataRow(CredentialType.VisualStudio, typeof(VisualStudioCredential))] + [DataRow(CredentialType.VisualStudioCode, typeof(VisualStudioCodeCredential))] + [DataRow(CredentialType.Interactive, typeof(InteractiveBrowserCredential))] + [DataRow(CredentialType.DeviceCode, typeof(DeviceCodeCredential))] + public void TestCreateCredential(CredentialType credentialType, Type expectedType) + { + var actual = CredentialFactory.CreateCredential(credentialType); + Assert.IsNotNull(actual); + Assert.AreEqual(expectedType, actual.GetType()); + + // Now test with a specific subscription id: + actual = CredentialFactory.CreateCredential(credentialType, SUBSCRIPTION); + Assert.IsNotNull(actual); + Assert.AreEqual(expectedType, actual.GetType()); + } + + [TestMethod] + public void TestInvalidCredentialType() + { + Assert.ThrowsException(() => CredentialFactory.CreateCredential((CredentialType)9999)); + } + + [TestMethod] + public void TestGetTenantId() + { + var actual = CredentialFactory.GetTenantId(SUBSCRIPTION); + Assert.IsNotNull(actual); + Assert.IsFalse(string.IsNullOrWhiteSpace(actual)); + + var actual2 = CredentialFactory.GetTenantId(SUBSCRIPTION); + Assert.AreEqual(actual, actual2); + } + + [DataTestMethod] + [DataRow(null, null)] + [DataRow("", null)] + [DataRow("some random string", null)] + [DataRow("string,with,random,values", null)] + [DataRow("string=with,random=,key=values", null)] + [DataRow("string=with,random=,authorization_uri=", null)] + [DataRow("string=with,invalid=authorization_uri,authorization_uri=some-random-value", null)] + [DataRow("string=with,invalid=authorization_uri,authorization_uri=http://foo.bar.com/some-random-value", null)] + [DataRow("string=missing,tenant_id=authorization_uri,authorization_uri=\"http://foo.bar.com/", null)] + [DataRow("authorization_uri=\"https://login.microsoftonline.com/tenantId\",key1=value1s,etc...", "tenantId")] + public void TestExtractTenantIdFromBearer(string? bearer, string? expected) + { + var actual = CredentialFactory.ExtractTenantIdFromBearer(bearer); + Assert.AreEqual(expected, actual); + } + } +} diff --git a/src/Azure/Azure.Quantum.Client.Test/Helpers/MockHelper.cs b/src/Azure/Azure.Quantum.Client.Test/Helpers/MockHelper.cs deleted file mode 100644 index cf34b116987..00000000000 --- a/src/Azure/Azure.Quantum.Client.Test/Helpers/MockHelper.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// - -using System.Collections.Generic; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; - -using Microsoft.Azure.Quantum.Client; - -using Moq; -using Moq.Protected; - -namespace Microsoft.Azure.Quantum.Test -{ - public class MockHelper - { - internal List RequestMessages { get; private set; } = new List(); - - internal HttpResponseMessage ResponseMessage { get; set; } - - public HttpClient GetHttpClientMock() - { - Mock mock = new Mock(); - - mock.Protected() - .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) - .Returns((HttpRequestMessage request, CancellationToken token) => - { - RequestMessages.Add(request); - - if (request.Method == HttpMethod.Delete) - { - return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent)); - } - - return Task.FromResult(ResponseMessage); - }); - - return new HttpClient(mock.Object); - } - - public class MockQuantumClient : QuantumClient - { - public MockQuantumClient(MockHelper mock) - : base(mock.GetHttpClientMock(), true) - { - } - } - } -} diff --git a/src/Azure/Azure.Quantum.Client.Test/Helpers/Problem.cs b/src/Azure/Azure.Quantum.Client.Test/Helpers/Problem.cs new file mode 100644 index 00000000000..25c4012ebeb --- /dev/null +++ b/src/Azure/Azure.Quantum.Client.Test/Helpers/Problem.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace Microsoft.Azure.Quantum.Test +{ + public enum ProblemType : int + { + PUBO = 0, + Ising = 1, + } + + /// + /// This is the data structure that represents a QIO problem payload on the service. + /// It's currently not exposed in C#, so we have it here so we can test job submission of + /// the client libraries without having to serialize Q# programs. + /// + public class Problem + { + private readonly HashSet terms = new HashSet(); + + public Problem(ProblemType type = ProblemType.PUBO) + { + ProblemType = type; + } + + public Problem(IEnumerable collection) + : this() + { + AddRange(collection); + } + + [JsonPropertyName("version")] + public string Version => "1.1"; + + [JsonPropertyName("type")] + [JsonConverter(typeof(JsonStringEnumConverter))] + public ProblemType ProblemType { get; } + + [JsonPropertyName("terms")] + public IEnumerable Terms => terms; + + public void Add(Term term) + { + terms.Add(term); + } + + public void Add(int i, float c) + { + terms.Add(new Term(new int[] { i }, c)); + } + + public void Add(int i, int j, float c) + { + terms.Add(new Term(new int[] { i, j }, c)); + } + + public void Add(int i, int j, int k, float c) + { + terms.Add(new Term(new int[] { i, j, k }, c)); + } + + public void AddRange(IEnumerable collection) + { + foreach (var term in collection) + { + terms.Add(term); + } + } + + public Task SerializeAsync(Stream stream) + { + var root = new SerializationWrapper + { + CostFunction = this, + }; + + // Save to the writer + return JsonSerializer.SerializeAsync(stream, root); + } + + public override string ToString() + { + var root = new SerializationWrapper + { + CostFunction = this, + }; + + return JsonSerializer.Serialize(root); + } + + private struct SerializationWrapper + { + [JsonPropertyName("cost_function")] + public Problem CostFunction { get; set; } + } + + public class Term + { + public Term(int[] ids, float c) + { + this.IDs = ids; + this.Weight = c; + } + + [JsonPropertyName("c")] + public float Weight { get; } + + [JsonPropertyName("ids")] + public int[] IDs { get; } + } + } +} diff --git a/src/Azure/Azure.Quantum.Client.Test/Helpers/TestConstants.cs b/src/Azure/Azure.Quantum.Client.Test/Helpers/TestConstants.cs deleted file mode 100644 index 6cc2c8aa96d..00000000000 --- a/src/Azure/Azure.Quantum.Client.Test/Helpers/TestConstants.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -namespace Microsoft.Azure.Quantum.Test -{ - public static class TestConstants - { - public const string SubscriptionId = "sub1"; - public const string ResourceGroupName = "rg1"; - public const string WorkspaceName = "ws1"; - public const string ProviderId = "provider1"; - public const string Endpoint = "https://test"; - } -} diff --git a/src/Azure/Azure.Quantum.Client.Test/Microsoft.Azure.Quantum.Client.Test.csproj b/src/Azure/Azure.Quantum.Client.Test/Microsoft.Azure.Quantum.Client.Test.csproj index 7965e696874..7ff14f03a27 100644 --- a/src/Azure/Azure.Quantum.Client.Test/Microsoft.Azure.Quantum.Client.Test.csproj +++ b/src/Azure/Azure.Quantum.Client.Test/Microsoft.Azure.Quantum.Client.Test.csproj @@ -10,7 +10,6 @@ - all diff --git a/src/Azure/Azure.Quantum.Client.Test/WorkspaceTest.cs b/src/Azure/Azure.Quantum.Client.Test/WorkspaceTest.cs index 48485da8f28..e9c87e7ac03 100644 --- a/src/Azure/Azure.Quantum.Client.Test/WorkspaceTest.cs +++ b/src/Azure/Azure.Quantum.Client.Test/WorkspaceTest.cs @@ -3,246 +3,291 @@ using System; using System.Collections.Generic; +using System.IO; +using System.IO.Compression; using System.Linq; using System.Net; -using System.Net.Http; -using Microsoft.Azure.Quantum.Client; -using Microsoft.Azure.Quantum.Client.Models; +using System.Threading; +using System.Threading.Tasks; + +using Azure.Quantum; +using Azure.Quantum.Jobs.Models; + using Microsoft.Azure.Quantum.Exceptions; +using Microsoft.Azure.Quantum.Storage; using Microsoft.VisualStudio.TestTools.UnitTesting; -using Newtonsoft.Json; namespace Microsoft.Azure.Quantum.Test { [TestClass] public class WorkspaceTest { - private MockHelper httpMock; + private const string SETUP = @" +Live tests require you to configure your environment with these variables: + * E2E_WORKSPACE_NAME: the name of an Azure Quantum workspace to use for live testing. + * E2E_SUBSCRIPTION_ID: the Azure Quantum workspace's Subscription Id. + * E2E_WORKSPACE_RG: the Azure Quantum workspace's resource group. + * E2E_WORKSPACE_LOCATION: the Azure Quantum workspace's location (region). - [TestInitialize] - public void Init() - { - this.httpMock = new MockHelper(); - } +We'll also try to authenticate with Azure using an instance of DefaultCredential. See +https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme#authenticate-the-client +for details. + +Tests will be marked as Inconclusive if the pre-reqs are not correctly setup."; [TestMethod] - public void SubmitJobTest() + [TestCategory("Live")] + public async Task SubmitJobTest() { - string jobId = Guid.NewGuid().ToString(); - - // Craft response - SetJobResponseMessage(jobId); - // Create Job - IWorkspace workspace = GetWorkspace(); - - JobDetails jobDetails = CreateJobDetails(jobId); - CloudJob job = new CloudJob(workspace, jobDetails); - CloudJob receivedJob; - - // -ve cases - try - { - jobDetails.ContainerUri = null; - receivedJob = workspace.SubmitJob(job); - Assert.Fail(); - } - catch (WorkspaceClientException) - { - jobDetails.ContainerUri = "https://uri"; - } - - try - { - jobDetails.ProviderId = null; - receivedJob = workspace.SubmitJob(job); - Assert.Fail(); - } - catch (WorkspaceClientException) - { - jobDetails.ProviderId = TestConstants.ProviderId; - } - - // Success - receivedJob = workspace.SubmitJob(job); + IWorkspace workspace = GetLiveWorkspace(); - // Validate request - ValidateJobRequestMessage(jobId, HttpMethod.Put); + CancellationTokenSource cts = new CancellationTokenSource(); + cts.CancelAfter(30000); - // Validate response - Assert.IsNotNull(receivedJob); + var job = await SubmitTestProblem(workspace); + AssertJob(job); - Assert.IsNotNull(receivedJob.Workspace); + await job.WaitForCompletion(cancellationToken: cts.Token); - Assert.AreEqual( - expected: jobId, - actual: receivedJob.Details.Id); + AssertJob(job); + Assert.IsTrue(job.Succeeded); } [TestMethod] - public void GetJobTest() + [TestCategory("Live")] + public async Task GetJobTest() { - string jobId = Guid.NewGuid().ToString(); + IWorkspace workspace = GetLiveWorkspace(); - // Craft response - SetJobResponseMessage(jobId); - - // Get Job - IWorkspace workspace = GetWorkspace(); - - CloudJob receivedJob = workspace.GetJob(jobId); - - // Validate request - ValidateJobRequestMessage(jobId, HttpMethod.Get); - - // Validate response - Assert.IsNotNull(receivedJob); + // Since this is a live workspace, we don't have much control about what jobs are in there + // Get the jobs, and call Get on the first. + await foreach (var job in workspace.ListJobsAsync()) + { + AssertJob(job); - Assert.IsNotNull(receivedJob.Workspace); + var current = workspace.GetJob(job.Id); + AssertJob(current); + Assert.AreEqual(job.Id, current.Id); - Assert.AreEqual( - expected: jobId, - actual: receivedJob.Details.Id); + break; + } } [TestMethod] - public void CancelJobTest() + [TestCategory("Live")] + public async Task CancelJobTest() { - string jobId = Guid.NewGuid().ToString(); - - // Craft response - SetJobResponseMessage(jobId); - - // Cancel Job - IWorkspace workspace = GetWorkspace(); + // Create Job + IWorkspace workspace = GetLiveWorkspace(); - CloudJob receivedJob = workspace.CancelJob(jobId); + var job = await SubmitTestProblem(workspace); + AssertJob(job); - // Validate request - ValidateJobRequestMessage(jobId, HttpMethod.Delete, HttpMethod.Get); + try + { + var result = workspace.CancelJob(job.Id); + AssertJob(result); + } + catch (WorkspaceClientException e) + { + Assert.AreEqual((int)HttpStatusCode.Conflict, e.Status); + } + } - // Validate response - Assert.IsNotNull(receivedJob); + [TestMethod] + [TestCategory("Live")] + public async Task ListJobsTest() + { + IWorkspace workspace = GetLiveWorkspace(); + int max = 3; - Assert.IsNotNull(receivedJob.Workspace); + // Since this is a live workspace, we don't have much control about what jobs are in there + // Just make sure there is more than one. + await foreach (var job in workspace.ListJobsAsync()) + { + Assert.IsNotNull(job); + Assert.IsNotNull(job.Details); + Assert.IsNotNull(job.Workspace); + Assert.IsFalse(string.IsNullOrWhiteSpace(job.Id)); + Assert.AreEqual(job.Details.Id, job.Id); + + max--; + if (max <= 0) + { + break; + } + } - Assert.AreEqual( - expected: jobId, - actual: receivedJob.Details.Id); + // Make sure we iterated through all the expected jobs: + Assert.AreEqual(0, max); + } - // Convenience method - CloudJob job = new CloudJob(workspace, CreateJobDetails(jobId)); - string newJobId = Guid.NewGuid().ToString(); - SetJobResponseMessage(newJobId); + [TestMethod] + [TestCategory("Live")] + public async Task ListQuotasTest() + { + IWorkspace workspace = GetLiveWorkspace(); + int max = 3; - Assert.AreEqual( - jobId, - job.Details.Id); + // Since this is a live workspace, we don't have much control about what quotas are in there + // Just make sure there is more than one. + await foreach (var q in workspace.ListQuotasAsync()) + { + Assert.IsNotNull(q); + Assert.IsNotNull(q.ProviderId); + Assert.IsNotNull(q.Dimension); - job.CancelAsync().Wait(); + max--; + if (max <= 0) + { + break; + } + } - Assert.AreEqual( - newJobId, - job.Details.Id); + // Make sure we iterated through all the expected jobs: + Assert.AreEqual(0, max); } [TestMethod] - public void ListJobsTest() + [TestCategory("Live")] + public async Task ListProviderStatusTest() { - // Craft response - JobDetails jobDetails = new JobDetails - { - ProviderId = TestConstants.ProviderId, - }; + IWorkspace workspace = GetLiveWorkspace(); + int max = 1; - dynamic page = new + // Since this is a live workspace, we don't have much control about what quotas are in there + // Just make sure there is more than one. + await foreach (var s in workspace.ListProvidersStatusAsync()) { - nextLink = (string)null, - value = new JobDetails[] { jobDetails }, - }; + Assert.IsNotNull(s); + Assert.IsNotNull(s.ProviderId); + Assert.IsNotNull(s.Targets); + Assert.IsTrue(s.Targets.Any()); - this.httpMock.ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(JsonConvert.SerializeObject(page)), - }; + max--; + if (max <= 0) + { + break; + } + } - // Cancel Job - IWorkspace workspace = GetWorkspace(); + // Make sure we iterated through all the expected jobs: + Assert.AreEqual(0, max); + } - List receivedJobs = workspace.ListJobs().ToList(); + private static void AssertJob(CloudJob job) + { + Assert.IsNotNull(job); + Assert.IsNotNull(job.Details); + Assert.IsNotNull(job.Workspace); + Assert.IsFalse(string.IsNullOrEmpty(job.Id)); + Assert.AreEqual(job.Id, job.Details.Id); + } - // Validate request - ValidateJobRequestMessage(null, HttpMethod.Get); + private IWorkspace GetLiveWorkspace() + { + if (string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("E2E_SUBSCRIPTION_ID")) || + string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("E2E_WORKSPACE_RG")) || + string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("E2E_WORKSPACE_NAME")) || + string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("E2E_SUBSCRIPTION_ID"))) + { + Assert.Inconclusive(SETUP); + } - // Validate response - Assert.IsNotNull(receivedJobs); + var options = new QuantumJobClientOptions(); + options.Diagnostics.ApplicationId = "ClientTests"; - Assert.IsNotNull(receivedJobs.Single().Workspace); + var credential = Authentication.CredentialFactory.CreateCredential(Authentication.CredentialType.Default); - Assert.AreEqual( - expected: jobDetails.ProviderId, - actual: receivedJobs.Single().Details.ProviderId); + return new Workspace( + subscriptionId: System.Environment.GetEnvironmentVariable("E2E_SUBSCRIPTION_ID"), + resourceGroupName: System.Environment.GetEnvironmentVariable("E2E_WORKSPACE_RG"), + workspaceName: System.Environment.GetEnvironmentVariable("E2E_WORKSPACE_NAME"), + location: System.Environment.GetEnvironmentVariable("E2E_WORKSPACE_LOCATION"), + options: options, + credential: credential); } - private IWorkspace GetWorkspace() + private static JobDetails CreateJobDetails(string jobId, string containerUri = null, string inputUri = null) { - return new Workspace( - subscriptionId: TestConstants.SubscriptionId, - resourceGroupName: TestConstants.ResourceGroupName, - workspaceName: TestConstants.WorkspaceName) + return new JobDetails( + containerUri: containerUri, + inputDataFormat: "microsoft.qio.v2", + providerId: "Microsoft", + target: "microsoft.paralleltempering-parameterfree.cpu") { - // Mock jobs client (only needed for unit tests) - QuantumClient = new MockHelper.MockQuantumClient(httpMock) + Id = jobId, + Name = "Azure.Quantum.Unittest", + OutputDataFormat = "microsoft.qio-results.v2", + InputParams = new Dictionary() { - SubscriptionId = TestConstants.SubscriptionId, - ResourceGroupName = TestConstants.ResourceGroupName, - WorkspaceName = TestConstants.WorkspaceName, - BaseUri = new Uri(TestConstants.Endpoint), + { "params", new Dictionary() }, }, + InputDataUri = inputUri, }; } - private void SetJobResponseMessage(string jobId) + private static Problem CreateTestProblem() { - this.httpMock.ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) + // Create an Ising-type problem for shipping-containers + var containerWeights = new int[] { 1, 5, 9, 21, 35, 5, 3, 5, 10, 11 }; + + var problem = new Problem(ProblemType.Ising); + for (int i = 0; i < containerWeights.Length; i++) { - Content = new StringContent(JsonConvert.SerializeObject(CreateJobDetails(jobId))), - }; - } + for (int j = 0; j < containerWeights.Length; j++) + { + if (i != j) + { + problem.Add(i, j, containerWeights[i] * containerWeights[j]); + } + } + } - private static JobDetails CreateJobDetails(string jobId) - { - return new JobDetails( - id: jobId, - containerUri: "https://uri", - inputDataFormat: "format1", - providerId: TestConstants.ProviderId, - target: "target"); + return problem; } - private void ValidateJobRequestMessage( - string jobId, - params HttpMethod[] methods) + private async Task<(string, string)> UploadProblem(IWorkspace workspace, Problem problem, string jobId) { - var requestMessages = httpMock.RequestMessages; - Assert.AreEqual(requestMessages.Count, methods.Length); + string intermediaryFile = Path.GetTempFileName(); + + // Save to the intermediary file + using (var intermediaryWriter = File.Create(intermediaryFile)) + { + using (var compressionStream = new GZipStream(intermediaryWriter, CompressionLevel.Fastest)) + { + await problem.SerializeAsync(compressionStream); + } + } - for (var i = 0; i < requestMessages.Count; i++) + using (var intermediaryReader = File.OpenRead(intermediaryFile)) { - var requestMessage = requestMessages[i]; - var method = methods[i]; - - // Url - string expectedUri = $"{TestConstants.Endpoint}/v1.0/subscriptions/{TestConstants.SubscriptionId}/resourceGroups/{TestConstants.ResourceGroupName}/providers/Microsoft.Quantum/workspaces/{TestConstants.WorkspaceName}/jobs/{jobId}"; - Assert.AreEqual( - expected: expectedUri.TrimEnd('/'), - actual: requestMessage.RequestUri.ToString()); - - // Method - Assert.AreEqual( - expected: method, - actual: requestMessage.Method); + var jobStorageHelper = new LinkedStorageJobHelper(workspace); + return await jobStorageHelper.UploadJobInputAsync(jobId, intermediaryReader); } } + + private async Task SubmitTestProblem(IWorkspace workspace) + { + CancellationTokenSource cts = new CancellationTokenSource(); + cts.CancelAfter(30000); + + var jobId = Guid.NewGuid().ToString(); + var problem = CreateTestProblem(); + + // Upload problem: + var (containerUri, inputUri) = await UploadProblem(workspace, problem, jobId); + + CloudJob src = new CloudJob(workspace, CreateJobDetails(jobId, containerUri, inputUri)); + AssertJob(src); + + var job = await workspace.SubmitJobAsync(src, cts.Token); + AssertJob(job); + Assert.AreEqual(jobId, job.Id); + Assert.IsFalse(job.Failed); + + return job; + } } } diff --git a/src/Azure/Azure.Quantum.Client/Authentication/ClientCredentials.cs b/src/Azure/Azure.Quantum.Client/Authentication/ClientCredentials.cs deleted file mode 100644 index e9082df95b1..00000000000 --- a/src/Azure/Azure.Quantum.Client/Authentication/ClientCredentials.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Rest; - -namespace Microsoft.Azure.Quantum.Authentication -{ - /// - /// Authorization client handler class. - /// - internal class ClientCredentials : ServiceClientCredentials - { - private const string AuthorizationHeaderName = "Authorization"; - private const string BearerScheme = "Bearer"; - - private readonly IAccessTokenProvider accessTokenProvider; - - /// - /// Initializes a new instance of the class. - /// - /// The access token provider. - public ClientCredentials(IAccessTokenProvider accessTokenProvider) - { - this.accessTokenProvider = accessTokenProvider; - } - - public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - if (request == null) - { - throw new ArgumentNullException("request"); - } - - if (!request.Headers.Contains(AuthorizationHeaderName)) - { - string accessToken = await this.accessTokenProvider.GetAccessTokenAsync(cancellationToken); - request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BearerScheme, accessToken); - } - - //request.Version = new Version(apiVersion); - await base.ProcessHttpRequestAsync(request, cancellationToken); - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/Authentication/CredentialFactory.cs b/src/Azure/Azure.Quantum.Client/Authentication/CredentialFactory.cs new file mode 100644 index 00000000000..8a1892a5bc4 --- /dev/null +++ b/src/Azure/Azure.Quantum.Client/Authentication/CredentialFactory.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#nullable enable + +namespace Microsoft.Azure.Quantum.Authentication +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + + using global::Azure.Core; + using global::Azure.Identity; + + /// + /// The enumeration of supported Credential Classes supported out of the box for + /// authentication in Azure Quantum. + /// NOTE: For more information + /// about authentication with Azure services and the different Credential types see + /// https://docs.microsoft.com/dotnet/api/overview/azure/identity-readme. + /// + public enum CredentialType + { + /// + /// Provides a simplified authentication experience to quickly start developing applications run in the Azure cloud. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.defaultazurecredential + /// + Default, + + /// + /// Authenticates a service principal or user via credential information specified in environment variables. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.environmentcredential + /// + Environment, + + /// + /// Authenticates the managed identity of an azure resource. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.managedidentitycredential + /// + ManagedIdentity, + + /// + /// Authenticate in a development environment with the Azure CLI. + /// See https://docs.microsoft.com/dotnet/api/azure.identity.azureclicredential + /// + CLI, + + /// + /// Authenticate using tokens in the local cache shared between Microsoft applications. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.sharedtokencachecredential + /// + SharedToken, + + /// + /// Authenticate using data from Visual Studio. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.visualstudiocredential + /// + VisualStudio, + + /// + /// Authenticate in a development environment with Visual Studio Code. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.visualstudiocodecredential + /// + VisualStudioCode, + + /// + /// A TokenCredential implementation which launches the system default browser to interactively authenticate a user, + /// and obtain an access token. The browser will only be launched to authenticate the user once, + /// then will silently acquire access tokens through the users refresh token as long as it's valid. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential + /// + Interactive, + + /// + /// A TokenCredential implementation which authenticates a user using the device code flow, + /// and provides access tokens for that user account. + /// See: https://docs.microsoft.com/dotnet/api/azure.identity.devicecodecredential + /// + DeviceCode, + } + + public static class CredentialFactory + { + // Used to fetch the tenantId automatically from ARM + private static readonly HttpClient Client = new HttpClient(); + + // Used to catch all the TenantIds: + private static readonly Dictionary TenantIds = new Dictionary(); + + public static TokenCredential CreateCredential(CredentialType credentialType, string? subscriptionId = null) => credentialType switch + { + CredentialType.SharedToken => CreateCredential(credentialType, () => SharedTokenOptions(subscriptionId)), + CredentialType.VisualStudio => CreateCredential(credentialType, () => VisualStudioOptions(subscriptionId)), + CredentialType.VisualStudioCode => CreateCredential(credentialType, () => VisualStudioCodeOptions(subscriptionId)), + CredentialType.Interactive => CreateCredential(credentialType, () => InteractiveOptions(subscriptionId)), + CredentialType.DeviceCode => CreateCredential(credentialType, () => DeviceCodeOptions(subscriptionId)), + CredentialType.Default => CreateCredential(credentialType, () => DefaultOptions(subscriptionId)), + _ => CreateCredential(credentialType, () => DefaultOptions(subscriptionId)), + }; + + /// + /// Creates an instance of TokenCredential that corresponds to the given . + /// It creates an instance of the Credential Class with default parameters. + /// + /// The type of Credential Class to create. + /// A configuration method for the corresponding credential options (not used for Environment, ManagedIdentity or CLI credentials). + /// An instance of TokenCredential for the corresponding value. + public static TokenCredential CreateCredential(CredentialType credentialType, Func options) => credentialType switch + { + CredentialType.Environment => new EnvironmentCredential(), + CredentialType.ManagedIdentity => new ManagedIdentityCredential(), + CredentialType.CLI => new AzureCliCredential(), + CredentialType.DeviceCode => new DeviceCodeCredential(options: options?.Invoke() as DeviceCodeCredentialOptions), + CredentialType.SharedToken => new SharedTokenCacheCredential(options: options?.Invoke() as SharedTokenCacheCredentialOptions), + CredentialType.VisualStudio => new VisualStudioCredential(options: options?.Invoke() as VisualStudioCredentialOptions), + CredentialType.VisualStudioCode => new VisualStudioCodeCredential(options: options?.Invoke() as VisualStudioCodeCredentialOptions), + CredentialType.Interactive => new InteractiveBrowserCredential(options: options?.Invoke() as InteractiveBrowserCredentialOptions), + CredentialType.Default => new DefaultAzureCredential(options: options?.Invoke() as DefaultAzureCredentialOptions), + _ => throw new ArgumentException($"Credentials of type {credentialType} are not supported.") + }; + + /// + /// Returns an DefaultAzureCredentialOptions, populated with the TenantId for the given subscription. + /// We als disabilitate VisualStudio credentials, since they don't currently work with Azure Quantum. + /// + /// An subscription Id. + /// A new instance of InteractiveBrowserCredentialOptions with the TenantId populated + public static DefaultAzureCredentialOptions DefaultOptions(string? subscriptionid) + { + string? tenantId = GetTenantId(subscriptionid); + + return new DefaultAzureCredentialOptions + { + // Disable VS credentials until https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1332071 is fixed: + ExcludeVisualStudioCredential = true, + ExcludeInteractiveBrowserCredential = false, + + InteractiveBrowserTenantId = tenantId, + SharedTokenCacheTenantId = tenantId, + VisualStudioCodeTenantId = tenantId, + VisualStudioTenantId = tenantId, + }; + } + + /// + /// Returns an InteractiveBrowserCredentialOptions, populated with the TenantId for the given subscription. + /// + /// An subscription Id. + /// A new instance of InteractiveBrowserCredentialOptions with the TenantId populated + public static InteractiveBrowserCredentialOptions InteractiveOptions(string? subscriptionid) => + new InteractiveBrowserCredentialOptions + { + TenantId = GetTenantId(subscriptionid), + }; + + /// + /// Returns an VisualStudioCodeCredentialOptions, populated with the TenantId for the given subscription. + /// + /// An subscription Id. + /// A new instance of InteractiveBrowserCredentialOptions with the TenantId populated + public static VisualStudioCodeCredentialOptions VisualStudioCodeOptions(string? subscriptionid) => + new VisualStudioCodeCredentialOptions + { + TenantId = GetTenantId(subscriptionid), + }; + + /// + /// Returns an VisualStudioCredentialOptions, populated with the TenantId for the given subscription. + /// + /// An subscription Id. + /// A new instance of InteractiveBrowserCredentialOptions with the TenantId populated + public static VisualStudioCredentialOptions VisualStudioOptions(string? subscriptionid) => + new VisualStudioCredentialOptions + { + TenantId = GetTenantId(subscriptionid), + }; + + /// + /// Returns an SharedTokenCacheCredentialOptions, populated with the TenantId for the given subscription. + /// + /// An subscription Id. + /// A new instance of InteractiveBrowserCredentialOptions with the TenantId populated + public static SharedTokenCacheCredentialOptions SharedTokenOptions(string? subscriptionid) => + new SharedTokenCacheCredentialOptions + { + TenantId = GetTenantId(subscriptionid), + }; + + /// + /// Returns an VisualStudioCodeCredentialOptions, populated with the TenantId for the given subscription. + /// + /// An subscription Id. + /// A new instance of InteractiveBrowserCredentialOptions with the TenantId populated + public static DeviceCodeCredentialOptions DeviceCodeOptions(string? subscriptionid) => + new DeviceCodeCredentialOptions + { + TenantId = GetTenantId(subscriptionid), + }; + + /// + /// This gnarly piece of code is how we get the guest tenant + /// authority associated with the subscription. + /// We make a unauthenticated request to ARM and extract the tenant + /// authority from the WWW-Authenticate header in the response. + /// + /// The subscriptionId. + /// The tenantId for the given subscription; null if it can be found or for a null subscription. + public static string? GetTenantId(string? subscriptionId) + { + if (subscriptionId == null) + { + return null; + } + + if (TenantIds.TryGetValue(subscriptionId, out string? tenantId)) + { + return tenantId; + } + + try + { + string url = $"https://management.azure.com/subscriptions/{subscriptionId}?api-version=2020-01-01"; + HttpResponseMessage response = Client.GetAsync(url).Result; + var header = response + .Headers + .WwwAuthenticate + .FirstOrDefault(v => v.Scheme == "Bearer") + ?.Parameter; + + tenantId = ExtractTenantIdFromBearer(header); + TenantIds[subscriptionId] = tenantId; + + return tenantId; + } + catch + { + return null; + } + } + + /// + /// Here we parse WWW-Authenticate header in the response to match the tenant id. + /// The header is of the form: + /// Bearer authorization_uri="https://login.microsoftonline.com/tenantId",key1=value1s,etc... + /// + /// The value of the Bearer in the WWWAuthenticate header + /// The tenant-id, or null if it can't find it. + public static string? ExtractTenantIdFromBearer(string? bearer) + { + if (bearer == null) + { + return null; + } + + // Split the key=value comma seperated list and look for the "authorization_uri" key: + var auth_uri = bearer + .Split(',') + .Select(kv => kv.Split('=', 2)) + .FirstOrDefault(pair => pair[0] == "authorization_uri")?[1]; + + // If found an authorization_uri, find the tenant id from a URL surrounded by quotes, i.e.: + // "https://login.microsoftonline.com/tenantId" + if (auth_uri != null && auth_uri.StartsWith('"') && auth_uri.EndsWith('"')) + { + var id = auth_uri + [1 .. ^1] + [auth_uri.LastIndexOf('/') .. ]; + + return id; + } + else + { + return null; + } + + } + } +} diff --git a/src/Azure/Azure.Quantum.Client/Authentication/CustomAccessTokenProvider.cs b/src/Azure/Azure.Quantum.Client/Authentication/CustomAccessTokenProvider.cs deleted file mode 100644 index b95e03237b1..00000000000 --- a/src/Azure/Azure.Quantum.Client/Authentication/CustomAccessTokenProvider.cs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Linq; -using System.Net.Http; -using System.Security.Authentication; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Azure.Quantum.Utility; -using Microsoft.Identity.Client; -using Microsoft.Identity.Client.Extensions.Msal; - -namespace Microsoft.Azure.Quantum.Authentication -{ - /// - /// This class manually uses MSAL to get an access token. - /// It first tries to get silently, if that doesn't work, it tries to get interactively. - /// - /// - internal class CustomAccessTokenProvider : IAccessTokenProvider - { - private readonly LazyAsync applicationLazy; - private readonly string[] scopes; - private readonly string subscriptionId; - - /// - /// Initializes a new instance of the class. - /// - /// The Subscription Id of the account in use. - public CustomAccessTokenProvider(string subscriptionId) - { - static async Task GetSubscriptionTenantUri(string subscriptionId) - { - var uri = $"https://management.azure.com/subscriptions/{subscriptionId}?api-version=2018-01-01"; - try - { - static string GetTenantUriFromHeader(System.Net.Http.Headers.AuthenticationHeaderValue header) => - header - .Parameter - .Replace("Bearer ", string.Empty) - .Split(",") - .Select(part => part.Split("=")) - .ToDictionary(rg => rg[0], rg => rg[1])["authorization_uri"] - .Trim('\'', '"'); - - using var client = new HttpClient(); - var httpResult = await client.GetAsync(uri); - - return httpResult - .Headers - .WwwAuthenticate - .Select(GetTenantUriFromHeader) - .Single(); - } - catch (System.Exception ex) - { - throw new AuthenticationException("Unable to extract tenantUri!", ex); - } - } - - this.scopes = new string[] { Constants.Aad.Audience }; - this.subscriptionId = subscriptionId; - this.applicationLazy = - new LazyAsync(async () => - { - var application = PublicClientApplicationBuilder - .Create(Constants.Aad.ApplicationId) - .WithDefaultRedirectUri() - .WithAuthority(await GetSubscriptionTenantUri(subscriptionId)) - .Build(); - var cacheHelper = await CreateCacheHelperAsync(); - cacheHelper.RegisterCache(application.UserTokenCache); - return application; - }); - } - - /// - /// Tries to get access token silently, if didn't work, tries to get it interactively. - /// - /// The cancellation token. - /// A encapsulating the access token. - public async Task GetAccessTokenAsync(CancellationToken cancellationToken) - { - var application = await applicationLazy.Value; - - try - { - var accounts = await application.GetAccountsAsync(); - - // Try silently first - var result = await application - .AcquireTokenSilent(scopes, accounts.FirstOrDefault()) - .ExecuteAsync(); - - return result.AccessToken; - } - catch (MsalUiRequiredException) - { - // Didn't work, perform interactive logging - var result = await application - .AcquireTokenInteractive(scopes) - .ExecuteAsync(); - - return result.AccessToken; - } - } - - private static async Task CreateCacheHelperAsync() - { - StorageCreationProperties storageProperties; - - storageProperties = new StorageCreationPropertiesBuilder( - Constants.Aad.CacheFileName, - MsalCacheHelper.UserRootDirectory, - Constants.Aad.ApplicationId) - .WithMacKeyChain( - Constants.Aad.KeyChainServiceName, - Constants.Aad.KeyChainAccountName) - .Build(); - - var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties).ConfigureAwait(false); - - cacheHelper.VerifyPersistence(); - return cacheHelper; - } - } -} \ No newline at end of file diff --git a/src/Azure/Azure.Quantum.Client/Authentication/IAccessTokenProvider.cs b/src/Azure/Azure.Quantum.Client/Authentication/IAccessTokenProvider.cs deleted file mode 100644 index e72e4a440b8..00000000000 --- a/src/Azure/Azure.Quantum.Client/Authentication/IAccessTokenProvider.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Threading; -using System.Threading.Tasks; - -namespace Microsoft.Azure.Quantum.Authentication -{ - /// - /// Generic interface to retrieve access token. This is not exposed to the user. - /// - internal interface IAccessTokenProvider - { - /// - /// Gets the access token. - /// - /// The cancellation token. - /// Access token string - Task GetAccessTokenAsync(CancellationToken cancellationToken); - } -} diff --git a/src/Azure/Azure.Quantum.Client/Authentication/StaticAccessTokenProvider.cs b/src/Azure/Azure.Quantum.Client/Authentication/StaticAccessTokenProvider.cs deleted file mode 100644 index d44aa2e88ef..00000000000 --- a/src/Azure/Azure.Quantum.Client/Authentication/StaticAccessTokenProvider.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Azure.Quantum.Utility; - -namespace Microsoft.Azure.Quantum.Authentication -{ - /// - /// This class accepts an access token string and provides it. - /// - /// - internal class StaticAccessTokenProvider : IAccessTokenProvider - { - private readonly string accessToken; - - /// - /// Initializes a new instance of the class. - /// - public StaticAccessTokenProvider(string accessToken) - { - Ensure.NotNullOrWhiteSpace(accessToken, nameof(accessToken)); - - this.accessToken = accessToken; - } - - /// - /// Returns the static access token. - /// - /// The cancellation token. - public Task GetAccessTokenAsync(CancellationToken cancellationToken) - { - return Task.FromResult(this.accessToken); - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/Authentication/TokenCredentialProvider.cs b/src/Azure/Azure.Quantum.Client/Authentication/TokenCredentialProvider.cs deleted file mode 100644 index dd4805f7fda..00000000000 --- a/src/Azure/Azure.Quantum.Client/Authentication/TokenCredentialProvider.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -using System.Threading; -using System.Threading.Tasks; -using Azure.Core; -using Microsoft.Azure.Quantum.Utility; - -namespace Microsoft.Azure.Quantum.Authentication -{ - /// - /// A provider for TokenCredential - /// - /// - internal class TokenCredentialProvider : IAccessTokenProvider - { - private readonly TokenCredential tokenCredential; - private readonly string[] scopes; - - /// - /// Initializes a new instance of the class. - /// - /// The token credential. - public TokenCredentialProvider(TokenCredential tokenCredential) - { - this.tokenCredential = tokenCredential; - this.scopes = new string[] { Constants.Aad.Audience }; - } - - /// - /// Gets the access token. - /// - /// The cancellation token. - /// - /// Access token string - /// - public async Task GetAccessTokenAsync(CancellationToken cancellationToken) - { - AccessToken accessToken = await this.tokenCredential.GetTokenAsync(new TokenRequestContext(this.scopes), cancellationToken); - return accessToken.Token; - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/Exceptions/WorkspaceClientException.cs b/src/Azure/Azure.Quantum.Client/Exceptions/WorkspaceClientException.cs index e33d38930ae..8f5c2327b89 100644 --- a/src/Azure/Azure.Quantum.Client/Exceptions/WorkspaceClientException.cs +++ b/src/Azure/Azure.Quantum.Client/Exceptions/WorkspaceClientException.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -using Microsoft.Azure.Quantum.Client.Models; using System; namespace Microsoft.Azure.Quantum.Exceptions @@ -50,7 +49,7 @@ public WorkspaceClientException( /// ID of the subscription used by the Azure workspace client. /// Name of the resource group used by the Azure workspace client. /// Name of the workspace used by the Azure workspace client. - /// URI used by the Azure workspace client. + /// Workspace's location (region). /// ID of the job involved in the operation that caused the exception. /// Exception that is the cause of the current one. public WorkspaceClientException( @@ -58,7 +57,7 @@ public WorkspaceClientException( string subscriptionId, string resourceGroupName, string workspaceName, - Uri baseUri, + string location, string jobId, Exception inner) : base( @@ -66,13 +65,23 @@ public WorkspaceClientException( $"SubscriptionId: {subscriptionId}{Environment.NewLine}" + $"ResourceGroupName: {resourceGroupName}{Environment.NewLine}" + $"WorkspaceName: {workspaceName}{Environment.NewLine}" + - $"BaseUri: {baseUri}{Environment.NewLine}" + + $"Location: {location}{Environment.NewLine}" + $"JobId: {jobId}{Environment.NewLine}" + FormatInnerException(inner), inner) { + // Handle specific types of exceptions for additional data + if (inner is global::Azure.RequestFailedException requestException) + { + this.ErrorCode = requestException.ErrorCode; + this.Status = requestException.Status; + } } + public string ErrorCode { get; } + + public int Status { get; } + /// /// Formats the contents of the inner exception in so it can be included in the /// exception message and presented in an informative way. @@ -87,19 +96,6 @@ private static string FormatInnerException(Exception ex) if (ex != null) { formattedException += $"Server Error: {ex.Message}{Environment.NewLine}"; - - // Handle specific types of exceptions for additional data - if (ex is RestErrorException restErrorException) - { - formattedException += $"Error Code: {restErrorException?.Body?.Error?.Code}{Environment.NewLine}" + - $"Server message: {restErrorException?.Body?.Error?.Message}{Environment.NewLine}"; - - var headers = restErrorException?.Response?.Headers; - if (headers != null && headers.ContainsKey("x-ms-request-id")) - { - formattedException += $"Server Request Id: {headers["x-ms-request-id"]}{Environment.NewLine}"; - } - } } return formattedException; diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/CloudJob.cs b/src/Azure/Azure.Quantum.Client/JobManagement/CloudJob.cs index bfc879eb9d2..1da6fbf039a 100644 --- a/src/Azure/Azure.Quantum.Client/JobManagement/CloudJob.cs +++ b/src/Azure/Azure.Quantum.Client/JobManagement/CloudJob.cs @@ -6,7 +6,9 @@ namespace Microsoft.Azure.Quantum using System; using System.Threading; using System.Threading.Tasks; - using Microsoft.Azure.Quantum.Client.Models; + + using global::Azure.Quantum.Jobs.Models; + using Microsoft.Azure.Quantum.Utility; using Microsoft.Quantum.Runtime; @@ -19,7 +21,7 @@ public class CloudJob : IQuantumMachineJob /// Initializes a new instance of the class. /// /// The workspace. - /// The job details. + /// The job Details?. public CloudJob(IWorkspace workspace, JobDetails jobDetails) { Ensure.NotNull(workspace, nameof(workspace)); @@ -38,47 +40,75 @@ public CloudJob(IWorkspace workspace, JobDetails jobDetails) /// /// Gets the job id. /// - public string Id => Details.Id; + public virtual string Id => Details?.Id; + + /// + /// Gets the job id. + /// + public virtual string Name => Details?.Name; /// /// Gets whether the job execution has completed. /// - public bool InProgress => Status != "Cancelled" && + public virtual bool InProgress => Status != "Cancelled" && Status != "Failed" && Status != "Succeeded"; /// /// Gets the status of the submitted job. /// - public string Status => Details.Status; + public virtual string Status => Details?.Status?.ToString(); /// /// Gets whether the job execution completed successfully. /// - public bool Succeeded => Status == "Succeeded"; + public virtual bool Succeeded => Status == "Succeeded"; /// /// Gets an URI to access the job. /// - public Uri Uri => GenerateUri(); + public virtual Uri Uri => GenerateUri(); /// /// Gets the workspace. /// - public IWorkspace Workspace { get; private set; } + public virtual IWorkspace Workspace { get; private set; } + + /// + /// Gets the unique identifier for the provider. + /// + public virtual string ProviderId => this.Details?.ProviderId; + + /// + /// Gets the target identifier to run the job. + /// + public string Target => this.Details?.Target; /// - /// Gets the job details. + /// If available, returns Uri with the results of the execution. + /// > + public virtual Uri OutputDataUri => (this.Details?.OutputDataUri != null) + ? new Uri(this.Details?.OutputDataUri) + : null; + + /// + /// If available, returns the data format of the execution results. + /// + public virtual string OutputDataFormat => this.Details?.OutputDataFormat; + + /// + /// Gets the underlying job Details?. /// - public JobDetails Details { get; private set; } + public virtual JobDetails Details { get; private set; } /// /// Refreshes the job. /// /// The cancellation token. - public async Task RefreshAsync(CancellationToken cancellationToken = default) + /// + public virtual async Task RefreshAsync(CancellationToken cancellationToken = default) { - CloudJob job = (CloudJob)await this.Workspace.GetJobAsync(this.Details.Id, cancellationToken); + CloudJob job = (CloudJob)await this.Workspace.GetJobAsync(this.Details?.Id, cancellationToken); this.Details = job.Details; } @@ -86,20 +116,33 @@ public async Task RefreshAsync(CancellationToken cancellationToken = default) /// Cancels the job. /// /// The cancellation token. - public async Task CancelAsync(CancellationToken cancellationToken = default) + /// + public virtual async Task CancelAsync(CancellationToken cancellationToken = default) { - CloudJob job = (CloudJob)await this.Workspace.CancelJobAsync(this.Details.Id, cancellationToken); + CloudJob job = (CloudJob)await this.Workspace.CancelJobAsync(this.Details?.Id, cancellationToken); this.Details = job.Details; } - private Uri GenerateUri() + /// + /// Keeps polling the server until the Job status changes to be not in progress. + /// + /// Time to wait between polls. Defaults to 500. + /// Cancellation token. + /// + public async Task WaitForCompletion(int pollIntervalMilliseconds = 500, CancellationToken cancellationToken = default) { - if (!(this.Workspace is Workspace cloudWorkspace)) + await this.RefreshAsync(cancellationToken); + + while (this.InProgress) { - throw new NotSupportedException($"{typeof(CloudJob)}'s Workspace is not of type {typeof(Workspace)} and does not have enough data to generate URI"); + await Task.Delay(TimeSpan.FromMilliseconds(pollIntervalMilliseconds)); + await this.RefreshAsync(); } + } - var uriStr = $"https://ms.portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/{cloudWorkspace.SubscriptionId}/resourceGroups/{cloudWorkspace.ResourceGroupName}/providers/Microsoft.Quantum/Workspaces/{cloudWorkspace.WorkspaceName}/job_management?microsoft_azure_quantum_jobid={Id}"; + private Uri GenerateUri() + { + var uriStr = $"https://portal.azure.com/#@microsoft.onmicrosoft.com/resource/subscriptions/{Workspace.SubscriptionId}/resourceGroups/{Workspace.ResourceGroupName}/providers/Microsoft.Quantum/Workspaces/{Workspace.WorkspaceName}/job_management?microsoft_azure_quantum_jobid={Id}"; return new Uri(uriStr); } } diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/IWorkspace.cs b/src/Azure/Azure.Quantum.Client/JobManagement/IWorkspace.cs index a7d9bab7170..739e9dc087c 100644 --- a/src/Azure/Azure.Quantum.Client/JobManagement/IWorkspace.cs +++ b/src/Azure/Azure.Quantum.Client/JobManagement/IWorkspace.cs @@ -1,18 +1,44 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Quantum.Runtime; - namespace Microsoft.Azure.Quantum { + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + + using global::Azure.Quantum.Jobs; + /// /// IWorkspace interface. /// public interface IWorkspace { + /// + /// The Workspace's Azure Subscription. + /// + string SubscriptionId { get; } + + /// + /// The Workspace's resource group in Azure. + /// + string ResourceGroupName { get; } + + /// + /// The Workspace's location (region) in Azure. + /// + string Location { get; } + + /// + /// The Workspace's name. + /// + string WorkspaceName { get; } + + /// + /// The low-level client used to communicate with the service. + /// + public QuantumJobClient Client { get; } + /// /// Submits the job. /// @@ -47,16 +73,24 @@ Task GetJobAsync( /// Lists the jobs. /// /// The cancellation token. - /// List of jobs - Task> ListJobsAsync( + /// List of jobs. + IAsyncEnumerable ListJobsAsync( CancellationToken cancellationToken = default); /// /// Returns the list of quotas for a workspace. /// /// The cancellation token. - /// List of jobs - Task> ListQuotasAsync( + /// List of quotas. + IAsyncEnumerable ListQuotasAsync( + CancellationToken cancellationToken = default); + + /// + /// Returns a list with the status of each of the Providers in a workspace + /// + /// The cancellation token. + /// List of provider status. + IAsyncEnumerable ListProvidersStatusAsync( CancellationToken cancellationToken = default); /// diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/ProviderStatusInfo.cs b/src/Azure/Azure.Quantum.Client/JobManagement/ProviderStatusInfo.cs new file mode 100644 index 00000000000..088d8ec2d12 --- /dev/null +++ b/src/Azure/Azure.Quantum.Client/JobManagement/ProviderStatusInfo.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#nullable enable + +namespace Microsoft.Azure.Quantum +{ + using System.Collections.Generic; + using System.Linq; + + using Microsoft.Azure.Quantum.Utility; + + using Models = global::Azure.Quantum.Jobs.Models; + + /// + /// Wrapper for Azure.Quantum.Jobs.Models.ProviderStatus. + /// + public class ProviderStatusInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The workspace. + /// The provider status details. + public ProviderStatusInfo(IWorkspace workspace, Models.ProviderStatus status) + { + Ensure.NotNull(workspace, nameof(workspace)); + Ensure.NotNull(status, nameof(status)); + + Workspace = workspace; + Details = status; + } + + /// + /// Initializes a new instance of the class. + /// Use only for testing. + /// + protected ProviderStatusInfo() + { + } + + /// + /// Gets the workspace. + /// + public virtual IWorkspace? Workspace { get; } + + /// + /// Provider id. + /// + public virtual string? ProviderId => this.Details?.Id; + + /// + /// Provider availability. + /// + public virtual Models.ProviderAvailability? CurrentAvailability => this.Details?.CurrentAvailability; + + /// + /// List of all available targets for this provider. + /// + public virtual IEnumerable? Targets => + this.Details?.Targets?.Select(ps => new TargetStatusInfo(ps)); + + /// + /// Gets the provider status information. + /// + protected Models.ProviderStatus? Details { get; private set; } + } +} diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/QuotaInfo.cs b/src/Azure/Azure.Quantum.Client/JobManagement/QuotaInfo.cs index 71160112136..12e3d8580aa 100644 --- a/src/Azure/Azure.Quantum.Client/JobManagement/QuotaInfo.cs +++ b/src/Azure/Azure.Quantum.Client/JobManagement/QuotaInfo.cs @@ -1,13 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +#nullable enable + namespace Microsoft.Azure.Quantum { - using Microsoft.Azure.Quantum.Client.Models; + using global::Azure.Quantum.Jobs.Models; + using Microsoft.Azure.Quantum.Utility; /// - /// Wrapper for Microsoft.Azure.Quantum.Client.Models.Quota. + /// Wrapper for . /// public class QuotaInfo { @@ -16,23 +19,68 @@ public class QuotaInfo /// /// The workspace. /// The job details. - public QuotaInfo(IWorkspace workspace, Quota quota) + public QuotaInfo(IWorkspace workspace, QuantumJobQuota quota) { Ensure.NotNull(workspace, nameof(workspace)); Ensure.NotNull(quota, nameof(quota)); Workspace = workspace; - Quota = quota; + Details = quota; + } + + /// + /// Initializes a new instance of the class. + /// Use only for testing. + /// + protected QuotaInfo() + { } /// /// Gets the workspace. /// - public IWorkspace Workspace { get; private set; } + public virtual IWorkspace? Workspace { get; private set; } + + /// + /// The name of the dimension associated with the quota. + /// + public virtual string? Dimension => Details?.Dimension; + + /// + /// The scope at which the quota is applied. + /// + public virtual DimensionScope? Scope => Details?.Scope; + + /// + /// The unique identifier for the provider. + /// + public virtual string? ProviderId => Details?.ProviderId; + + /// + /// The amount of the usage that has been applied for the current period. + /// + public virtual float? Utilization => Details?.Utilization; + + /// + /// The amount of the usage that has been reserved but not applied for the current + /// period. + /// + public virtual float? Holds => Details?.Holds; + + /// + /// The maximum amount of usage allowed for the current period. + /// + public virtual float? Limit => Details?.Limit; + + /// + /// The time period in which the quota's underlying meter is accumulated. Based on + /// calendar year. 'None' is used for concurrent quotas. + /// + public virtual MeterPeriod? Period => Details?.Period; /// /// Gets the quota information. /// - public Quota Quota { get; private set; } + protected QuantumJobQuota? Details { get; private set; } } } diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/TargetStatusInfo.cs b/src/Azure/Azure.Quantum.Client/JobManagement/TargetStatusInfo.cs new file mode 100644 index 00000000000..98afab13a36 --- /dev/null +++ b/src/Azure/Azure.Quantum.Client/JobManagement/TargetStatusInfo.cs @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#nullable enable + +namespace Microsoft.Azure.Quantum +{ + using Microsoft.Azure.Quantum.Utility; + + using Models = global::Azure.Quantum.Jobs.Models; + + /// + /// Wrapper for Azure.Quantum.Jobs.Models.ProviderStatus. + /// + public class TargetStatusInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The workspace. + /// The provider status details. + public TargetStatusInfo(Models.TargetStatus status) + { + Ensure.NotNull(status, nameof(status)); + + Details = status; + } + + /// + /// Initializes a new instance of the class. + /// Use only for testing. + /// + protected TargetStatusInfo() + { + } + + /// + /// Target id. + /// + public virtual string? TargetId => Details?.Id; + + /// + /// Target availability. + /// + public virtual Models.TargetAvailability? CurrentAvailability => Details?.CurrentAvailability; + + /// + /// Average queue time in seconds. + /// + public virtual long? AverageQueueTime => Details?.AverageQueueTime; + + /// + /// A page with detailed status of the provider. + /// + public virtual string? StatusPage => Details?.StatusPage; + + /// + /// Gets the provider status information. + /// + protected Models.TargetStatus? Details { get; private set; } + } +} diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/Workspace.cs b/src/Azure/Azure.Quantum.Client/JobManagement/Workspace.cs index ec306e5e2dd..e6c9a7e1f97 100644 --- a/src/Azure/Azure.Quantum.Client/JobManagement/Workspace.cs +++ b/src/Azure/Azure.Quantum.Client/JobManagement/Workspace.cs @@ -6,12 +6,16 @@ namespace Microsoft.Azure.Quantum using System; using System.Collections.Generic; using System.Linq; + using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using global::Azure.Core; + using global::Azure.Identity; + using global::Azure.Quantum; + using global::Azure.Quantum.Jobs; + using global::Azure.Quantum.Jobs.Models; + using Microsoft.Azure.Quantum.Authentication; - using Microsoft.Azure.Quantum.Client; - using Microsoft.Azure.Quantum.Client.Models; using Microsoft.Azure.Quantum.Exceptions; using Microsoft.Azure.Quantum.Utility; @@ -21,159 +25,59 @@ namespace Microsoft.Azure.Quantum /// public class Workspace : IWorkspace { - private readonly Uri baseUri; - private readonly string resourceGroupName; - private readonly string subscriptionId; - private readonly string workspaceName; - /// /// Initializes a new instance of the class. /// /// The subscription identifier. /// Name of the resource group. /// Name of the workspace. - /// The token credential. - /// The base URI. - public Workspace( - string subscriptionId, - string resourceGroupName, - string workspaceName, - TokenCredential tokenCredential = null, - Uri baseUri = null) - : this( - subscriptionId, - resourceGroupName, - workspaceName, - tokenCredential == null ? null : new TokenCredentialProvider(tokenCredential), - baseUri) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The subscription identifier. - /// Name of the resource group. - /// Name of the workspace. - /// Normalized location to use with the default endpoint. - /// The token credential. + /// Azure region where the workspace was created. + /// The credentials to connect to Azure. If not provided it defaults to an interactive DefaultAzureCredentials. + /// Options for the client library when communication with Azure Service.. public Workspace( string subscriptionId, string resourceGroupName, string workspaceName, string location, - TokenCredential tokenCredential = null) - : this( - subscriptionId, - resourceGroupName, - workspaceName, - tokenCredential, - new Uri($"https://{location}.{Constants.DefaultLocationlessEndpoint}/")) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The subscription identifier. - /// Name of the resource group. - /// Name of the workspace. - /// The access token. - /// The base URI. - public Workspace( - string subscriptionId, - string resourceGroupName, - string workspaceName, - string accessToken, - Uri baseUri = null) - : this( - subscriptionId, - resourceGroupName, - workspaceName, - new StaticAccessTokenProvider(accessToken), - baseUri) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The subscription identifier. - /// Name of the resource group. - /// Name of the workspace. - /// The access token. - /// Normalized location to use with the default endpoint. - public Workspace( - string subscriptionId, - string resourceGroupName, - string workspaceName, - string accessToken, - string location) - : this( - subscriptionId, - resourceGroupName, - workspaceName, - new StaticAccessTokenProvider(accessToken), - new Uri($"https://{location}.{Constants.DefaultLocationlessEndpoint}/")) - { - } - - private Workspace( - string subscriptionId, - string resourceGroupName, - string workspaceName, - IAccessTokenProvider accessTokenProvider, - Uri baseUri = null) + TokenCredential credential = null, + QuantumJobClientOptions options = default) { - this.baseUri = baseUri ?? new Uri($"https://{Constants.DefaultLocation}.{Constants.DefaultLocationlessEndpoint}/"); + // Required parameters: Ensure.NotNullOrWhiteSpace(subscriptionId, nameof(subscriptionId)); - this.subscriptionId = subscriptionId; Ensure.NotNullOrWhiteSpace(resourceGroupName, nameof(resourceGroupName)); - this.resourceGroupName = resourceGroupName; Ensure.NotNullOrWhiteSpace(workspaceName, nameof(workspaceName)); - this.workspaceName = workspaceName; - - try - { - accessTokenProvider = accessTokenProvider ?? new CustomAccessTokenProvider(subscriptionId); - } - catch (Exception ex) - { - throw CreateException(ex, "Could not create an access token provider"); - } - - Ensure.NotNull(accessTokenProvider, nameof(accessTokenProvider)); - - try - { - this.QuantumClient = new QuantumClient(new ClientCredentials(accessTokenProvider)) - { - BaseUri = this.baseUri, - SubscriptionId = subscriptionId, - ResourceGroupName = resourceGroupName, - WorkspaceName = workspaceName, - }; - } - catch (Exception ex) - { - throw CreateException(ex, "Could not create an Azure quantum service client"); - } + Ensure.NotNullOrWhiteSpace(location, nameof(location)); + + // Optional parameters: + credential ??= CredentialFactory.CreateCredential(CredentialType.Default, subscriptionId); + options ??= new QuantumJobClientOptions(); + + this.ResourceGroupName = resourceGroupName; + this.WorkspaceName = workspaceName; + this.SubscriptionId = subscriptionId; + this.Location = location; + + this.Client = new QuantumJobClient( + subscriptionId, + resourceGroupName, + workspaceName, + location, + credential, + options); } - public string ResourceGroupName { get => resourceGroupName; } + public string ResourceGroupName { get; } + + public string SubscriptionId { get; } - public string SubscriptionId { get => subscriptionId; } + public string WorkspaceName { get; } - public string WorkspaceName { get => workspaceName; } + public string Location { get; } /// - /// Gets or sets the jobs client. - /// Internal only. + /// The client used to communicate with the service. /// - /// - /// The jobs client. - /// - internal IQuantumClient QuantumClient { get; set; } + public QuantumJobClient Client { get; } /// /// Submits the job. @@ -188,12 +92,12 @@ public async Task SubmitJobAsync( CancellationToken cancellationToken = default) { Ensure.NotNull(jobDefinition, nameof(jobDefinition)); - Ensure.NotNullOrWhiteSpace(jobDefinition.Details.Id, nameof(jobDefinition.Details.Id)); + Ensure.NotNullOrWhiteSpace(jobDefinition.Id, nameof(jobDefinition.Id)); try { - JobDetails jobDetails = await this.QuantumClient.Jobs.CreateAsync( - jobId: jobDefinition.Details.Id, + JobDetails jobDetails = await this.Client.CreateJobAsync( + jobId: jobDefinition.Id, job: jobDefinition.Details, cancellationToken: cancellationToken); @@ -201,7 +105,7 @@ public async Task SubmitJobAsync( } catch (Exception ex) { - throw CreateException(ex, "Could not submit job", jobDefinition.Details.Id); + throw CreateException(ex, "Could not submit job", jobDefinition.Id); } } @@ -217,11 +121,11 @@ public async Task CancelJobAsync(string jobId, CancellationToken cance try { - await this.QuantumClient.Jobs.CancelAsync( + await this.Client.CancelJobAsync( jobId: jobId, cancellationToken: cancellationToken); - JobDetails jobDetails = this.QuantumClient.Jobs.Get(jobId); + JobDetails jobDetails = this.Client.GetJob(jobId); return new CloudJob(this, jobDetails); } @@ -245,7 +149,7 @@ public async Task GetJobAsync(string jobId, CancellationToken cancella try { - JobDetails jobDetails = await this.QuantumClient.Jobs.GetAsync( + JobDetails jobDetails = await this.Client.GetJobAsync( jobId: jobId, cancellationToken: cancellationToken); @@ -264,19 +168,13 @@ public async Task GetJobAsync(string jobId, CancellationToken cancella /// /// List of jobs. /// - public async Task> ListJobsAsync(CancellationToken cancellationToken = default) + public async IAsyncEnumerable ListJobsAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) { - try - { - var jobs = await this.QuantumClient.Jobs.ListAsync( - cancellationToken: cancellationToken); + var jobs = this.Client.GetJobsAsync().WithCancellation(cancellationToken); - return jobs - .Select(details => new CloudJob(this, details)); - } - catch (Exception ex) + await foreach (var j in jobs) { - throw CreateException(ex, "Could not list jobs"); + yield return new CloudJob(this, j); } } @@ -287,18 +185,30 @@ public async Task> ListJobsAsync(CancellationToken cancell /// /// List of quotas. /// - public async Task> ListQuotasAsync(CancellationToken cancellationToken = default) + public async IAsyncEnumerable ListQuotasAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) { - try - { - var quotas = await this.QuantumClient.Quotas.ListAsync( - cancellationToken: cancellationToken); + var quotas = this.Client.GetQuotasAsync(cancellationToken); - return quotas.Select(quota => new QuotaInfo(this, quota)); + await foreach (var q in quotas) + { + yield return new QuotaInfo(this, q); } - catch (Exception ex) + } + + /// + /// Lists the quotas. + /// + /// The cancellation token. + /// + /// List of quotas. + /// + public async IAsyncEnumerable ListProvidersStatusAsync([EnumeratorCancellation] CancellationToken cancellationToken = default) + { + var status = this.Client.GetProviderStatusAsync(cancellationToken); + + await foreach (var s in status) { - throw CreateException(ex, "Could not list quotas"); + yield return new ProviderStatusInfo(this, s); } } @@ -313,14 +223,13 @@ public async Task> ListQuotasAsync(CancellationToken canc /// public async Task GetSasUriAsync(string containerName, string blobName = null, CancellationToken cancellationToken = default) { - BlobDetails details = new BlobDetails + BlobDetails details = new BlobDetails(containerName) { - ContainerName = containerName, BlobName = blobName, }; - var response = await this.QuantumClient.Storage.SasUriAsync(details, cancellationToken); - return response.SasUri; + var response = await this.Client.GetStorageSasUriAsync(details, cancellationToken); + return response.Value.SasUri; } private WorkspaceClientException CreateException( @@ -330,10 +239,10 @@ private WorkspaceClientException CreateException( { return new WorkspaceClientException( message, - subscriptionId, - resourceGroupName, - workspaceName, - baseUri, + this.SubscriptionId, + this.ResourceGroupName, + this.WorkspaceName, + this.Location, jobId, inner); } diff --git a/src/Azure/Azure.Quantum.Client/JobManagement/WorkspaceExtensions.cs b/src/Azure/Azure.Quantum.Client/JobManagement/WorkspaceExtensions.cs index 6d1730003b5..3e49c020285 100644 --- a/src/Azure/Azure.Quantum.Client/JobManagement/WorkspaceExtensions.cs +++ b/src/Azure/Azure.Quantum.Client/JobManagement/WorkspaceExtensions.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -using System.Collections.Generic; - namespace Microsoft.Azure.Quantum { /// @@ -44,15 +42,5 @@ public static CloudJob GetJob(this IWorkspace workspace, string jobId) { return workspace.GetJobAsync(jobId).GetAwaiter().GetResult(); } - - /// - /// Lists the jobs. - /// - /// The workspace. - /// List of job identifiers. - public static IEnumerable ListJobs(this IWorkspace workspace) - { - return workspace.ListJobsAsync().GetAwaiter().GetResult(); - } } } diff --git a/src/Azure/Azure.Quantum.Client/Microsoft.Azure.Quantum.Client.csproj b/src/Azure/Azure.Quantum.Client/Microsoft.Azure.Quantum.Client.csproj index 5cbb18eb53b..28a0ded1164 100644 --- a/src/Azure/Azure.Quantum.Client/Microsoft.Azure.Quantum.Client.csproj +++ b/src/Azure/Azure.Quantum.Client/Microsoft.Azure.Quantum.Client.csproj @@ -19,11 +19,10 @@ - + + + - - - all diff --git a/src/Azure/Azure.Quantum.Client/generated/IJobsOperations.cs b/src/Azure/Azure.Quantum.Client/generated/IJobsOperations.cs deleted file mode 100644 index af9fd24eb91..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/IJobsOperations.cs +++ /dev/null @@ -1,134 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - - /// - /// JobsOperations operations. - /// - public partial interface IJobsOperations - { - /// - /// List jobs. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task>> ListWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - /// - /// Get job by id - /// - /// - /// Id of the job. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task> GetWithHttpMessagesAsync(string jobId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - /// - /// Create a job. - /// - /// - /// Id of the job. - /// - /// - /// The complete metadata of the job to submit. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task> CreateWithHttpMessagesAsync(string jobId, JobDetails job, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - /// - /// Cancel a job. - /// - /// - /// Id of the job. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when a required parameter is null - /// - Task CancelWithHttpMessagesAsync(string jobId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - /// - /// List jobs. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/IProvidersOperations.cs b/src/Azure/Azure.Quantum.Client/generated/IProvidersOperations.cs deleted file mode 100644 index 2cc635ca7c8..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/IProvidersOperations.cs +++ /dev/null @@ -1,68 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - - /// - /// ProvidersOperations operations. - /// - public partial interface IProvidersOperations - { - /// - /// Get provider status. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task>> GetStatusWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - /// - /// Get provider status. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task>> GetStatusNextWithHttpMessagesAsync(string nextPageLink, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/IQuantumClient.cs b/src/Azure/Azure.Quantum.Client/generated/IQuantumClient.cs deleted file mode 100644 index 6f0f9edbf5c..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/IQuantumClient.cs +++ /dev/null @@ -1,99 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using Newtonsoft.Json; - - /// - /// Azure Quantum REST API client - /// - public partial interface IQuantumClient : System.IDisposable - { - /// - /// The base URI of the service. - /// - System.Uri BaseUri { get; set; } - - /// - /// Gets or sets json serialization settings. - /// - JsonSerializerSettings SerializationSettings { get; } - - /// - /// Gets or sets json deserialization settings. - /// - JsonSerializerSettings DeserializationSettings { get; } - - /// - /// Credentials needed for the client to connect to Azure. - /// - ServiceClientCredentials Credentials { get; } - - /// - /// The Azure subscription ID. This is a GUID-formatted string (e.g. - /// 00000000-0000-0000-0000-000000000000) - /// - string SubscriptionId { get; set; } - - /// - /// Name of an Azure resource group. - /// - string ResourceGroupName { get; set; } - - /// - /// Name of the workspace. - /// - string WorkspaceName { get; set; } - - /// - /// The preferred language for the response. - /// - string AcceptLanguage { get; set; } - - /// - /// The retry timeout in seconds for Long Running Operations. Default - /// value is 30. - /// - int? LongRunningOperationRetryTimeout { get; set; } - - /// - /// Whether a unique x-ms-client-request-id should be generated. When - /// set to true a unique x-ms-client-request-id value is generated and - /// included in each request. Default is true. - /// - bool? GenerateClientRequestId { get; set; } - - - /// - /// Gets the IJobsOperations. - /// - IJobsOperations Jobs { get; } - - /// - /// Gets the IProvidersOperations. - /// - IProvidersOperations Providers { get; } - - /// - /// Gets the IStorageOperations. - /// - IStorageOperations Storage { get; } - - /// - /// Gets the IQuotasOperations. - /// - IQuotasOperations Quotas { get; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/IQuotasOperations.cs b/src/Azure/Azure.Quantum.Client/generated/IQuotasOperations.cs deleted file mode 100644 index b25390bb5df..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/IQuotasOperations.cs +++ /dev/null @@ -1,68 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - - /// - /// QuotasOperations operations. - /// - public partial interface IQuotasOperations - { - /// - /// List quotas for the given workspace. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task>> ListWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - /// - /// List quotas for the given workspace. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/IStorageOperations.cs b/src/Azure/Azure.Quantum.Client/generated/IStorageOperations.cs deleted file mode 100644 index 838761aab6c..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/IStorageOperations.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - - /// - /// StorageOperations operations. - /// - public partial interface IStorageOperations - { - /// - /// Gets a URL with SAS token for a container/blob in the storage - /// account associated with the workspace. The SAS URL can be used to - /// upload job input and/or download job output. - /// - /// - /// The details (name and container) of the blob to store or download - /// data. - /// - /// - /// The headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - Task> SasUriWithHttpMessagesAsync(BlobDetails blobDetails, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/JobsOperations.cs b/src/Azure/Azure.Quantum.Client/generated/JobsOperations.cs deleted file mode 100644 index 250d26ab5a2..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/JobsOperations.cs +++ /dev/null @@ -1,974 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - - /// - /// JobsOperations operations. - /// - internal partial class JobsOperations : IServiceOperations, IJobsOperations - { - /// - /// Initializes a new instance of the JobsOperations class. - /// - /// - /// Reference to the service client. - /// - /// - /// Thrown when a required parameter is null - /// - internal JobsOperations(QuantumClient client) - { - if (client == null) - { - throw new System.ArgumentNullException("client"); - } - Client = client; - } - - /// - /// Gets a reference to the QuantumClient - /// - public QuantumClient Client { get; private set; } - - /// - /// List jobs. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task>> ListWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex = new CloudException(_errorBody.Message); - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse>(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - /// - /// Get job by id - /// - /// - /// Id of the job. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task> GetWithHttpMessagesAsync(string jobId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - if (jobId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "jobId"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("jobId", jobId); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - _url = _url.Replace("{jobId}", System.Uri.EscapeDataString(jobId)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - /// - /// Create a job. - /// - /// - /// Id of the job. - /// - /// - /// The complete metadata of the job to submit. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task> CreateWithHttpMessagesAsync(string jobId, JobDetails job, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - if (jobId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "jobId"); - } - if (job == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "job"); - } - if (job != null) - { - job.Validate(); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("jobId", jobId); - tracingParameters.Add("job", job); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - _url = _url.Replace("{jobId}", System.Uri.EscapeDataString(jobId)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("PUT"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - if(job != null) - { - _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(job, Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); - _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); - } - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200 && (int)_statusCode != 201) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - // Deserialize Response - if ((int)_statusCode == 201) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - /// - /// Cancel a job. - /// - /// - /// Id of the job. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task CancelWithHttpMessagesAsync(string jobId, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - if (jobId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "jobId"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("jobId", jobId); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - _url = _url.Replace("{jobId}", System.Uri.EscapeDataString(jobId)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("DELETE"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 204) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - /// - /// List jobs. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (nextPageLink == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("nextPageLink", nextPageLink); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); - } - // Construct URL - string _url = "{nextLink}"; - _url = _url.Replace("{nextLink}", nextPageLink); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex = new CloudException(_errorBody.Message); - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse>(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/JobsOperationsExtensions.cs b/src/Azure/Azure.Quantum.Client/generated/JobsOperationsExtensions.cs deleted file mode 100644 index 24fa241b994..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/JobsOperationsExtensions.cs +++ /dev/null @@ -1,192 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Threading; - using System.Threading.Tasks; - - /// - /// Extension methods for JobsOperations. - /// - public static partial class JobsOperationsExtensions - { - /// - /// List jobs. - /// - /// - /// The operations group for this extension method. - /// - public static IPage List(this IJobsOperations operations) - { - return operations.ListAsync().GetAwaiter().GetResult(); - } - - /// - /// List jobs. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The cancellation token. - /// - public static async Task> ListAsync(this IJobsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - /// - /// Get job by id - /// - /// - /// The operations group for this extension method. - /// - /// - /// Id of the job. - /// - public static JobDetails Get(this IJobsOperations operations, string jobId) - { - return operations.GetAsync(jobId).GetAwaiter().GetResult(); - } - - /// - /// Get job by id - /// - /// - /// The operations group for this extension method. - /// - /// - /// Id of the job. - /// - /// - /// The cancellation token. - /// - public static async Task GetAsync(this IJobsOperations operations, string jobId, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.GetWithHttpMessagesAsync(jobId, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - /// - /// Create a job. - /// - /// - /// The operations group for this extension method. - /// - /// - /// Id of the job. - /// - /// - /// The complete metadata of the job to submit. - /// - public static JobDetails Create(this IJobsOperations operations, string jobId, JobDetails job) - { - return operations.CreateAsync(jobId, job).GetAwaiter().GetResult(); - } - - /// - /// Create a job. - /// - /// - /// The operations group for this extension method. - /// - /// - /// Id of the job. - /// - /// - /// The complete metadata of the job to submit. - /// - /// - /// The cancellation token. - /// - public static async Task CreateAsync(this IJobsOperations operations, string jobId, JobDetails job, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.CreateWithHttpMessagesAsync(jobId, job, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - /// - /// Cancel a job. - /// - /// - /// The operations group for this extension method. - /// - /// - /// Id of the job. - /// - public static void Cancel(this IJobsOperations operations, string jobId) - { - operations.CancelAsync(jobId).GetAwaiter().GetResult(); - } - - /// - /// Cancel a job. - /// - /// - /// The operations group for this extension method. - /// - /// - /// Id of the job. - /// - /// - /// The cancellation token. - /// - public static async Task CancelAsync(this IJobsOperations operations, string jobId, CancellationToken cancellationToken = default(CancellationToken)) - { - (await operations.CancelWithHttpMessagesAsync(jobId, null, cancellationToken).ConfigureAwait(false)).Dispose(); - } - - /// - /// List jobs. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - public static IPage ListNext(this IJobsOperations operations, string nextPageLink) - { - return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); - } - - /// - /// List jobs. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// The cancellation token. - /// - public static async Task> ListNextAsync(this IJobsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/BlobDetails.cs b/src/Azure/Azure.Quantum.Client/generated/Models/BlobDetails.cs deleted file mode 100644 index 6698af8a001..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/BlobDetails.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Microsoft.Rest; - using Newtonsoft.Json; - using System.Linq; - - /// - /// Blob details. - /// - public partial class BlobDetails - { - /// - /// Initializes a new instance of the BlobDetails class. - /// - public BlobDetails() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the BlobDetails class. - /// - /// The container name. - /// The blob name. - public BlobDetails(string containerName, string blobName = default(string)) - { - ContainerName = containerName; - BlobName = blobName; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets or sets the container name. - /// - [JsonProperty(PropertyName = "containerName")] - public string ContainerName { get; set; } - - /// - /// Gets or sets the blob name. - /// - [JsonProperty(PropertyName = "blobName")] - public string BlobName { get; set; } - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public virtual void Validate() - { - if (ContainerName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "ContainerName"); - } - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/DimensionScope.cs b/src/Azure/Azure.Quantum.Client/generated/Models/DimensionScope.cs deleted file mode 100644 index 2f00b039adc..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/DimensionScope.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - - /// - /// Defines values for DimensionScope. - /// - public static class DimensionScope - { - public const string Workspace = "Workspace"; - public const string Subscription = "Subscription"; - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/ErrorData.cs b/src/Azure/Azure.Quantum.Client/generated/Models/ErrorData.cs deleted file mode 100644 index c817ad9fa72..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/ErrorData.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Newtonsoft.Json; - using System.Linq; - - /// - /// An error response from Azure. - /// - public partial class ErrorData - { - /// - /// Initializes a new instance of the ErrorData class. - /// - public ErrorData() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the ErrorData class. - /// - /// An identifier for the error. Codes are invariant - /// and are intended to be consumed programmatically. - /// A message describing the error, intended to - /// be suitable for displaying in a user interface. - public ErrorData(string code = default(string), string message = default(string)) - { - Code = code; - Message = message; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets or sets an identifier for the error. Codes are invariant and - /// are intended to be consumed programmatically. - /// - [JsonProperty(PropertyName = "code")] - public string Code { get; set; } - - /// - /// Gets or sets a message describing the error, intended to be - /// suitable for displaying in a user interface. - /// - [JsonProperty(PropertyName = "message")] - public string Message { get; set; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/JobDetails.cs b/src/Azure/Azure.Quantum.Client/generated/Models/JobDetails.cs deleted file mode 100644 index e4a0a5a2711..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/JobDetails.cs +++ /dev/null @@ -1,233 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Microsoft.Rest; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - - /// - /// Job details. - /// - public partial class JobDetails - { - /// - /// Initializes a new instance of the JobDetails class. - /// - public JobDetails() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the JobDetails class. - /// - /// The blob container SAS uri, the - /// container is used to host job data. - /// The format of the input data. - /// The unique identifier for the - /// provider. - /// The target identifier to run the job. - /// The job id. - /// The job name. Is not required for the name to be - /// unique and it's only used for display purposes. - /// The input blob SAS uri, if specified, it - /// will override the default input blob in the container. - /// The input parameters for the job. JSON - /// object used by the target solver. It is expected that the size of - /// this object is small and only used to specify parameters for the - /// execution target, not the input data. - /// The job metadata. Metadata provides client - /// the ability to store client-specific information - /// The output blob SAS uri. When a job - /// finishes successfully, results will be uploaded to this - /// blob. - /// The format of the output - /// data. - /// The job status. Possible values include: - /// 'Waiting', 'Executing', 'Succeeded', 'Failed', 'Cancelled' - /// The creation time of the job. - /// The time when the job began - /// execution. - /// The time when the job finished - /// execution. - /// The time when a job was successfully - /// cancelled. - /// The error data for the job. This is - /// expected only when Status 'Failed'. - public JobDetails(string containerUri, string inputDataFormat, string providerId, string target, string id = default(string), string name = default(string), string inputDataUri = default(string), object inputParams = default(object), IDictionary metadata = default(IDictionary), string outputDataUri = default(string), string outputDataFormat = default(string), string status = default(string), System.DateTime? creationTime = default(System.DateTime?), System.DateTime? beginExecutionTime = default(System.DateTime?), System.DateTime? endExecutionTime = default(System.DateTime?), System.DateTime? cancellationTime = default(System.DateTime?), ErrorData errorData = default(ErrorData)) - { - Id = id; - Name = name; - ContainerUri = containerUri; - InputDataUri = inputDataUri; - InputDataFormat = inputDataFormat; - InputParams = inputParams; - ProviderId = providerId; - Target = target; - Metadata = metadata; - OutputDataUri = outputDataUri; - OutputDataFormat = outputDataFormat; - Status = status; - CreationTime = creationTime; - BeginExecutionTime = beginExecutionTime; - EndExecutionTime = endExecutionTime; - CancellationTime = cancellationTime; - ErrorData = errorData; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets or sets the job id. - /// - [JsonProperty(PropertyName = "id")] - public string Id { get; set; } - - /// - /// Gets or sets the job name. Is not required for the name to be - /// unique and it's only used for display purposes. - /// - [JsonProperty(PropertyName = "name")] - public string Name { get; set; } - - /// - /// Gets or sets the blob container SAS uri, the container is used to - /// host job data. - /// - [JsonProperty(PropertyName = "containerUri")] - public string ContainerUri { get; set; } - - /// - /// Gets or sets the input blob SAS uri, if specified, it will override - /// the default input blob in the container. - /// - [JsonProperty(PropertyName = "inputDataUri")] - public string InputDataUri { get; set; } - - /// - /// Gets or sets the format of the input data. - /// - [JsonProperty(PropertyName = "inputDataFormat")] - public string InputDataFormat { get; set; } - - /// - /// Gets or sets the input parameters for the job. JSON object used by - /// the target solver. It is expected that the size of this object is - /// small and only used to specify parameters for the execution target, - /// not the input data. - /// - [JsonProperty(PropertyName = "inputParams")] - public object InputParams { get; set; } - - /// - /// Gets or sets the unique identifier for the provider. - /// - [JsonProperty(PropertyName = "providerId")] - public string ProviderId { get; set; } - - /// - /// Gets or sets the target identifier to run the job. - /// - [JsonProperty(PropertyName = "target")] - public string Target { get; set; } - - /// - /// Gets or sets the job metadata. Metadata provides client the ability - /// to store client-specific information - /// - [JsonProperty(PropertyName = "metadata")] - public IDictionary Metadata { get; set; } - - /// - /// Gets or sets the output blob SAS uri. When a job finishes - /// successfully, results will be uploaded to this blob. - /// - [JsonProperty(PropertyName = "outputDataUri")] - public string OutputDataUri { get; set; } - - /// - /// Gets or sets the format of the output data. - /// - [JsonProperty(PropertyName = "outputDataFormat")] - public string OutputDataFormat { get; set; } - - /// - /// Gets the job status. Possible values include: 'Waiting', - /// 'Executing', 'Succeeded', 'Failed', 'Cancelled' - /// - [JsonProperty(PropertyName = "status")] - public string Status { get; private set; } - - /// - /// Gets the creation time of the job. - /// - [JsonProperty(PropertyName = "creationTime")] - public System.DateTime? CreationTime { get; private set; } - - /// - /// Gets the time when the job began execution. - /// - [JsonProperty(PropertyName = "beginExecutionTime")] - public System.DateTime? BeginExecutionTime { get; private set; } - - /// - /// Gets the time when the job finished execution. - /// - [JsonProperty(PropertyName = "endExecutionTime")] - public System.DateTime? EndExecutionTime { get; private set; } - - /// - /// Gets the time when a job was successfully cancelled. - /// - [JsonProperty(PropertyName = "cancellationTime")] - public System.DateTime? CancellationTime { get; private set; } - - /// - /// Gets the error data for the job. This is expected only when Status - /// 'Failed'. - /// - [JsonProperty(PropertyName = "errorData")] - public ErrorData ErrorData { get; private set; } - - /// - /// Validate the object. - /// - /// - /// Thrown if validation fails - /// - public virtual void Validate() - { - if (ContainerUri == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "ContainerUri"); - } - if (InputDataFormat == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "InputDataFormat"); - } - if (ProviderId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "ProviderId"); - } - if (Target == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "Target"); - } - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/JobStatus.cs b/src/Azure/Azure.Quantum.Client/generated/Models/JobStatus.cs deleted file mode 100644 index cf79f42d3e9..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/JobStatus.cs +++ /dev/null @@ -1,25 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - - /// - /// Defines values for JobStatus. - /// - public static class JobStatus - { - public const string Waiting = "Waiting"; - public const string Executing = "Executing"; - public const string Succeeded = "Succeeded"; - public const string Failed = "Failed"; - public const string Cancelled = "Cancelled"; - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/MeterPeriod.cs b/src/Azure/Azure.Quantum.Client/generated/Models/MeterPeriod.cs deleted file mode 100644 index c8c8092b34f..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/MeterPeriod.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - - /// - /// Defines values for MeterPeriod. - /// - public static class MeterPeriod - { - public const string None = "None"; - public const string Monthly = "Monthly"; - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/Page.cs b/src/Azure/Azure.Quantum.Client/generated/Models/Page.cs deleted file mode 100644 index faf255dd623..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/Page.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - - /// - /// Defines a page in Azure responses. - /// - /// Type of the page content items - [JsonObject] - public class Page : IPage - { - /// - /// Gets the link to the next page. - /// - [JsonProperty("nextLink")] - public string NextPageLink { get; private set; } - - [JsonProperty("value")] - private IList Items{ get; set; } - - /// - /// Returns an enumerator that iterates through the collection. - /// - /// A an enumerator that can be used to iterate through the collection. - public IEnumerator GetEnumerator() - { - return Items == null ? System.Linq.Enumerable.Empty().GetEnumerator() : Items.GetEnumerator(); - } - - /// - /// Returns an enumerator that iterates through the collection. - /// - /// A an enumerator that can be used to iterate through the collection. - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/ProviderAvailability.cs b/src/Azure/Azure.Quantum.Client/generated/Models/ProviderAvailability.cs deleted file mode 100644 index 73232a3ff71..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/ProviderAvailability.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - - /// - /// Defines values for ProviderAvailability. - /// - public static class ProviderAvailability - { - public const string Available = "Available"; - public const string Degraded = "Degraded"; - public const string Unavailable = "Unavailable"; - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/ProviderStatus.cs b/src/Azure/Azure.Quantum.Client/generated/Models/ProviderStatus.cs deleted file mode 100644 index 43baf39b445..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/ProviderStatus.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - - /// - /// Providers status. - /// - public partial class ProviderStatus - { - /// - /// Initializes a new instance of the ProviderStatus class. - /// - public ProviderStatus() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the ProviderStatus class. - /// - /// Provider id. - /// Provider availability. Possible - /// values include: 'Available', 'Degraded', 'Unavailable' - public ProviderStatus(string id = default(string), string currentAvailability = default(string), IList targets = default(IList)) - { - Id = id; - CurrentAvailability = currentAvailability; - Targets = targets; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets provider id. - /// - [JsonProperty(PropertyName = "id")] - public string Id { get; private set; } - - /// - /// Gets provider availability. Possible values include: 'Available', - /// 'Degraded', 'Unavailable' - /// - [JsonProperty(PropertyName = "currentAvailability")] - public string CurrentAvailability { get; private set; } - - /// - /// - [JsonProperty(PropertyName = "targets")] - public IList Targets { get; private set; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/Quota.cs b/src/Azure/Azure.Quantum.Client/generated/Models/Quota.cs deleted file mode 100644 index dc0ca8d75aa..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/Quota.cs +++ /dev/null @@ -1,114 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Newtonsoft.Json; - using System.Linq; - - /// - /// Quota information. - /// - public partial class Quota - { - /// - /// Initializes a new instance of the Quota class. - /// - public Quota() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the Quota class. - /// - /// The name of the dimension associated with - /// the quota. - /// The scope at which the quota is applied. - /// Possible values include: 'Workspace', 'Subscription' - /// The unique identifier for the - /// provider. - /// The amount of the usage that has been - /// applied for the current period. - /// The amount of the usage that has been reserved - /// but not applied for the current period. - /// The maximum amount of usage allowed for the - /// current period. - /// The time period in which the quota's - /// underlying meter is accumulated. Based on calendar year. 'None' is - /// used for concurrent quotas. Possible values include: 'None', - /// 'Monthly' - public Quota(string dimension = default(string), string scope = default(string), string providerId = default(string), double? utilization = default(double?), double? holds = default(double?), double? limit = default(double?), string period = default(string)) - { - Dimension = dimension; - Scope = scope; - ProviderId = providerId; - Utilization = utilization; - Holds = holds; - Limit = limit; - Period = period; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets or sets the name of the dimension associated with the quota. - /// - [JsonProperty(PropertyName = "dimension")] - public string Dimension { get; set; } - - /// - /// Gets or sets the scope at which the quota is applied. Possible - /// values include: 'Workspace', 'Subscription' - /// - [JsonProperty(PropertyName = "scope")] - public string Scope { get; set; } - - /// - /// Gets or sets the unique identifier for the provider. - /// - [JsonProperty(PropertyName = "providerId")] - public string ProviderId { get; set; } - - /// - /// Gets or sets the amount of the usage that has been applied for the - /// current period. - /// - [JsonProperty(PropertyName = "utilization")] - public double? Utilization { get; set; } - - /// - /// Gets or sets the amount of the usage that has been reserved but not - /// applied for the current period. - /// - [JsonProperty(PropertyName = "holds")] - public double? Holds { get; set; } - - /// - /// Gets or sets the maximum amount of usage allowed for the current - /// period. - /// - [JsonProperty(PropertyName = "limit")] - public double? Limit { get; set; } - - /// - /// Gets or sets the time period in which the quota's underlying meter - /// is accumulated. Based on calendar year. 'None' is used for - /// concurrent quotas. Possible values include: 'None', 'Monthly' - /// - [JsonProperty(PropertyName = "period")] - public string Period { get; set; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/RestError.cs b/src/Azure/Azure.Quantum.Client/generated/Models/RestError.cs deleted file mode 100644 index 3545335a6ba..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/RestError.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Newtonsoft.Json; - using System.Linq; - - /// - /// Error information returned by the API - /// - public partial class RestError - { - /// - /// Initializes a new instance of the RestError class. - /// - public RestError() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the RestError class. - /// - public RestError(ErrorData error = default(ErrorData)) - { - Error = error; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// - [JsonProperty(PropertyName = "error")] - public ErrorData Error { get; set; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/RestErrorException.cs b/src/Azure/Azure.Quantum.Client/generated/Models/RestErrorException.cs deleted file mode 100644 index cb5804185a0..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/RestErrorException.cs +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Microsoft.Rest; - - /// - /// Exception thrown for an invalid response with RestError information. - /// - public partial class RestErrorException : RestException - { - /// - /// Gets information about the associated HTTP request. - /// - public HttpRequestMessageWrapper Request { get; set; } - - /// - /// Gets information about the associated HTTP response. - /// - public HttpResponseMessageWrapper Response { get; set; } - - /// - /// Gets or sets the body object. - /// - public RestError Body { get; set; } - - /// - /// Initializes a new instance of the RestErrorException class. - /// - public RestErrorException() - { - } - - /// - /// Initializes a new instance of the RestErrorException class. - /// - /// The exception message. - public RestErrorException(string message) - : this(message, null) - { - } - - /// - /// Initializes a new instance of the RestErrorException class. - /// - /// The exception message. - /// Inner exception. - public RestErrorException(string message, System.Exception innerException) - : base(message, innerException) - { - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/SasUriResponse.cs b/src/Azure/Azure.Quantum.Client/generated/Models/SasUriResponse.cs deleted file mode 100644 index b811d2e06a6..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/SasUriResponse.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Newtonsoft.Json; - using System.Linq; - - /// - /// Get SAS URL operation response. - /// - public partial class SasUriResponse - { - /// - /// Initializes a new instance of the SasUriResponse class. - /// - public SasUriResponse() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the SasUriResponse class. - /// - /// A URL with a SAS token to upload a blob for - /// execution in the given workspace. - public SasUriResponse(string sasUri = default(string)) - { - SasUri = sasUri; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets or sets a URL with a SAS token to upload a blob for execution - /// in the given workspace. - /// - [JsonProperty(PropertyName = "sasUri")] - public string SasUri { get; set; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/TargetAvailability.cs b/src/Azure/Azure.Quantum.Client/generated/Models/TargetAvailability.cs deleted file mode 100644 index a2009e7852c..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/TargetAvailability.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - - /// - /// Defines values for TargetAvailability. - /// - public static class TargetAvailability - { - public const string Available = "Available"; - public const string Degraded = "Degraded"; - public const string Unavailable = "Unavailable"; - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/Models/TargetStatus.cs b/src/Azure/Azure.Quantum.Client/generated/Models/TargetStatus.cs deleted file mode 100644 index 78c150b3c95..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/Models/TargetStatus.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client.Models -{ - using Newtonsoft.Json; - using System.Linq; - - /// - /// Target status. - /// - public partial class TargetStatus - { - /// - /// Initializes a new instance of the TargetStatus class. - /// - public TargetStatus() - { - CustomInit(); - } - - /// - /// Initializes a new instance of the TargetStatus class. - /// - /// Target id. - /// Target availability. Possible - /// values include: 'Available', 'Degraded', 'Unavailable' - /// Average queue time in - /// seconds. - /// A page with detailed status of the - /// provider. - public TargetStatus(string id = default(string), string currentAvailability = default(string), long? averageQueueTime = default(long?), string statusPage = default(string)) - { - Id = id; - CurrentAvailability = currentAvailability; - AverageQueueTime = averageQueueTime; - StatusPage = statusPage; - CustomInit(); - } - - /// - /// An initialization method that performs custom operations like setting defaults - /// - partial void CustomInit(); - - /// - /// Gets target id. - /// - [JsonProperty(PropertyName = "id")] - public string Id { get; private set; } - - /// - /// Gets target availability. Possible values include: 'Available', - /// 'Degraded', 'Unavailable' - /// - [JsonProperty(PropertyName = "currentAvailability")] - public string CurrentAvailability { get; private set; } - - /// - /// Gets average queue time in seconds. - /// - [JsonProperty(PropertyName = "averageQueueTime")] - public long? AverageQueueTime { get; private set; } - - /// - /// Gets a page with detailed status of the provider. - /// - [JsonProperty(PropertyName = "statusPage")] - public string StatusPage { get; private set; } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/ProvidersOperations.cs b/src/Azure/Azure.Quantum.Client/generated/ProvidersOperations.cs deleted file mode 100644 index 9cf8af20c06..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/ProvidersOperations.cs +++ /dev/null @@ -1,397 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - - /// - /// ProvidersOperations operations. - /// - internal partial class ProvidersOperations : IServiceOperations, IProvidersOperations - { - /// - /// Initializes a new instance of the ProvidersOperations class. - /// - /// - /// Reference to the service client. - /// - /// - /// Thrown when a required parameter is null - /// - internal ProvidersOperations(QuantumClient client) - { - if (client == null) - { - throw new System.ArgumentNullException("client"); - } - Client = client; - } - - /// - /// Gets a reference to the QuantumClient - /// - public QuantumClient Client { get; private set; } - - /// - /// Get provider status. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task>> GetStatusWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "GetStatus", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/providerStatus").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse>(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - /// - /// Get provider status. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task>> GetStatusNextWithHttpMessagesAsync(string nextPageLink, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (nextPageLink == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("nextPageLink", nextPageLink); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "GetStatusNext", tracingParameters); - } - // Construct URL - string _url = "{nextLink}"; - _url = _url.Replace("{nextLink}", nextPageLink); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse>(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/ProvidersOperationsExtensions.cs b/src/Azure/Azure.Quantum.Client/generated/ProvidersOperationsExtensions.cs deleted file mode 100644 index 649d483f64a..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/ProvidersOperationsExtensions.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Threading; - using System.Threading.Tasks; - - /// - /// Extension methods for ProvidersOperations. - /// - public static partial class ProvidersOperationsExtensions - { - /// - /// Get provider status. - /// - /// - /// The operations group for this extension method. - /// - public static IPage GetStatus(this IProvidersOperations operations) - { - return operations.GetStatusAsync().GetAwaiter().GetResult(); - } - - /// - /// Get provider status. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The cancellation token. - /// - public static async Task> GetStatusAsync(this IProvidersOperations operations, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.GetStatusWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - /// - /// Get provider status. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - public static IPage GetStatusNext(this IProvidersOperations operations, string nextPageLink) - { - return operations.GetStatusNextAsync(nextPageLink).GetAwaiter().GetResult(); - } - - /// - /// Get provider status. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// The cancellation token. - /// - public static async Task> GetStatusNextAsync(this IProvidersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.GetStatusNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/QuantumClient.cs b/src/Azure/Azure.Quantum.Client/generated/QuantumClient.cs deleted file mode 100644 index 7344a8506c4..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/QuantumClient.cs +++ /dev/null @@ -1,381 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Microsoft.Rest.Serialization; - using Models; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - - /// - /// Azure Quantum REST API client - /// - public partial class QuantumClient : ServiceClient, IQuantumClient, IAzureClient - { - /// - /// The base URI of the service. - /// - public System.Uri BaseUri { get; set; } - - /// - /// Gets or sets json serialization settings. - /// - public JsonSerializerSettings SerializationSettings { get; private set; } - - /// - /// Gets or sets json deserialization settings. - /// - public JsonSerializerSettings DeserializationSettings { get; private set; } - - /// - /// Credentials needed for the client to connect to Azure. - /// - public ServiceClientCredentials Credentials { get; private set; } - - /// - /// The Azure subscription ID. This is a GUID-formatted string (e.g. - /// 00000000-0000-0000-0000-000000000000) - /// - public string SubscriptionId { get; set; } - - /// - /// Name of an Azure resource group. - /// - public string ResourceGroupName { get; set; } - - /// - /// Name of the workspace. - /// - public string WorkspaceName { get; set; } - - /// - /// The preferred language for the response. - /// - public string AcceptLanguage { get; set; } - - /// - /// The retry timeout in seconds for Long Running Operations. Default value is - /// 30. - /// - public int? LongRunningOperationRetryTimeout { get; set; } - - /// - /// Whether a unique x-ms-client-request-id should be generated. When set to - /// true a unique x-ms-client-request-id value is generated and included in - /// each request. Default is true. - /// - public bool? GenerateClientRequestId { get; set; } - - /// - /// Gets the IJobsOperations. - /// - public virtual IJobsOperations Jobs { get; private set; } - - /// - /// Gets the IProvidersOperations. - /// - public virtual IProvidersOperations Providers { get; private set; } - - /// - /// Gets the IStorageOperations. - /// - public virtual IStorageOperations Storage { get; private set; } - - /// - /// Gets the IQuotasOperations. - /// - public virtual IQuotasOperations Quotas { get; private set; } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// HttpClient to be used - /// - /// - /// True: will dispose the provided httpClient on calling QuantumClient.Dispose(). False: will not dispose provided httpClient - protected QuantumClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient) - { - Initialize(); - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - protected QuantumClient(params DelegatingHandler[] handlers) : base(handlers) - { - Initialize(); - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - protected QuantumClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) - { - Initialize(); - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Optional. The base URI of the service. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - protected QuantumClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) - { - if (baseUri == null) - { - throw new System.ArgumentNullException("baseUri"); - } - BaseUri = baseUri; - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Optional. The base URI of the service. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - protected QuantumClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) - { - if (baseUri == null) - { - throw new System.ArgumentNullException("baseUri"); - } - BaseUri = baseUri; - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public QuantumClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) - { - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - Credentials = credentials; - if (Credentials != null) - { - Credentials.InitializeServiceClient(this); - } - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// HttpClient to be used - /// - /// - /// True: will dispose the provided httpClient on calling QuantumClient.Dispose(). False: will not dispose provided httpClient - /// - /// Thrown when a required parameter is null - /// - public QuantumClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient) - { - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - Credentials = credentials; - if (Credentials != null) - { - Credentials.InitializeServiceClient(this); - } - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public QuantumClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) - { - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - Credentials = credentials; - if (Credentials != null) - { - Credentials.InitializeServiceClient(this); - } - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Optional. The base URI of the service. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public QuantumClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) - { - if (baseUri == null) - { - throw new System.ArgumentNullException("baseUri"); - } - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - BaseUri = baseUri; - Credentials = credentials; - if (Credentials != null) - { - Credentials.InitializeServiceClient(this); - } - } - - /// - /// Initializes a new instance of the QuantumClient class. - /// - /// - /// Optional. The base URI of the service. - /// - /// - /// Required. Credentials needed for the client to connect to Azure. - /// - /// - /// Optional. The http client handler used to handle http transport. - /// - /// - /// Optional. The delegating handlers to add to the http client pipeline. - /// - /// - /// Thrown when a required parameter is null - /// - public QuantumClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) - { - if (baseUri == null) - { - throw new System.ArgumentNullException("baseUri"); - } - if (credentials == null) - { - throw new System.ArgumentNullException("credentials"); - } - BaseUri = baseUri; - Credentials = credentials; - if (Credentials != null) - { - Credentials.InitializeServiceClient(this); - } - } - - /// - /// An optional partial-method to perform custom initialization. - /// - partial void CustomInitialize(); - /// - /// Initializes client properties. - /// - private void Initialize() - { - Jobs = new JobsOperations(this); - Providers = new ProvidersOperations(this); - Storage = new StorageOperations(this); - Quotas = new QuotasOperations(this); - BaseUri = new System.Uri("https://quantum.azure.com"); - AcceptLanguage = "en-US"; - LongRunningOperationRetryTimeout = 30; - GenerateClientRequestId = true; - SerializationSettings = new JsonSerializerSettings - { - Formatting = Newtonsoft.Json.Formatting.Indented, - DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, - DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, - ContractResolver = new ReadOnlyJsonContractResolver(), - Converters = new List - { - new Iso8601TimeSpanConverter() - } - }; - DeserializationSettings = new JsonSerializerSettings - { - DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, - DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, - ContractResolver = new ReadOnlyJsonContractResolver(), - Converters = new List - { - new Iso8601TimeSpanConverter() - } - }; - CustomInitialize(); - DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); - } - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/QuotasOperations.cs b/src/Azure/Azure.Quantum.Client/generated/QuotasOperations.cs deleted file mode 100644 index 639526087e5..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/QuotasOperations.cs +++ /dev/null @@ -1,397 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - - /// - /// QuotasOperations operations. - /// - internal partial class QuotasOperations : IServiceOperations, IQuotasOperations - { - /// - /// Initializes a new instance of the QuotasOperations class. - /// - /// - /// Reference to the service client. - /// - /// - /// Thrown when a required parameter is null - /// - internal QuotasOperations(QuantumClient client) - { - if (client == null) - { - throw new System.ArgumentNullException("client"); - } - Client = client; - } - - /// - /// Gets a reference to the QuantumClient - /// - public QuantumClient Client { get; private set; } - - /// - /// List quotas for the given workspace. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task>> ListWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/quotas").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse>(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - /// - /// List quotas for the given workspace. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (nextPageLink == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("nextPageLink", nextPageLink); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); - } - // Construct URL - string _url = "{nextLink}"; - _url = _url.Replace("{nextLink}", nextPageLink); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("GET"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse>(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/QuotasOperationsExtensions.cs b/src/Azure/Azure.Quantum.Client/generated/QuotasOperationsExtensions.cs deleted file mode 100644 index 99f5cc55e9b..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/QuotasOperationsExtensions.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Threading; - using System.Threading.Tasks; - - /// - /// Extension methods for QuotasOperations. - /// - public static partial class QuotasOperationsExtensions - { - /// - /// List quotas for the given workspace. - /// - /// - /// The operations group for this extension method. - /// - public static IPage List(this IQuotasOperations operations) - { - return operations.ListAsync().GetAwaiter().GetResult(); - } - - /// - /// List quotas for the given workspace. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The cancellation token. - /// - public static async Task> ListAsync(this IQuotasOperations operations, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - /// - /// List quotas for the given workspace. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - public static IPage ListNext(this IQuotasOperations operations, string nextPageLink) - { - return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); - } - - /// - /// List quotas for the given workspace. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The NextLink from the previous successful call to List operation. - /// - /// - /// The cancellation token. - /// - public static async Task> ListNextAsync(this IQuotasOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/StorageOperations.cs b/src/Azure/Azure.Quantum.Client/generated/StorageOperations.cs deleted file mode 100644 index 885842c24c3..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/StorageOperations.cs +++ /dev/null @@ -1,249 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using Newtonsoft.Json; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - - /// - /// StorageOperations operations. - /// - internal partial class StorageOperations : IServiceOperations, IStorageOperations - { - /// - /// Initializes a new instance of the StorageOperations class. - /// - /// - /// Reference to the service client. - /// - /// - /// Thrown when a required parameter is null - /// - internal StorageOperations(QuantumClient client) - { - if (client == null) - { - throw new System.ArgumentNullException("client"); - } - Client = client; - } - - /// - /// Gets a reference to the QuantumClient - /// - public QuantumClient Client { get; private set; } - - /// - /// Gets a URL with SAS token for a container/blob in the storage account - /// associated with the workspace. The SAS URL can be used to upload job input - /// and/or download job output. - /// - /// - /// The details (name and container) of the blob to store or download data. - /// - /// - /// Headers that will be added to request. - /// - /// - /// The cancellation token. - /// - /// - /// Thrown when the operation returned an invalid status code - /// - /// - /// Thrown when unable to deserialize the response - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// Thrown when a required parameter is null - /// - /// - /// A response object containing the response body and response headers. - /// - public async Task> SasUriWithHttpMessagesAsync(BlobDetails blobDetails, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) - { - if (Client.SubscriptionId == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); - } - if (Client.ResourceGroupName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); - } - if (Client.WorkspaceName == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName"); - } - if (blobDetails == null) - { - throw new ValidationException(ValidationRules.CannotBeNull, "blobDetails"); - } - if (blobDetails != null) - { - blobDetails.Validate(); - } - // Tracing - bool _shouldTrace = ServiceClientTracing.IsEnabled; - string _invocationId = null; - if (_shouldTrace) - { - _invocationId = ServiceClientTracing.NextInvocationId.ToString(); - Dictionary tracingParameters = new Dictionary(); - tracingParameters.Add("blobDetails", blobDetails); - tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "SasUri", tracingParameters); - } - // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/storage/sasUri").ToString(); - _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); - _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); - _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName)); - List _queryParameters = new List(); - if (_queryParameters.Count > 0) - { - _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); - } - // Create HTTP transport objects - var _httpRequest = new HttpRequestMessage(); - HttpResponseMessage _httpResponse = null; - _httpRequest.Method = new HttpMethod("POST"); - _httpRequest.RequestUri = new System.Uri(_url); - // Set Headers - if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) - { - _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); - } - if (Client.AcceptLanguage != null) - { - if (_httpRequest.Headers.Contains("accept-language")) - { - _httpRequest.Headers.Remove("accept-language"); - } - _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); - } - - - if (customHeaders != null) - { - foreach(var _header in customHeaders) - { - if (_httpRequest.Headers.Contains(_header.Key)) - { - _httpRequest.Headers.Remove(_header.Key); - } - _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); - } - } - - // Serialize Request - string _requestContent = null; - if(blobDetails != null) - { - _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(blobDetails, Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); - _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); - } - // Set Credentials - if (Client.Credentials != null) - { - cancellationToken.ThrowIfCancellationRequested(); - await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - } - // Send Request - if (_shouldTrace) - { - ServiceClientTracing.SendRequest(_invocationId, _httpRequest); - } - cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); - if (_shouldTrace) - { - ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); - } - HttpStatusCode _statusCode = _httpResponse.StatusCode; - cancellationToken.ThrowIfCancellationRequested(); - string _responseContent = null; - if ((int)_statusCode != 200) - { - var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); - try - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - if (_errorBody != null) - { - ex.Body = _errorBody; - } - } - catch (JsonException) - { - // Ignore the exception - } - ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); - ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); - if (_shouldTrace) - { - ServiceClientTracing.Error(_invocationId, ex); - } - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw ex; - } - // Create Result - var _result = new AzureOperationResponse(); - _result.Request = _httpRequest; - _result.Response = _httpResponse; - if (_httpResponse.Headers.Contains("x-ms-request-id")) - { - _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); - } - // Deserialize Response - if ((int)_statusCode == 200) - { - _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); - try - { - _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, Client.DeserializationSettings); - } - catch (JsonException ex) - { - _httpRequest.Dispose(); - if (_httpResponse != null) - { - _httpResponse.Dispose(); - } - throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); - } - } - if (_shouldTrace) - { - ServiceClientTracing.Exit(_invocationId, _result); - } - return _result; - } - - } -} diff --git a/src/Azure/Azure.Quantum.Client/generated/StorageOperationsExtensions.cs b/src/Azure/Azure.Quantum.Client/generated/StorageOperationsExtensions.cs deleted file mode 100644 index a01a20f0eb9..00000000000 --- a/src/Azure/Azure.Quantum.Client/generated/StorageOperationsExtensions.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. See License.txt in the project root for -// license information. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is -// regenerated. -// - -namespace Microsoft.Azure.Quantum.Client -{ - using Microsoft.Rest; - using Microsoft.Rest.Azure; - using Models; - using System.Threading; - using System.Threading.Tasks; - - /// - /// Extension methods for StorageOperations. - /// - public static partial class StorageOperationsExtensions - { - /// - /// Gets a URL with SAS token for a container/blob in the storage account - /// associated with the workspace. The SAS URL can be used to upload job input - /// and/or download job output. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The details (name and container) of the blob to store or download data. - /// - public static SasUriResponse SasUri(this IStorageOperations operations, BlobDetails blobDetails) - { - return operations.SasUriAsync(blobDetails).GetAwaiter().GetResult(); - } - - /// - /// Gets a URL with SAS token for a container/blob in the storage account - /// associated with the workspace. The SAS URL can be used to upload job input - /// and/or download job output. - /// - /// - /// The operations group for this extension method. - /// - /// - /// The details (name and container) of the blob to store or download data. - /// - /// - /// The cancellation token. - /// - public static async Task SasUriAsync(this IStorageOperations operations, BlobDetails blobDetails, CancellationToken cancellationToken = default(CancellationToken)) - { - using (var _result = await operations.SasUriWithHttpMessagesAsync(blobDetails, null, cancellationToken).ConfigureAwait(false)) - { - return _result.Body; - } - } - - } -} diff --git a/src/Quantum.Development.Kit/Microsoft.Quantum.Development.Kit.nuspec b/src/Quantum.Development.Kit/Microsoft.Quantum.Development.Kit.nuspec index de6a81b711b..03fb92cef4f 100644 --- a/src/Quantum.Development.Kit/Microsoft.Quantum.Development.Kit.nuspec +++ b/src/Quantum.Development.Kit/Microsoft.Quantum.Development.Kit.nuspec @@ -20,7 +20,7 @@ Quantum Q# QSharp - + diff --git a/src/Simulation/AutoSubstitution/AutoSubstitution.csproj b/src/Simulation/AutoSubstitution/AutoSubstitution.csproj index 636efa33244..bb6f737fba1 100644 --- a/src/Simulation/AutoSubstitution/AutoSubstitution.csproj +++ b/src/Simulation/AutoSubstitution/AutoSubstitution.csproj @@ -12,7 +12,7 @@ - + diff --git a/src/Simulation/CSharpGeneration/Microsoft.Quantum.CSharpGeneration.fsproj b/src/Simulation/CSharpGeneration/Microsoft.Quantum.CSharpGeneration.fsproj index 03714fb820f..088820b458c 100644 --- a/src/Simulation/CSharpGeneration/Microsoft.Quantum.CSharpGeneration.fsproj +++ b/src/Simulation/CSharpGeneration/Microsoft.Quantum.CSharpGeneration.fsproj @@ -22,7 +22,7 @@ - + diff --git a/src/Simulation/EntryPointDriver.Tests/Tests.fs b/src/Simulation/EntryPointDriver.Tests/Tests.fs index 9ca3ad61330..9d75e67c648 100644 --- a/src/Simulation/EntryPointDriver.Tests/Tests.fs +++ b/src/Simulation/EntryPointDriver.Tests/Tests.fs @@ -192,7 +192,7 @@ let private testWithTarget defaultTarget = |> testWithConstants /// Standard command-line arguments for the "submit" command without specifying a target. -let private submitWithoutTarget = +let private submitWithoutTargetAndLocation = [ "submit" "--subscription" "mySubscription" @@ -201,6 +201,10 @@ let private submitWithoutTarget = "--workspace" "myWorkspace" ] + +/// Standard command-line arguments for the "submit" command without specifying a target. +let private submitWithoutTarget = submitWithoutTargetAndLocation @ ["--location"; "myLocation"] + /// Standard command-line arguments for the "submit" command using the "test.nothing" target. let private submitWithNothingTarget = submitWithoutTarget @ ["--target"; "test.nothing"] @@ -562,9 +566,9 @@ let ``Submit uses default values`` () = Workspace: myWorkspace Target: test.nothing Storage: - AAD Token: Base URI: - Location: + Location: myLocation + Credential: Default Job Name: Shots: 500 Output: FriendlyUri @@ -582,9 +586,9 @@ let ``Submit uses default values with default target`` () = Workspace: myWorkspace Target: test.nothing Storage: - AAD Token: Base URI: - Location: + Location: myLocation + Credential: Default Job Name: Shots: 500 Output: FriendlyUri @@ -602,21 +606,21 @@ let ``Submit allows overriding default values`` () = "myStorage" "--aad-token" "myToken" - "--base-uri" - "myBaseUri" "--job-name" "myJobName" "--shots" "750" + "--credential" + "cli" ]) |> yields "Subscription: mySubscription Resource Group: myResourceGroup Workspace: myWorkspace Target: test.nothing Storage: myStorage - AAD Token: myToken - Base URI: myBaseUri - Location: + Base URI: + Location: myLocation + Credential: CLI Job Name: myJobName Shots: 750 Output: FriendlyUri @@ -624,7 +628,43 @@ let ``Submit allows overriding default values`` () = Verbose: True https://www.example.com/00000000-0000-0000-0000-0000000000000" - + +[] +let ``Submit extracts the location from a quantum endpoint`` () = + let given = test "Returns Unit" + given (submitWithoutTargetAndLocation @ [ + "--verbose" + "--storage" + "myStorage" + "--aad-token" + "myToken" + "--base-uri" + "https://westus.quantum.microsoft.com/" + "--job-name" + "myJobName" + "--credential" + "VisualStudio" + "--shots" + "750" + "--target" + "test.nothing" + ]) + |> yields "Subscription: mySubscription + Resource Group: myResourceGroup + Workspace: myWorkspace + Target: test.nothing + Storage: myStorage + Base URI: https://westus.quantum.microsoft.com/ + Location: westus + Credential: VisualStudio + Job Name: myJobName + Shots: 750 + Output: FriendlyUri + Dry Run: False + Verbose: True + + https://www.example.com/00000000-0000-0000-0000-0000000000000" + [] let ``Submit allows overriding default values with default target`` () = let given = testWithTarget "foo.target" "Returns Unit" @@ -632,10 +672,10 @@ let ``Submit allows overriding default values with default target`` () = "--verbose" "--storage" "myStorage" + "--credential" + "Interactive" "--aad-token" "myToken" - "--base-uri" - "myBaseUri" "--job-name" "myJobName" "--shots" @@ -646,9 +686,9 @@ let ``Submit allows overriding default values with default target`` () = Workspace: myWorkspace Target: test.nothing Storage: myStorage - AAD Token: myToken - Base URI: myBaseUri - Location: + Base URI: + Location: myLocation + Credential: Interactive Job Name: myJobName Shots: 750 Output: FriendlyUri @@ -663,27 +703,27 @@ let ``Submit does not allow to include mutually exclusive options`` () = given (submitWithNothingTarget @ [ "--base-uri" "myBaseUri" - "--location" - "myLocation" ]) |> failsWith "Options --base-uri, --location cannot be used together." - + [] let ``Submit allows to include --base-uri option when --location is not present`` () = let given = testWithTarget "foo.target" "Returns Unit" - given (submitWithNothingTarget @ [ + given (submitWithoutTargetAndLocation @ [ "--verbose" "--base-uri" - "myBaseUri" + "http://myBaseUri.foo.com/" + "--target" + "test.nothing" ]) |> yields "Subscription: mySubscription Resource Group: myResourceGroup Workspace: myWorkspace Target: test.nothing Storage: - AAD Token: - Base URI: myBaseUri - Location: + Base URI: http://mybaseuri.foo.com/ + Location: mybaseuri + Credential: Default Job Name: Shots: 500 Output: FriendlyUri @@ -697,17 +737,15 @@ let ``Submit allows to include --location option when --base-uri is not present` let given = testWithTarget "foo.target" "Returns Unit" given (submitWithNothingTarget @ [ "--verbose" - "--location" - "myLocation" ]) |> yields "Subscription: mySubscription Resource Group: myResourceGroup Workspace: myWorkspace Target: test.nothing Storage: - AAD Token: Base URI: Location: myLocation + Credential: Default Job Name: Shots: 500 Output: FriendlyUri @@ -719,19 +757,21 @@ let ``Submit allows to include --location option when --base-uri is not present` [] let ``Submit allows spaces for the --location option`` () = let given = test "Returns Unit" - given (submitWithNothingTarget @ [ + given (submitWithoutTargetAndLocation @ [ "--verbose" "--location" "My Location" + "--target" + "test.nothing" ]) |> yields "Subscription: mySubscription Resource Group: myResourceGroup Workspace: myWorkspace Target: test.nothing Storage: - AAD Token: Base URI: Location: My Location + Credential: Default Job Name: Shots: 500 Output: FriendlyUri @@ -739,15 +779,15 @@ let ``Submit allows spaces for the --location option`` () = Verbose: True https://www.example.com/00000000-0000-0000-0000-0000000000000" - + [] -let ``Submit does not allow an invalid value for the --location option`` () = +let ``Submit fails if both --location and --baseUri are missing`` () = let given = test "Returns Unit" - given (submitWithNothingTarget @ [ - "--location" - "my!nv@lidLocation" + given (submitWithoutTargetAndLocation @ [ + "--target" + "test.nothing" ]) - |> failsWith "\"my!nv@lidLocation\" is an invalid value for the --location option." + |> failsWith "Either --location or --base-uri must be provided." [] let ``Submit requires a positive number of shots`` () = @@ -783,7 +823,7 @@ let ``Submit has required options`` () = // Try every possible combination of arguments. The command should succeed only when all of the arguments are // included. - let commandName = List.head submitWithNothingTarget + let commandName = List.head (submitWithoutTargetAndLocation @ ["--target"; "test.nothing"]) let allArgs = submitWithNothingTarget |> List.tail |> List.chunkBySize 2 for args in powerSet allArgs do given (commandName :: List.concat args) @@ -844,6 +884,7 @@ let ``Shows help text for submit command`` () = --resource-group (REQUIRED) The resource group name. --workspace (REQUIRED) The workspace name. --target (REQUIRED) The target device ID. + --credential The type of credential to use to authenticate with Azure. --storage The storage account connection string. --aad-token The Azure Active Directory authentication token. --base-uri The base URI of the Azure Quantum endpoint. @@ -873,6 +914,7 @@ let ``Shows help text for submit command with default target`` () = --resource-group (REQUIRED) The resource group name. --workspace (REQUIRED) The workspace name. --target The target device ID. + --credential The type of credential to use to authenticate with Azure. --storage The storage account connection string. --aad-token The Azure Active Directory authentication token. --base-uri The base URI of the Azure Quantum endpoint. @@ -930,6 +972,8 @@ let ``Supports submitting multiple entry points`` () = "myResourceGroup" "--workspace" "myWorkspace" + "--location" + "location" "--target" "test.nothing" ] @@ -951,6 +995,8 @@ let ``Supports submitting multiple entry points with different parameters`` () = "myResourceGroup" "--workspace" "myWorkspace" + "--location" + "location" "--target" "test.nothing" ] diff --git a/src/Simulation/EntryPointDriver/Azure.cs b/src/Simulation/EntryPointDriver/Azure.cs index 9f33f7baec5..eb43ae2e193 100644 --- a/src/Simulation/EntryPointDriver/Azure.cs +++ b/src/Simulation/EntryPointDriver/Azure.cs @@ -3,8 +3,14 @@ using System; using System.Linq; +using System.Threading; using System.Threading.Tasks; + +using Azure.Core; +using Azure.Identity; + using Microsoft.Azure.Quantum; +using Microsoft.Azure.Quantum.Authentication; using Microsoft.Azure.Quantum.Exceptions; using Microsoft.Quantum.Runtime; using Microsoft.Quantum.Simulation.Common.Exceptions; @@ -35,6 +41,13 @@ public static async Task Submit(EntryPointInfo info, Console.WriteLine(); } + if ((settings.Location is null) && (settings.BaseUri is null)) + { + DisplayWithColor(ConsoleColor.Red, Console.Error, + $"Either --location or --base-uri must be provided."); + return 1; + } + var machine = CreateMachine(settings); if (machine is null) { @@ -202,18 +215,34 @@ public enum OutputFormat /// public sealed class AzureSettings { + private class AADTokenCredential : TokenCredential + { + AccessToken Token { get; } + + public AADTokenCredential(string token) + { + Token = new AccessToken(token, DateTime.Now.AddMinutes(5)); + } + + public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) => + Token; + + public override ValueTask GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) => + new ValueTask(Token); + } + /// /// The subscription ID. /// public string? Subscription { get; set; } /// - /// The resource group name. + /// The Azure Quantum workspace's resource group name. /// public string? ResourceGroup { get; set; } /// - /// The workspace name. + /// The Azure Quantum workspace's name. /// public string? Workspace { get; set; } @@ -232,15 +261,24 @@ public sealed class AzureSettings /// public string? AadToken { get; set; } + /// + /// The type of Credentials to use to authenticate with Azure. For more information + /// about authentication with Azure services see: https://docs.microsoft.com/dotnet/api/overview/azure/identity-readme + /// NOTE: If both and properties are specified, takes precedence. + /// If none are provided, then it uses . + /// + public CredentialType? Credential { get; set; } + /// /// The base URI of the Azure Quantum endpoint. - /// If both and properties are not null, takes precedence. + /// NOTE: This parameter is deprected, please always use . + /// If both and properties are not null, takes precedence. /// public Uri? BaseUri { get; set; } /// - /// The location to use with the default Azure Quantum endpoint. - /// If both and properties are not null, takes precedence. + /// The Azure Quantum Workspace's location (region). + /// If both and properties are not null, takes precedence. /// public string? Location { get; set; } @@ -269,32 +307,35 @@ public sealed class AzureSettings /// public bool Verbose { get; set; } - /// - /// Creates a based on the settings. - /// - /// The based on the settings. - internal Workspace CreateWorkspace() + internal TokenCredential CreateCredentials() { - if (BaseUri != null) - { - return AadToken is null - ? new Workspace(Subscription, ResourceGroup, Workspace, baseUri: BaseUri) - : new Workspace(Subscription, ResourceGroup, Workspace, AadToken, baseUri: BaseUri); - } - else if (Location != null) + if (!(AadToken is null)) { - return AadToken is null - ? new Workspace(Subscription, ResourceGroup, Workspace, location: NormalizeLocation(Location)) - : new Workspace(Subscription, ResourceGroup, Workspace, AadToken, location: NormalizeLocation(Location)); + return new AADTokenCredential(AadToken); } else { - return AadToken is null - ? new Workspace(Subscription, ResourceGroup, Workspace, baseUri: null) - : new Workspace(Subscription, ResourceGroup, Workspace, AadToken, baseUri: null); + return CredentialFactory.CreateCredential(Credential ?? CredentialType.Default, Subscription); } } + /// + /// Creates a based on the settings. + /// + /// The based on the settings. + internal Workspace CreateWorkspace() + { + var credentials = CreateCredentials(); + var location = NormalizeLocation(Location ?? ExtractLocation(BaseUri)); + + return new Workspace( + subscriptionId: Subscription, + resourceGroupName: ResourceGroup, + workspaceName: Workspace, + location: location, + credential: credentials); + } + public override string ToString() => string.Join(System.Environment.NewLine, $"Subscription: {Subscription}", @@ -302,15 +343,25 @@ public override string ToString() => $"Workspace: {Workspace}", $"Target: {Target}", $"Storage: {Storage}", - $"AAD Token: {AadToken}", $"Base URI: {BaseUri}", - $"Location: {Location}", + $"Location: {Location ?? ExtractLocation(BaseUri)}", + $"Credential: {Credential}", $"Job Name: {JobName}", $"Shots: {Shots}", $"Output: {Output}", $"Dry Run: {DryRun}", $"Verbose: {Verbose}"); + internal static string ExtractLocation(Uri? baseUri) + { + if (baseUri is null || !baseUri.IsAbsoluteUri) + { + return ""; + } + + return baseUri.Host.Substring(0, baseUri.Host.IndexOf('.')); + } + internal static string NormalizeLocation(string location) => string.Concat(location.Where(c => !char.IsWhiteSpace(c))).ToLower(); } diff --git a/src/Simulation/EntryPointDriver/Driver.cs b/src/Simulation/EntryPointDriver/Driver.cs index 7997a87db01..1a3943c0f00 100644 --- a/src/Simulation/EntryPointDriver/Driver.cs +++ b/src/Simulation/EntryPointDriver/Driver.cs @@ -14,6 +14,8 @@ using System.Text; using System.Threading.Tasks; +using Microsoft.Azure.Quantum.Authentication; + namespace Microsoft.Quantum.EntryPointDriver { using Validators = ImmutableList>; @@ -47,6 +49,14 @@ public sealed class Driver private static readonly OptionInfo StorageOption = new OptionInfo( ImmutableList.Create("--storage"), default, "The storage account connection string."); + /// + /// The credential option. + /// + private static readonly OptionInfo CredentialOption = new OptionInfo( + ImmutableList.Create("--credential"), + CredentialType.Default, + "The type of credential to use to authenticate with Azure."); + /// /// The AAD token option. /// @@ -417,7 +427,8 @@ private CommandWithValidators CreateSubmitEntryPointCommand(IEntryPoint entryPoi var validators = AddOptionIfAvailable(command, SubscriptionOption) .Concat(AddOptionIfAvailable(command, ResourceGroupOption)) .Concat(AddOptionIfAvailable(command, WorkspaceOption)) - .Concat(AddOptionIfAvailable(command, this.TargetOption)) + .Concat(AddOptionIfAvailable(command, TargetOption)) + .Concat(AddOptionIfAvailable(command, CredentialOption)) .Concat(AddOptionIfAvailable(command, StorageOption)) .Concat(AddOptionIfAvailable(command, AadTokenOption)) .Concat(AddOptionIfAvailable(command, BaseUriOption)) @@ -457,11 +468,11 @@ private Task Submit(ParseResult parseResult, AzureSettings azureSettings, I Subscription = azureSettings.Subscription, ResourceGroup = azureSettings.ResourceGroup, Workspace = azureSettings.Workspace, - Target = DefaultIfShadowed(entryPoint, this.TargetOption, azureSettings.Target), + Target = DefaultIfShadowed(entryPoint, TargetOption, azureSettings.Target), Storage = DefaultIfShadowed(entryPoint, StorageOption, azureSettings.Storage), - AadToken = DefaultIfShadowed(entryPoint, AadTokenOption, azureSettings.AadToken), BaseUri = DefaultIfShadowed(entryPoint, BaseUriOption, azureSettings.BaseUri), Location = DefaultIfShadowed(entryPoint, LocationOption, azureSettings.Location), + Credential = DefaultIfShadowed(entryPoint, CredentialOption, azureSettings.Credential), JobName = DefaultIfShadowed(entryPoint, JobNameOption, azureSettings.JobName), Shots = DefaultIfShadowed(entryPoint, ShotsOption, azureSettings.Shots), Output = DefaultIfShadowed(entryPoint, OutputOption, azureSettings.Output), diff --git a/src/Xunit/Microsoft.Quantum.Xunit.nuspec b/src/Xunit/Microsoft.Quantum.Xunit.nuspec index f4be81d5e51..03bcb5d652b 100644 --- a/src/Xunit/Microsoft.Quantum.Xunit.nuspec +++ b/src/Xunit/Microsoft.Quantum.Xunit.nuspec @@ -22,7 +22,7 @@ - +